text stringlengths 8 4.13M |
|---|
use thiserror::Error as ThisError;
use ukis_clickhouse_arrow_grpc::{ClickhouseException, Error as CAGError};
#[derive(ThisError, Debug)]
pub enum Error {
#[error(transparent)]
Polars(#[from] polars::error::PolarsError),
#[error(transparent)]
H3ronPolars(#[from] h3ron_polars::error::Error),
#[error(transparent)]
Arrow(#[from] polars::error::ArrowError),
#[error(transparent)]
TonicStatus(#[from] ukis_clickhouse_arrow_grpc::export::tonic::Status),
#[error(transparent)]
TonicTansport(#[from] ukis_clickhouse_arrow_grpc::export::tonic::transport::Error),
#[error("ClickhouseException({})", .0.to_string())]
ClickhouseException(ClickhouseException),
#[error("mismatch of arrays in chunk to number of casts")]
CastArrayLengthMismatch,
#[error("arrow chunk is missing field '{0}'")]
ArrowChunkMissingField(String),
#[error(transparent)]
JoinError(#[from] tokio::task::JoinError),
#[error(transparent)]
H3ron(#[from] h3ron::Error),
#[error("dataframe h3index column '{0}' is typed as {1}, but should be UInt64")]
DataframeInvalidH3IndexType(String, String),
#[error("dataframe contains no column named '{0}'")]
DataframeMissingColumn(String),
#[error("Unsupported H3 resolution: {0}")]
UnsupportedH3Resolution(u8),
#[error("no queryable tables found")]
NoQueryableTables,
#[error("mixed h3 resolutions")]
MixedH3Resolutions,
#[error("empty cells")]
EmptyCells,
#[error("missing query placeholder {0}")]
MissingQueryPlaceholder(String),
#[error("schema error validating {0}: {1}")]
SchemaValidationError(&'static str, String),
#[error("no h3 resolutions defined")]
NoH3ResolutionsDefined,
#[error("missing preconditions for partial optimization")]
MissingPrecondidtionsForPartialOptimization,
#[error("tableset not found: {0}")]
TableSetNotFound(String),
#[error("database not found: {0}")]
DatabaseNotFound(String),
#[error("missing index value")]
MissingIndexValue,
#[error("abort has been triggered")]
Abort,
#[error("acquiring lock failed")]
AcquiringLockFailed,
#[error(transparent)]
Io(#[from] std::io::Error),
}
impl From<CAGError> for Error {
fn from(cagerror: CAGError) -> Self {
match cagerror {
CAGError::Polars(e) => Self::Polars(e),
CAGError::Arrow(e) => Self::Arrow(e),
CAGError::TonicStatus(e) => Self::TonicStatus(e),
CAGError::ClickhouseException(ce) => Self::ClickhouseException(ce),
CAGError::CastArrayLengthMismatch => Self::CastArrayLengthMismatch,
CAGError::ArrowChunkMissingField(name) => Self::ArrowChunkMissingField(name),
CAGError::JoinError(e) => Self::JoinError(e),
}
}
}
|
pub trait Entity {
fn dormant_begin();
fn dormant_end();
}
|
use std::slice;
use std::iter::repeat;
use std::ops::{Index, IndexMut};
use super::{BOX_WIDTH, BOX_HEIGHT};
use super::{Colorspace, ColorRGBA};
#[derive(Copy, Clone, Debug)]
pub struct Rect {
left: usize,
width: usize,
top: usize,
height: usize,
}
#[derive(Copy, Clone, Debug)]
pub struct Size {
width: usize,
height: usize,
}
impl Rect {
fn overrender(&self) -> Rect {
// TODO: remove this restriction.
assert_eq!(self.top, 0);
assert_eq!(self.left, 0);
let mut width = self.width;
let width_partial_tile = width % BOX_WIDTH;
if width_partial_tile > 0 {
width -= width_partial_tile;
width += BOX_WIDTH;
}
let mut height = self.height;
let height_partial_tile = height % BOX_HEIGHT;
if height_partial_tile > 0 {
height -= height_partial_tile;
height += BOX_HEIGHT;
}
Rect {
left: self.left,
width: width,
top: self.top,
height: height,
}
}
}
#[derive(Clone)]
pub struct Surface<CS=ColorRGBA<u8>> {
pub rect: Rect,
pub align_size: Size,
background: CS,
buffer: Vec<CS>,
}
impl<CS> Surface<CS> where CS: Colorspace {
pub fn iter_pixels<'a>(&'a self) -> ::std::slice::Iter<'a, CS> {
self.buffer.iter()
}
pub fn iter_pixels_mut<'a>(&'a mut self) -> ::std::slice::IterMut<'a, CS> {
self.buffer.iter_mut()
}
}
mod zigzag {
use super::super::{BOX_WIDTH, BOX_HEIGHT};
pub fn to_idx(orig_size: (usize, usize), coord: (usize, usize)) -> usize {
let (width, height) = orig_size;
assert!(width % BOX_WIDTH == 0);
assert!(height % BOX_HEIGHT == 0);
let box_length = BOX_WIDTH * BOX_HEIGHT;
let boxes_across = width / BOX_WIDTH;
let (x, y) = coord;
if width <= x {
panic!("`x` out of bounds: {} <= {} < {}", 0, x, width);
}
if height <= y {
panic!("`y` out of bounds: {} <= {} < {}", 0, y, height);
}
let box_x = x / BOX_WIDTH;
let box_y = y / BOX_HEIGHT;
let inner_x = x % BOX_WIDTH;
let inner_y = y % BOX_HEIGHT;
let mut idx = 0;
idx += box_y * boxes_across + box_x;
idx *= box_length;
idx += inner_y * BOX_WIDTH + inner_x;
idx
}
pub fn to_coord(orig_size: (usize, usize), idx: usize) -> (usize, usize) {
// let (width, height) = orig_size;
// assert!(width % BOX_WIDTH == 0);
// assert!(height % BOX_HEIGHT == 0);
// let box_length = BOX_WIDTH * BOX_HEIGHT;
// let boxes_across = width / BOX_WIDTH;
// let (box_idx, inner_idx) = (idx / box_length, idx % box_length);
// let (box_x, box_y) = (box_idx % boxes_across, box_idx / boxes_across);
// let (inner_x, inner_y) = (inner_idx % BOX_WIDTH, inner_idx / BOX_WIDTH);
// (box_x * BOX_WIDTH + inner_x, box_y * BOX_HEIGHT + inner_y)
(0, 0)
}
}
fn align_number(number: usize, align_to: usize) -> usize {
let mut divisions = number / align_to;
if (number % align_to) > 0 {
divisions += 1
}
return divisions * align_to;
}
impl<CS> Surface<CS> where CS: Colorspace {
pub fn new_black(width: usize, height: usize) -> Surface<CS> {
Surface::new(width, height, CS::black())
}
pub fn new(width: usize, height: usize, background: CS) -> Surface<CS> {
let align_width = align_number(width, BOX_WIDTH);
let align_height = align_number(height, BOX_HEIGHT);
Surface {
rect: Rect {
top: 0,
height: height,
left: 0,
width: width,
},
align_size: Size {
width: align_width,
height: align_height,
},
background: background,
buffer: repeat(background).take(align_width * align_height).collect()
}
}
pub fn divide<'a>(&'a self) -> Tiles<'a, CS> {
Tiles::new(self)
}
pub fn divide_mut<'a>(&'a mut self) -> TilesMut<'a, CS> {
TilesMut::new(self)
}
pub fn overrender_size(&self) -> (usize, usize) {
(self.align_size.width, self.align_size.height)
}
#[inline]
pub fn pixel_count(&self) -> usize {
self.buffer.len()
}
#[inline]
pub fn width(&self) -> usize {
self.rect.width
}
#[inline]
pub fn height(&self) -> usize {
self.rect.height
}
pub fn pixels_raw(&self) -> &[CS] {
&self.buffer
}
pub fn pixels(&self) -> Vec<CS> {
let mut out = Vec::with_capacity(self.rect.width * self.rect.height);
for x in 0..self.rect.width {
for y in 0..self.rect.height {
out.push(self[(x, y)].clone());
}
}
out
}
}
impl<CS> Index<usize> for Surface<CS> where CS: Colorspace {
type Output = CS;
fn index<'a>(&'a self, index: usize) -> &'a CS {
&self.buffer[index]
}
}
impl<CS> IndexMut<usize> for Surface<CS> where CS: Colorspace {
fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut CS {
&mut self.buffer[index]
}
}
impl<CS> Index<(usize, usize)> for Surface<CS> where CS: Colorspace {
type Output = CS;
fn index<'a>(&'a self, coord: (usize, usize)) -> &'a CS {
assert_eq!(self.rect.top, 0);
assert_eq!(self.rect.left, 0);
let orig_size = (self.align_size.width, self.align_size.height);
let idx = zigzag::to_idx(orig_size, coord);
&self.buffer[idx]
}
}
impl<CS> IndexMut<(usize, usize)> for Surface<CS> where CS: Colorspace {
fn index_mut<'a>(&'a mut self, coord: (usize, usize)) -> &'a mut CS {
assert_eq!(self.rect.top, 0);
assert_eq!(self.rect.left, 0);
let orig_size = (self.align_size.width, self.align_size.height);
let idx = zigzag::to_idx(orig_size, coord);
&mut self.buffer[idx]
}
}
pub struct Tile<'a, CS=ColorRGBA<u8>> where CS: Colorspace + 'a {
location: Rect,
backing: &'a [CS],
}
impl<'a, CS> Tile<'a, CS> where CS: Colorspace + 'a {
fn new(location: Rect, backing: &'a [CS]) -> Self {
Tile {
location: location,
backing: backing,
}
}
fn coords(&self) -> TileCoordIter {
TileCoordIter::new(self.location)
}
pub fn pixels(&'a self) -> PixelIter<'a, CS> {
PixelIter::new(self.backing, self.coords())
}
}
impl<'a, CS> Index<(usize, usize)> for Tile<'a, CS> where CS: Colorspace + 'a {
type Output = CS;
fn index<'b>(&'b self, (abs_x, abs_y): (usize, usize)) -> &'b CS {
assert_eq!(self.location.top % BOX_HEIGHT, 0);
assert_eq!(self.location.left % BOX_WIDTH, 0);
let x = abs_x - self.location.left;
if self.location.width <= x {
panic!("`x` out of bounds: {} <= {} < {}",
self.location.left, abs_x,
self.location.left + self.location.width);
}
let y = abs_y - self.location.top;
if self.location.height <= y {
panic!("`y` out of bounds: {} <= {} < {}",
self.location.top, abs_y,
self.location.top + self.location.height);
}
let idx = zigzag::to_idx((BOX_WIDTH, BOX_HEIGHT), (x, y));
&self.backing[idx]
}
}
pub struct TileMut<'a, CS=ColorRGBA<u8>> where CS: Colorspace + 'a {
location: Rect,
backing: &'a mut [CS],
}
impl<'a, CS> TileMut<'a, CS> where CS: Colorspace + 'a {
fn new(location: Rect, backing: &'a mut [CS]) -> Self {
TileMut {
location: location,
backing: backing,
}
}
fn coords(&self) -> TileCoordIter {
TileCoordIter::new(self.location)
}
pub fn pixels(&'a self) -> PixelIter<'a, CS> {
PixelIter::new(&self.backing, self.coords())
}
pub fn pixels_mut(&'a mut self) -> PixelMutIter<'a, CS> {
let coords = self.coords();
PixelMutIter::new(&mut self.backing, coords)
}
}
impl<'a, CS> Index<(usize, usize)> for TileMut<'a, CS> where CS: Colorspace + 'a {
type Output = CS;
fn index<'b>(&'b self, (abs_x, abs_y): (usize, usize)) -> &'b CS {
assert_eq!(self.location.top % BOX_HEIGHT, 0);
assert_eq!(self.location.left % BOX_WIDTH, 0);
let x = abs_x - self.location.left;
if x < self.location.width {
panic!("`x` out of bounds: {} <= {} < {}",
self.location.left, abs_x,
self.location.left + self.location.width);
}
let y = abs_y - self.location.top;
if y < self.location.height {
panic!("`y` out of bounds: {} <= {} < {}",
self.location.top, abs_y,
self.location.top + self.location.height);
}
let idx = zigzag::to_idx((BOX_WIDTH, BOX_HEIGHT), (x, y));
&self.backing[idx]
}
}
impl<'a, CS> IndexMut<(usize, usize)> for TileMut<'a, CS> where CS: Colorspace + 'a {
fn index_mut<'b>(&'b mut self, coord: (usize, usize)) -> &'b mut CS {
assert_eq!(self.location.top, 0);
assert_eq!(self.location.left, 0);
let orig_size = (self.location.width, self.location.height);
let idx = zigzag::to_idx(orig_size, coord);
&mut self.backing[idx]
}
}
struct TileRectIter {
size: (usize, usize),
box_idx: usize,
box_idx_end: usize,
}
impl TileRectIter {
fn new(image: Rect) -> Self {
let Rect { width, height, .. } = image.overrender();
let idx_end = width * height / (BOX_WIDTH * BOX_HEIGHT);
TileRectIter {
size: (width, height),
box_idx: 0,
box_idx_end: idx_end,
}
}
}
impl Iterator for TileRectIter {
type Item = Rect;
fn next(&mut self) -> Option<Rect> {
if self.box_idx_end == self.box_idx {
return None;
}
let offset = self.box_idx * BOX_WIDTH * BOX_HEIGHT;
let (x, y) = zigzag::to_coord(self.size, offset);
self.box_idx += 1;
let rect = Rect {
left: x,
width: BOX_WIDTH,
top: y,
height: BOX_HEIGHT,
};
Some(rect)
}
}
/// Yields pixel locations inside of a local 128x8 rectangle inside of
/// a `Surface`.
struct TileCoordIter {
/// location of the local space in global space
rect: Rect,
idx: usize,
idx_end: usize,
}
impl TileCoordIter {
fn new(rect: Rect) -> Self {
// Ensure the subsurface is tile aligned (performance).
assert_eq!(rect.left % BOX_WIDTH, 0);
assert_eq!(rect.top % BOX_HEIGHT, 0);
TileCoordIter {
rect: rect,
idx: 0,
idx_end: BOX_WIDTH * BOX_HEIGHT,
}
}
}
impl Iterator for TileCoordIter {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
if self.idx == self.idx_end {
return None;
}
let bottom = self.rect.top + self.rect.height;
if BOX_WIDTH * bottom <= self.idx {
return None;
}
let (mut x, mut y) = (self.idx % BOX_WIDTH, self.idx / BOX_WIDTH);
if self.rect.width <= x {
// jump forward: (x, y) = (0, y + 1)
self.idx += self.rect.width - x;
x = self.idx % BOX_WIDTH;
y = self.idx / BOX_WIDTH;
assert_eq!(x, 0);
}
self.idx += 1;
let rv = (x + self.rect.left, y + self.rect.top);
Some(rv)
}
}
pub struct PixelIter<'a, CS=ColorRGBA<u8>> where CS: 'a {
items: slice::Iter<'a, CS>,
coords: TileCoordIter,
}
impl<'a, CS> PixelIter<'a, CS> where CS: Colorspace + 'a {
fn new(pixels: &'a [CS], coords: TileCoordIter) -> Self {
assert_eq!(pixels.len(), BOX_HEIGHT * BOX_WIDTH);
PixelIter { items: pixels.iter(), coords: coords }
}
}
impl<'a, CS> Iterator for PixelIter<'a, CS> {
type Item = (usize, usize, &'a CS);
fn next(&mut self) -> Option<(usize, usize, &'a CS)> {
match (self.coords.next(), self.items.next()) {
(Some((x, y)), Some(pixel)) => Some((x, y, pixel)),
(Some(_), None) => unreachable!(),
(None, Some(_)) => unreachable!(),
(None, None) => None,
}
}
}
pub struct PixelMutIter<'a, CS: 'a> {
items: slice::IterMut<'a, CS>,
coords: TileCoordIter,
}
impl<'a, CS> PixelMutIter<'a, CS> where CS: 'a {
fn new(pixels: &'a mut [CS], coords: TileCoordIter) -> Self {
assert_eq!(pixels.len(), BOX_HEIGHT * BOX_WIDTH);
PixelMutIter { items: pixels.iter_mut(), coords: coords }
}
}
impl<'a, CS> Iterator for PixelMutIter<'a, CS> {
type Item = (usize, usize, &'a mut CS);
fn next(&mut self) -> Option<(usize, usize, &'a mut CS)> {
match (self.coords.next(), self.items.next()) {
(Some((x, y)), Some(pixel)) => Some((x, y, pixel)),
(Some(_), None) => unreachable!("coord was some"),
(None, Some(_)) => unreachable!("items was some"),
(None, None) => None,
}
}
}
pub struct Tiles<'a, CS: 'a> {
rects: TileRectIter,
chunks: slice::Chunks<'a, CS>,
}
impl<'a, CS> Tiles<'a, CS> where CS: Colorspace + 'a {
pub fn new(surf: &'a Surface<CS>) -> Self {
Tiles {
rects: TileRectIter::new(surf.rect),
chunks: surf.buffer.chunks(BOX_WIDTH * BOX_HEIGHT),
}
}
}
impl<'a, CS> Iterator for Tiles<'a, CS> where CS: Colorspace + 'a {
type Item = Tile<'a, CS>;
fn next(&mut self) -> Option<Tile<'a, CS>> {
match (self.rects.next(), self.chunks.next()) {
(Some(rect), Some(backing)) => Some(Tile::new(rect, backing)),
(Some(_), None) => unreachable!(),
(None, Some(_)) => unreachable!(),
(None, None) => None,
}
}
}
pub struct TilesMut<'a, CS: 'a> {
rects: TileRectIter,
chunks: slice::ChunksMut<'a, CS>,
}
impl<'a, CS> TilesMut<'a, CS> where CS: Colorspace + 'a {
pub fn new(surf: &'a mut Surface<CS>) -> Self {
TilesMut {
rects: TileRectIter::new(surf.rect),
chunks: surf.buffer.chunks_mut(BOX_WIDTH * BOX_HEIGHT),
}
}
}
impl<'a, CS> Iterator for TilesMut<'a, CS> where CS: Colorspace + 'a {
type Item = TileMut<'a, CS>;
fn next(&mut self) -> Option<TileMut<'a, CS>> {
match (self.rects.next(), self.chunks.next()) {
(Some(rect), Some(backing)) => Some(TileMut::new(rect, backing)),
(Some(_), None) => unreachable!(),
(None, Some(_)) => unreachable!(),
(None, None) => None,
}
}
}
#[cfg(test)]
mod tests {
use std::thread;
use super::{zigzag, Surface};
use super::super::ColorRGBA;
use test::Bencher;
#[test]
fn test_paint_it_red() {
let width = 896;
let height = 600;
let mut surf: Surface<_> = Surface::new_black(width, height);
{
// let mut joiners = Vec::new();
for tile in surf.divide_mut() {
let mut xtile = tile;
for (_, _, pixel) in xtile.pixels_mut() {
*pixel = ColorRGBA::new_rgb(255_u8, 0, 0)
}
}
}
for color in surf.iter_pixels() {
assert_eq!(color.r, 255);
assert_eq!(color.g, 0);
assert_eq!(color.b, 0);
}
}
#[bench]
fn bench_zigzag_to_idx(b: &mut Bencher) {
use test::black_box;
const WIDTH: usize = 896;
const HEIGHT: usize = 600;
const X: usize = 743;
const Y: usize = 397;
b.iter(|| {
let width = black_box(WIDTH);
let height = black_box(HEIGHT);
let x = ::test::black_box(X);
let y = ::test::black_box(Y);
zigzag::to_idx((width, height), (x, y))
});
}
#[test]
fn test_tile_rect_iter() {
use std::ops::Add;
use super::{Rect, TileRectIter};
let tile_iter = TileRectIter::new(Rect {
left: 0,
width: 896,
top: 0,
height: 600,
});
assert_eq!(tile_iter.map(|_| 1).fold(0_u32, Add::add), 525);
}
}
|
pub mod model;
pub mod analysis;
pub mod types;
use na::{Matrix, Real, Dim};
use na::storage::Storage;
pub fn max<N : Real, C : Dim, R: Dim, S : Storage<N, C, R>>(mat : &Matrix<N, C, R, S>) -> N {
mat.iter().fold(N::zero(), |store, item| { store.max(*item) })
} |
use super::*;
#[derive(Clone)]
pub struct ModuleRef(pub Row);
impl ModuleRef {
pub fn name(&self) -> &'static str {
self.0.str(0)
}
}
|
fn main() {
step_1();
step_2();
step_3();
}
fn step_1() {
let mut s = String::from("hello world");
let word = first_word(&s);
println!("1ใ็ฎใฎใฏใผใ {}", word);
s.clear();
println!("็ฉบใฎใฏใ [{}]", s);
}
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item ==b' ' {
return &s[0..i];
}
}
return &s[..];
}
fn step_2() {
let s = String::from("hello world");
println!("2ๆๅญ็ฎใใ 6ๆๅญ็ฎ {}", &s[1..7]);
println!("4ๆๅญ็ฎไปฅ้ {}", &s[3..]);
println!("้ ญใใ8ๆๅญ็ฎ {}", &s[..8]);
}
fn step_3() {
let s = String::from("hello world");
println!("2ใ็ฎใฎใฏใผใ {}", second_word(&s));
}
fn second_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item ==b' ' {
return &s[i..];
}
}
return &s[..];
} |
use std::{fmt, io::{Bytes, Read}};
use crate::{data::Message, user::User};
#[derive(Debug,Clone)]
pub enum PacketError{
DisconnectError,
ParseError,
}
//์๋ฌ ์ธ๋ถํ ํด์ผํจ.(CannatParse, WrongCommand, ...)
impl fmt::Display for PacketError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Self::DisconnectError => {
write!(f, "socket is disconnected.")
},
&Self::ParseError => {
write!(f, "wrong packet data.")
}
}
}
}
pub enum Command {
Register(User), //ํ์๊ฐ์
Login(User),
JoinChatRoom, //์ฑํ
๋ฐฉ์ ์ ์
CreateChatRoom,
Message(Message), //๋ฉ์์ง ์ ์ก
}
pub enum Response {
}
pub type Result<T> = std::result::Result<T, PacketError>;
pub trait Framing {
//type T to byte stream data.
fn encode_data(&self) -> Vec<u8>;
fn decode<T: Read>(data: &mut Bytes<T>) -> Result<Self> where Self: Sized;
}
impl Framing for Response {
fn encode_data(&self) -> Vec<u8> {
todo!()
}
fn decode<T: Read>(data: &mut Bytes<T>) -> Result<Self> where Self: Sized {
todo!()
}
}
impl Framing for Command {
fn encode_data(&self) -> Vec<u8> {
let mut encoded = Vec::new();
match self {
&Command::Register(ref user) => {
encoded.push(0x30);
encoded.extend(user.encode_data().iter());
},
&Command::Login(ref user) => {
encoded.push(0x31);
encoded.extend(user.encode_data().iter());
}
&Command::Message(ref msg) => {
encoded.push(0x35);
encoded.extend(msg.encode_data().iter());
}
_ => {
}
}
encoded
}
fn decode<T: Read>(data: &mut Bytes<T>) -> Result<Self> {
let command_code = data.next();
if let None = command_code {
return Err(PacketError::DisconnectError);
}
match command_code {
Some(Ok(0x30)) => {
let decoded = User::decode(data).unwrap();
Ok(Self::Register(decoded))
},
Some(Ok(0x31)) => {
//์๋ค๋ ๋ค Err๋ก ๋ฐ๊ฟ์ค์ผํจ.
let decoded = User::decode(data).unwrap();
Ok(Self::Login(decoded))
},
Some(Ok(0x35)) => {
let decoded = Message::decode(data).unwrap();
Ok(Self::Message(decoded))
}
_ => {
Err(PacketError::ParseError)
}
}
}
} |
#[macro_use]
extern crate nom;
#[macro_use]
extern crate log;
pub mod client;
mod event;
mod parser;
mod stream;
mod utils;
|
// Standard library
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
// This crate
use crate::actions::{Action, ActionAnswer, ActionContext, ACT_REG};
use crate::exts::LockIt;
use crate::signals::{order::mqtt::MSG_OUTPUT, SIG_REG};
use crate::skills::hermes::messages::IntentMessage;
use crate::skills::SkillLoader;
// Other crates
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use bytes::Bytes;
use lazy_static::lazy_static;
use rumqttc::{AsyncClient, QoS};
use serde::Serialize;
use tokio::sync::{mpsc, oneshot};
use unic_langid::LanguageIdentifier;
lazy_static! {
static ref HERMES_API_OUTPUT: Arc<Mutex<Option<HermesApiOutput>>> = Arc::new(Mutex::new(None));
static ref HERMES_API_INPUT: Arc<Mutex<Option<HermesApiInput>>> = Arc::new(Mutex::new(None));
}
mod messages {
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Deserialize)]
pub struct SayMessage {
pub text: String,
#[serde(default)]
pub lang: Option<String>,
#[serde(default)]
pub id: Option<String>,
#[serde(default)]
pub volume: Option<f32>,
#[serde(default = "default_site", rename = "siteId")]
pub site_id: String,
#[serde(default, rename = "sessionId")]
pub session_id: Option<String>,
}
#[derive(Serialize)]
pub struct IntentMessage {
pub input: String,
pub intent: ObjectIntentMessage,
#[serde(default)]
pub id: Option<String>,
#[serde(default = "default_site", rename = "siteId")]
pub site_id: String,
#[serde(default, rename = "sessionId")]
pub session_id: Option<String>,
#[serde(default, rename = "customData")]
pub custom_data: Option<String>,
#[serde(default, rename = "asrTokens")]
pub asr_tokens: Vec<AsrTokenIntentMessage>,
#[serde(default, rename = "asrConfidence")]
pub asr_confidence: Option<f32>,
}
#[derive(Serialize)]
pub struct ObjectIntentMessage {
#[serde(rename = "intentName")]
pub intent_name: String,
#[serde(rename = "confidenceScore")]
pub confidence_score: f32,
#[serde(default)]
pub slots: Vec<SlotIntentMessage>,
}
#[derive(Serialize)]
pub struct SlotIntentMessage {
pub entity: String,
#[serde(rename = "slotName")]
pub slot_name: String,
#[serde(rename = "rawValue")]
pub raw_value: String,
pub value: ValueSlotIntentMessage,
#[serde(default)]
pub range: Option<RangeSlotIntentMessage>,
}
#[derive(Serialize)]
pub struct ValueSlotIntentMessage {
pub value: Value, // TODO: This is supposed to be ANY in the definition
}
#[derive(Serialize)]
pub struct RangeSlotIntentMessage {
start: i32,
end: i32,
}
#[derive(Serialize)]
pub struct AsrTokenIntentMessage {
value: String,
confidence: f32,
range_start: i32,
range_end: i32,
}
fn default_site() -> String {
"default".into()
}
}
pub struct HermesLoader {}
impl HermesLoader {
pub fn new() -> Self {
Self {}
}
}
#[async_trait(?Send)]
impl SkillLoader for HermesLoader {
fn load_skills(&mut self, _langs: &[LanguageIdentifier]) -> Result<()> {
// For the time being we are going to put everything as a single skill called "hermes"
// TODO: Get all intents from somewhere
let mut act_grd = ACT_REG.lock_it();
let sig_grd = SIG_REG.lock_it();
let sig_order = sig_grd
.get_sig_order()
.expect("Order signal was not initialized");
let intents: Vec<String> = Vec::new();
for intent_name in intents {
let arc_intent_name = Arc::new(intent_name.clone());
let action = Arc::new(Mutex::new(HermesAction::new(
arc_intent_name.clone(),
arc_intent_name,
)));
act_grd.insert("hermes", &intent_name, action.clone())?;
// TODO! Add to sig order!
}
Ok(())
}
async fn run_loader(&mut self) -> Result<()> {
Ok(())
}
}
pub struct HermesApiIn {
def_lang: LanguageIdentifier,
}
impl HermesApiIn {
pub fn new(def_lang: LanguageIdentifier) -> Self {
Self { def_lang }
}
pub async fn subscribe(client: &Arc<Mutex<AsyncClient>>) -> Result<()> {
let client_raw = client.lock_it();
client_raw
.subscribe("hermes/tts/say", QoS::AtLeastOnce)
.await?;
Ok(())
}
pub async fn handle_tts_say(&self, payload: &Bytes) -> Result<()> {
if let Ok(Some(msg)) = HERMES_API_INPUT
.lock_it()
.as_mut()
.expect("No Hermes API input")
.intercept_tts_say(payload)
{
MSG_OUTPUT.with::<_, Result<()>>(|m| match *m.borrow_mut() {
Some(ref mut output) => {
let l = msg
.lang
.and_then(|s| s.parse().ok())
.unwrap_or_else(|| self.def_lang.clone());
output.answer(msg.text, &l, msg.site_id)
}
_ => Err(anyhow!("No output channel")),
})
} else {
Ok(())
}
}
}
pub struct HermesApiInput {
tts_say_map: HashMap<String, oneshot::Sender<messages::SayMessage>>,
}
impl HermesApiInput {
pub async fn wait_answer(&mut self, uuid: &str) -> messages::SayMessage {
let (sender, mut receiver) = oneshot::channel();
self.tts_say_map.insert(uuid.to_string(), sender);
receiver.try_recv().expect("TTS Say channel dropped")
}
pub fn intercept_tts_say(&mut self, msg: &Bytes) -> Result<Option<messages::SayMessage>> {
let msg: messages::SayMessage = serde_json::from_reader(std::io::Cursor::new(msg))?;
if let Some(s) = self.tts_say_map.remove(&msg.site_id) {
s.send(msg).map_err(|_| anyhow!("TTS Say channel error"))?;
Ok(None)
} else {
Ok(Some(msg))
}
}
}
pub struct HermesApiOut {
common_out: mpsc::Receiver<(String, String)>,
}
impl HermesApiOut {
pub fn new() -> Result<Self> {
let (sender, common_out) = mpsc::channel(100);
let output = HermesApiOutput::new(sender);
HERMES_API_OUTPUT.lock_it().replace(output);
Ok(Self { common_out })
}
pub async fn handle_out(&mut self, client: &Arc<Mutex<AsyncClient>>) -> Result<()> {
loop {
let (topic, payload) = self.common_out.recv().await.expect("Out channel broken");
client
.lock_it()
.publish(topic, QoS::AtMostOnce, false, payload)
.await?;
}
}
}
pub struct HermesApiOutput {
client: mpsc::Sender<(String, String)>,
}
impl HermesApiOutput {
pub fn new(client: mpsc::Sender<(String, String)>) -> Self {
Self { client }
}
pub fn send<M: Serialize>(&self, path: String, msg: &M) -> Result<()> {
let msg_str = serde_json::to_string(msg)?;
self.client.try_send((path, msg_str)).unwrap();
Ok(())
}
}
pub struct HermesAction {
name: Arc<String>,
intent_name: Arc<String>,
}
impl HermesAction {
pub fn new(name: Arc<String>, intent_name: Arc<String>) -> Self {
Self { name, intent_name }
}
}
#[async_trait(?Send)]
impl Action for HermesAction {
async fn call(&mut self, context: &ActionContext) -> Result<ActionAnswer> {
const ERR: &str = "DynamicDict lacks mandatory element";
let intent_name = (*self.intent_name).clone();
let intent_data = context.data.as_intent().expect(ERR);
let msg = IntentMessage {
id: None,
input: intent_data.input.clone(),
intent: messages::ObjectIntentMessage {
intent_name: intent_name.clone(),
confidence_score: 1.0,
slots: intent_data
.slots
.iter()
.map(|(n, v)| {
messages::SlotIntentMessage {
raw_value: v.clone(),
value: messages::ValueSlotIntentMessage {
value: serde_json::Value::String(v.clone()),
},
entity: n.to_string(),
slot_name: n.clone(),
range: None, // TODO: Actually get to pass this information
}
})
.collect(),
},
site_id: context.satellite.as_ref().expect(ERR).uuid.clone(),
session_id: None,
custom_data: None,
asr_tokens: vec![],
asr_confidence: None,
};
HERMES_API_OUTPUT
.lock_it()
.as_ref()
.unwrap()
.send(format!("/hermes/intent/{}", intent_name), &msg)?;
let msg = HERMES_API_INPUT
.lock_it()
.as_mut()
.unwrap()
.wait_answer("/hermes/tts/say")
.await;
// TODO: Check that it is for the same site
// TODO: Only end session if requested
ActionAnswer::send_text(msg.text, true)
}
fn get_name(&self) -> String {
self.name.as_ref().clone()
}
}
|
extern crate rand;
extern crate rand_chacha;
use criterion::{criterion_group, Criterion};
use kvs::thread_pool::{RayonThreadPool, SharedQueueThreadPool, ThreadPool};
use kvs::{KvStore, SledKvStore};
use kvs::{KvsClient, KvsServer};
use std::net::TcpStream;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use tempfile::TempDir;
static SERVER_THREAD_NUMS: &[i32] = &[1, 2, 4, 8, 16];
static CLIENT_THREAD_NUM: u32 = 64;
fn thread_pool_set(thread_pool: &impl ThreadPool, addr: SocketAddr) {
let (sender, receiver) = mpsc::channel();
for i in 0..1000 {
let sender = mpsc::Sender::clone(&sender);
thread_pool.spawn(move || {
let mut client = KvsClient::new(&addr).unwrap();
client.set(format!("key{}", i), "value".to_owned()).unwrap();
sender.send(()).unwrap();
});
}
drop(sender);
for _ in receiver {}
}
fn thread_pool_get(thread_pool: &impl ThreadPool, addr: SocketAddr) {
let (sender, receiver) = mpsc::channel();
for i in 0..1000 {
let sender = mpsc::Sender::clone(&sender);
thread_pool.spawn(move || {
let mut client = KvsClient::new(&addr).unwrap();
let response = client.get(format!("key{}", i)).unwrap();
assert_eq!(response, Some("value".to_string()));
sender.send(()).unwrap();
});
}
drop(sender);
for _ in receiver {}
}
fn write_queued_kvstore(c: &mut Criterion) {
c.bench_function_over_inputs(
"write queued kvstore",
|b, &num| {
let temp_dir = TempDir::new().expect("unable to create temporary working directory");
let store = KvStore::open(temp_dir.path()).unwrap();
let pool = SharedQueueThreadPool::new(*num as u32).unwrap();
let (tx, rx) = mpsc::channel();
let server = KvsServer::new(store, pool, Some(rx));
let port = 4000;
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
let handle = thread::spawn(move || {
server.run(addr).unwrap();
});
thread::sleep(Duration::from_millis(100));
{
let client_pool = SharedQueueThreadPool::new(CLIENT_THREAD_NUM).unwrap();
b.iter(|| thread_pool_set(&client_pool, addr));
}
tx.send(()).unwrap();
TcpStream::connect(addr).unwrap();
handle.join().unwrap();
},
SERVER_THREAD_NUMS,
);
}
fn read_queued_kvstore(c: &mut Criterion) {
c.bench_function_over_inputs(
"read queued kvstore",
|b, &num| {
let temp_dir = TempDir::new().expect("unable to create temporary working directory");
let store = KvStore::open(temp_dir.path()).unwrap();
let pool = SharedQueueThreadPool::new(*num as u32).unwrap();
let (tx, rx) = mpsc::channel();
let server = KvsServer::new(store, pool, Some(rx));
let port = 4000;
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
let handle = thread::spawn(move || {
server.run(addr).unwrap();
});
thread::sleep(Duration::from_millis(100));
{
let client_pool = SharedQueueThreadPool::new(CLIENT_THREAD_NUM).unwrap();
thread_pool_set(&client_pool, addr);
b.iter(|| {
thread_pool_get(&client_pool, addr);
});
}
tx.send(()).unwrap();
TcpStream::connect(addr).unwrap();
handle.join().unwrap();
},
SERVER_THREAD_NUMS,
);
}
fn write_rayon_kvstore(c: &mut Criterion) {
c.bench_function_over_inputs(
"write rayon kvstore",
|b, &num| {
let temp_dir = TempDir::new().expect("unable to create temporary working directory");
let store = KvStore::open(temp_dir.path()).unwrap();
let pool = RayonThreadPool::new(*num as u32).unwrap();
let (tx, rx) = mpsc::channel();
let server = KvsServer::new(store, pool, Some(rx));
let port = 4000;
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
let handle = thread::spawn(move || {
server.run(addr).unwrap();
});
thread::sleep(Duration::from_millis(100));
{
let client_pool = SharedQueueThreadPool::new(CLIENT_THREAD_NUM).unwrap();
b.iter(|| {
thread_pool_set(&client_pool, addr);
});
}
tx.send(()).unwrap();
TcpStream::connect(addr).unwrap();
handle.join().unwrap();
},
SERVER_THREAD_NUMS,
);
}
fn read_rayon_kvstore(c: &mut Criterion) {
c.bench_function_over_inputs(
"read rayon kvstore",
|b, &num| {
let temp_dir = TempDir::new().expect("unable to create temporary working directory");
let store = KvStore::open(temp_dir.path()).unwrap();
let pool = RayonThreadPool::new(*num as u32).unwrap();
let (tx, rx) = mpsc::channel();
let server = KvsServer::new(store, pool, Some(rx));
let port = 4000;
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
let handle = thread::spawn(move || {
server.run(addr).unwrap();
});
thread::sleep(Duration::from_millis(100));
{
let client_pool = SharedQueueThreadPool::new(CLIENT_THREAD_NUM).unwrap();
thread_pool_set(&client_pool, addr);
b.iter(|| {
thread_pool_get(&client_pool, addr);
});
}
tx.send(()).unwrap();
TcpStream::connect(addr).unwrap();
handle.join().unwrap();
},
SERVER_THREAD_NUMS,
);
}
fn write_queued_sled_kvstore(c: &mut Criterion) {
c.bench_function_over_inputs(
"write queued sled kvstore",
|b, &num| {
let temp_dir = TempDir::new().expect("unable to create temporary working directory");
let store = SledKvStore::open(temp_dir.path()).unwrap();
let pool = SharedQueueThreadPool::new(*num as u32).unwrap();
let (tx, rx) = mpsc::channel();
let server = KvsServer::new(store, pool, Some(rx));
let port = 4000;
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
let handle = thread::spawn(move || {
server.run(addr).unwrap();
});
thread::sleep(Duration::from_millis(100));
{
let client_pool = SharedQueueThreadPool::new(CLIENT_THREAD_NUM).unwrap();
b.iter(|| {
thread_pool_set(&client_pool, addr);
});
}
tx.send(()).unwrap();
TcpStream::connect(addr).unwrap();
handle.join().unwrap();
},
SERVER_THREAD_NUMS,
);
}
fn read_queued_sled_kvstore(c: &mut Criterion) {
c.bench_function_over_inputs(
"read queued sled kvstore",
|b, &num| {
let temp_dir = TempDir::new().expect("unable to create temporary working directory");
let store = SledKvStore::open(temp_dir.path()).unwrap();
let pool = SharedQueueThreadPool::new(*num as u32).unwrap();
let (tx, rx) = mpsc::channel();
let server = KvsServer::new(store, pool, Some(rx));
let port = 4000;
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
let handle = thread::spawn(move || {
server.run(addr).unwrap();
});
thread::sleep(Duration::from_millis(100));
{
let client_pool = SharedQueueThreadPool::new(CLIENT_THREAD_NUM).unwrap();
thread_pool_set(&client_pool, addr);
b.iter(|| {
thread_pool_get(&client_pool, addr);
});
}
tx.send(()).unwrap();
TcpStream::connect(addr).unwrap();
handle.join().unwrap();
},
SERVER_THREAD_NUMS,
);
}
fn write_rayon_sled_kvstore(c: &mut Criterion) {
c.bench_function_over_inputs(
"write rayon sled kvstore",
|b, &num| {
let temp_dir = TempDir::new().expect("unable to create temporary working directory");
let store = SledKvStore::open(temp_dir.path()).unwrap();
let pool = RayonThreadPool::new(*num as u32).unwrap();
let (tx, rx) = mpsc::channel();
let server = KvsServer::new(store, pool, Some(rx));
let port = 4000;
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
let handle = thread::spawn(move || {
server.run(addr).unwrap();
});
thread::sleep(Duration::from_millis(100));
{
let client_pool = SharedQueueThreadPool::new(CLIENT_THREAD_NUM).unwrap();
b.iter(|| {
thread_pool_set(&client_pool, addr);
});
}
tx.send(()).unwrap();
TcpStream::connect(addr).unwrap();
handle.join().unwrap();
},
SERVER_THREAD_NUMS,
);
}
fn read_rayon_sled_kvstore(c: &mut Criterion) {
c.bench_function_over_inputs(
"read rayon sled kvstore",
|b, &num| {
let temp_dir = TempDir::new().expect("unable to create temporary working directory");
let store = SledKvStore::open(temp_dir.path()).unwrap();
let pool = RayonThreadPool::new(*num as u32).unwrap();
let (tx, rx) = mpsc::channel();
let server = KvsServer::new(store, pool, Some(rx));
let port = 4000;
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
let handle = thread::spawn(move || {
server.run(addr).unwrap();
});
thread::sleep(Duration::from_millis(100));
{
let client_pool = SharedQueueThreadPool::new(CLIENT_THREAD_NUM).unwrap();
thread_pool_set(&client_pool, addr);
b.iter(|| {
thread_pool_get(&client_pool, addr);
});
}
tx.send(()).unwrap();
TcpStream::connect(addr).unwrap();
handle.join().unwrap();
},
SERVER_THREAD_NUMS,
);
}
criterion_group!(
write_queued,
write_queued_kvstore,
write_queued_sled_kvstore
);
criterion_group!(write_rayon, write_rayon_kvstore, write_rayon_sled_kvstore);
criterion_group!(read_queued, read_queued_kvstore, read_queued_sled_kvstore);
criterion_group!(read_rayon, read_rayon_kvstore, read_rayon_sled_kvstore);
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - UART Data"]
pub dr: DR,
_reserved_1_ecr: [u8; 4usize],
_reserved2: [u8; 16usize],
#[doc = "0x18 - UART Flag"]
pub fr: FR,
_reserved3: [u8; 4usize],
#[doc = "0x20 - UART IrDA Low-Power Register"]
pub ilpr: ILPR,
#[doc = "0x24 - UART Integer Baud-Rate Divisor"]
pub ibrd: IBRD,
#[doc = "0x28 - UART Fractional Baud-Rate Divisor"]
pub fbrd: FBRD,
#[doc = "0x2c - UART Line Control"]
pub lcrh: LCRH,
#[doc = "0x30 - UART Control"]
pub ctl: CTL,
#[doc = "0x34 - UART Interrupt FIFO Level Select"]
pub ifls: IFLS,
#[doc = "0x38 - UART Interrupt Mask"]
pub im: IM,
#[doc = "0x3c - UART Raw Interrupt Status"]
pub ris: RIS,
#[doc = "0x40 - UART Masked Interrupt Status"]
pub mis: MIS,
#[doc = "0x44 - UART Interrupt Clear"]
pub icr: ICR,
#[doc = "0x48 - UART DMA Control"]
pub dmactl: DMACTL,
_reserved14: [u8; 88usize],
#[doc = "0xa4 - UART 9-Bit Self Address"]
pub _9bitaddr: _9BITADDR,
#[doc = "0xa8 - UART 9-Bit Self Address Mask"]
pub _9bitamask: _9BITAMASK,
_reserved16: [u8; 3860usize],
#[doc = "0xfc0 - UART Peripheral Properties"]
pub pp: PP,
_reserved17: [u8; 4usize],
#[doc = "0xfc8 - UART Clock Configuration"]
pub cc: CC,
}
impl RegisterBlock {
#[doc = "0x04 - UART Receive Status/Error Clear"]
#[inline(always)]
pub fn ecr(&self) -> &ECR {
unsafe { &*(((self as *const Self) as *const u8).add(4usize) as *const ECR) }
}
#[doc = "0x04 - UART Receive Status/Error Clear"]
#[inline(always)]
pub fn ecr_mut(&self) -> &mut ECR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(4usize) as *mut ECR) }
}
#[doc = "0x04 - UART Receive Status/Error Clear"]
#[inline(always)]
pub fn rsr(&self) -> &RSR {
unsafe { &*(((self as *const Self) as *const u8).add(4usize) as *const RSR) }
}
#[doc = "0x04 - UART Receive Status/Error Clear"]
#[inline(always)]
pub fn rsr_mut(&self) -> &mut RSR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(4usize) as *mut RSR) }
}
}
#[doc = "UART Data\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dr](dr) module"]
pub type DR = crate::Reg<u32, _DR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DR;
#[doc = "`read()` method returns [dr::R](dr::R) reader structure"]
impl crate::Readable for DR {}
#[doc = "`write(|w| ..)` method takes [dr::W](dr::W) writer structure"]
impl crate::Writable for DR {}
#[doc = "UART Data"]
pub mod dr;
#[doc = "UART Receive Status/Error Clear\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rsr](rsr) module"]
pub type RSR = crate::Reg<u32, _RSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RSR;
#[doc = "`read()` method returns [rsr::R](rsr::R) reader structure"]
impl crate::Readable for RSR {}
#[doc = "`write(|w| ..)` method takes [rsr::W](rsr::W) writer structure"]
impl crate::Writable for RSR {}
#[doc = "UART Receive Status/Error Clear"]
pub mod rsr;
#[doc = "UART Receive Status/Error Clear\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ecr](ecr) module"]
pub type ECR = crate::Reg<u32, _ECR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ECR;
#[doc = "`read()` method returns [ecr::R](ecr::R) reader structure"]
impl crate::Readable for ECR {}
#[doc = "`write(|w| ..)` method takes [ecr::W](ecr::W) writer structure"]
impl crate::Writable for ECR {}
#[doc = "UART Receive Status/Error Clear"]
pub mod ecr;
#[doc = "UART Flag\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fr](fr) module"]
pub type FR = crate::Reg<u32, _FR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FR;
#[doc = "`read()` method returns [fr::R](fr::R) reader structure"]
impl crate::Readable for FR {}
#[doc = "UART Flag"]
pub mod fr;
#[doc = "UART IrDA Low-Power Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ilpr](ilpr) module"]
pub type ILPR = crate::Reg<u32, _ILPR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ILPR;
#[doc = "`read()` method returns [ilpr::R](ilpr::R) reader structure"]
impl crate::Readable for ILPR {}
#[doc = "`write(|w| ..)` method takes [ilpr::W](ilpr::W) writer structure"]
impl crate::Writable for ILPR {}
#[doc = "UART IrDA Low-Power Register"]
pub mod ilpr;
#[doc = "UART Integer Baud-Rate Divisor\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ibrd](ibrd) module"]
pub type IBRD = crate::Reg<u32, _IBRD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IBRD;
#[doc = "`read()` method returns [ibrd::R](ibrd::R) reader structure"]
impl crate::Readable for IBRD {}
#[doc = "`write(|w| ..)` method takes [ibrd::W](ibrd::W) writer structure"]
impl crate::Writable for IBRD {}
#[doc = "UART Integer Baud-Rate Divisor"]
pub mod ibrd;
#[doc = "UART Fractional Baud-Rate Divisor\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fbrd](fbrd) module"]
pub type FBRD = crate::Reg<u32, _FBRD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FBRD;
#[doc = "`read()` method returns [fbrd::R](fbrd::R) reader structure"]
impl crate::Readable for FBRD {}
#[doc = "`write(|w| ..)` method takes [fbrd::W](fbrd::W) writer structure"]
impl crate::Writable for FBRD {}
#[doc = "UART Fractional Baud-Rate Divisor"]
pub mod fbrd;
#[doc = "UART Line Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [lcrh](lcrh) module"]
pub type LCRH = crate::Reg<u32, _LCRH>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _LCRH;
#[doc = "`read()` method returns [lcrh::R](lcrh::R) reader structure"]
impl crate::Readable for LCRH {}
#[doc = "`write(|w| ..)` method takes [lcrh::W](lcrh::W) writer structure"]
impl crate::Writable for LCRH {}
#[doc = "UART Line Control"]
pub mod lcrh;
#[doc = "UART Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ctl](ctl) module"]
pub type CTL = crate::Reg<u32, _CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CTL;
#[doc = "`read()` method returns [ctl::R](ctl::R) reader structure"]
impl crate::Readable for CTL {}
#[doc = "`write(|w| ..)` method takes [ctl::W](ctl::W) writer structure"]
impl crate::Writable for CTL {}
#[doc = "UART Control"]
pub mod ctl;
#[doc = "UART Interrupt FIFO Level Select\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ifls](ifls) module"]
pub type IFLS = crate::Reg<u32, _IFLS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IFLS;
#[doc = "`read()` method returns [ifls::R](ifls::R) reader structure"]
impl crate::Readable for IFLS {}
#[doc = "`write(|w| ..)` method takes [ifls::W](ifls::W) writer structure"]
impl crate::Writable for IFLS {}
#[doc = "UART Interrupt FIFO Level Select"]
pub mod ifls;
#[doc = "UART Interrupt Mask\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [im](im) module"]
pub type IM = crate::Reg<u32, _IM>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IM;
#[doc = "`read()` method returns [im::R](im::R) reader structure"]
impl crate::Readable for IM {}
#[doc = "`write(|w| ..)` method takes [im::W](im::W) writer structure"]
impl crate::Writable for IM {}
#[doc = "UART Interrupt Mask"]
pub mod im;
#[doc = "UART Raw Interrupt Status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ris](ris) module"]
pub type RIS = crate::Reg<u32, _RIS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RIS;
#[doc = "`read()` method returns [ris::R](ris::R) reader structure"]
impl crate::Readable for RIS {}
#[doc = "UART Raw Interrupt Status"]
pub mod ris;
#[doc = "UART Masked Interrupt Status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mis](mis) module"]
pub type MIS = crate::Reg<u32, _MIS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MIS;
#[doc = "`read()` method returns [mis::R](mis::R) reader structure"]
impl crate::Readable for MIS {}
#[doc = "UART Masked Interrupt Status"]
pub mod mis;
#[doc = "UART Interrupt Clear\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [icr](icr) module"]
pub type ICR = crate::Reg<u32, _ICR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ICR;
#[doc = "`write(|w| ..)` method takes [icr::W](icr::W) writer structure"]
impl crate::Writable for ICR {}
#[doc = "UART Interrupt Clear"]
pub mod icr;
#[doc = "UART DMA Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmactl](dmactl) module"]
pub type DMACTL = crate::Reg<u32, _DMACTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DMACTL;
#[doc = "`read()` method returns [dmactl::R](dmactl::R) reader structure"]
impl crate::Readable for DMACTL {}
#[doc = "`write(|w| ..)` method takes [dmactl::W](dmactl::W) writer structure"]
impl crate::Writable for DMACTL {}
#[doc = "UART DMA Control"]
pub mod dmactl;
#[doc = "UART 9-Bit Self Address\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [_9bitaddr](_9bitaddr) module"]
pub type _9BITADDR = crate::Reg<u32, __9BITADDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct __9BITADDR;
#[doc = "`read()` method returns [_9bitaddr::R](_9bitaddr::R) reader structure"]
impl crate::Readable for _9BITADDR {}
#[doc = "`write(|w| ..)` method takes [_9bitaddr::W](_9bitaddr::W) writer structure"]
impl crate::Writable for _9BITADDR {}
#[doc = "UART 9-Bit Self Address"]
pub mod _9bitaddr;
#[doc = "UART 9-Bit Self Address Mask\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [_9bitamask](_9bitamask) module"]
pub type _9BITAMASK = crate::Reg<u32, __9BITAMASK>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct __9BITAMASK;
#[doc = "`read()` method returns [_9bitamask::R](_9bitamask::R) reader structure"]
impl crate::Readable for _9BITAMASK {}
#[doc = "`write(|w| ..)` method takes [_9bitamask::W](_9bitamask::W) writer structure"]
impl crate::Writable for _9BITAMASK {}
#[doc = "UART 9-Bit Self Address Mask"]
pub mod _9bitamask;
#[doc = "UART Peripheral Properties\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pp](pp) module"]
pub type PP = crate::Reg<u32, _PP>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PP;
#[doc = "`read()` method returns [pp::R](pp::R) reader structure"]
impl crate::Readable for PP {}
#[doc = "UART Peripheral Properties"]
pub mod pp;
#[doc = "UART Clock Configuration\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cc](cc) module"]
pub type CC = crate::Reg<u32, _CC>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CC;
#[doc = "`read()` method returns [cc::R](cc::R) reader structure"]
impl crate::Readable for CC {}
#[doc = "`write(|w| ..)` method takes [cc::W](cc::W) writer structure"]
impl crate::Writable for CC {}
#[doc = "UART Clock Configuration"]
pub mod cc;
|
pub mod storage_contract;
pub mod storage_instruction;
pub mod storage_processor;
pub const SLOTS_PER_SEGMENT: u64 = 16;
pub fn get_segment_from_slot(slot: u64) -> usize {
(slot / SLOTS_PER_SEGMENT) as usize
}
const STORAGE_PROGRAM_ID: [u8; 32] = [
6, 162, 25, 123, 127, 68, 233, 59, 131, 151, 21, 152, 162, 120, 90, 37, 154, 88, 86, 5, 156,
221, 182, 201, 142, 103, 151, 112, 0, 0, 0, 0,
];
morgan_interface::morgan_program_id!(STORAGE_PROGRAM_ID);
|
#[doc = "Reader of register CR2"]
pub type R = crate::R<u32, super::CR2>;
#[doc = "Writer for register CR2"]
pub type W = crate::W<u32, super::CR2>;
#[doc = "Register CR2 `reset()`'s with value 0x80"]
impl crate::ResetValue for super::CR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x80
}
}
#[doc = "HSI14 clock enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HSI14ON_A {
#[doc = "0: HSI14 oscillator off"]
OFF = 0,
#[doc = "1: HSI14 oscillator on"]
ON = 1,
}
impl From<HSI14ON_A> for bool {
#[inline(always)]
fn from(variant: HSI14ON_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `HSI14ON`"]
pub type HSI14ON_R = crate::R<bool, HSI14ON_A>;
impl HSI14ON_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> HSI14ON_A {
match self.bits {
false => HSI14ON_A::OFF,
true => HSI14ON_A::ON,
}
}
#[doc = "Checks if the value of the field is `OFF`"]
#[inline(always)]
pub fn is_off(&self) -> bool {
*self == HSI14ON_A::OFF
}
#[doc = "Checks if the value of the field is `ON`"]
#[inline(always)]
pub fn is_on(&self) -> bool {
*self == HSI14ON_A::ON
}
}
#[doc = "Write proxy for field `HSI14ON`"]
pub struct HSI14ON_W<'a> {
w: &'a mut W,
}
impl<'a> HSI14ON_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: HSI14ON_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "HSI14 oscillator off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(HSI14ON_A::OFF)
}
#[doc = "HSI14 oscillator on"]
#[inline(always)]
pub fn on(self) -> &'a mut W {
self.variant(HSI14ON_A::ON)
}
#[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 = "HR14 clock ready flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HSI14RDY_A {
#[doc = "0: HSI14 oscillator not ready"]
NOTREADY = 0,
#[doc = "1: HSI14 oscillator ready"]
READY = 1,
}
impl From<HSI14RDY_A> for bool {
#[inline(always)]
fn from(variant: HSI14RDY_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `HSI14RDY`"]
pub type HSI14RDY_R = crate::R<bool, HSI14RDY_A>;
impl HSI14RDY_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> HSI14RDY_A {
match self.bits {
false => HSI14RDY_A::NOTREADY,
true => HSI14RDY_A::READY,
}
}
#[doc = "Checks if the value of the field is `NOTREADY`"]
#[inline(always)]
pub fn is_not_ready(&self) -> bool {
*self == HSI14RDY_A::NOTREADY
}
#[doc = "Checks if the value of the field is `READY`"]
#[inline(always)]
pub fn is_ready(&self) -> bool {
*self == HSI14RDY_A::READY
}
}
#[doc = "HSI14 clock request from ADC disable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HSI14DIS_A {
#[doc = "0: ADC can turn on the HSI14 oscillator"]
ALLOW = 0,
#[doc = "1: ADC can not turn on the HSI14 oscillator"]
DISALLOW = 1,
}
impl From<HSI14DIS_A> for bool {
#[inline(always)]
fn from(variant: HSI14DIS_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `HSI14DIS`"]
pub type HSI14DIS_R = crate::R<bool, HSI14DIS_A>;
impl HSI14DIS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> HSI14DIS_A {
match self.bits {
false => HSI14DIS_A::ALLOW,
true => HSI14DIS_A::DISALLOW,
}
}
#[doc = "Checks if the value of the field is `ALLOW`"]
#[inline(always)]
pub fn is_allow(&self) -> bool {
*self == HSI14DIS_A::ALLOW
}
#[doc = "Checks if the value of the field is `DISALLOW`"]
#[inline(always)]
pub fn is_disallow(&self) -> bool {
*self == HSI14DIS_A::DISALLOW
}
}
#[doc = "Write proxy for field `HSI14DIS`"]
pub struct HSI14DIS_W<'a> {
w: &'a mut W,
}
impl<'a> HSI14DIS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: HSI14DIS_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "ADC can turn on the HSI14 oscillator"]
#[inline(always)]
pub fn allow(self) -> &'a mut W {
self.variant(HSI14DIS_A::ALLOW)
}
#[doc = "ADC can not turn on the HSI14 oscillator"]
#[inline(always)]
pub fn disallow(self) -> &'a mut W {
self.variant(HSI14DIS_A::DISALLOW)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `HSI14TRIM`"]
pub type HSI14TRIM_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `HSI14TRIM`"]
pub struct HSI14TRIM_W<'a> {
w: &'a mut W,
}
impl<'a> HSI14TRIM_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x1f << 3)) | (((value as u32) & 0x1f) << 3);
self.w
}
}
#[doc = "Reader of field `HSI14CAL`"]
pub type HSI14CAL_R = crate::R<u8, u8>;
#[doc = "HSI48 clock enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HSI48ON_A {
#[doc = "0: HSI48 oscillator off"]
OFF = 0,
#[doc = "1: HSI48 oscillator on"]
ON = 1,
}
impl From<HSI48ON_A> for bool {
#[inline(always)]
fn from(variant: HSI48ON_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `HSI48ON`"]
pub type HSI48ON_R = crate::R<bool, HSI48ON_A>;
impl HSI48ON_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> HSI48ON_A {
match self.bits {
false => HSI48ON_A::OFF,
true => HSI48ON_A::ON,
}
}
#[doc = "Checks if the value of the field is `OFF`"]
#[inline(always)]
pub fn is_off(&self) -> bool {
*self == HSI48ON_A::OFF
}
#[doc = "Checks if the value of the field is `ON`"]
#[inline(always)]
pub fn is_on(&self) -> bool {
*self == HSI48ON_A::ON
}
}
#[doc = "Write proxy for field `HSI48ON`"]
pub struct HSI48ON_W<'a> {
w: &'a mut W,
}
impl<'a> HSI48ON_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: HSI48ON_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "HSI48 oscillator off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(HSI48ON_A::OFF)
}
#[doc = "HSI48 oscillator on"]
#[inline(always)]
pub fn on(self) -> &'a mut W {
self.variant(HSI48ON_A::ON)
}
#[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 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "HSI48 clock ready flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HSI48RDY_A {
#[doc = "0: HSI48 oscillator ready"]
NOTREADY = 0,
#[doc = "1: HSI48 oscillator ready"]
READY = 1,
}
impl From<HSI48RDY_A> for bool {
#[inline(always)]
fn from(variant: HSI48RDY_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `HSI48RDY`"]
pub type HSI48RDY_R = crate::R<bool, HSI48RDY_A>;
impl HSI48RDY_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> HSI48RDY_A {
match self.bits {
false => HSI48RDY_A::NOTREADY,
true => HSI48RDY_A::READY,
}
}
#[doc = "Checks if the value of the field is `NOTREADY`"]
#[inline(always)]
pub fn is_not_ready(&self) -> bool {
*self == HSI48RDY_A::NOTREADY
}
#[doc = "Checks if the value of the field is `READY`"]
#[inline(always)]
pub fn is_ready(&self) -> bool {
*self == HSI48RDY_A::READY
}
}
#[doc = "Reader of field `HSI48CAL`"]
pub type HSI48CAL_R = crate::R<u8, u8>;
impl R {
#[doc = "Bit 0 - HSI14 clock enable"]
#[inline(always)]
pub fn hsi14on(&self) -> HSI14ON_R {
HSI14ON_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - HR14 clock ready flag"]
#[inline(always)]
pub fn hsi14rdy(&self) -> HSI14RDY_R {
HSI14RDY_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - HSI14 clock request from ADC disable"]
#[inline(always)]
pub fn hsi14dis(&self) -> HSI14DIS_R {
HSI14DIS_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bits 3:7 - HSI14 clock trimming"]
#[inline(always)]
pub fn hsi14trim(&self) -> HSI14TRIM_R {
HSI14TRIM_R::new(((self.bits >> 3) & 0x1f) as u8)
}
#[doc = "Bits 8:15 - HSI14 clock calibration"]
#[inline(always)]
pub fn hsi14cal(&self) -> HSI14CAL_R {
HSI14CAL_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bit 16 - HSI48 clock enable"]
#[inline(always)]
pub fn hsi48on(&self) -> HSI48ON_R {
HSI48ON_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - HSI48 clock ready flag"]
#[inline(always)]
pub fn hsi48rdy(&self) -> HSI48RDY_R {
HSI48RDY_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bits 24:31 - HSI48 factory clock calibration"]
#[inline(always)]
pub fn hsi48cal(&self) -> HSI48CAL_R {
HSI48CAL_R::new(((self.bits >> 24) & 0xff) as u8)
}
}
impl W {
#[doc = "Bit 0 - HSI14 clock enable"]
#[inline(always)]
pub fn hsi14on(&mut self) -> HSI14ON_W {
HSI14ON_W { w: self }
}
#[doc = "Bit 2 - HSI14 clock request from ADC disable"]
#[inline(always)]
pub fn hsi14dis(&mut self) -> HSI14DIS_W {
HSI14DIS_W { w: self }
}
#[doc = "Bits 3:7 - HSI14 clock trimming"]
#[inline(always)]
pub fn hsi14trim(&mut self) -> HSI14TRIM_W {
HSI14TRIM_W { w: self }
}
#[doc = "Bit 16 - HSI48 clock enable"]
#[inline(always)]
pub fn hsi48on(&mut self) -> HSI48ON_W {
HSI48ON_W { w: self }
}
}
|
use crate::handlers::types::*;
use pusher::PusherBuilder;
pub async fn push_user_message(channel: &String, event: &String, message: &UserMessage) {
let pusher_url = format!(
"http://{}:{}@api-{}.pusher.com/apps/{}",
std::env::var("PUSHER_KEY").expect("PUSHER KEY not set"),
std::env::var("PUSHER_SECRET").expect("PUSHER SECRET not set"),
std::env::var("PUSHER_CLUSTER").expect("PUSHER CLUSTER not set"),
std::env::var("PUSHER_ID").expect("PUSHER ID not set"),
);
let pusher = PusherBuilder::from_url(&pusher_url).finalize();
pusher.trigger(channel, event, message).await.unwrap();
}
pub async fn push_channel_message(channel: &String, event: &String, message: &ChannelMessage) {
let pusher_url = format!(
"http://{}:{}@api-{}.pusher.com/apps/{}",
std::env::var("PUSHER_KEY").expect("PUSHER KEY not set"),
std::env::var("PUSHER_SECRET").expect("PUSHER SECRET not set"),
std::env::var("PUSHER_CLUSTER").expect("PUSHER CLUSTER not set"),
std::env::var("PUSHER_ID").expect("PUSHER ID not set"),
);
let pusher = PusherBuilder::from_url(&pusher_url).finalize();
pusher.trigger(channel, event, message).await.unwrap();
}
pub async fn push_thread_message(channel: &String, event: &String, message: &ThreadMessage) {
let pusher_url = format!(
"http://{}:{}@api-{}.pusher.com/apps/{}",
std::env::var("PUSHER_KEY").expect("PUSHER KEY not set"),
std::env::var("PUSHER_SECRET").expect("PUSHER SECRET not set"),
std::env::var("PUSHER_CLUSTER").expect("PUSHER CLUSTER not set"),
std::env::var("PUSHER_ID").expect("PUSHER ID not set"),
);
let pusher = PusherBuilder::from_url(&pusher_url).finalize();
pusher.trigger(channel, event, message).await.unwrap();
}
|
use crate::{CoordinateType, Point};
use std::iter::FromIterator;
/// A collection of [`Point`s](struct.Point.html).
///
/// # Examples
///
/// Iterating over a `MultiPoint` yields the `Point`s inside.
///
/// ```
/// use geo_types::{MultiPoint, Point};
/// let points: MultiPoint<_> = vec![(0., 0.), (1., 2.)].into();
/// for point in points {
/// println!("Point x = {}, y = {}", point.x(), point.y());
/// }
/// ```
#[derive(Eq, PartialEq, Clone, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MultiPoint<T>(pub Vec<Point<T>>)
where
T: CoordinateType;
impl<T: CoordinateType, IP: Into<Point<T>>> From<IP> for MultiPoint<T> {
/// Convert a single `Point` (or something which can be converted to a `Point`) into a
/// one-member `MultiPoint`
fn from(x: IP) -> MultiPoint<T> {
MultiPoint(vec![x.into()])
}
}
impl<T: CoordinateType, IP: Into<Point<T>>> From<Vec<IP>> for MultiPoint<T> {
/// Convert a `Vec` of `Points` (or `Vec` of things which can be converted to a `Point`) into a
/// `MultiPoint`.
fn from(v: Vec<IP>) -> MultiPoint<T> {
MultiPoint(v.into_iter().map(|p| p.into()).collect())
}
}
impl<T: CoordinateType, IP: Into<Point<T>>> FromIterator<IP> for MultiPoint<T> {
/// Collect the results of a `Point` iterator into a `MultiPoint`
fn from_iter<I: IntoIterator<Item = IP>>(iter: I) -> Self {
MultiPoint(iter.into_iter().map(|p| p.into()).collect())
}
}
/// Iterate over the `Point`s in this `MultiPoint`.
impl<T: CoordinateType> IntoIterator for MultiPoint<T> {
type Item = Point<T>;
type IntoIter = ::std::vec::IntoIter<Point<T>>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
|
// spell-checker:ignore logoption openlog setlogmask upto
pub(crate) use syslog::make_module;
#[pymodule(name = "syslog")]
mod syslog {
use crate::common::lock::PyRwLock;
use crate::vm::{
builtins::{PyStr, PyStrRef},
function::{OptionalArg, OptionalOption},
utils::ToCString,
PyObjectRef, PyPayload, PyResult, VirtualMachine,
};
use std::{ffi::CStr, os::raw::c_char};
#[pyattr]
use libc::{
LOG_ALERT, LOG_AUTH, LOG_CONS, LOG_CRIT, LOG_DAEMON, LOG_DEBUG, LOG_EMERG, LOG_ERR,
LOG_INFO, LOG_KERN, LOG_LOCAL0, LOG_LOCAL1, LOG_LOCAL2, LOG_LOCAL3, LOG_LOCAL4, LOG_LOCAL5,
LOG_LOCAL6, LOG_LOCAL7, LOG_LPR, LOG_MAIL, LOG_NDELAY, LOG_NEWS, LOG_NOTICE, LOG_NOWAIT,
LOG_ODELAY, LOG_PID, LOG_SYSLOG, LOG_USER, LOG_UUCP, LOG_WARNING,
};
#[cfg(not(target_os = "redox"))]
#[pyattr]
use libc::{LOG_AUTHPRIV, LOG_CRON, LOG_PERROR};
fn get_argv(vm: &VirtualMachine) -> Option<PyStrRef> {
if let Some(argv) = vm.state.settings.argv.first() {
if !argv.is_empty() {
return Some(
PyStr::from(match argv.find('\\') {
Some(value) => &argv[value..],
None => argv,
})
.into_ref(&vm.ctx),
);
}
}
None
}
#[derive(Debug)]
enum GlobalIdent {
Explicit(Box<CStr>),
Implicit,
}
impl GlobalIdent {
fn as_ptr(&self) -> *const c_char {
match self {
GlobalIdent::Explicit(ref cstr) => cstr.as_ptr(),
GlobalIdent::Implicit => std::ptr::null(),
}
}
}
fn global_ident() -> &'static PyRwLock<Option<GlobalIdent>> {
rustpython_common::static_cell! {
static IDENT: PyRwLock<Option<GlobalIdent>>;
};
IDENT.get_or_init(|| PyRwLock::new(None))
}
#[derive(Default, FromArgs)]
struct OpenLogArgs {
#[pyarg(any, optional)]
ident: OptionalOption<PyStrRef>,
#[pyarg(any, optional)]
logoption: OptionalArg<i32>,
#[pyarg(any, optional)]
facility: OptionalArg<i32>,
}
#[pyfunction]
fn openlog(args: OpenLogArgs, vm: &VirtualMachine) -> PyResult<()> {
let logoption = args.logoption.unwrap_or(0);
let facility = args.facility.unwrap_or(LOG_USER);
let ident = match args.ident.flatten() {
Some(args) => Some(args.to_cstring(vm)?),
None => get_argv(vm).map(|argv| argv.to_cstring(vm)).transpose()?,
}
.map(|ident| ident.into_boxed_c_str());
let ident = match ident {
Some(ident) => GlobalIdent::Explicit(ident),
None => GlobalIdent::Implicit,
};
{
let mut locked_ident = global_ident().write();
unsafe { libc::openlog(ident.as_ptr(), logoption, facility) };
*locked_ident = Some(ident);
}
Ok(())
}
#[derive(FromArgs)]
struct SysLogArgs {
#[pyarg(positional)]
priority: PyObjectRef,
#[pyarg(positional, optional)]
message_object: OptionalOption<PyStrRef>,
}
#[pyfunction]
fn syslog(args: SysLogArgs, vm: &VirtualMachine) -> PyResult<()> {
let (priority, msg) = match args.message_object.flatten() {
Some(s) => (args.priority.try_into_value(vm)?, s),
None => (LOG_INFO, args.priority.try_into_value(vm)?),
};
if global_ident().read().is_none() {
openlog(OpenLogArgs::default(), vm)?;
}
let (cformat, cmsg) = ("%s".to_cstring(vm)?, msg.to_cstring(vm)?);
unsafe { libc::syslog(priority, cformat.as_ptr(), cmsg.as_ptr()) };
Ok(())
}
#[pyfunction]
fn closelog() {
if global_ident().read().is_some() {
let mut locked_ident = global_ident().write();
unsafe { libc::closelog() };
*locked_ident = None;
}
}
#[pyfunction]
fn setlogmask(maskpri: i32) -> i32 {
unsafe { libc::setlogmask(maskpri) }
}
#[inline]
#[pyfunction(name = "LOG_MASK")]
fn log_mask(pri: i32) -> i32 {
pri << 1
}
#[inline]
#[pyfunction(name = "LOG_UPTO")]
fn log_upto(pri: i32) -> i32 {
(1 << (pri + 1)) - 1
}
}
|
#[doc = "Reader of register DC0"]
pub type R = crate::R<u32, super::DC0>;
#[doc = "Flash Size\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u16)]
pub enum FLASHSZ_A {
#[doc = "3: 8 KB of Flash"]
_8KB = 3,
#[doc = "7: 16 KB of Flash"]
_16KB = 7,
#[doc = "15: 32 KB of Flash"]
_32KB = 15,
#[doc = "31: 64 KB of Flash"]
_64KB = 31,
#[doc = "47: 96 KB of Flash"]
_96KB = 47,
#[doc = "63: 128 KB of Flash"]
_128K = 63,
#[doc = "95: 192 KB of Flash"]
_192K = 95,
#[doc = "127: 256 KB of Flash"]
_256K = 127,
}
impl From<FLASHSZ_A> for u16 {
#[inline(always)]
fn from(variant: FLASHSZ_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `FLASHSZ`"]
pub type FLASHSZ_R = crate::R<u16, FLASHSZ_A>;
impl FLASHSZ_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u16, FLASHSZ_A> {
use crate::Variant::*;
match self.bits {
3 => Val(FLASHSZ_A::_8KB),
7 => Val(FLASHSZ_A::_16KB),
15 => Val(FLASHSZ_A::_32KB),
31 => Val(FLASHSZ_A::_64KB),
47 => Val(FLASHSZ_A::_96KB),
63 => Val(FLASHSZ_A::_128K),
95 => Val(FLASHSZ_A::_192K),
127 => Val(FLASHSZ_A::_256K),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `_8KB`"]
#[inline(always)]
pub fn is_8kb(&self) -> bool {
*self == FLASHSZ_A::_8KB
}
#[doc = "Checks if the value of the field is `_16KB`"]
#[inline(always)]
pub fn is_16kb(&self) -> bool {
*self == FLASHSZ_A::_16KB
}
#[doc = "Checks if the value of the field is `_32KB`"]
#[inline(always)]
pub fn is_32kb(&self) -> bool {
*self == FLASHSZ_A::_32KB
}
#[doc = "Checks if the value of the field is `_64KB`"]
#[inline(always)]
pub fn is_64kb(&self) -> bool {
*self == FLASHSZ_A::_64KB
}
#[doc = "Checks if the value of the field is `_96KB`"]
#[inline(always)]
pub fn is_96kb(&self) -> bool {
*self == FLASHSZ_A::_96KB
}
#[doc = "Checks if the value of the field is `_128K`"]
#[inline(always)]
pub fn is_128k(&self) -> bool {
*self == FLASHSZ_A::_128K
}
#[doc = "Checks if the value of the field is `_192K`"]
#[inline(always)]
pub fn is_192k(&self) -> bool {
*self == FLASHSZ_A::_192K
}
#[doc = "Checks if the value of the field is `_256K`"]
#[inline(always)]
pub fn is_256k(&self) -> bool {
*self == FLASHSZ_A::_256K
}
}
#[doc = "SRAM Size\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u16)]
pub enum SRAMSZ_A {
#[doc = "7: 2 KB of SRAM"]
_2KB = 7,
#[doc = "15: 4 KB of SRAM"]
_4KB = 15,
#[doc = "23: 6 KB of SRAM"]
_6KB = 23,
#[doc = "31: 8 KB of SRAM"]
_8KB = 31,
#[doc = "47: 12 KB of SRAM"]
_12KB = 47,
#[doc = "63: 16 KB of SRAM"]
_16KB = 63,
#[doc = "79: 20 KB of SRAM"]
_20KB = 79,
#[doc = "95: 24 KB of SRAM"]
_24KB = 95,
#[doc = "127: 32 KB of SRAM"]
_32KB = 127,
}
impl From<SRAMSZ_A> for u16 {
#[inline(always)]
fn from(variant: SRAMSZ_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `SRAMSZ`"]
pub type SRAMSZ_R = crate::R<u16, SRAMSZ_A>;
impl SRAMSZ_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u16, SRAMSZ_A> {
use crate::Variant::*;
match self.bits {
7 => Val(SRAMSZ_A::_2KB),
15 => Val(SRAMSZ_A::_4KB),
23 => Val(SRAMSZ_A::_6KB),
31 => Val(SRAMSZ_A::_8KB),
47 => Val(SRAMSZ_A::_12KB),
63 => Val(SRAMSZ_A::_16KB),
79 => Val(SRAMSZ_A::_20KB),
95 => Val(SRAMSZ_A::_24KB),
127 => Val(SRAMSZ_A::_32KB),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `_2KB`"]
#[inline(always)]
pub fn is_2kb(&self) -> bool {
*self == SRAMSZ_A::_2KB
}
#[doc = "Checks if the value of the field is `_4KB`"]
#[inline(always)]
pub fn is_4kb(&self) -> bool {
*self == SRAMSZ_A::_4KB
}
#[doc = "Checks if the value of the field is `_6KB`"]
#[inline(always)]
pub fn is_6kb(&self) -> bool {
*self == SRAMSZ_A::_6KB
}
#[doc = "Checks if the value of the field is `_8KB`"]
#[inline(always)]
pub fn is_8kb(&self) -> bool {
*self == SRAMSZ_A::_8KB
}
#[doc = "Checks if the value of the field is `_12KB`"]
#[inline(always)]
pub fn is_12kb(&self) -> bool {
*self == SRAMSZ_A::_12KB
}
#[doc = "Checks if the value of the field is `_16KB`"]
#[inline(always)]
pub fn is_16kb(&self) -> bool {
*self == SRAMSZ_A::_16KB
}
#[doc = "Checks if the value of the field is `_20KB`"]
#[inline(always)]
pub fn is_20kb(&self) -> bool {
*self == SRAMSZ_A::_20KB
}
#[doc = "Checks if the value of the field is `_24KB`"]
#[inline(always)]
pub fn is_24kb(&self) -> bool {
*self == SRAMSZ_A::_24KB
}
#[doc = "Checks if the value of the field is `_32KB`"]
#[inline(always)]
pub fn is_32kb(&self) -> bool {
*self == SRAMSZ_A::_32KB
}
}
impl R {
#[doc = "Bits 0:15 - Flash Size"]
#[inline(always)]
pub fn flashsz(&self) -> FLASHSZ_R {
FLASHSZ_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 16:31 - SRAM Size"]
#[inline(always)]
pub fn sramsz(&self) -> SRAMSZ_R {
SRAMSZ_R::new(((self.bits >> 16) & 0xffff) as u16)
}
}
|
use ::AB_JTM;
fn assert_ab_jtm(t1: AB_JTM, t2: AB_JTM) {
assert_eq!(t1.ab_sec, t2.ab_sec);
assert_eq!(t1.ab_min, t2.ab_min);
assert_eq!(t1.ab_hour, t2.ab_hour);
assert_eq!(t1.ab_days, t2.ab_days);
}
#[test]
fn it_has_a_valid_initializer() {
let t1 = AB_JTM::new();
let t2 = AB_JTM {
ab_sec: 0,
ab_min: 0,
ab_hour: 0,
ab_days: 0,
};
assert_ab_jtm(t1, t2);
}
#[test]
fn it_has_a_valid_from_secs_initializer() {
let t1 = AB_JTM {
ab_sec: 0,
ab_min: 30,
ab_hour: 16,
ab_days: 8326,
};
let t2 = AB_JTM::from_secs(719425800);
assert_ab_jtm(t1, t2);
}
#[test]
fn it_has_a_valid_to_secs_converter() {
let t1 = 719425800;
assert_eq!(t1, AB_JTM::from_secs(t1).to_secs());
}
|
/// Chain two functions.
///
/// Takes functions `f` and `g` and returns `g โ f` (in other words something
/// _like_ `|a: A| g(f(a))`.
///
/// # Examples:
/// ```
/// use fntools::unstable::chain;
///
/// let add_two = |a: i32| a + 2;
/// let add_three = |a: i32| a + 3;
/// let add_five = chain(add_two, add_three);
///
/// assert_eq!(add_five(4), 9);
/// ```
///
/// See also:
/// - stable version of this function: [`fntools::chain`]
/// - extension on all functions: [`FnExt::chain`]
///
/// [`FnExt::chain`]: crate::unstable::FnExt::chain
/// [`fntools::chain`]: crate::chain
#[inline]
pub fn chain<A, F, G>(f: F, g: G) -> Chain<F, G>
where
F: FnOnce<A>,
G: FnOnce<(F::Output,)>,
{
Chain::new(f, g)
}
/// Represents composition of 2 functions `G โ F`.
///
/// > Note: `Chain` and [`Compose`] have no differences but argument order.
///
/// For documentation see [`chain`].
///
/// [`Compose`]: crate::unstable::Compose
#[must_use = "function combinators are lazy and do nothing unless called"]
#[derive(Debug, Clone, Copy)]
pub struct Chain<F, G> {
f: F,
g: G,
}
impl<F, G> Chain<F, G> {
/// Creates chain of functions `f` and `g`.
///
/// It's preferred to use [`chain`] instead.
#[inline]
pub fn new<A>(f: F, g: G) -> Self
where
F: FnOnce<A>,
G: FnOnce<(F::Output,)>,
{
Chain { f, g }
}
/// Returns inner functions.
#[inline]
pub fn into_inner(self) -> (F, G) {
let Chain { f, g } = self;
(f, g)
}
/// Returns references to inner functions.
#[inline]
pub fn as_inner(&self) -> (&F, &G) {
let Chain { f, g } = self;
(f, g)
}
}
impl<A, F, G> FnOnce<A> for Chain<F, G>
where
F: FnOnce<A>,
G: FnOnce<(F::Output,)>,
{
type Output = G::Output;
#[inline]
extern "rust-call" fn call_once(self, args: A) -> Self::Output {
let Chain { f, g } = self;
let b: F::Output = f.call_once(args);
let c: G::Output = g(b);
c
}
}
impl<A, F, G> FnMut<A> for Chain<F, G>
where
F: FnMut<A>,
G: FnMut<(F::Output,)>,
{
#[inline]
extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
let Chain { f, g } = self;
let b: F::Output = f.call_mut(args);
let c: G::Output = g(b);
c
}
}
impl<A, F, G> Fn<A> for Chain<F, G>
where
F: Fn<A>,
G: Fn<(F::Output,)>,
{
#[inline]
extern "rust-call" fn call(&self, args: A) -> Self::Output {
let Chain { f, g } = self;
let b: F::Output = f.call(args);
let c: G::Output = g(b);
c
}
}
|
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Enable RADIO in TX mode"]
pub tasks_txen: TASKS_TXEN,
#[doc = "0x04 - Enable RADIO in RX mode"]
pub tasks_rxen: TASKS_RXEN,
#[doc = "0x08 - Start RADIO"]
pub tasks_start: TASKS_START,
#[doc = "0x0c - Stop RADIO"]
pub tasks_stop: TASKS_STOP,
#[doc = "0x10 - Disable RADIO"]
pub tasks_disable: TASKS_DISABLE,
#[doc = "0x14 - Start the RSSI and take one single sample of the receive signal strength"]
pub tasks_rssistart: TASKS_RSSISTART,
#[doc = "0x18 - Stop the RSSI measurement"]
pub tasks_rssistop: TASKS_RSSISTOP,
#[doc = "0x1c - Start the bit counter"]
pub tasks_bcstart: TASKS_BCSTART,
#[doc = "0x20 - Stop the bit counter"]
pub tasks_bcstop: TASKS_BCSTOP,
#[doc = "0x24 - Start the energy detect measurement used in IEEE 802.15.4 mode"]
pub tasks_edstart: TASKS_EDSTART,
#[doc = "0x28 - Stop the energy detect measurement"]
pub tasks_edstop: TASKS_EDSTOP,
#[doc = "0x2c - Start the clear channel assessment used in IEEE 802.15.4 mode"]
pub tasks_ccastart: TASKS_CCASTART,
#[doc = "0x30 - Stop the clear channel assessment"]
pub tasks_ccastop: TASKS_CCASTOP,
_reserved13: [u8; 204usize],
#[doc = "0x100 - RADIO has ramped up and is ready to be started"]
pub events_ready: EVENTS_READY,
#[doc = "0x104 - Address sent or received"]
pub events_address: EVENTS_ADDRESS,
#[doc = "0x108 - Packet payload sent or received"]
pub events_payload: EVENTS_PAYLOAD,
#[doc = "0x10c - Packet sent or received"]
pub events_end: EVENTS_END,
#[doc = "0x110 - RADIO has been disabled"]
pub events_disabled: EVENTS_DISABLED,
#[doc = "0x114 - A device address match occurred on the last received packet"]
pub events_devmatch: EVENTS_DEVMATCH,
#[doc = "0x118 - No device address match occurred on the last received packet"]
pub events_devmiss: EVENTS_DEVMISS,
#[doc = "0x11c - Sampling of receive signal strength complete"]
pub events_rssiend: EVENTS_RSSIEND,
_reserved21: [u8; 8usize],
#[doc = "0x128 - Bit counter reached bit count value"]
pub events_bcmatch: EVENTS_BCMATCH,
_reserved22: [u8; 4usize],
#[doc = "0x130 - Packet received with CRC ok"]
pub events_crcok: EVENTS_CRCOK,
#[doc = "0x134 - Packet received with CRC error"]
pub events_crcerror: EVENTS_CRCERROR,
#[doc = "0x138 - IEEE 802.15.4 length field received"]
pub events_framestart: EVENTS_FRAMESTART,
#[doc = "0x13c - Sampling of energy detection complete. A new ED sample is ready for readout from the RADIO.EDSAMPLE register."]
pub events_edend: EVENTS_EDEND,
#[doc = "0x140 - The sampling of energy detection has stopped"]
pub events_edstopped: EVENTS_EDSTOPPED,
#[doc = "0x144 - Wireless medium in idle - clear to send"]
pub events_ccaidle: EVENTS_CCAIDLE,
#[doc = "0x148 - Wireless medium busy - do not send"]
pub events_ccabusy: EVENTS_CCABUSY,
#[doc = "0x14c - The CCA has stopped"]
pub events_ccastopped: EVENTS_CCASTOPPED,
#[doc = "0x150 - Ble_LR CI field received, receive mode is changed from Ble_LR125Kbit to Ble_LR500Kbit."]
pub events_rateboost: EVENTS_RATEBOOST,
#[doc = "0x154 - RADIO has ramped up and is ready to be started TX path"]
pub events_txready: EVENTS_TXREADY,
#[doc = "0x158 - RADIO has ramped up and is ready to be started RX path"]
pub events_rxready: EVENTS_RXREADY,
#[doc = "0x15c - MAC header match found"]
pub events_mhrmatch: EVENTS_MHRMATCH,
_reserved34: [u8; 12usize],
#[doc = "0x16c - Generated in Ble_LR125Kbit, Ble_LR500Kbit and BleIeee802154_250Kbit modes when last bit is sent on air."]
pub events_phyend: EVENTS_PHYEND,
_reserved35: [u8; 144usize],
#[doc = "0x200 - Shortcut register"]
pub shorts: SHORTS,
_reserved36: [u8; 256usize],
#[doc = "0x304 - Enable interrupt"]
pub intenset: INTENSET,
#[doc = "0x308 - Disable interrupt"]
pub intenclr: INTENCLR,
_reserved38: [u8; 244usize],
#[doc = "0x400 - CRC status"]
pub crcstatus: CRCSTATUS,
_reserved39: [u8; 4usize],
#[doc = "0x408 - Received address"]
pub rxmatch: RXMATCH,
#[doc = "0x40c - CRC field of previously received packet"]
pub rxcrc: RXCRC,
#[doc = "0x410 - Device address match index"]
pub dai: DAI,
#[doc = "0x414 - Payload status"]
pub pdustat: PDUSTAT,
_reserved43: [u8; 236usize],
#[doc = "0x504 - Packet pointer"]
pub packetptr: PACKETPTR,
#[doc = "0x508 - Frequency"]
pub frequency: FREQUENCY,
#[doc = "0x50c - Output power"]
pub txpower: TXPOWER,
#[doc = "0x510 - Data rate and modulation"]
pub mode: MODE,
#[doc = "0x514 - Packet configuration register 0"]
pub pcnf0: PCNF0,
#[doc = "0x518 - Packet configuration register 1"]
pub pcnf1: PCNF1,
#[doc = "0x51c - Base address 0"]
pub base0: BASE0,
#[doc = "0x520 - Base address 1"]
pub base1: BASE1,
#[doc = "0x524 - Prefixes bytes for logical addresses 0-3"]
pub prefix0: PREFIX0,
#[doc = "0x528 - Prefixes bytes for logical addresses 4-7"]
pub prefix1: PREFIX1,
#[doc = "0x52c - Transmit address select"]
pub txaddress: TXADDRESS,
#[doc = "0x530 - Receive address select"]
pub rxaddresses: RXADDRESSES,
#[doc = "0x534 - CRC configuration"]
pub crccnf: CRCCNF,
#[doc = "0x538 - CRC polynomial"]
pub crcpoly: CRCPOLY,
#[doc = "0x53c - CRC initial value"]
pub crcinit: CRCINIT,
_reserved58: [u8; 4usize],
#[doc = "0x544 - Interframe spacing in us"]
pub tifs: TIFS,
#[doc = "0x548 - RSSI sample"]
pub rssisample: RSSISAMPLE,
_reserved60: [u8; 4usize],
#[doc = "0x550 - Current radio state"]
pub state: STATE,
#[doc = "0x554 - Data whitening initial value"]
pub datawhiteiv: DATAWHITEIV,
_reserved62: [u8; 8usize],
#[doc = "0x560 - Bit counter compare"]
pub bcc: BCC,
_reserved63: [u8; 156usize],
#[doc = "0x600 - Description collection[n]: Device address base segment n"]
pub dab: [DAB; 8],
#[doc = "0x620 - Description collection[n]: Device address prefix n"]
pub dap: [DAP; 8],
#[doc = "0x640 - Device address match configuration"]
pub dacnf: DACNF,
#[doc = "0x644 - Search pattern configuration"]
pub mhrmatchconf: MHRMATCHCONF,
#[doc = "0x648 - Pattern mask"]
pub mhrmatchmas: MHRMATCHMAS,
_reserved68: [u8; 4usize],
#[doc = "0x650 - Radio mode configuration register 0"]
pub modecnf0: MODECNF0,
_reserved69: [u8; 12usize],
#[doc = "0x660 - IEEE 802.15.4 start of frame delimiter"]
pub sfd: SFD,
#[doc = "0x664 - IEEE 802.15.4 energy detect loop count"]
pub edcnt: EDCNT,
#[doc = "0x668 - IEEE 802.15.4 energy detect level"]
pub edsample: EDSAMPLE,
#[doc = "0x66c - IEEE 802.15.4 clear channel assessment control"]
pub ccactrl: CCACTRL,
_reserved73: [u8; 2444usize],
#[doc = "0xffc - Peripheral power control"]
pub power: POWER,
}
#[doc = "Enable RADIO in TX mode"]
pub struct TASKS_TXEN {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Enable RADIO in TX mode"]
pub mod tasks_txen;
#[doc = "Enable RADIO in RX mode"]
pub struct TASKS_RXEN {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Enable RADIO in RX mode"]
pub mod tasks_rxen;
#[doc = "Start RADIO"]
pub struct TASKS_START {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start RADIO"]
pub mod tasks_start;
#[doc = "Stop RADIO"]
pub struct TASKS_STOP {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Stop RADIO"]
pub mod tasks_stop;
#[doc = "Disable RADIO"]
pub struct TASKS_DISABLE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Disable RADIO"]
pub mod tasks_disable;
#[doc = "Start the RSSI and take one single sample of the receive signal strength"]
pub struct TASKS_RSSISTART {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start the RSSI and take one single sample of the receive signal strength"]
pub mod tasks_rssistart;
#[doc = "Stop the RSSI measurement"]
pub struct TASKS_RSSISTOP {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Stop the RSSI measurement"]
pub mod tasks_rssistop;
#[doc = "Start the bit counter"]
pub struct TASKS_BCSTART {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start the bit counter"]
pub mod tasks_bcstart;
#[doc = "Stop the bit counter"]
pub struct TASKS_BCSTOP {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Stop the bit counter"]
pub mod tasks_bcstop;
#[doc = "Start the energy detect measurement used in IEEE 802.15.4 mode"]
pub struct TASKS_EDSTART {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start the energy detect measurement used in IEEE 802.15.4 mode"]
pub mod tasks_edstart;
#[doc = "Stop the energy detect measurement"]
pub struct TASKS_EDSTOP {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Stop the energy detect measurement"]
pub mod tasks_edstop;
#[doc = "Start the clear channel assessment used in IEEE 802.15.4 mode"]
pub struct TASKS_CCASTART {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start the clear channel assessment used in IEEE 802.15.4 mode"]
pub mod tasks_ccastart;
#[doc = "Stop the clear channel assessment"]
pub struct TASKS_CCASTOP {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Stop the clear channel assessment"]
pub mod tasks_ccastop;
#[doc = "RADIO has ramped up and is ready to be started"]
pub struct EVENTS_READY {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "RADIO has ramped up and is ready to be started"]
pub mod events_ready;
#[doc = "Address sent or received"]
pub struct EVENTS_ADDRESS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Address sent or received"]
pub mod events_address;
#[doc = "Packet payload sent or received"]
pub struct EVENTS_PAYLOAD {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Packet payload sent or received"]
pub mod events_payload;
#[doc = "Packet sent or received"]
pub struct EVENTS_END {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Packet sent or received"]
pub mod events_end;
#[doc = "RADIO has been disabled"]
pub struct EVENTS_DISABLED {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "RADIO has been disabled"]
pub mod events_disabled;
#[doc = "A device address match occurred on the last received packet"]
pub struct EVENTS_DEVMATCH {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "A device address match occurred on the last received packet"]
pub mod events_devmatch;
#[doc = "No device address match occurred on the last received packet"]
pub struct EVENTS_DEVMISS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "No device address match occurred on the last received packet"]
pub mod events_devmiss;
#[doc = "Sampling of receive signal strength complete"]
pub struct EVENTS_RSSIEND {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Sampling of receive signal strength complete"]
pub mod events_rssiend;
#[doc = "Bit counter reached bit count value"]
pub struct EVENTS_BCMATCH {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Bit counter reached bit count value"]
pub mod events_bcmatch;
#[doc = "Packet received with CRC ok"]
pub struct EVENTS_CRCOK {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Packet received with CRC ok"]
pub mod events_crcok;
#[doc = "Packet received with CRC error"]
pub struct EVENTS_CRCERROR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Packet received with CRC error"]
pub mod events_crcerror;
#[doc = "IEEE 802.15.4 length field received"]
pub struct EVENTS_FRAMESTART {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "IEEE 802.15.4 length field received"]
pub mod events_framestart;
#[doc = "Sampling of energy detection complete. A new ED sample is ready for readout from the RADIO.EDSAMPLE register."]
pub struct EVENTS_EDEND {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Sampling of energy detection complete. A new ED sample is ready for readout from the RADIO.EDSAMPLE register."]
pub mod events_edend;
#[doc = "The sampling of energy detection has stopped"]
pub struct EVENTS_EDSTOPPED {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "The sampling of energy detection has stopped"]
pub mod events_edstopped;
#[doc = "Wireless medium in idle - clear to send"]
pub struct EVENTS_CCAIDLE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Wireless medium in idle - clear to send"]
pub mod events_ccaidle;
#[doc = "Wireless medium busy - do not send"]
pub struct EVENTS_CCABUSY {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Wireless medium busy - do not send"]
pub mod events_ccabusy;
#[doc = "The CCA has stopped"]
pub struct EVENTS_CCASTOPPED {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "The CCA has stopped"]
pub mod events_ccastopped;
#[doc = "Ble_LR CI field received, receive mode is changed from Ble_LR125Kbit to Ble_LR500Kbit."]
pub struct EVENTS_RATEBOOST {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Ble_LR CI field received, receive mode is changed from Ble_LR125Kbit to Ble_LR500Kbit."]
pub mod events_rateboost;
#[doc = "RADIO has ramped up and is ready to be started TX path"]
pub struct EVENTS_TXREADY {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "RADIO has ramped up and is ready to be started TX path"]
pub mod events_txready;
#[doc = "RADIO has ramped up and is ready to be started RX path"]
pub struct EVENTS_RXREADY {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "RADIO has ramped up and is ready to be started RX path"]
pub mod events_rxready;
#[doc = "MAC header match found"]
pub struct EVENTS_MHRMATCH {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MAC header match found"]
pub mod events_mhrmatch;
#[doc = "Generated in Ble_LR125Kbit, Ble_LR500Kbit and BleIeee802154_250Kbit modes when last bit is sent on air."]
pub struct EVENTS_PHYEND {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Generated in Ble_LR125Kbit, Ble_LR500Kbit and BleIeee802154_250Kbit modes when last bit is sent on air."]
pub mod events_phyend;
#[doc = "Shortcut register"]
pub struct SHORTS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Shortcut register"]
pub mod shorts;
#[doc = "Enable interrupt"]
pub struct INTENSET {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Enable interrupt"]
pub mod intenset;
#[doc = "Disable interrupt"]
pub struct INTENCLR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Disable interrupt"]
pub mod intenclr;
#[doc = "CRC status"]
pub struct CRCSTATUS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "CRC status"]
pub mod crcstatus;
#[doc = "Received address"]
pub struct RXMATCH {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Received address"]
pub mod rxmatch;
#[doc = "CRC field of previously received packet"]
pub struct RXCRC {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "CRC field of previously received packet"]
pub mod rxcrc;
#[doc = "Device address match index"]
pub struct DAI {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Device address match index"]
pub mod dai;
#[doc = "Payload status"]
pub struct PDUSTAT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Payload status"]
pub mod pdustat;
#[doc = "Packet pointer"]
pub struct PACKETPTR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Packet pointer"]
pub mod packetptr;
#[doc = "Frequency"]
pub struct FREQUENCY {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Frequency"]
pub mod frequency;
#[doc = "Output power"]
pub struct TXPOWER {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Output power"]
pub mod txpower;
#[doc = "Data rate and modulation"]
pub struct MODE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Data rate and modulation"]
pub mod mode;
#[doc = "Packet configuration register 0"]
pub struct PCNF0 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Packet configuration register 0"]
pub mod pcnf0;
#[doc = "Packet configuration register 1"]
pub struct PCNF1 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Packet configuration register 1"]
pub mod pcnf1;
#[doc = "Base address 0"]
pub struct BASE0 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Base address 0"]
pub mod base0;
#[doc = "Base address 1"]
pub struct BASE1 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Base address 1"]
pub mod base1;
#[doc = "Prefixes bytes for logical addresses 0-3"]
pub struct PREFIX0 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Prefixes bytes for logical addresses 0-3"]
pub mod prefix0;
#[doc = "Prefixes bytes for logical addresses 4-7"]
pub struct PREFIX1 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Prefixes bytes for logical addresses 4-7"]
pub mod prefix1;
#[doc = "Transmit address select"]
pub struct TXADDRESS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Transmit address select"]
pub mod txaddress;
#[doc = "Receive address select"]
pub struct RXADDRESSES {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Receive address select"]
pub mod rxaddresses;
#[doc = "CRC configuration"]
pub struct CRCCNF {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "CRC configuration"]
pub mod crccnf;
#[doc = "CRC polynomial"]
pub struct CRCPOLY {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "CRC polynomial"]
pub mod crcpoly;
#[doc = "CRC initial value"]
pub struct CRCINIT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "CRC initial value"]
pub mod crcinit;
#[doc = "Interframe spacing in us"]
pub struct TIFS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Interframe spacing in us"]
pub mod tifs;
#[doc = "RSSI sample"]
pub struct RSSISAMPLE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "RSSI sample"]
pub mod rssisample;
#[doc = "Current radio state"]
pub struct STATE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Current radio state"]
pub mod state;
#[doc = "Data whitening initial value"]
pub struct DATAWHITEIV {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Data whitening initial value"]
pub mod datawhiteiv;
#[doc = "Bit counter compare"]
pub struct BCC {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Bit counter compare"]
pub mod bcc;
#[doc = "Description collection[n]: Device address base segment n"]
pub struct DAB {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Description collection[n]: Device address base segment n"]
pub mod dab;
#[doc = "Description collection[n]: Device address prefix n"]
pub struct DAP {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Description collection[n]: Device address prefix n"]
pub mod dap;
#[doc = "Device address match configuration"]
pub struct DACNF {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Device address match configuration"]
pub mod dacnf;
#[doc = "Search pattern configuration"]
pub struct MHRMATCHCONF {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Search pattern configuration"]
pub mod mhrmatchconf;
#[doc = "Pattern mask"]
pub struct MHRMATCHMAS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Pattern mask"]
pub mod mhrmatchmas;
#[doc = "Radio mode configuration register 0"]
pub struct MODECNF0 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Radio mode configuration register 0"]
pub mod modecnf0;
#[doc = "IEEE 802.15.4 start of frame delimiter"]
pub struct SFD {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "IEEE 802.15.4 start of frame delimiter"]
pub mod sfd;
#[doc = "IEEE 802.15.4 energy detect loop count"]
pub struct EDCNT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "IEEE 802.15.4 energy detect loop count"]
pub mod edcnt;
#[doc = "IEEE 802.15.4 energy detect level"]
pub struct EDSAMPLE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "IEEE 802.15.4 energy detect level"]
pub mod edsample;
#[doc = "IEEE 802.15.4 clear channel assessment control"]
pub struct CCACTRL {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "IEEE 802.15.4 clear channel assessment control"]
pub mod ccactrl;
#[doc = "Peripheral power control"]
pub struct POWER {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Peripheral power control"]
pub mod power;
|
use std::collections::HashMap;
use std::fmt;
use std::fmt::Formatter;
use std::marker::PhantomData;
use serde::{Deserialize, Deserializer};
use serde::de::{MapAccess, SeqAccess, Visitor};
use serde::Serialize;
fn format_bool<'de, D>(deserializer: D) -> Result<bool, D::Error> where D: Deserializer<'de>, {
let s = u8::deserialize(deserializer)?;
Ok(s == 1)
}
struct WebSitesHashMapVisitor {
marker: PhantomData<fn() -> HashMap<String, String>>
}
impl WebSitesHashMapVisitor {
fn new() -> Self {
WebSitesHashMapVisitor {
marker: PhantomData
}
}
}
impl<'de> Visitor<'de> for WebSitesHashMapVisitor {
type Value = HashMap<String, String>;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("ใใใกใถใ")
}
fn visit_seq<A>(self, _seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
Ok(HashMap::new())
}
fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut map = HashMap::with_capacity(access.size_hint().unwrap_or(0));
while let Some((key, value)) = access.next_entry()? {
map.insert(key, value);
}
Ok(map)
}
}
fn format_web_sites_map<'de, D>(deserializer: D) -> Result<HashMap<String, String>, D::Error> where D: Deserializer<'de>, {
Ok(deserializer.deserialize_any(WebSitesHashMapVisitor::new())?)
}
#[derive(Serialize, Deserialize)]
pub struct User {
id: u16,
name: String,
description: Option<String>,
icon_image_id: Option<String>,
icon_image: Option<Image>,
created_at: String,
updated_at: String,
}
#[derive(Serialize, Deserialize)]
pub struct Image {
id: String,
format: String,
#[serde(rename = "type")]
_type: u8,
url: String,
}
#[derive(Serialize, Deserialize)]
pub struct LatestPing {
server_id: u16,
#[serde(deserialize_with = "format_bool")]
is_running: bool,
millisecond: Option<u16>,
protocol: Option<u16>,
version: Option<String>,
current_player: Option<u16>,
max_player: Option<u16>,
created_at: String,
}
#[derive(Serialize, Deserialize)]
pub struct YesterdayStatistics {
date: String,
#[serde(rename = "type")]
_type: u8,
server_id: u16,
all_ping_count: u16,
valid_ping_count: u16,
average_player: f32,
max_player: u16,
created_at: String,
}
#[derive(Serialize, Deserialize)]
pub struct Votes {
entire: u8,
recently: u8,
}
#[derive(Serialize, Deserialize)]
pub struct Server {
id: u16,
user_id: u16,
name: String,
address: Option<String>,
port: Option<u16>,
description: Option<String>,
color: Option<String>,
categories: Vec<u8>,
#[serde(deserialize_with = "format_web_sites_map")]
web_sites: HashMap<String, String>,
top_image_id: Option<String>,
back_image_id: Option<String>,
#[serde(deserialize_with = "format_bool")]
is_verified: bool,
#[serde(deserialize_with = "format_bool")]
is_archived: bool,
#[serde(deserialize_with = "format_bool")]
is_display_server: bool,
#[serde(deserialize_with = "format_bool")]
is_display_address: bool,
#[serde(deserialize_with = "format_bool")]
is_display_statistics: bool,
created_at: String,
updated_at: String,
user: User,
top_image: Option<Image>,
back_image: Option<Image>,
latest_ping: LatestPing,
yesterday_statistics: YesterdayStatistics,
votes: Votes,
}
#[derive(Deserialize, Serialize)]
pub struct StatusAndServers {
status: u8,
pub servers: Vec<Server>,
}
#[derive(Serialize)]
pub struct GetServersResponse {
pub servers: Vec<Server>
}
#[derive(Deserialize)]
#[serde(tag = "cmd", rename_all = "camelCase")]
pub enum Cmd {
GetServersCommand {
callback: String,
error: String,
}
}
|
extern crate iron;
extern crate router;
extern crate persistent;
extern crate bodyparser;
extern crate formdata;
extern crate multipart;
extern crate hyper;
extern crate hyper_native_tls;
extern crate params;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate serde;
extern crate toml;
extern crate uuid;
extern crate bcrypt;
extern crate r2d2;
extern crate r2d2_postgres;
extern crate r2d2_redis;
extern crate postgres;
extern crate redis;
//#[macro_use]
extern crate diesel;
extern crate r2d2_diesel;
extern crate dotenv;
extern crate jsonwebtoken;
extern crate url;
//extern crate time;
extern crate chrono;
#[macro_use]
extern crate slog;
extern crate slog_json;
extern crate iron_slog;
extern crate oauth2;
extern crate common;
use common::{config, configmisc};
use slog::Drain;
mod server;
mod dal;
fn main() {
let log_file_nane = "log/store-backend.log";
let log_file_handle = match std::fs::OpenOptions::new()
.create(true)
.append(true)
.write(true)
.open(log_file_nane) {
Ok(x) => x,
Err(_) => {
std::process::exit(-1);
}
};
let drain = std::sync::Mutex::new(slog_json::Json::default(log_file_handle));
let root_logger = slog::Logger::root(
drain.fuse(),
o!("version" => env!("CARGO_PKG_VERSION"), "child" => "main"),
);
let c = config::Config::load(root_logger.new(o!("child" => "ConfigLoader")));
let pg_dal = dal::DalPostgresPool::get_postgres_pool(root_logger.new(o!("child" => "DalPostgresPool")), &c);
// let pg_rw_pool = pg_dal.rw_pool;
// let pg_ro_pool = pg_dal.ro_pool;
// let dal::DalPostgresPool { rw_pool: pg_rw_pool, ro_pool: pg_ro_pool } =
// dal::DalPostgresPool::get_postgres_pool(&c);
//let redis_dal = dal::DalRedisPool::get_redis_pool(root_logger.new(o!("child" => "DalRedisPool")), &c);
//let diesel_pg_dal = dal::DalDieselPool::get_diesel_pool(root_logger.new(o!("child" => "DalDieselPool")), &c);
// SERDE JSON
// {
// let json_c = serde_json::to_string(&c).unwrap();
// info!(root_logger, "c : [{}]", json_c);
//
// let des_c: config::Config = serde_json::from_str(&json_c).unwrap();
// info!(root_logger, "des_c [{:?}", des_c);
// }
//
// TODO : this should come from an encrypted file
let config_misc = configmisc::ConfigMisc {
//jwt_secret: "secretsecret1234567890".to_string()
//jwt_secret: uuid::Uuid::new_v4().simple().to_string()
jwt_secret: uuid::Uuid::new_v4().to_string(),
jwt_time_variation: 60, // 60 seconds time relaxation for jwt validation
};
server::serve(
root_logger.new(o!("child" => "server")),
c,
pg_dal,
config_misc,
);
}
|
extern crate paillier;
#[cfg(not(feature="keygen"))]
fn main() {
println!("*** please run with 'keygen' feature ***")
}
#[cfg(feature="keygen")]
fn main() {
use paillier::{AbstractPaillier, BigInteger, integral}; // could be a specific type such as RampBigInteger as well
use paillier::coding::*;
use paillier::traits::*;
type MyScheme = AbstractPaillier<BigInteger>;
let (ek, dk) = MyScheme::keypair().keys();
let code = integral::Code::default();
let eek = ek.with_code(&code);
let c1 = MyScheme::encrypt(&eek, &10);
let c2 = MyScheme::encrypt(&eek, &20);
let c3 = MyScheme::encrypt(&eek, &30);
let c4 = MyScheme::encrypt(&eek, &40);
// add up all four encryptions
let c = MyScheme::add(&ek,
&MyScheme::add(&ek, &c1, &c2),
&MyScheme::add(&ek, &c3, &c4)
);
let m: u64 = code.decode(&MyScheme::decrypt(&dk, &c));
println!("decrypted total sum is {}", m);
}
|
use cell_extras::atomic_init_cell::AtomicInitCell;
use cell_extras::atomic_ref_cell::AtomicRefCell;
use engine::{self, EngineMessage};
use math::*;
use polygon::light::*;
use std::mem;
use std::sync::Arc;
// TODO: This shouldn't be fully public, only public within the crate.
pub type LightInner = Arc<(AtomicInitCell<LightId>, AtomicRefCell<Light>)>;
#[derive(Debug)]
pub struct DirectionalLight {
data: LightInner,
}
impl DirectionalLight {
pub fn new(direction: Vector3, color: Color, strength: f32) -> DirectionalLight {
let light = Light::directional(direction, strength, color);
let data = Arc::new((AtomicInitCell::new(), AtomicRefCell::new(light)));
engine::send_message(EngineMessage::Light(data.clone()));
DirectionalLight {
data: data,
}
}
pub fn forget(self) {
mem::forget(self);
}
}
#[derive(Debug)]
pub struct PointLight {
data: LightInner,
}
impl PointLight {
pub fn new(radius: f32, color: Color, strength: f32) -> PointLight {
let light = Light::point(radius, strength, color);
let data = Arc::new((AtomicInitCell::new(), AtomicRefCell::new(light)));
engine::send_message(EngineMessage::Light(data.clone()));
PointLight {
data: data,
}
}
pub fn forget(self) {
mem::forget(self);
}
}
|
use std::io;
fn main() {
let mut buf = String::new();
io::stdin().read_line(&mut buf).unwrap();
let n: usize = buf.trim().parse().unwrap();
let s: Vec<char> = {
buf = String::new();
io::stdin().read_line(&mut buf).unwrap();
buf.trim().chars().collect()
};
let mut r_count = 0;
let mut g_count = 0;
let mut b_count = 0;
for i in 0..n {
match s[i] {
'R' => r_count += 1,
'G' => g_count += 1,
'B' => b_count += 1,
_ => (),
}
}
let count = r_count * g_count * b_count;
let mut minus_count = 0;
for i in 0..n {
let mut j = i + 1;
let mut k = i + 2;
while k < n {
if s[i] != s[j] && s[j] != s[k] && s[i] != s[k] {
minus_count += 1;
}
j += 1;
k = j + (j - i);
}
}
println!("{}", count - minus_count);
}
|
fn use_pointer(x : &u32) {
println!("x = {}, Address of x = {:p}", x, &x);
}
fn main() {
let x:u32 = 1;
println!("x = {}, Address of x = {:p}", x, &x);
use_pointer(&x);
let a:u32 = 1;
let b = &a;
println!("{}", *b);
println!("{:p}", b);
println!("{}", b);
}
|
pub use libra_language_e2e_tests::compile::*;
|
/// https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
///
/// Stepping takes about 24 nanoseconds per cell on my
/// somewhat slow laptop.
use std::fmt::{Display, Formatter, Error};
use std::ops::{Index, IndexMut};
use std::time::Instant;
struct Board {
cells: Vec<bool>,
size: usize
}
impl Board {
fn new(size: usize) -> Board {
let mut cells = Vec::new();
for _ in 0..(size * size) {
cells.push(false);
}
Board{cells: cells, size: size}
}
fn count_neighbors(&self, row: usize, col: usize) -> usize {
let mut count = 0usize;
if row > 0 && row + 1 < self.size && col > 0 && col + 1 < self.size {
for i in &[row - 1, row, row + 1] {
for j in &[col - 1, col, col + 1] {
if *i == row && *j == col {
continue
}
if self[(*i, *j)] {
count += 1;
}
}
}
} else {
let additions = [0, 1, self.size - 1];
for i in &additions {
for j in &additions {
if *i == 0 && *j == 0 {
continue
}
if self[((row + *i) % self.size, (col + *j) % self.size)] {
count += 1;
}
}
}
}
count
}
fn step(&self) -> Board {
let mut res = Board::new(self.size);
for i in 0..self.size {
for j in 0..self.size {
let count = self.count_neighbors(i, j);
if self[(i, j)] {
if count == 2 || count == 3 {
res[(i, j)] = true;
}
} else if count == 3 {
res[(i, j)] = true;
}
}
}
res
}
}
impl Index<(usize, usize)> for Board {
type Output = bool;
fn index(&self, index: (usize, usize)) -> &bool {
assert!(index.0 < self.size);
assert!(index.1 < self.size);
&self.cells[index.0 * self.size + index.1]
}
}
impl IndexMut<(usize, usize)> for Board {
fn index_mut(&mut self, index: (usize, usize)) -> &mut bool {
assert!(index.0 < self.size);
assert!(index.1 < self.size);
&mut self.cells[index.0 * self.size + index.1]
}
}
impl Display for Board {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
for i in 0..self.size {
if i != 0 {
write!(f, "\n")?;
}
for j in 0..self.size {
if self[(i, j)] {
write!(f, "##")?;
} else {
write!(f, " ")?;
}
}
}
Ok(())
}
}
fn main() {
let mut board = Board::new(18);
create_icolumn(&mut board, 0, 3);
for _ in 0..16 {
println!("{}", board);
println!("-------");
board = board.step();
}
board = Board::new(1000);
for i in 0..(board.size / 18) {
for j in 0..(board.size / 18) {
create_icolumn(&mut board, i*18, j*18);
}
}
let start = Instant::now();
board.step();
let elapsed = start.elapsed() / 1000000;
println!("time: {}ns/cell", elapsed.subsec_nanos());
}
fn create_icolumn(board: &mut Board, row: usize, col: usize) {
for i in 5..13 {
for j in 4..7 {
if j != 5 || (i != 6 && i != 11) {
board[(i + row, j + col)] = true;
}
}
}
}
|
use anyhow::{anyhow, Result};
use ropey::Rope;
use tree_sitter::{Language, Parser, Query, QueryCursor, Tree};
use tree_sitter_typescript::{language_tsx, language_typescript};
const QUERY: &str = "(import_statement (string) @import)(export_statement (string) @import)";
pub enum Lang {
TypeScript,
TypeScriptTsx,
}
fn to_language(language: &Lang) -> Language {
match language {
Lang::TypeScript => language_typescript(),
Lang::TypeScriptTsx => language_tsx(),
}
}
pub struct TextSlice {
start_row: usize,
start_col: usize,
end_row: usize,
end_col: usize,
}
impl TextSlice {
pub fn to_index_range(&self, rope: &Rope) -> (usize, usize) {
let start_idx = rope.line_to_char(self.start_row) + self.start_col;
let end_idx = rope.line_to_char(self.end_row) + self.end_col;
(start_idx, end_idx)
}
}
pub struct ImportFinder {
tree: Tree,
query: Query,
cursor: QueryCursor,
}
impl ImportFinder {
pub fn new(source_code: &str, lang: Lang) -> Result<Self> {
let language = to_language(&lang);
let tree = parse_treesitter_tree(source_code, language)?;
let query = Query::new(language, &QUERY).unwrap();
let cursor = QueryCursor::new();
Ok(Self {
tree,
query,
cursor,
})
}
pub fn find_imports(&mut self) -> impl Iterator<Item = TextSlice> + '_ {
self.cursor
.matches(&self.query, self.tree.root_node(), |_| "")
.into_iter()
.flat_map(|qm| qm.captures.iter())
.map(|query_capture| query_capture.node)
.map(|node| {
let start_point = node.start_position();
let end_point = node.end_position();
TextSlice {
start_row: start_point.row,
start_col: start_point.column + 1,
end_row: end_point.row,
end_col: end_point.column - 1,
}
})
}
}
fn parse_treesitter_tree(source_code: &str, language: Language) -> Result<Tree> {
let mut parser = Parser::new();
parser
.set_language(language)
.map_err(|_| anyhow!("Language error"))?;
parser
.parse(source_code, None)
.ok_or_else(|| anyhow!("Failed to parse"))
}
// (call_expression
// (identifier) @constant
// (#match? @constant "require")
// (arguments (string) @lol)
// (call_expression
// (identifier) @constant
// (#match? @constant "require")
// (arguments (string) @lol)
// )
// )
//
//
//
// (call_expression
// (import)
// (arguments (string) @lol)
// )
// (import_statement (string) @lol)
// (call_expression
// (identifier) @constant
// (#match? @constant "require")
// (arguments (string) @lol)
// )
//
//
//
// (call_expression
// (identifier) @function_name
// (match? @function_name "require")
// (arguments (string) @import_string))
//
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Display;
use std::hash::Hash;
use anyerror::AnyError;
use cbordata::Cbor;
use cbordata::FromCbor;
use cbordata::IntoCbor;
use common_exception::ErrorCode;
use common_expression::types::DataType;
use xorfilter::Xor8;
use crate::filters::Filter;
use crate::filters::FilterBuilder;
use crate::Index;
/// A builder that builds a xor8 filter.
///
/// When a filter is built, the source key set should be updated(by calling `add_keys()`), although Xor8 itself allows.
pub struct Xor8Builder {
builder: xorfilter::Xor8Builder,
}
pub struct Xor8Filter {
filter: Xor8,
}
#[derive(thiserror::Error, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[error("{msg}; cause: {cause}")]
pub struct Xor8CodecError {
msg: String,
#[source]
cause: AnyError,
}
#[derive(thiserror::Error, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[error("fail to build xor8 filter; cause: {cause}")]
pub struct Xor8BuildingError {
#[source]
cause: AnyError,
}
impl FilterBuilder for Xor8Builder {
type Filter = Xor8Filter;
type Error = Xor8BuildingError;
fn add_key<K: Hash>(&mut self, key: &K) {
self.builder.insert(key)
}
fn add_keys<K: Hash>(&mut self, keys: &[K]) {
self.builder.populate(keys)
}
fn add_digests<'i, I: IntoIterator<Item = &'i u64>>(&mut self, digests: I) {
self.builder.populate_digests(digests)
}
fn build(&mut self) -> Result<Self::Filter, Self::Error> {
let f = self
.builder
.build()
.map_err(|e| Xor8BuildingError::new(&e))?;
Ok(Xor8Filter { filter: f })
}
}
impl Xor8Builder {
pub fn create() -> Self {
Xor8Builder {
builder: xorfilter::Xor8Builder::default(),
}
}
}
impl Filter for Xor8Filter {
type CodecError = Xor8CodecError;
fn len(&self) -> Option<usize> {
self.filter.len()
}
fn contains<K: ?Sized + Hash>(&self, key: &K) -> bool {
self.filter.contains(key)
}
fn contains_digest(&self, digest: u64) -> bool {
self.filter.contains_digest(digest)
}
fn to_bytes(&self) -> Result<Vec<u8>, Xor8CodecError> {
let mut buf: Vec<u8> = vec![];
let cbor_val = self
.filter
.clone()
.into_cbor()
.map_err(|e| Xor8CodecError::new("fail to build cbor", &e))?;
cbor_val
.encode(&mut buf)
.map_err(|e| Xor8CodecError::new("fail to encode cbor", &e))?;
Ok(buf)
}
fn from_bytes(mut buf: &[u8]) -> Result<(Self, usize), Xor8CodecError> {
let (cbor_val, n) =
Cbor::decode(&mut buf).map_err(|e| Xor8CodecError::new("fail to decode cbor", &e))?;
let xor_value = Xor8::from_cbor(cbor_val)
.map_err(|e| Xor8CodecError::new("fail to build filter from cbor", &e))?;
Ok((Self { filter: xor_value }, n))
}
}
impl Index for Xor8Filter {
fn supported_type(data_type: &DataType) -> bool {
let inner_type = data_type.remove_nullable();
matches!(
inner_type,
DataType::Number(_) | DataType::String | DataType::Timestamp | DataType::Date
)
}
}
impl Xor8CodecError {
pub fn new(msg: impl Display, cause: &(impl std::error::Error + 'static)) -> Self {
Self {
msg: msg.to_string(),
cause: AnyError::new(cause),
}
}
}
impl From<Xor8CodecError> for ErrorCode {
fn from(e: Xor8CodecError) -> Self {
ErrorCode::Internal(e.to_string())
}
}
impl Xor8BuildingError {
pub fn new(cause: &(impl std::error::Error + 'static)) -> Self {
Self {
cause: AnyError::new(cause),
}
}
}
impl From<Xor8BuildingError> for ErrorCode {
fn from(e: Xor8BuildingError) -> Self {
ErrorCode::Internal(e.to_string())
}
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
mod transfer;
pub use transfer::*;
|
use num::ToPrimitive;
use time::now_utc;
use std::io::Write;
use std::fs;
use std::path;
use postgres;
use std::collections;
pub fn gen_timecode() -> String {
now_utc().strftime("%y%m%d%H%M%S").unwrap().to_string()
}
pub fn gen_full_name(name: &str) -> String {
format!("_{}_{}", gen_timecode(), name)
}
pub fn create_migration_file(name: &str, base_path: path::PathBuf) -> String {
let full_name = gen_full_name(name);
let final_path = base_path.join(&format!("{}.rs", full_name)[..]);
let mut file = match fs::OpenOptions::new().create(true).write(true).open(&final_path) {
Ok(f) => f,
Err(e) => panic!("file error: {}", e),
};
file.write_all(b"").unwrap();
full_name
}
pub struct Migration<Conn> {
version: u64,
name: String,
raw: Box<RawMigration<Conn> + 'static>
}
impl<Conn> Migration<Conn> {
pub fn new(version: u64, name: &str, raw: Box<RawMigration<Conn> + 'static>) -> Migration<Conn> {
Migration {
version: version,
name: name.to_string(),
raw: raw
}
}
pub fn version(&self) -> &u64 { &self.version }
pub fn name(&self) -> &str { &self.name }
pub fn raw(&self) -> &Box<RawMigration<Conn> + 'static> { &self.raw }
}
pub trait RawMigration<Conn> {
fn up(&self, cn: &Conn);
fn down(&self, cn: &Conn);
}
pub type Migrations = Vec<Box<Migration<postgres::Connection>>>;
pub type MigrationRefs<'a> = Vec<&'a Box<Migration<postgres::Connection>>>;
pub fn ensure_schema_migrations(cn: &postgres::Connection) {
cn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (
version BIGINT NOT NULL
);", &[]).unwrap();
}
pub fn insert_version(version: &i64, cn: &postgres::Connection) {
cn.execute("INSERT INTO schema_migrations VALUES ($1);", &[version]).unwrap();
}
pub fn delete_version(version: &i64, cn: &postgres::Connection) {
cn.execute("DELETE FROM schema_migrations WHERE version = $1;", &[version]).unwrap();
}
pub fn get_versions_as_hash(cn: &postgres::Connection) -> collections::HashMap<i64, bool> {
let stmt = cn.prepare("SELECT version FROM schema_migrations ORDER BY version desc;").unwrap();
let rows = stmt.query(&[]).unwrap();
let mut db_versions: collections::HashMap<i64, bool> = collections::HashMap::new();
for row in rows {
db_versions.insert(row.get(0), true);
}
db_versions
}
pub fn get_versions_as_vec(cn: &postgres::Connection) -> Vec<i64> {
let stmt = cn.prepare("SELECT version FROM schema_migrations ORDER BY version desc;").unwrap();
let rows = stmt.query(&[]).unwrap();
let mut db_versions: Vec<i64> = vec![];
for row in rows {
db_versions.push(row.get(0));
}
db_versions
}
pub fn run(migrations: &Migrations, cn: &postgres::Connection) {
ensure_schema_migrations(cn);
let db_versions = get_versions_as_hash(cn);
let migrations_to_run: MigrationRefs = migrations.iter().filter(|m| {
let version = m.version().to_i64().unwrap();
!db_versions.contains_key(&version)
}).collect();
for migration in migrations_to_run.iter() {
migration.raw().up(cn);
insert_version(&migration.version().to_i64().unwrap(), cn);
println!("Migration completed: {} {}", migration.version(), migration.name());
}
}
pub fn rollback(steps: usize, migrations: &Migrations, cn: &postgres::Connection) {
ensure_schema_migrations(cn);
let db_versions = get_versions_as_vec(cn);
let db_versions_to_run = &db_versions[0..steps];
let migrations_to_run: MigrationRefs = migrations.iter().filter(|m| {
let version = m.version().to_i64().unwrap();
db_versions_to_run.contains(&version)
}).collect();
for migration in migrations_to_run.iter() {
migration.raw().down(cn);
delete_version(&migration.version().to_i64().unwrap(), cn);
println!("Migration reverted: {} {}", migration.version(), migration.name());
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::collections::btree_set::BTreeSet;
use lazy_static::lazy_static;
//use super::super::Kernel;
use super::super::qlib::common::*;
use super::super::qlib::linux_def::*;
use super::super::qlib::limits::*;
use super::super::syscalls::syscalls::*;
use super::super::task::Task;
use super::super::threadmgr::thread::*;
lazy_static! {
pub static ref SETABLE_LIMITS : BTreeSet<LimitType> = [
LimitType::NumberOfFiles,
LimitType::AS,
LimitType::CPU,
LimitType::Data,
LimitType::FileSize,
LimitType::MemoryLocked,
LimitType::Stack,
// These are not enforced, but we include them here to avoid returning
// EPERM, since some apps expect them to succeed.
LimitType::Core,
LimitType::ProcessCount,
].iter().cloned().collect();
}
pub fn PrLimit64(thread: &Thread, resource: LimitType, newLimit: Option<Limit>) -> Result<Limit> {
let tg = thread.ThreadGroup();
let limits = tg.Limits();
if newLimit.is_none() {
return Ok(limits.Get(resource));
}
if !SETABLE_LIMITS.contains(&resource) {
return Err(Error::SysError(SysErr::EPERM))
}
// "A privileged process (under Linux: one with the CAP_SYS_RESOURCE
// capability in the initial user namespace) may make arbitrary changes
// to either limit value."
let kernel = thread.Kernel();
let root = kernel.RootUserNamespace();
let privileged = thread.HasCapabilityIn(Capability::CAP_SYS_RESOURCE, &root);
let oldLim = limits.Set(resource, newLimit.unwrap(), privileged)?;
if resource == LimitType::CPU {
thread.NotifyRlimitCPUUpdated()
}
return Ok(oldLim)
}
#[derive(Default, Clone, Copy)]
pub struct RLimit64 {
pub Cur: u64,
pub Max: u64,
}
impl RLimit64 {
pub fn ToLimit(&self) -> Limit {
return Limit {
Cur: FromLinux(self.Cur),
Max: FromLinux(self.Max)
}
}
pub fn FromLimit(lim: &Limit) -> Self {
return Self {
Cur: ToLinux(lim.Cur),
Max: ToLinux(lim.Max),
}
}
}
// Getrlimit implements linux syscall getrlimit(2).
pub fn SysGetrlimit(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let lr = args.arg0 as i32;
let addr = args.arg1 as u64;
let resource = match FROM_LINUX_RESOURCE.get(&lr) {
None => return Err(Error::SysError(SysErr::EINVAL)),
Some(r) => *r,
};
let lim = PrLimit64(&task.Thread(), resource, None)?;
let rlim = RLimit64::FromLimit(&lim);
//*task.GetTypeMut(addr)? = rlim;
task.CopyOutObj(&rlim, addr)?;
return Ok(0)
}
pub fn SysSetrlimit(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let lr = args.arg0 as i32;
let addr = args.arg1 as u64;
let resource = match FROM_LINUX_RESOURCE.get(&lr) {
None => return Err(Error::SysError(SysErr::EINVAL)),
Some(r) => *r,
};
let rlim : RLimit64 = task.CopyInObj(addr)?;
PrLimit64(&task.Thread(), resource, Some(rlim.ToLimit()))?;
return Ok(0)
}
pub fn SysPrlimit64(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let tid = args.arg0 as i32;
let lr = args.arg1 as i32;
let newRlimAddr = args.arg2 as u64;
let oldRlimAddr = args.arg3 as u64;
let resource = match FROM_LINUX_RESOURCE.get(&lr) {
None => return Err(Error::SysError(SysErr::EINVAL)),
Some(r) => *r,
};
let newlim = if newRlimAddr != 0 {
let nrl : RLimit64 = task.CopyInObj(newRlimAddr)?;
Some(nrl.ToLimit())
} else {
None
};
if tid < 0 {
return Err(Error::SysError(SysErr::EINVAL));
}
let thread = task.Thread();
let pidns = thread.PIDNamespace();
let ot = if tid > 0 {
let ot = match pidns.TaskWithID(tid) {
None => return Err(Error::SysError(SysErr::ESRCH)),
Some(t) => t,
};
ot
} else {
thread.clone()
};
// "To set or get the resources of a process other than itself, the caller
// must have the CAP_SYS_RESOURCE capability, or the real, effective, and
// saved set user IDs of the target process must match the real user ID of
// the caller and the real, effective, and saved set group IDs of the
// target process must match the real group ID of the caller."
if !thread.HasCapabilityIn(Capability::CAP_SYS_RESOURCE, &pidns.UserNamespace()) {
let cred = thread.Credentials();
let tcred = ot.Credentials();
if cred != tcred {
let credlock = cred.lock();
let tcredlock = tcred.lock();
if credlock.RealKUID != tcredlock.RealKUID ||
credlock.RealKUID != tcredlock.EffectiveKUID ||
credlock.RealKUID != tcredlock.SavedKUID ||
credlock.RealKGID != tcredlock.RealKGID ||
credlock.RealKGID != tcredlock.EffectiveKGID ||
credlock.RealKGID != tcredlock.SavedKGID {
return Err(Error::SysError(SysErr::EPERM))
}
}
}
let oldLim = PrLimit64(&ot, resource, newlim)?;
if oldRlimAddr != 0 {
let rlim = RLimit64::FromLimit(&oldLim);
//*task.GetTypeMut(oldRlimAddr)? = rlim;
task.CopyOutObj(&rlim, oldRlimAddr)?;
}
return Ok(0)
}
/*pub fn SysPrlimit64(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let pid = args.arg0;
let resource = args.arg1 as u64;
let newLimit = args.arg2 as u64;
let oldLimit = args.arg3 as u64;
let newLimit = if let Ok(newLimit) = task.CheckedV2P(newLimit) {
newLimit
} else {
return Err(Error::SysError(SysErr::EINVAL));
};
let oldLimit = if let Ok(oldLimit) = task.CheckedV2P(oldLimit) {
oldLimit
} else {
return Err(Error::SysError(SysErr::EINVAL));
};
return Ok(Kernel::HostSpace::PRLimit(pid as i32, resource as i32, newLimit, oldLimit));
}*/ |
// Copyright 2021 Chiral Ltd.
// Licensed under the Apache-2.0 license (https://opensource.org/licenses/Apache-2.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
use crate::core;
use super::element;
use super::bond;
/// Hash atom charge
/// Postive charge value > 200, Neutral = 100, Negative < 100
const DEFAULT_CHARGE_HASH_VALUE: usize = 100;
fn get_charge_hash_value_from_atom_purr(atom_purr: &purr::graph::Atom) -> usize {
match &atom_purr.kind {
purr::feature::AtomKind::Star => DEFAULT_CHARGE_HASH_VALUE,
purr::feature::AtomKind::Aliphatic(_) => DEFAULT_CHARGE_HASH_VALUE,
purr::feature::AtomKind::Aromatic(_) => DEFAULT_CHARGE_HASH_VALUE,
purr::feature::AtomKind::Bracket {
isotope: _, symbol: _, hcount: _, configuration: _, charge, map: _
} => match charge {
Some(c) => {
let charge_of_atom: i8 = c.into();
match charge_of_atom > 0 {
true => 200 + charge_of_atom as usize,
false => (0 - charge_of_atom) as usize
}
},
None => DEFAULT_CHARGE_HASH_VALUE
}
}
}
#[derive(Debug, Clone)]
pub struct Atom {
pub kind: String, // purr::feature::AtomKind of the current version does not support trait Clone, so use String instead
pub bonds: Vec<bond::Bond>,
charge: usize,
atomic_number: usize,
is_aromatic: bool,
is_breaking_symmetry: bool,
}
impl Atom {
pub fn from_atom_purr(atom_purr: &purr::graph::Atom) -> Self {
let atomic_number: usize = element::atomic_number(&atom_purr.kind) as usize;
let is_aromatic: bool = atom_purr.is_aromatic();
let kind: String = atom_purr.kind.to_string();
let bonds: Vec<bond::Bond> = atom_purr.bonds
.iter()
.map(|b| bond::Bond::from_bond_purr(&b))
.collect();
let is_breaking_symmetry: bool = false;
let charge: usize = get_charge_hash_value_from_atom_purr(atom_purr);
Self { kind, bonds, charge, atomic_number, is_aromatic, is_breaking_symmetry }
}
}
impl core::graph::Vertex for Atom {
fn fixed_hash_value(&self) -> core::graph::VertexFixedHashValue {
self.charge * 10 * 1000 * 10 * 10
+ self.bonds.len() * 10 * 1000 * 10
+ self.is_aromatic as usize * 10 * 1000
+ self.atomic_number as usize * 10
+ self.is_breaking_symmetry as usize
}
fn break_symmetry_vertex(&mut self) {
self.is_breaking_symmetry = true;
}
fn break_symmetry_edge(&mut self, tid: usize) {
for bond in self.bonds.iter_mut() {
if bond.tid == tid {
bond.break_symmetry();
}
}
}
fn degree(&self) -> usize {
self.bonds.len()
}
fn neighbour_indexes(&self) -> Vec<usize> {
self.bonds.iter()
.map(|b| b.tid)
.collect()
}
fn custom_new_in_reduced_graph(
self_index: usize,
atomic_number: usize,
edges_from: &Vec<(usize, usize)>,
edges_to: &Vec<(usize, usize)>,
atoms: &Vec<Atom>,
numbering: &Vec<usize>
) -> Self {
let kind: String = "CustomAtom".to_string();
let mut bonds: Vec<bond::Bond> = vec![];
let is_aromatic: bool = false;
let is_breaking_symmetry: bool = false;
let charge: usize = DEFAULT_CHARGE_HASH_VALUE;
// bonds construction
for idx in 0..edges_from.len() {
let edge_from = edges_from[idx];
let bonds_found: Vec<bond::Bond> = atoms[edge_from.0].bonds.clone().into_iter()
.filter(|b| b.tid == edge_from.1)
.collect();
if bonds_found.len() != 1 {
panic!("Create New Atom: cannot find bond for edges: {:?}\n bonds found: {:?}\n from atom bonds: {:?}", edges_from, bonds_found, atoms[edge_from.0].bonds);
}
let mut new_bond: bond::Bond = bonds_found[0].clone();
new_bond.set_kind_value(numbering, &(self_index, new_bond.tid));
new_bond.tid = edges_to[idx].1;
bonds.push(new_bond);
}
Self { kind, bonds, charge, atomic_number, is_aromatic, is_breaking_symmetry }
}
fn update_edges_in_reduced_graph(&mut self,
self_index: usize,
reduced_groups: &std::collections::HashMap<usize, usize>,
numbering: &Vec<usize>
) {
for bond in self.bonds.iter_mut() {
match reduced_groups.get(&bond.tid) {
Some(&target_index) => {
bond.set_kind_value(numbering, &(self_index, bond.tid));
bond.tid = target_index;
},
None => ()
}
}
}
fn custom_new_in_separated_graph(
atomic_number: usize,
vertex: usize,
valid_neighbours: &Vec<usize>,
atoms: &Vec<Atom>
) -> Self {
let kind: String = "CustomAtom".to_string();
let is_aromatic: bool = false;
let is_breaking_symmetry: bool = false;
let bonds: Vec<bond::Bond> = atoms[vertex].bonds.clone().into_iter()
.filter(|b| valid_neighbours.contains(&b.tid))
.collect();
let charge: usize = DEFAULT_CHARGE_HASH_VALUE;
Self { kind, bonds, charge, atomic_number, is_aromatic, is_breaking_symmetry }
}
fn custom_new_in_folded_graph(
atomic_number: usize,
boundary_edge: &(usize, usize),
atoms: &Vec<Atom>
) -> Self {
let kind: String = "CustomAtom".to_string();
let bonds: Vec<bond::Bond> = atoms[boundary_edge.1].bonds.clone().into_iter()
.filter(|b| b.tid == boundary_edge.0)
.collect();
let is_aromatic: bool = false;
let is_breaking_symmetry: bool = false;
let charge: usize = DEFAULT_CHARGE_HASH_VALUE;
Self { kind, bonds, charge, atomic_number, is_aromatic, is_breaking_symmetry }
}
fn debug_print(&self) {
println!("Atomic number: {}, Bonds: {:?}", self.atomic_number, self.bonds);
}
}
#[cfg(test)]
mod test_ext_mol_atom {
use super::*;
use crate::core::graph::*;
use crate::ext::molecule::molecule;
#[test]
fn test_atom_fixed_hash_value() {
let mol = molecule::Molecule::from_smiles("c1ccccc1CN");
assert_eq!(mol.atoms[0].fixed_hash_value(), 100210060);
assert_eq!(mol.atoms[5].fixed_hash_value(), 100310060);
assert_eq!(mol.atoms[6].fixed_hash_value(), 100200060);
}
#[test]
fn test_break_symmetry() {
let mut mol = molecule::Molecule::from_smiles("c1ccccc1CN");
mol.atoms[6].break_symmetry_vertex();
assert_eq!(mol.atoms[6].fixed_hash_value(), 100200061);
mol.atoms[6].break_symmetry_edge(7);
assert_eq!(mol.atoms[6].bonds[0].fixed_hash_value(), 10);
assert_eq!(mol.atoms[6].bonds[1].fixed_hash_value(), 11);
}
#[test]
fn test_custom_new_in_reduce_graph() {
let mol = molecule::Molecule::from_smiles("c1ccccc1CN");
let new_custom = Atom::custom_new_in_reduced_graph(0, 200, &vec![(6, 7)], &vec![(1, 2)], &mol.atoms, &vec![0;8]);
assert_eq!(new_custom.kind, "CustomAtom".to_string());
assert_eq!(new_custom.bonds.len(), 1);
assert_eq!(new_custom.bonds[0].tid, 2);
}
#[test]
fn test_custom_new_in_folded_graph() {
let mol = molecule::Molecule::from_smiles("c1ccccc1CN");
let new_custom = Atom::custom_new_in_folded_graph(200, &(5, 6), &mol.atoms);
assert_eq!(new_custom.kind, "CustomAtom".to_string());
assert_eq!(new_custom.bonds.len(), 1);
assert_eq!(new_custom.bonds[0].tid, 5);
}
#[test]
fn test_update_edges_in_reduced_graph() {
// let mol = molecule::Molecule::from_smiles("c1cc2cccc3c4cccc5cccc(c(c1)c23)c54"); // 2065990
// let new_custom = Atom::custom_new_in_folded_graph(200, &(5, 6), &mol.atoms);
// unimplemented!();
// TBI
}
#[test]
fn test_charge() {
type InputType1 = String;
type InputType2 = usize;
type ReturnType = usize;
let test_data: Vec<(InputType1, InputType2, ReturnType)> = vec![
("c1ccc2cc3ccccc3cc2c1", 1, DEFAULT_CHARGE_HASH_VALUE),
("c1[c+]cc2cc3ccccc3cc2c1", 1, 201),
("c1[n-]cc2cc3ccccc3cc2c1", 1, 1),
].iter().map(|td| (td.0.to_string(), td.1.clone(), td.2.clone())).collect();
for td in test_data.iter() {
let (smiles, vertex_index, charge_hash_value) = td;
let mol = molecule::Molecule::from_smiles(&smiles);
assert_eq!(mol.atoms[*vertex_index].charge, *charge_hash_value);
}
}
} |
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Start generation of key-stream. This operation will stop by itself when completed."]
pub tasks_ksgen: TASKS_KSGEN,
#[doc = "0x04 - Start encryption/decryption. This operation will stop by itself when completed."]
pub tasks_crypt: TASKS_CRYPT,
#[doc = "0x08 - Stop encryption/decryption"]
pub tasks_stop: TASKS_STOP,
#[doc = "0x0c - Override DATARATE setting in MODE register with the contents of the RATEOVERRIDE register for any ongoing encryption/decryption"]
pub tasks_rateoverride: TASKS_RATEOVERRIDE,
_reserved4: [u8; 240usize],
#[doc = "0x100 - Key-stream generation complete"]
pub events_endksgen: EVENTS_ENDKSGEN,
#[doc = "0x104 - Encrypt/decrypt complete"]
pub events_endcrypt: EVENTS_ENDCRYPT,
#[doc = "0x108 - Deprecated register - CCM error event"]
pub events_error: EVENTS_ERROR,
_reserved7: [u8; 244usize],
#[doc = "0x200 - Shortcut register"]
pub shorts: SHORTS,
_reserved8: [u8; 256usize],
#[doc = "0x304 - Enable interrupt"]
pub intenset: INTENSET,
#[doc = "0x308 - Disable interrupt"]
pub intenclr: INTENCLR,
_reserved10: [u8; 244usize],
#[doc = "0x400 - MIC check result"]
pub micstatus: MICSTATUS,
_reserved11: [u8; 252usize],
#[doc = "0x500 - Enable"]
pub enable: ENABLE,
#[doc = "0x504 - Operation mode"]
pub mode: MODE,
#[doc = "0x508 - Pointer to data structure holding AES key and NONCE vector"]
pub cnfptr: CNFPTR,
#[doc = "0x50c - Input pointer"]
pub inptr: INPTR,
#[doc = "0x510 - Output pointer"]
pub outptr: OUTPTR,
#[doc = "0x514 - Pointer to data area used for temporary storage"]
pub scratchptr: SCRATCHPTR,
#[doc = "0x518 - Length of key-stream generated when MODE.LENGTH = Extended."]
pub maxpacketsize: MAXPACKETSIZE,
#[doc = "0x51c - Data rate override setting."]
pub rateoverride: RATEOVERRIDE,
}
#[doc = "Start generation of key-stream. This operation will stop by itself when completed."]
pub struct TASKS_KSGEN {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start generation of key-stream. This operation will stop by itself when completed."]
pub mod tasks_ksgen;
#[doc = "Start encryption/decryption. This operation will stop by itself when completed."]
pub struct TASKS_CRYPT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start encryption/decryption. This operation will stop by itself when completed."]
pub mod tasks_crypt;
#[doc = "Stop encryption/decryption"]
pub struct TASKS_STOP {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Stop encryption/decryption"]
pub mod tasks_stop;
#[doc = "Override DATARATE setting in MODE register with the contents of the RATEOVERRIDE register for any ongoing encryption/decryption"]
pub struct TASKS_RATEOVERRIDE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Override DATARATE setting in MODE register with the contents of the RATEOVERRIDE register for any ongoing encryption/decryption"]
pub mod tasks_rateoverride;
#[doc = "Key-stream generation complete"]
pub struct EVENTS_ENDKSGEN {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Key-stream generation complete"]
pub mod events_endksgen;
#[doc = "Encrypt/decrypt complete"]
pub struct EVENTS_ENDCRYPT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Encrypt/decrypt complete"]
pub mod events_endcrypt;
#[doc = "Deprecated register - CCM error event"]
pub struct EVENTS_ERROR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Deprecated register - CCM error event"]
pub mod events_error;
#[doc = "Shortcut register"]
pub struct SHORTS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Shortcut register"]
pub mod shorts;
#[doc = "Enable interrupt"]
pub struct INTENSET {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Enable interrupt"]
pub mod intenset;
#[doc = "Disable interrupt"]
pub struct INTENCLR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Disable interrupt"]
pub mod intenclr;
#[doc = "MIC check result"]
pub struct MICSTATUS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MIC check result"]
pub mod micstatus;
#[doc = "Enable"]
pub struct ENABLE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Enable"]
pub mod enable;
#[doc = "Operation mode"]
pub struct MODE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Operation mode"]
pub mod mode;
#[doc = "Pointer to data structure holding AES key and NONCE vector"]
pub struct CNFPTR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Pointer to data structure holding AES key and NONCE vector"]
pub mod cnfptr;
#[doc = "Input pointer"]
pub struct INPTR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Input pointer"]
pub mod inptr;
#[doc = "Output pointer"]
pub struct OUTPTR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Output pointer"]
pub mod outptr;
#[doc = "Pointer to data area used for temporary storage"]
pub struct SCRATCHPTR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Pointer to data area used for temporary storage"]
pub mod scratchptr;
#[doc = "Length of key-stream generated when MODE.LENGTH = Extended."]
pub struct MAXPACKETSIZE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Length of key-stream generated when MODE.LENGTH = Extended."]
pub mod maxpacketsize;
#[doc = "Data rate override setting."]
pub struct RATEOVERRIDE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Data rate override setting."]
pub mod rateoverride;
|
extern crate phf_codegen;
extern crate unicase;
use phf_codegen::Map as PhfMap;
use unicase::UniCase;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufWriter;
use std::path::Path;
use std::env;
use std::collections::BTreeMap;
use mime_types::MIME_TYPES;
#[path="src/mime_types.rs"]
mod mime_types;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("mime_types_generated.rs");
let mut outfile = BufWriter::new(File::create(dest_path).unwrap());
build_forward_map(&mut outfile);
build_rev_map(&mut outfile);
}
// Build forward mappings (ext -> mime type)
fn build_forward_map<W: Write>(out: &mut W) {
write!(out, "static MIME_TYPES: phf::Map<UniCase<&'static str>, &'static str> = ").unwrap();
let mut forward_map = PhfMap::new();
for &(key, val) in MIME_TYPES {
forward_map.entry(UniCase(key), &format!("{:?}", val));
}
forward_map.build(out).unwrap();
writeln!(out, ";").unwrap();
}
// Build reverse mappings (mime type -> ext)
fn build_rev_map<W: Write>(out: &mut W) {
// First, collect all the mime type -> ext mappings)
let mut dyn_map = BTreeMap::new();
for &(key, val) in MIME_TYPES {
let (top, sub) = split_mime(val);
dyn_map.entry(UniCase(top))
.or_insert_with(BTreeMap::new)
.entry(UniCase(sub))
.or_insert_with(Vec::new)
.push(key);
}
write!(out, "static REV_MAPPINGS: phf::Map<UniCase<&'static str>, TopLevelExts> = ").unwrap();
let mut rev_map = PhfMap::new();
let mut exts = Vec::new();
for (top, subs) in dyn_map {
let top_start = exts.len();
let mut sub_map = PhfMap::new();
for(sub, sub_exts) in subs {
let sub_start = exts.len();
exts.extend(sub_exts);
let sub_end = exts.len();
sub_map.entry(sub, &format!("({}, {})", sub_start, sub_end));
}
let top_end = exts.len();
let mut subs_bytes = Vec::<u8>::new();
sub_map.build(&mut subs_bytes).unwrap();
let subs_str = ::std::str::from_utf8(&subs_bytes).unwrap();
rev_map.entry(
top,
&format!("TopLevelExts {{ start: {}, end: {}, subs: {} }}", top_start, top_end, subs_str)
);
}
rev_map.build(out).unwrap();
writeln!(out, ";").unwrap();
writeln!(out, "const EXTS: &'static [&'static str] = &{:?};", exts).unwrap();
}
fn split_mime(mime: &str) -> (&str, &str) {
let split_idx = mime.find('/').unwrap();
(&mime[..split_idx], &mime[split_idx + 1 ..])
}
|
extern crate clap;
extern crate dirs;
use std::error::Error;
use std::fs::File;
use std::process;
use std::io::prelude::*;
use std::process::Command;
use std::os::unix::process::CommandExt;
pub fn run(args: clap::ArgMatches) -> Result<(), Box<dyn Error>> {
// .gdbs, .gbdibit ใธใฎใใน
let mut path_to_gdbs = dirs::home_dir().unwrap();
path_to_gdbs.push(".gdbs");
let mut path_to_gdbinit = dirs::home_dir().unwrap();
path_to_gdbinit.push(".gdbinit");
let gdb_type = gdb_type_check(&args);
// .gdbs ใฎ่ชญใฟ่พผใฟ
let mut f = File::open(&path_to_gdbs)?;
let mut contents = String::new();
f.read_to_string(&mut contents)?;
// source gdb
let source_path = search(&gdb_type, &contents);
// .gdbinit ใๆธใๆใใ
let mut f = File::create(path_to_gdbinit)?;
writeln!(f, "{}", source_path)?;
// -i ใง่งฃๆใใใfileใๅผๆฐใซๅใฃใใจใใฏgdbใ่ตทๅใใ
if let Some(o) = args.value_of("filename") {
run_gdb(o.to_string());
};
Ok(())
}
fn gdb_type_check(args: &clap::ArgMatches) -> String {
// ๆกไปถใซใใฃใใใใฎgdbใฎ็จฎ้กใ่ฟใ
let mut gdb_type = String::new();
if let Some(arg) = args.value_of("type") {
gdb_type = arg.to_string();
gdb_type = match &*gdb_type {
"p" | "peda" | "gdb-peda" => "peda".to_string(),
"g" | "gef" => "gef".to_string(),
"d" | "dbg" | "pwndbg" => "pwndbg".to_string(),
_ => {
eprintln!("Argument error: No such argument");
process::exit(1);
}
};
};
gdb_type
}
fn search(gdb_type: &str, contents: &str) -> String {
let mut source_path = String::new();
// .gdbsใใgdbใฎ็จฎ้กใฎไธ่ดใใใฎใ่ฟใ
for line in contents.lines() {
if line.contains(gdb_type) {
source_path = line.to_string()
}
}
source_path
}
fn run_gdb(filename: String) {
// gdb -q ./filename
let _ = Command::new("gdb")
.arg("-q")
.arg(filename)
.exec();
} |
use super::*;
use rand::{thread_rng, Rng};
use display::{Display, DisplayWeapon};
use inflector::Inflector;
use rustache::*;
use std::io::Cursor;
pub enum Results {
Begin { log: String },
Round { log: String },
End {
log: String,
winner: CombatantId,
duration: i32,
},
}
/// The results builder liberally refers to a and b. A is the player, B is the
/// opponent.
pub struct ResultsBuilder<'a, T, U> where T: Combatant, U: Combatant, T: 'a, U: 'a {
template_log: String,
data: HashBuilder<'a>,
a: &'a T,
b: &'a U,
}
impl<'a, T, U> ResultsBuilder<'a, T, U> where T: Combatant, U: Combatant {
// Constructor, include only that what is always needed or always available.
pub fn new(a: &'a T, b: &'a U) -> ResultsBuilder<'a, T, U> {
let a_weapon = a.best_weapon();
let b_weapon = b.best_weapon();
let str_builder = HashBuilder::new()
.insert("a_name", a.name())
.insert("b_name", b.name())
.insert("a_weapon", a_weapon.name())
.insert("a_weapon_action", a_weapon.display_offensive_action_1st())
.insert("b_weapon", b_weapon.name())
.insert("b_weapon_action", b_weapon.display_offensive_action_2nd());
ResultsBuilder {
template_log: String::new(),
data: str_builder,
a, b
}
}
// Builder functions (finalizers)
pub fn build_begin(mut self) -> Results {
// The begin always looks the same, set the log to that.
self.template_log = BEGIN.to_owned();
Results::Begin { log: self.fill_template() }
}
pub fn build_round(self) -> Results {
Results::Round { log: self.fill_template() }
}
pub fn build_end(self, winner: CombatantId, duration: i32) -> Results {
Results::End {
log: self.fill_template(),
winner: winner,
duration: duration,
}
}
/// Fills in the variables into the template.
fn fill_template(&self) -> String {
let mut out = Cursor::new(Vec::new());
self.data.render(&self.template_log, &mut out).unwrap();
String::from_utf8(out.into_inner()).unwrap()
}
pub fn write_round(mut self, a_outcomes: &Vec<Outcome>, b_outcomes: &Vec<Outcome>) -> ResultsBuilder<'a, T, U> {
let (mut sentences, a_killed, b_killed) = ResultsBuilder::<T, U>::outcome_sentences(a_outcomes, b_outcomes);
// Randomize the order of sentences
{
let slice: &mut [String] = sentences.as_mut_slice();
thread_rng().shuffle(slice);
}
// Add the kill sentence to the end
if let Some(s) = ResultsBuilder::<T, U>::kill_sentence(a_killed, b_killed) {
sentences.push(s);
}
self.template_log.push_str(&sentences.join(" "));
self
}
// Internals
fn outcome_sentences(a_outcomes: &Vec<Outcome>, b_outcomes: &Vec<Outcome>) -> (Vec<String>, bool, bool) {
let mut sentences = Vec::with_capacity(a_outcomes.len() + b_outcomes.len());
let mut a_killed = false;
for outcome in a_outcomes {
match *outcome {
Outcome::Miss => {
sentences.push(THEY_MISS.to_owned());
},
Outcome::Hit(_) => {
sentences.push(THEY_HIT.to_owned());
},
Outcome::Killed => {
a_killed = true;
break;
}
}
}
let mut b_killed = false;
for outcome in b_outcomes {
match *outcome {
Outcome::Miss => {
sentences.push(YOU_MISS.to_owned());
},
Outcome::Hit(_) => {
sentences.push(YOU_HIT.to_owned());
},
Outcome::Killed => {
b_killed = true;
break;
}
}
}
(sentences, a_killed, b_killed)
}
fn kill_sentence(a_killed: bool, b_killed: bool) -> Option<String> {
match (a_killed, b_killed) {
(true, true) =>
Some(BOTH_KILL.to_owned()),
(true, false) =>
Some(THEY_KILL.to_owned()),
(false, true) =>
Some(YOU_KILL.to_owned()),
_ => None,
}
}
}
static BEGIN: &str = "The {{b_name}} notices you and attacks.";
static YOU_MISS: &str = "You attempt to {{a_weapon_action}} the {{b_name}} with the {{a_weapon}} but \
miss.";
static THEY_MISS: &str = "The {{b_name}} attempts to {{b_weapon_action}} you with a {{b_weapon}} but \
misses.";
static YOU_HIT: &str = "You {{a_weapon_action}} the {{b_name}} with the {{a_weapon}}, wounding it.";
static THEY_HIT: &str = "The {{b_name}} {{b_weapon_action}} you with a {{b_weapon}}, wounding you.";
static YOU_KILL: &str = "You {{a_weapon_action}} the {{b_name}} with the {{a_weapon}} until you are \
certain that you are the only living thing in the room. You are safe now.";
static THEY_KILL: &str = "The {{b_name}} {{b_weapon_action}} you with their {{b_weapon}}, causing you \
to feel lightheaded. You suddenly lose consciousness. You die.";
static BOTH_KILL: &str = "The {{b_name}} {{b_weapon_action}} you with their {{b_weapon}}, causing you \
to feel lightheaded. You {{a_weapon_action}} the {{b_name}} with the \
{{a_weapon}}, causing yet another untimely death. Soon after the \
{{b_name}}'s death you suddenly collapse. Despite your best efforts, you \
are unable to stop the hemorrhaging and quickly (try to) make peace with \
your god.";
/*
## Example (25.8.-17)
BEGIN
The goblin notices you and attacks.
YOU_MISS / THEY_MISS
You attempt to bash the goblin with the stick but miss. The goblin attempts
to hit you with a fist but misses.
YOU_HIT / THEY_HIT
You bash the goblin with the stick, wounding them. The goblin hits you with a
fist, wounding you.
YOU_KILL
<goblin hits>. You bash the goblin with the stick until you are certain that
you are the only living thing in the room. You are safe now.
THEY_KILL
<player hits>. The goblin hits you with their fist, causing you to feel
lightheaded. You suddenly lose consciousness. You die.
BOTH_KILL
The goblin hits you with their fist, causing you to feel lightheaded. You bash
the goblin with the stick, causing yet another untimely death. Soon after the
goblin's death you suddenly collapse. Despite your best attempts, you are
unable to stop the hemorrhaging and quickly (try to) make peace with your god.
*/
/*
## Notes
the -> definite article
randomize the order of sentences per round, unless a party has died
### Flow
Begin -> N x Round -> End
Begin: 1 sentence
Round: N + M sentences, O variants each (N,M <= number of actions per entity)
End:
*/
|
pub struct ModelTexture {
texture_id: u32,
}
impl ModelTexture {
pub fn new(texture_id: u32) -> ModelTexture {
ModelTexture { texture_id }
}
pub fn get_texture_id(&self) -> &u32 {
&self.texture_id
}
}
|
use regex::Regex;
use std::error::Error;
use std::io::Read;
use std::fs::File;
fn inc(lights: &mut [[u16; 1000]; 1000], amount: u16, x1: usize, x2: usize, y1: usize, y2: usize) {
for x in x1..(x2+1) {
for y in y1..(y2+1) {
lights[x][y] += amount;
}
}
}
fn dec(lights: &mut [[u16; 1000]; 1000], amount: u16, x1: usize, x2: usize, y1: usize, y2: usize) {
for x in x1..(x2+1) {
for y in y1..(y2+1) {
if lights[x][y] > amount {
lights[x][y] -= amount;
}
else {
lights[x][y] = 0;
}
}
}
}
fn count(lights: &[[u16; 1000]; 1000]) -> u32 {
let mut n: u32 = 0;
for x in 0..1000 {
for y in 0..1000 {
n += lights[x][y] as u32;
}
}
return n;
}
pub fn part2() {
let re = Regex::new(r"(?m)^(?P<instruction>turn on|turn off|toggle)\s(?P<x1>\d+),(?P<y1>\d+)\sthrough\s(?P<x2>\d+),(?P<y2>\d+)$").unwrap();
let mut lights = [[0u16; 1000]; 1000];
let mut file = match File::open("input.txt") {
Err(why) => panic!("couldn't open input: {}", Error::description(&why)),
Ok(file) => file,
};
let mut instructions = String::new();
match file.read_to_string(&mut instructions) {
Err(why) => panic!("couldn't read input: {}", Error::description(&why)),
Ok(_) => (),
}
for cap in re.captures_iter(&instructions) {
let x1 = cap.name("x1").unwrap().parse::<usize>().unwrap();
let x2 = cap.name("x2").unwrap().parse::<usize>().unwrap();
let y1 = cap.name("y1").unwrap().parse::<usize>().unwrap();
let y2 = cap.name("y2").unwrap().parse::<usize>().unwrap();
match cap.name("instruction").unwrap() {
"toggle" => inc(&mut lights, 2, x1, x2, y1, y2),
"turn on" => inc(&mut lights, 1, x1, x2, y1, y2),
"turn off" => dec(&mut lights, 1, x1, x2, y1, y2),
_ => (),
}
}
println!("After following Santa's instructions the total brightness will be {}", count(&lights));
}
|
use std::time::Duration;
use anyhow::Result;
use bytes::Bytes;
use lfan::preconfig::concurrent::{new_ttl_cache, TTLLRUCache};
use menmos_client::{Client, Meta, Query, QueryResponse};
static META_TTL: Duration = Duration::from_secs(30 * 60); // 30 min.
static QUERY_TTL: Duration = Duration::from_secs(30);
pub struct CachedClient {
client: Client,
meta_cache: TTLLRUCache<String, Option<Meta>>,
query_cache: TTLLRUCache<Query, QueryResponse>,
}
impl CachedClient {
pub fn new(client: Client) -> Self {
Self {
client,
meta_cache: new_ttl_cache(10000, META_TTL),
query_cache: new_ttl_cache(50, QUERY_TTL),
}
}
pub async fn get_meta(&self, blob_id: &str) -> Result<Option<Meta>> {
match self.meta_cache.get(blob_id).await {
Some(meta_maybe) => Ok(meta_maybe),
None => {
let meta_maybe = self.client.get_meta(blob_id).await?;
self.meta_cache
.insert(String::from(blob_id), meta_maybe.clone())
.await;
Ok(meta_maybe)
}
}
}
pub async fn query(&self, query: Query) -> Result<QueryResponse> {
let query_response = {
match self.query_cache.get(&query).await {
Some(query_response) => query_response,
None => {
let response = self.client.query(query.clone()).await?;
self.query_cache.insert(query, response.clone()).await;
response
}
}
};
// Since query results come with the blob meta, we can insert each blob's meta in the cache directly, making subsequent individual file lookups
// much faster.
self.meta_cache
.batch_insert(
query_response
.hits
.iter()
.map(|hit| (hit.id.clone(), Some(hit.meta.clone()))),
)
.await;
Ok(query_response)
}
pub async fn read_range(&self, blob_id: &str, range: (u64, u64)) -> Result<Vec<u8>> {
// Not cached for now.
Ok(self.client.read_range(blob_id, range).await?)
}
pub async fn create_empty(&self, meta: Meta) -> Result<String> {
self.query_cache.clear().await;
Ok(self.client.create_empty(meta).await?)
}
pub async fn write(&self, blob_id: &str, offset: u64, buffer: Bytes) -> Result<()> {
self.meta_cache.clear().await;
Ok(self.client.write(blob_id, offset, buffer).await?)
}
pub async fn update_meta(&self, blob_id: &str, meta: Meta) -> Result<()> {
self.query_cache.clear().await;
self.client.update_meta(blob_id, meta).await?;
Ok(())
}
pub async fn fsync(&self, blob_id: &str) -> Result<()> {
self.client.fsync(blob_id).await?;
Ok(())
}
pub async fn delete(&self, blob_id: String) -> Result<()> {
// a delete is obviously not cached, but it _does_ invalidate our query cache.
self.query_cache.clear().await;
Ok(self.client.delete(blob_id).await?)
}
}
|
use crate::core::colors::RgbaColor;
use crate::render::ui::gui::{HorizontalAlign, VerticalAlign};
use crate::render::ui::text::Text;
use crate::render::ui::{DrawData, Gui, Panel};
use glfw::MouseButton;
pub struct Button {
/// Text of the button
text: String,
/// dimension of the button. If none, will use enough space for the text
dimensions: Option<glam::Vec2>,
/// top-left corner for the button
anchor: glam::Vec2,
/// Override default style
text_color: Option<RgbaColor>,
hover_text_color: Option<RgbaColor>,
background_color: Option<RgbaColor>,
hover_background_color: Option<RgbaColor>,
font_size: Option<f32>,
text_align: Option<(HorizontalAlign, VerticalAlign)>,
padding: Option<f32>,
}
impl Button {
pub fn new(text: String, position: glam::Vec2) -> Self {
Self {
text,
dimensions: None,
anchor: position,
text_color: None,
hover_text_color: None,
background_color: None,
hover_background_color: None,
font_size: None,
text_align: None,
padding: None,
}
}
pub fn dimensions(mut self, dim: glam::Vec2) -> Self {
self.dimensions = Some(dim);
self
}
pub fn set_font_size(mut self, size: f32) -> Self {
self.font_size = Some(size);
self
}
pub fn set_bg_color(mut self, color: RgbaColor, hover_color: RgbaColor) -> Self {
self.background_color = Some(color);
self.hover_background_color = Some(hover_color);
self
}
pub fn set_text_color(mut self, color: RgbaColor, hover_color: RgbaColor) -> Self {
self.text_color = Some(color);
self.hover_text_color = Some(hover_color);
self
}
pub fn set_text_align(
mut self,
horizontal_align: HorizontalAlign,
vertical_align: VerticalAlign,
) -> Self {
self.text_align = Some((horizontal_align, vertical_align));
self
}
pub fn set_padding(mut self, padding: f32) -> Self {
self.padding = Some(padding);
self
}
fn text_color(&self, ui: &Gui, is_above: bool) -> RgbaColor {
if is_above {
self.hover_text_color
.unwrap_or(ui.style.button_hovered_text_color)
} else {
self.text_color.unwrap_or(ui.style.button_text_color)
}
}
fn background_color(&self, ui: &Gui, is_above: bool) -> RgbaColor {
if is_above {
self.hover_background_color
.unwrap_or(ui.style.button_hover_bg_color)
} else {
self.background_color.unwrap_or(ui.style.button_bg_color)
}
}
pub fn build(self, ui: &mut Gui) -> bool {
//let padding = self.padding.unwrap_or(10.0);
let font_size = self.font_size.unwrap_or(ui.style.font_size);
let text_position = self.anchor; // + glam::Vec2::unit_y() * font_size;
let text_align = self.text_align.unwrap_or(ui.style.button_text_align);
let dimensions = if let Some(dimension) = self.dimensions {
dimension
} else {
ui.text_bounds(self.text.as_str(), font_size)
};
let mouse_pos_rel = ui.mouse_pos - self.anchor;
let is_above = mouse_pos_rel.x >= 0.0
&& mouse_pos_rel.x < dimensions.x
&& mouse_pos_rel.y >= 0.0
&& mouse_pos_rel.y <= dimensions.y;
let color = self.background_color(ui, is_above);
let text_color = self.text_color(ui, is_above);
let (vertices, indices) = Panel {
anchor: self.anchor,
dimensions,
color,
}
.vertices(ui.window_dim);
ui.draw_data.push(DrawData::Vertices(vertices, indices));
//let horizontal_align = self.text_align.unwrap_or(ui.style.button_text_align).0;
ui.draw_data.push(DrawData::Text(
Text {
content: self.text,
font_size,
color: text_color,
align: text_align,
},
text_position,
));
if ui.mouse_clicked.contains(&MouseButton::Button1) {
return is_above;
}
false
}
}
|
use diesel::{self, prelude::*};
use rocket_contrib::json::Json;
use crate::atividades_administrativas_model::{
AtividadesAdministrativas, InsertableAtividadeAdministrativa,
};
use crate::schema;
use crate::DbConn;
#[post(
"/atividades_administrativas/<id_professor>",
data = "<atividades_administrativas>"
)]
pub fn create_atividades_administrativas(
conn: DbConn,
atividades_administrativas: Json<Vec<InsertableAtividadeAdministrativa>>,
id_professor: i32,
) -> Result<String, String> {
match delete_atividades_administrativas(id_professor, &conn) {
Ok(_) => println!("OK"),
Err(_) => println!("Error"),
};
let inserted_rows = diesel::insert_into(schema::atividades_administrativas::table)
.values(&atividades_administrativas.0)
.execute(&conn.0)
.map_err(|err| -> String {
println!("Error inserting row: {:?}", err);
"Error inserting row into database".into()
})?;
Ok(format!("Inserted {} row(s).", inserted_rows))
}
#[get("/atividades_administrativas/<id_professor>")]
pub fn read_atividades_administrativas(
id_professor: i32,
conn: DbConn,
) -> Result<Json<Vec<AtividadesAdministrativas>>, String> {
schema::atividades_administrativas::table
.filter(schema::atividades_administrativas::id_professor.eq(id_professor))
.load(&conn.0)
.map_err(|err| -> String {
println!("Error querying atividades_administrativas: {:?}", err);
"Error querying atividades_administrativas from the database".into()
})
.map(Json)
}
pub fn delete_atividades_administrativas(
id_professor: i32,
conn: &DbConn,
) -> Result<String, String> {
let deleted_rows = diesel::delete(
schema::atividades_administrativas::table
.filter(schema::atividades_administrativas::id_professor.eq(id_professor)),
)
.execute(&conn.0)
.map_err(|err| -> String {
println!("Error deleting row: {:?}", err);
"Error deleting row into database".into()
})?;
Ok(format!("Deleted {} row(s).", deleted_rows))
}
|
#![feature(test)]
extern crate test;
#[cfg(test)]
mod tests {
fn is_square_number(num: usize) -> bool {
(num as f64).sqrt().fract() == 0.0
}
fn is_square_number_cast(num: usize) -> bool {
let sqrt = (num as f64).sqrt() as usize;
(sqrt * sqrt) == num
}
use rand::prelude::*;
use test::{black_box, Bencher};
#[bench]
fn bench_fract(b: &mut Bencher) {
let mut rng = rand::thread_rng();
b.iter(|| {
for _ in 2..20_000 {
let num = rng.gen::<u32>() as usize;
black_box(is_square_number(num));
}
})
}
#[bench]
fn bench_cast(b: &mut Bencher) {
let mut rng = rand::thread_rng();
b.iter(|| {
for _ in 2..20_000 {
let num = rng.gen::<u32>() as usize;
black_box(is_square_number_cast(num));
}
})
}
}
|
use super::{Op, Span, SyntaxError};
use crate::index::*;
use std::str;
define_index_type! {
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Ident(usize);
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Token {
EOF,
KwLoc,
KwProc,
KwReg,
KwRun,
KwIf,
KwLoop,
KwElse,
KwReturn,
KwBreak,
KwIgnore,
KwRead,
KwWrite,
KwUpdate,
KwAcq,
KwRel,
KwSc,
Ident(Ident),
Int(i64),
Op(Op),
Assign,
From,
Lparen,
Rparen,
Lbracket,
Rbracket,
Lbrace,
Rbrace,
Comma,
Semi,
Error,
}
pub struct Lexer<'a> {
code: &'a [u8],
off: usize,
itab: ISet<Ident, Box<[u8]>>,
errors: Vec<SyntaxError>,
}
const KEYWORDS: [(Token, &str); 16] = [
(Token::KwLoc, "loc"),
(Token::KwProc, "proc"),
(Token::KwReg, "reg"),
(Token::KwRun, "run"),
(Token::KwIf, "if"),
(Token::KwLoop, "loop"),
(Token::KwElse, "else"),
(Token::KwReturn, "return"),
(Token::KwBreak, "break"),
(Token::KwIgnore, "ignore"),
(Token::KwRead, "read"),
(Token::KwWrite, "write"),
(Token::KwUpdate, "update"),
(Token::KwAcq, "acq"),
(Token::KwRel, "rel"),
(Token::KwSc, "sc"),
];
impl<'a> Lexer<'a> {
#[inline]
pub fn new(code: &'a [u8]) -> Self {
let mut r = Lexer {
code,
off: 0,
itab: ISet::new(),
errors: Vec::new(),
};
for (i, (_, name)) in KEYWORDS.iter().cloned().enumerate() {
assert_eq!(r.itab.insert(Box::from(name.as_bytes())), Ident(i));
}
r
}
pub fn ident(&self, i: Ident) -> &str {
str::from_utf8(self.itab.at(i)).unwrap()
}
#[inline]
fn skip_spaces(&mut self) {
let n = find_not(self.code, is_space);
self.off += n;
self.code = &self.code[n..];
}
#[inline]
fn read_word<C: Fn(u8) -> bool>(&mut self, cond: C) -> &'a [u8] {
let n = find_not(self.code, cond);
assert!(n > 0);
self.off += n;
let (w, rest) = self.code.split_at(n);
self.code = rest;
w
}
pub fn errors(&mut self) -> &mut Vec<SyntaxError> {
&mut self.errors
}
pub fn into_errors(self) -> Vec<SyntaxError> {
self.errors
}
fn error(&mut self, off0: usize, msg: &'static str) {
self.errors.push(SyntaxError {
span: Span(off0, self.off - 1),
msg,
})
}
#[inline]
pub fn next(&mut self) -> (Token, Span) {
self.skip_spaces();
let off0 = self.off;
let c0 = match self.code.first() {
Some(v) => *v,
None => return (Token::EOF, Span(off0, off0)),
};
let tok = if is_ident(c0) {
let w = self.read_word(is_ident);
if is_decimal(w[0]) {
let w = std::str::from_utf8(w).unwrap();
match i64::from_str_radix(w, 10) {
Ok(i) => Token::Int(i),
Err(_) => {
self.error(off0, "not a base-10 integer");
Token::Error
}
}
} else {
match self.itab.entry(w) {
ISetEntry::Occupied(e) => {
let i = e.index();
let ii = i.as_usize();
if ii < KEYWORDS.len() {
KEYWORDS[ii].0
} else {
Token::Ident(i)
}
}
ISetEntry::Vacant(e) => Token::Ident(e.insert(Box::from(w)).index()),
}
}
} else if is_op(c0) {
match self.read_word(is_op) {
b"+" => Token::Op(Op::Add),
b"-" => Token::Op(Op::Sub),
b"*" => Token::Op(Op::Mul),
b"/" => Token::Op(Op::Div),
b"%" => Token::Op(Op::Mod),
b"==" => Token::Op(Op::Eq),
b"!=" => Token::Op(Op::Ne),
b"<" => Token::Op(Op::Lt),
b"<=" => Token::Op(Op::Le),
b">" => Token::Op(Op::Gt),
b">=" => Token::Op(Op::Ge),
b"&&" => Token::Op(Op::LogicalAnd),
b"||" => Token::Op(Op::LogicalOr),
b"!" => Token::Op(Op::LogicalNot),
b"=" => Token::Assign,
b"<-" => Token::From,
_ => {
self.error(off0, "unknown operator");
Token::Error
}
}
} else {
self.off += 1;
self.code = &self.code[1..];
match c0 {
b'(' => Token::Lparen,
b')' => Token::Rparen,
b'[' => Token::Lbracket,
b']' => Token::Rbracket,
b'{' => Token::Lbrace,
b'}' => Token::Rbrace,
b',' => Token::Comma,
b';' => Token::Semi,
_ => {
self.error(off0, "unexpected character");
Token::Error
}
}
};
(tok, Span(off0, self.off - 1))
}
}
#[inline]
fn is_space(v: u8) -> bool {
v == b'\t' || v == b'\n' || v == b' '
}
#[inline]
fn is_ident(v: u8) -> bool {
v >= b'0' && v <= b'9' || v >= b'A' && v <= b'Z' || v == b'_' || v >= b'a' && v <= b'z'
}
#[inline]
fn is_decimal(v: u8) -> bool {
v >= b'0' && v <= b'9'
}
#[inline]
fn is_op(v: u8) -> bool {
match v {
b'!' | b'%' | b'&' | b'*' | b'+' | b'-' | b'/' | b'<' | b'=' | b'>' | b'|' => true,
_ => false,
}
}
#[inline]
fn find_not(v: &[u8], f: impl Fn(u8) -> bool) -> usize {
for (i, v) in v.iter().enumerate() {
if !f(*v) {
return i;
}
}
v.len()
}
#[test]
fn smoke() {
let mut l = Lexer::new(&b"word word_2 0 != ! = word 1234 (*"[..]);
assert_eq!(l.next().0, Token::Ident(Ident(KEYWORDS.len())));
assert_eq!(l.next().0, Token::Ident(Ident(KEYWORDS.len() + 1)));
assert_eq!(l.next().0, Token::Int(0));
assert_eq!(l.next().0, Token::Op(Op::Ne));
assert_eq!(l.next().0, Token::Op(Op::LogicalNot));
assert_eq!(l.next().0, Token::Assign);
assert_eq!(l.next().0, Token::Ident(Ident(KEYWORDS.len())));
assert_eq!(l.next().0, Token::Int(1234));
assert_eq!(l.next().0, Token::Lparen);
assert_eq!(l.next().0, Token::Op(Op::Mul));
assert_eq!(l.next().0, Token::EOF);
assert_eq!(l.next().0, Token::EOF);
}
#[test]
fn bad_ident() {
let mut l = Lexer::new(&b"1a"[..]);
assert_eq!(l.next(), (Token::Error, Span(0, 1)));
}
#[test]
fn unknown_op() {
let mut l = Lexer::new(&b"+ ==="[..]);
assert_eq!(l.next().0, Token::Op(Op::Add));
assert_eq!(l.next().0, Token::Error);
}
|
use std::mem;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt;
use std::str;
use std::slice;
use cql_bindgen::CASS_VALUE_TYPE_ASCII;
use cql_bindgen::CASS_VALUE_TYPE_VARCHAR;
use cql_bindgen::CASS_VALUE_TYPE_TEXT;
use cql_bindgen::CASS_OK;
use cql_bindgen::cass_value_get_int32;
use cql_bindgen::cass_value_get_int64;
use cql_bindgen::cass_value_get_float;
use cql_bindgen::cass_value_get_double;
use cql_bindgen::cass_value_get_bool;
use cql_bindgen::cass_value_get_uuid;
use cql_bindgen::cass_value_get_string;
use cql_bindgen::cass_value_get_inet;
use cql_bindgen::cass_iterator_from_map;
use cql_bindgen::cass_iterator_from_user_type;
use cql_bindgen::cass_iterator_from_collection;
use cql_bindgen::cass_value_type;
use cql_bindgen::CassValue as _CassValue;
use cql_ffi::uuid::CassUuid;
//use cql_ffi::udt::CassUserType;
use cql_ffi::value::CassValueType;
use cql_ffi::collection::set::SetIterator;
use cql_ffi::inet::CassInet;
use cql_ffi::collection::map::MapIterator;
use cql_ffi::udt::UserTypeIterator;
use cql_ffi::error::CassErrorTypes;
use cql_ffi::error::CassError;
#[repr(C)]
#[derive(Copy,Debug,Clone)]
pub enum CassColumnType {
PARTITION_KEY = 0,
CLUSTERING_KEY = 1,
REGULAR = 2,
COMPACT_VALUE = 3,
STATIC = 4,
UNKNOWN = 5,
}
pub struct CassColumn(pub *const _CassValue);
impl Debug for CassColumn {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.get_type() {
CassValueType::UNKNOWN => write!(f, "UNKNOWN Cassandra type"),
CassValueType::CUSTOM => write!(f, "CUSTOM Cassandra type"),
CassValueType::ASCII => write!(f, "ASCII Cassandra type"),
CassValueType::BIGINT => write!(f, "BIGINT Cassandra type"),
CassValueType::BLOB => write!(f, "BLOB Cassandra type"),
CassValueType::BOOLEAN => write!(f, "BOOLEAN Cassandra type"),
CassValueType::COUNTER => write!(f, "COUNTER Cassandra type"),
CassValueType::DECIMAL => write!(f, "DECIMAL Cassandra type"),
CassValueType::DOUBLE => write!(f, "DOUBLE Cassandra type"),
CassValueType::FLOAT => write!(f, "FLOAT Cassandra type"),
CassValueType::INT => write!(f, "INT Cassandra type"),
CassValueType::TEXT => write!(f, "TEXT Cassandra type"),
CassValueType::TIMESTAMP => write!(f, "TIMESTAMP Cassandra type"),
CassValueType::UUID => write!(f, "UUID Cassandra type"),
CassValueType::VARCHAR => write!(f, "VARCHAR: {:?}", self.get_string()),
CassValueType::VARINT => Ok(()),
CassValueType::TIMEUUID => write!(f, "TIMEUUID Cassandra type"),
CassValueType::INET => write!(f, "INET Cassandra type"),
CassValueType::LIST => {
for item in self.set_iter().unwrap() {
try!(write!(f, "LIST {:?}", item ))
}
Ok(())
}
CassValueType::MAP => {
for item in self.map_iter().unwrap() {
try!(write!(f, "LIST {:?}", item ))
}
Ok(())
}
CassValueType::SET => {
for item in self.set_iter().unwrap() {
try!(write!(f, "SET {:?}", item ))
}
Ok(())
}
CassValueType::UDT => write!(f, "UDT Cassandra type"),
CassValueType::TUPLE => write!(f, "Tuple Cassandra type"),
CassValueType::LASTENTRY => write!(f, "LAST_ENTRY Cassandra type"),
}
}
}
impl Display for CassColumn {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.get_type() {
CassValueType::UNKNOWN => write!(f, "UNKNOWN Cassandra type"),
CassValueType::CUSTOM => write!(f, "CUSTOM Cassandra type"),
CassValueType::ASCII => write!(f, "ASCII Cassandra type"),
CassValueType::BIGINT => write!(f, "BIGINT Cassandra type"),
CassValueType::BLOB => write!(f, "BLOB Cassandra type"),
CassValueType::BOOLEAN => write!(f, "BOOLEAN Cassandra type"),
CassValueType::COUNTER => write!(f, "COUNTER Cassandra type"),
CassValueType::DECIMAL => write!(f, "DECIMAL Cassandra type"),
CassValueType::DOUBLE => write!(f, "DOUBLE Cassandra type"),
CassValueType::FLOAT => write!(f, "FLOAT Cassandra type"),
CassValueType::INT => write!(f, "INT Cassandra type"),
CassValueType::TEXT => write!(f, "TEXT Cassandra type"),
CassValueType::TIMESTAMP => write!(f, "TIMESTAMP Cassandra type"),
CassValueType::UUID => write!(f, "UUID Cassandra type"),
CassValueType::VARCHAR => write!(f, "{}", self.get_string().unwrap()),
CassValueType::VARINT => Ok(()),
CassValueType::TIMEUUID => write!(f, "TIMEUUID Cassandra type"),
CassValueType::INET => write!(f, "INET Cassandra type"),
CassValueType::LIST => {
for item in self.set_iter().unwrap() {
try!(write!(f, "LIST {:?}", item ))
}
Ok(())
}
CassValueType::MAP => {
for item in self.map_iter().unwrap() {
try!(write!(f, "LIST {:?}", item ))
}
Ok(())
}
CassValueType::SET => {
for item in self.set_iter().unwrap() {
try!(write!(f, "SET {:?}", item ))
}
Ok(())
}
CassValueType::UDT => write!(f, "UDT Cassandra type"),
CassValueType::TUPLE => write!(f, "Tuple Cassandra type"),
CassValueType::LASTENTRY => write!(f, "LAST_ENTRY Cassandra type"),
}
}
}
trait AsTypedColumn {
type T;
fn get(col: CassColumn) -> Result<Self::T, CassError>;
}
impl AsTypedColumn for bool {
type T = Self;
fn get(col: CassColumn) -> Result<Self, CassError> {
col.get_bool()
}
}
impl CassColumn {
pub fn get_type(&self) -> CassValueType {
unsafe {
CassValueType::build(cass_value_type(self.0))
}
}
pub unsafe fn get_inet(&self, mut output: CassInet) -> Result<CassInet, CassError> {
CassError::build(cass_value_get_inet(self.0,&mut output.0)).wrap(output)
}
pub fn get_string(&self) -> Result<String, CassError> {
unsafe {
match cass_value_type(self.0) {
CASS_VALUE_TYPE_ASCII | CASS_VALUE_TYPE_TEXT | CASS_VALUE_TYPE_VARCHAR => {
let mut message = mem::zeroed();
let mut message_length = mem::zeroed();
match cass_value_get_string(self.0, &mut message, &mut message_length) {
CASS_OK => {
let slice = slice::from_raw_parts(message as *const u8,
message_length as usize);
Ok(str::from_utf8(slice).unwrap().to_owned())
}
err => Err(CassError::build(err)),
}
}
err => Err(CassError::build(err)),
}
}
}
pub fn get_int32(&self) -> Result<i32, CassError> {
unsafe {
let mut output = mem::zeroed();
CassError::build(cass_value_get_int32(self.0,&mut output)).wrap(output)
}
}
pub fn get_int64(&self) -> Result<i64, CassError> {
unsafe {
let mut output = mem::zeroed();
CassError::build(cass_value_get_int64(self.0,&mut output)).wrap(output)
}
}
pub fn get_float(&self) -> Result<f32, CassError> {
unsafe {
let mut output = mem::zeroed();
CassError::build(cass_value_get_float(self.0,&mut output)).wrap(output)
}
}
pub fn get_double(&self) -> Result<f64, CassError> {
unsafe {
let mut output = mem::zeroed();
CassError::build(cass_value_get_double(self.0,&mut output)).wrap(output)
}
}
pub fn get_bool(&self) -> Result<bool, CassError> {
unsafe {
let mut output = mem::zeroed();
CassError::build(cass_value_get_bool(self.0,&mut output)).wrap(output > 0)
}
}
pub fn get_uuid(&self) -> Result<CassUuid, CassError> {
unsafe {
let mut output: CassUuid = mem::zeroed();
CassError::build(cass_value_get_uuid(self.0,&mut output.0)).wrap(output)
}
}
pub fn map_iter(&self) -> Result<MapIterator, CassError> {
unsafe {
match self.get_type() {
CassValueType::MAP => Ok(MapIterator(cass_iterator_from_map(self.0))),
_ => Err(CassError::build(CassErrorTypes::LIB_INVALID_VALUE_TYPE as u32)),
}
}
}
pub fn set_iter(&self) -> Result<SetIterator, CassError> {
unsafe {
match self.get_type() {
CassValueType::SET => Ok(SetIterator(cass_iterator_from_collection(self.0))),
_ => Err(CassError::build(1)),
}
}
}
pub fn use_type_iter(&self) -> Result<UserTypeIterator, CassError> {
unsafe {
match self.get_type() {
CassValueType::UDT => Ok(UserTypeIterator(cass_iterator_from_user_type(self.0))),
_ => Err(CassError::build(1)),
}
}
}
}
|
test_stdout!(without_exiting_returns_true, "true\n");
// `with_exiting_returns_false` in unit tests
|
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate rand;
use rand::{thread_rng, Rng};
use std::error::Error;
#[repr(u8)]
#[derive(Debug, Clone, Copy)]
enum Building {
Defense = 0,
Attack = 1,
Energy = 2,
}
impl std::fmt::Display for Building {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", *self as u8)
}
}
const STATE_PATH: &str = "state.json";
const COMMAND_PATH: &str = "command.txt";
#[derive(Debug, Clone, Copy)]
struct Command {
x: u32,
y: u32,
building: Building,
}
impl std::fmt::Display for Command {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{},{},{}", self.x, self.y, self.building)
}
}
mod state;
fn current_energy(state: &state::State) -> u32 {
state.players.iter()
.filter(|p| p.player_type == 'A')
.map(|p| p.energy)
.next()
.unwrap_or(0)
}
fn can_afford_all_buildings(state: &state::State) -> bool {
can_afford_attack_buildings(state) &&
can_afford_defence_buildings(state) &&
can_afford_energy_buildings(state)
}
fn can_afford_attack_buildings(state: &state::State) -> bool {
current_energy(state) >= state.game_details.building_prices.attack
}
fn can_afford_defence_buildings(state: &state::State) -> bool {
current_energy(state) >= state.game_details.building_prices.defense
}
fn can_afford_energy_buildings(state: &state::State) -> bool {
current_energy(state) >= state.game_details.building_prices.energy
}
fn is_under_attack(state: &state::State, y: u32) -> bool {
let attack = state.game_map[y as usize].iter()
.any(|cell| cell.buildings.iter()
.any(|building| building.player_type == 'B' &&
building.building_type == "ATTACK"));
let defences = state.game_map[y as usize].iter()
.any(|cell| cell.buildings.iter()
.any(|building| building.player_type == 'A' &&
building.building_type == "DEFENSE"));
attack && !defences
}
fn is_occupied(state: &state::State, x: u32, y: u32) -> bool {
!state.game_map[y as usize][x as usize].buildings.is_empty()
}
fn unoccupied_in_row(state: &state::State, y: u32) -> Vec<u32> {
(0..state.game_details.map_width/2)
.filter(|&x| !is_occupied(&state, x, y))
.collect()
}
fn unoccupied_cells(state: &state::State) -> Vec<(u32, u32)> {
(0..state.game_details.map_width/2)
.flat_map(|x| (0..state.game_details.map_height)
.map(|y| (x, y))
.collect::<Vec<(u32, u32)>>())
.filter(|&(x, y)| !is_occupied(&state, x, y))
.collect()
}
fn choose_move(state: &state::State) -> Option<Command> {
let mut rng = thread_rng();
if can_afford_defence_buildings(state) {
for y in 0..state.game_details.map_height {
if is_under_attack(state, y) {
let x_options = unoccupied_in_row(state, y);
if let Some(&x) = rng.choose(&x_options) {
return Some(Command {
x: x,
y: y,
building: Building::Defense
});
}
}
}
}
if can_afford_all_buildings(state) {
let options = unoccupied_cells(state);
let option = rng.choose(&options);
let buildings = [Building::Attack, Building::Defense, Building::Energy];
let building = rng.choose(&buildings);
match (option, building) {
(Some(&(x, y)), Some(&building)) => Some(Command {
x: x,
y: y,
building: building
}),
_ => None
}
}
else {
None
}
}
use std::fs::File;
use std::io::prelude::*;
fn write_command(filename: &str, command: Option<Command>) -> Result<(), Box<Error> > {
let mut file = File::create(filename)?;
if let Some(command) = command {
write!(file, "{}", command)?;
}
Ok(())
}
use std::process;
fn main() {
let state = match state::read_state_from_file(STATE_PATH) {
Ok(state) => state,
Err(error) => {
eprintln!("Failed to read the {} file. {}", STATE_PATH, error);
process::exit(1);
}
};
let command = choose_move(&state);
match write_command(COMMAND_PATH, command) {
Ok(()) => {}
Err(error) => {
eprintln!("Failed to write the {} file. {}", COMMAND_PATH, error);
process::exit(1);
}
}
}
|
use crate::backend::c;
use bitflags::bitflags;
/// `struct itimerspec` for use with [`timerfd_gettime`] and
/// [`timerfd_settime`].
///
/// [`timerfd_gettime`]: crate::time::timerfd_gettime
/// [`timerfd_settime`]: crate::time::timerfd_settime
pub type Itimerspec = linux_raw_sys::general::__kernel_itimerspec;
bitflags! {
/// `TFD_*` flags for use with [`timerfd_create`].
///
/// [`timerfd_create`]: crate::time::timerfd_create
#[repr(transparent)]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct TimerfdFlags: c::c_uint {
/// `TFD_NONBLOCK`
const NONBLOCK = linux_raw_sys::general::TFD_NONBLOCK;
/// `TFD_CLOEXEC`
const CLOEXEC = linux_raw_sys::general::TFD_CLOEXEC;
}
}
bitflags! {
/// `TFD_TIMER_*` flags for use with [`timerfd_settime`].
///
/// [`timerfd_settime`]: crate::time::timerfd_settime
#[repr(transparent)]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct TimerfdTimerFlags: c::c_uint {
/// `TFD_TIMER_ABSTIME`
const ABSTIME = linux_raw_sys::general::TFD_TIMER_ABSTIME;
/// `TFD_TIMER_CANCEL_ON_SET`
const CANCEL_ON_SET = linux_raw_sys::general::TFD_TIMER_CANCEL_ON_SET;
}
}
/// `CLOCK_*` constants for use with [`timerfd_create`].
///
/// [`timerfd_create`]: crate::time::timerfd_create
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[repr(u32)]
#[non_exhaustive]
pub enum TimerfdClockId {
/// `CLOCK_REALTIME`โA clock that tells the โrealโ time.
///
/// This is a clock that tells the amount of time elapsed since the
/// Unix epoch, 1970-01-01T00:00:00Z. The clock is externally settable, so
/// it is not monotonic. Successive reads may see decreasing times, so it
/// isn't reliable for measuring durations.
Realtime = linux_raw_sys::general::CLOCK_REALTIME,
/// `CLOCK_MONOTONIC`โA clock that tells an abstract time.
///
/// Unlike `Realtime`, this clock is not based on a fixed known epoch, so
/// individual times aren't meaningful. However, since it isn't settable,
/// it is reliable for measuring durations.
///
/// This clock does not advance while the system is suspended; see
/// `Boottime` for a clock that does.
Monotonic = linux_raw_sys::general::CLOCK_MONOTONIC,
/// `CLOCK_BOOTTIME`โLike `Monotonic`, but advances while suspended.
///
/// This clock is similar to `Monotonic`, but does advance while the system
/// is suspended.
Boottime = linux_raw_sys::general::CLOCK_BOOTTIME,
/// `CLOCK_REALTIME_ALARM`โLike `Realtime`, but wakes a suspended system.
///
/// This clock is like `Realtime`, but can wake up a suspended system.
///
/// Use of this clock requires the `CAP_WAKE_ALARM` Linux capability.
RealtimeAlarm = linux_raw_sys::general::CLOCK_REALTIME_ALARM,
/// `CLOCK_BOOTTIME_ALARM`โLike `Boottime`, but wakes a suspended system.
///
/// This clock is like `Boottime`, but can wake up a suspended system.
///
/// Use of this clock requires the `CAP_WAKE_ALARM` Linux capability.
BoottimeAlarm = linux_raw_sys::general::CLOCK_BOOTTIME_ALARM,
}
|
mod generic;
mod lifetime;
mod trait_demo;
fn main() {
generic::gn();
trait_demo::trait_demo();
lifetime::life();
}
|
mod send;
use crate::{
helpers::{array::get_slice, assertions::ensure_vote_exists, params::get_public_key},
types::{
Ballot, Cipher, PublicKey as SubstratePK, ShufflePayload, ShuffleProof,
ShuffleState, Topic, TopicId, Vote, VoteId, VotePhase, Wrapper,
},
};
use crate::{
Call, Ciphers, Error, Module, Sealers, ShuffleStateStore, Topics, Trait, VoteIds,
Votes,
};
use core::convert::TryInto;
use crypto::{
encryption::ElGamal, types::Cipher as BigCipher, types::PublicKey as ElGamalPK,
};
use frame_support::{
debug,
storage::{StorageDoubleMap, StorageMap, StorageValue},
traits::Get,
};
use frame_system::offchain::{Account, SendSignedTransaction, Signer};
use num_bigint::BigUint;
use send::send_signed;
use sp_std::{vec, vec::Vec};
impl<T: Trait> Module<T> {
pub fn offchain_signed_tx(
block_number: T::BlockNumber,
vote_id: Vec<u8>,
topic_id: Vec<u8>,
) -> Result<(), Error<T>> {
ensure_vote_exists::<T>(&vote_id)?;
// We retrieve a signer and check if it is valid.
// ref: https://substrate.dev/rustdocs/v2.0.0/frame_system/offchain/struct.Signer.html
let signer = Signer::<T, T::AuthorityId>::any_account();
// translating the current block number to number and submit it on-chain
let number: u64 = block_number.try_into().unwrap_or(0u64) as u64;
// transform u64 to BigUint
let number_as_biguint: BigUint = BigUint::from(number);
// get public key
let pk: ElGamalPK = get_public_key::<T>(&vote_id)?.into();
let q = &pk.params.q();
// get a random value < q
let r = Self::get_random_biguint_less_than(q)?;
// encrypt the current block number
let cipher: Cipher = ElGamal::encrypt_encode(&number_as_biguint, &r, &pk).into();
let answers: Vec<(TopicId, Cipher)> = vec![(topic_id, cipher)];
let ballot: Ballot = Ballot { answers };
return send_signed::<T>(
signer,
Call::cast_ballot(vote_id.clone(), ballot.clone()),
);
}
pub fn offchain_shuffling(block_number: T::BlockNumber) -> Result<(), Error<T>> {
// if the offchain worker is not a validator, we don't shuffle the votes
if !sp_io::offchain::is_validator() {
return Ok(());
}
// Only attempt to shuffle votes
// every #BlockDuration of blocks
let duration = T::BlockDuration::get();
let zero: T::BlockNumber = T::BlockNumber::from(0u32);
if block_number % duration != zero {
return Ok(());
}
// get all vote_ids
let vote_ids: Vec<VoteId> = VoteIds::get();
debug::info!("vote_ids: {:?}", vote_ids);
for vote_id in vote_ids.iter() {
// check vote state -> TALLYING
let vote: Vote<T::AccountId> = Votes::<T>::get(&vote_id);
let state: VotePhase = vote.phase;
// early return if the vote is not in
if state != VotePhase::Tallying {
continue;
}
debug::info!("vote_id: {:?}, state: VotePhase::Tallying", vote_id);
// get all topics
let topics: Vec<Topic> = Topics::get(vote_id);
// get public key
let pk: SubstratePK = get_public_key::<T>(&vote_id)?;
let pk: ElGamalPK = pk.into();
for (topic_id, _) in topics.iter() {
// get shuffle state
let shuffle_state: ShuffleState = ShuffleStateStore::get((
vote_id, topic_id,
))
.expect("shuffle state should exist for all existing votes & topics!");
debug::info!("shuffle_state: {:?}", shuffle_state);
// if the shuffling has been completed -> skip to next topic
if shuffle_state.done {
continue;
}
// check who's turn it is
let sealers: Vec<T::AccountId> = Sealers::<T>::get();
let current_sealer = Self::get_current_sealer(block_number, sealers);
// get the signer for the transaction
let signer = Signer::<T, T::AuthorityId>::any_account();
// if it's the current_sealer's turn, then shuffle + submit ciphers + proof
// else, submit empty transaction
let transaction_response = signer.send_signed_transaction(|_acct| {
let local_address = &_acct.id;
if current_sealer.eq(local_address) {
debug::info!("my turn!");
// shuffle ciphers + create proof
let payload_response = Self::offchain_shuffle_and_proof(
&topic_id,
shuffle_state.iteration,
&pk,
shuffle_state.start_position,
shuffle_state.batch_size,
);
let payload: ShufflePayload = payload_response.unwrap();
Call::submit_shuffled_votes_and_proof(
vote_id.to_vec(),
topic_id.to_vec(),
payload,
)
// do nothing in case that it is not this sealer's turn
} else {
debug::info!("not my turn!");
Call::do_nothing_when_its_not_your_turn()
}
});
Self::handle_transaction_response(
&vote_id,
¤t_sealer,
transaction_response,
)?;
}
}
Ok(())
}
pub fn offchain_shuffle_and_proof(
topic_id: &TopicId,
iteration: u8,
pk: &ElGamalPK,
start_position: u64,
batch_size: u64,
) -> Result<ShufflePayload, Error<T>> {
// get all encrypted votes (ciphers)
// for the topic with id: topic_id and the # of shuffles (iteration)
debug::info!("topic_id: {:?}", topic_id);
let ciphers: Vec<Cipher> = Ciphers::get(&topic_id, iteration);
// type conversion: Cipher (Vec<u8>) to BigCipher (BigUint)
let encryptions: Vec<BigCipher> = Wrapper(ciphers).into();
// retrieve the ciphers for the computed range
let slice =
get_slice::<T, BigCipher>(encryptions.clone(), start_position, batch_size);
// for each topic_id & vote_id
// shuffle the votes
let (shuffled_slice, re_encryption_randoms, permutation): (
Vec<BigCipher>,
Vec<BigUint>,
Vec<usize>,
) = Self::shuffle_ciphers(&pk, slice.to_vec())?;
// generate the shuffle proof
let proof: ShuffleProof = Self::generate_shuffle_proof(
&topic_id,
slice,
shuffled_slice.clone(),
re_encryption_randoms,
&permutation,
&pk,
)?;
// create transaction payload
let payload = ShufflePayload {
ciphers: Wrapper(shuffled_slice).into(),
proof: proof.into(),
iteration,
start_position,
batch_size,
};
Ok(payload)
}
/// retrieves the current sealer, depends on the block number
fn get_current_sealer(
block_number: T::BlockNumber,
sealers: Vec<T::AccountId>,
) -> T::AccountId {
let n: T::BlockNumber = (sealers.len() as u32).into();
let index = block_number % n;
let index_as_u64 = TryInto::<u64>::try_into(index)
.ok()
.expect("BockNumber to u64 type conversion failed!");
let sealer: T::AccountId = sealers[index_as_u64 as usize].clone();
debug::info!("current turn: sealer {:?} (index: {:?})", sealer, index);
sealer
}
fn handle_transaction_response(
vote_id: &VoteId,
current_sealer: &T::AccountId,
transaction_response: Option<(Account<T>, Result<(), ()>)>,
) -> Result<(), Error<T>> {
// handle the response
if let Some((acc, res)) = transaction_response {
// display error if the signed tx fails.
if res.is_err() {
debug::error!(
"failure in offchain tx, acc: {:?}, res: {:?}",
acc.id,
res
);
}
// transaction is sent successfully
if current_sealer.eq(&acc.id) {
debug::info!(
"votes shuffled in offchain worker -> vote_id: {:?}",
vote_id
);
}
Ok(())
} else {
// the case of `None`: no account is available for sending
debug::error!("No local account available");
return Err(<Error<T>>::NoLocalAcctForSigning);
}
}
}
|
mod args;
mod client;
mod dlm_error;
mod downloader;
mod file_link;
mod progress_bar_manager;
mod retry;
mod user_agents;
mod utils;
use crate::args::{get_args, Arguments};
use crate::client::make_client;
use crate::dlm_error::DlmError;
use crate::downloader::download_link;
use crate::progress_bar_manager::ProgressBarManager;
use crate::retry::{retry_handler, retry_strategy};
use crate::user_agents::{random_user_agent, UserAgent};
use crate::DlmError::EmptyInputFile;
use futures_util::stream::StreamExt;
use tokio::fs as tfs;
use tokio::io::AsyncBufReadExt;
use tokio_retry::RetryIf;
use tokio_stream::wrappers::LinesStream;
#[tokio::main]
async fn main() {
let result = main_result().await;
std::process::exit(match result {
Ok(_) => 0,
Err(err) => {
eprintln!("{}", err);
1
}
});
}
async fn main_result() -> Result<(), DlmError> {
// CLI args
let Arguments {
input_file,
max_concurrent_downloads,
output_dir,
user_agent,
proxy,
retry,
connection_timeout_secs,
} = get_args()?;
let nb_of_lines = count_non_empty_lines(&input_file).await?;
if nb_of_lines == 0 {
return Err(EmptyInputFile);
}
// setup HTTP clients
let client = make_client(&user_agent, &proxy, true, connection_timeout_secs)?;
let c_ref = &client;
let client_no_redirect = make_client(&user_agent, &proxy, false, connection_timeout_secs)?;
let c_no_redirect_ref = &client_no_redirect;
let od_ref = &output_dir;
// setup progress bar manager
let pbm = ProgressBarManager::init(max_concurrent_downloads, nb_of_lines as u64).await;
let pbm_ref = &pbm;
// print startup info
let msg_header = format!(
"Starting dlm with at most {} concurrent downloads",
max_concurrent_downloads
);
pbm.log_above_progress_bars(msg_header);
let msg_count = format!("Found {} URLs in input file {}", nb_of_lines, input_file);
pbm.log_above_progress_bars(msg_count);
// start streaming lines from file
let file = tfs::File::open(input_file).await?;
let file_reader = tokio::io::BufReader::new(file);
let line_stream = LinesStream::new(file_reader.lines());
line_stream
.for_each_concurrent(max_concurrent_downloads, |link_res| async move {
let message = match link_res {
Err(e) => format!("Error with links iterator {}", e),
Ok(link) if link.trim().is_empty() => "Skipping empty line".to_string(),
Ok(link) => {
// claim a progress bar for the upcoming download
let dl_pb = pbm_ref
.rx
.recv()
.await
.expect("claiming progress bar should not fail");
// exponential backoff retries for network errors
let retry_strategy = retry_strategy(retry);
let processed = RetryIf::spawn(
retry_strategy,
|| {
download_link(
&link,
c_ref,
c_no_redirect_ref,
connection_timeout_secs,
od_ref,
&dl_pb,
pbm_ref,
)
},
|e: &DlmError| retry_handler(e, pbm_ref, &link),
)
.await;
// reset & release progress bar
ProgressBarManager::reset_progress_bar(&dl_pb);
pbm_ref
.tx
.send(dl_pb)
.await
.expect("releasing progress bar should not fail");
// extract result
match processed {
Ok(info) => info,
Err(e) => format!("Unrecoverable error while processing {}: {}", link, e),
}
}
};
pbm_ref.log_above_progress_bars(message);
pbm_ref.increment_global_progress();
})
.await;
// cleanup phase
pbm_ref.finish_all().await?;
Ok(())
}
async fn count_non_empty_lines(input_file: &str) -> Result<i32, DlmError> {
let file = tfs::File::open(input_file).await?;
let file_reader = tokio::io::BufReader::new(file);
let stream = LinesStream::new(file_reader.lines());
let line_nb = stream
.fold(0, |acc, rl| async move {
match rl {
Ok(l) if !l.trim().is_empty() => acc + 1,
_ => acc,
}
})
.await;
Ok(line_nb)
}
|
pub fn matrix_mul(a: &Vec<i32>,b: &Vec<i32>,l: usize,m: usize,n: usize) -> Vec<i32>{
let r = l * n;
let mut c: Vec<i32> = vec![0;r];
for i in 0..r{
for j in 0..m{
c[i] = c[i] + (a[i / n * m + j] * b[(i % n) + j * n]);
}
}
return c;
}
|
mod canvas;
mod color;
mod coord;
mod lang;
mod scene;
mod traits;
use canvas::Canvas;
use color::{Color, BLACK};
use coord::{WorldCoordinate, ORIGIN};
use lang::parser::{LightDefinition, Parser, SceneDefinition};
use log::error;
use pixels::SurfaceTexture;
use scene::object::light::Light;
use scene::object::shape::Sphere;
use scene::{Scene, ViewPort};
use std::env;
use std::fs;
use winit::event::{Event, VirtualKeyCode};
use winit::event_loop::{ControlFlow, EventLoop};
use winit_input_helper::WinitInputHelper;
fn main() -> Result<(), String> {
env_logger::init();
let args: Vec<_> = env::args().collect();
let file = if args.len() >= 2 { &args[1] } else { "" };
if file.is_empty() {
return Err("Supply a valid file name".into());
}
let contents =
fs::read_to_string(&file).map_err(|e| format!("Failed to read '{}': {}", &file, e))?;
let mut parser = Parser::new(&contents);
let definitions = parser.parse()?;
let scene = load_scene(definitions);
let event_loop = EventLoop::new();
let mut input = WinitInputHelper::new();
let canvas = scene.canvas();
let window = canvas.window().build(&event_loop).unwrap();
let mut pixels = {
let window_size = window.inner_size();
let surface_texture = SurfaceTexture::new(window_size.width, window_size.height, &window);
canvas
.create_pixels(surface_texture)
.map_err(|e| format!("Failed to create canvas {:?}", e))?
};
event_loop.run(move |event, _, control_flow| {
// Draw the current frame
if let Event::RedrawRequested(_) = event {
let frame = pixels.get_frame();
scene.render(frame);
if pixels
.render()
.map_err(|e| error!("pixels.render() failed: {}", e))
.is_err()
{
*control_flow = ControlFlow::Exit;
return;
}
}
// Handle input events
if input.update(&event) {
// Close events
if input.key_pressed(VirtualKeyCode::Escape) || input.quit() {
*control_flow = ControlFlow::Exit;
return;
}
// Resize the window
if let Some(size) = input.window_resized() {
pixels.resize(size.width, size.height);
}
// Update internal state and request a redraw
window.request_redraw();
}
});
}
fn load_scene(definition: SceneDefinition) -> Scene {
let mut window_width = canvas::DEFAULT_WIDTH;
let mut window_height = canvas::DEFAULT_HEIGHT;
let mut canvas = Canvas::default();
let mut window_title = String::from("Giraffics");
if let Some(window_def) = definition.window {
if let Some(width) = window_def.width {
window_width = width as usize;
}
if let Some(height) = window_def.height {
window_height = height as usize;
}
if let Some(title) = window_def.title {
window_title = title;
}
}
let lights = definition
.lights
.into_iter()
.map(|light_def| match light_def {
LightDefinition::AmbientLight { intensity } => Light::ambient(intensity),
LightDefinition::DirectionLight {
intensity,
direction,
} => Light::direction(WorldCoordinate::from_tuple(direction), intensity),
LightDefinition::PointLight {
intensity,
position,
} => Light::point(WorldCoordinate::from_tuple(position), intensity),
})
.collect();
let spheres = definition
.spheres
.into_iter()
.map(|sphere| {
Sphere::new(
sphere.radius,
WorldCoordinate::from_tuple(sphere.center),
Color::from_rgb_tuple(sphere.color),
)
})
.collect();
canvas = canvas.with_height(window_height).with_width(window_width);
Scene::new(ORIGIN, ViewPort::default(), canvas, BLACK, window_title)
.with_lights(lights)
.with_spheres(spheres)
}
|
use crate::environment::blockchain_interface::BlockchainInterface;
use near_vm_logic::mocks::mock_external::MockedExternal;
use near_vm_logic::mocks::mock_memory::MockedMemory;
use near_vm_logic::types::PromiseResult;
use near_vm_logic::{Config, External, MemoryLike, VMContext, VMLogic};
use std::cell::RefCell;
use std::collections::BTreeMap;
/// Mocked blockchain that can be used in the tests for the smart contracts.
/// It implements `BlockchainInterface` by redirecting calls to `VMLogic`. It unwraps errors of
/// `VMLogic` to cause panic during the unit test similarly to how errors of `VMLogic` would cause
/// the termination of guest program execution. Unit tests can even assert the expected error
/// message.
pub struct MockedBlockchain {
logic: RefCell<VMLogic<'static>>,
// We keep ownership over logic fixture so that references in `VMLogic` are valid.
#[allow(dead_code)]
logic_fixture: LogicFixture,
}
struct LogicFixture {
ext: Box<MockedExternal>,
memory: Box<dyn MemoryLike>,
promise_results: Box<Vec<PromiseResult>>,
config: Box<Config>,
}
impl MockedBlockchain {
pub fn new(
context: VMContext,
config: Config,
promise_results: Vec<PromiseResult>,
storage: BTreeMap<Vec<u8>, Vec<u8>>,
) -> Self {
let mut ext = Box::new(MockedExternal::new());
ext.fake_trie = storage;
let memory = Box::new(MockedMemory {});
let promise_results = Box::new(promise_results);
let config = Box::new(config);
let mut logic_fixture = LogicFixture { ext, memory, config, promise_results };
let logic = unsafe {
VMLogic::new(
&mut *(logic_fixture.ext.as_mut() as *mut dyn External),
context,
&*(logic_fixture.config.as_mut() as *const Config),
&*(logic_fixture.promise_results.as_ref().as_slice() as *const [PromiseResult]),
&mut *(logic_fixture.memory.as_mut() as *mut dyn MemoryLike),
)
};
let logic = RefCell::new(logic);
Self { logic, logic_fixture }
}
pub fn take_storage(&mut self) -> BTreeMap<Vec<u8>, Vec<u8>> {
std::mem::replace(&mut self.logic_fixture.ext.fake_trie, Default::default())
}
}
impl BlockchainInterface for MockedBlockchain {
unsafe fn read_register(&self, register_id: u64, ptr: u64) {
self.logic.borrow_mut().read_register(register_id, ptr).unwrap()
}
unsafe fn register_len(&self, register_id: u64) -> u64 {
self.logic.borrow_mut().register_len(register_id).unwrap()
}
unsafe fn current_account_id(&self, register_id: u64) {
self.logic.borrow_mut().current_account_id(register_id).unwrap()
}
unsafe fn signer_account_id(&self, register_id: u64) {
self.logic.borrow_mut().signer_account_id(register_id).unwrap()
}
unsafe fn signer_account_pk(&self, register_id: u64) {
self.logic.borrow_mut().signer_account_pk(register_id).unwrap()
}
unsafe fn predecessor_account_id(&self, register_id: u64) {
self.logic.borrow_mut().predecessor_account_id(register_id).unwrap()
}
unsafe fn input(&self, register_id: u64) {
self.logic.borrow_mut().input(register_id).unwrap()
}
unsafe fn block_index(&self) -> u64 {
self.logic.borrow_mut().block_index().unwrap()
}
unsafe fn block_timestamp(&self) -> u64 {
self.logic.borrow_mut().block_timestamp().unwrap()
}
unsafe fn storage_usage(&self) -> u64 {
self.logic.borrow_mut().storage_usage().unwrap()
}
unsafe fn account_balance(&self, balance_ptr: u64) {
self.logic.borrow_mut().account_balance(balance_ptr).unwrap()
}
unsafe fn attached_deposit(&self, balance_ptr: u64) {
self.logic.borrow_mut().attached_deposit(balance_ptr).unwrap()
}
unsafe fn prepaid_gas(&self) -> u64 {
self.logic.borrow_mut().prepaid_gas().unwrap()
}
unsafe fn used_gas(&self) -> u64 {
self.logic.borrow_mut().used_gas().unwrap()
}
unsafe fn random_seed(&self, register_id: u64) {
self.logic.borrow_mut().random_seed(register_id).unwrap()
}
unsafe fn sha256(&self, value_len: u64, value_ptr: u64, register_id: u64) {
self.logic.borrow_mut().sha256(value_len, value_ptr, register_id).unwrap()
}
unsafe fn value_return(&self, value_len: u64, value_ptr: u64) {
self.logic.borrow_mut().value_return(value_len, value_ptr).unwrap()
}
unsafe fn panic(&self) {
self.logic.borrow_mut().panic().unwrap()
}
unsafe fn panic_utf8(&self, len: u64, ptr: u64) {
self.logic.borrow_mut().panic_utf8(len, ptr).unwrap()
}
unsafe fn log_utf8(&self, len: u64, ptr: u64) {
self.logic.borrow_mut().log_utf8(len, ptr).unwrap()
}
unsafe fn log_utf16(&self, len: u64, ptr: u64) {
self.logic.borrow_mut().log_utf16(len, ptr).unwrap()
}
unsafe fn promise_create(
&self,
account_id_len: u64,
account_id_ptr: u64,
method_name_len: u64,
method_name_ptr: u64,
arguments_len: u64,
arguments_ptr: u64,
amount_ptr: u64,
gas: u64,
) -> u64 {
self.logic
.borrow_mut()
.promise_create(
account_id_len,
account_id_ptr,
method_name_len,
method_name_ptr,
arguments_len,
arguments_ptr,
amount_ptr,
gas,
)
.unwrap()
}
unsafe fn promise_then(
&self,
promise_index: u64,
account_id_len: u64,
account_id_ptr: u64,
method_name_len: u64,
method_name_ptr: u64,
arguments_len: u64,
arguments_ptr: u64,
amount_ptr: u64,
gas: u64,
) -> u64 {
self.logic
.borrow_mut()
.promise_then(
promise_index,
account_id_len,
account_id_ptr,
method_name_len,
method_name_ptr,
arguments_len,
arguments_ptr,
amount_ptr,
gas,
)
.unwrap()
}
unsafe fn promise_and(&self, promise_idx_ptr: u64, promise_idx_count: u64) -> u64 {
self.logic.borrow_mut().promise_and(promise_idx_ptr, promise_idx_count).unwrap()
}
unsafe fn promise_batch_create(&self, account_id_len: u64, account_id_ptr: u64) -> u64 {
self.logic.borrow_mut().promise_batch_create(account_id_len, account_id_ptr).unwrap()
}
unsafe fn promise_batch_then(
&self,
promise_index: u64,
account_id_len: u64,
account_id_ptr: u64,
) -> u64 {
self.logic
.borrow_mut()
.promise_batch_then(promise_index, account_id_len, account_id_ptr)
.unwrap()
}
unsafe fn promise_batch_action_create_account(&self, promise_index: u64) {
self.logic.borrow_mut().promise_batch_action_create_account(promise_index).unwrap()
}
unsafe fn promise_batch_action_deploy_contract(
&self,
promise_index: u64,
code_len: u64,
code_ptr: u64,
) {
self.logic
.borrow_mut()
.promise_batch_action_deploy_contract(promise_index, code_len, code_ptr)
.unwrap()
}
unsafe fn promise_batch_action_function_call(
&self,
promise_index: u64,
method_name_len: u64,
method_name_ptr: u64,
arguments_len: u64,
arguments_ptr: u64,
amount_ptr: u64,
gas: u64,
) {
self.logic
.borrow_mut()
.promise_batch_action_function_call(
promise_index,
method_name_len,
method_name_ptr,
arguments_len,
arguments_ptr,
amount_ptr,
gas,
)
.unwrap()
}
unsafe fn promise_batch_action_transfer(&self, promise_index: u64, amount_ptr: u64) {
self.logic.borrow_mut().promise_batch_action_transfer(promise_index, amount_ptr).unwrap()
}
unsafe fn promise_batch_action_stake(
&self,
promise_index: u64,
amount_ptr: u64,
public_key_len: u64,
public_key_ptr: u64,
) {
self.logic
.borrow_mut()
.promise_batch_action_stake(promise_index, amount_ptr, public_key_len, public_key_ptr)
.unwrap()
}
unsafe fn promise_batch_action_add_key_with_full_access(
&self,
promise_index: u64,
public_key_len: u64,
public_key_ptr: u64,
nonce: u64,
) {
self.logic
.borrow_mut()
.promise_batch_action_add_key_with_full_access(
promise_index,
public_key_len,
public_key_ptr,
nonce,
)
.unwrap()
}
unsafe fn promise_batch_action_add_key_with_function_call(
&self,
promise_index: u64,
public_key_len: u64,
public_key_ptr: u64,
nonce: u64,
allowance_ptr: u64,
receiver_id_len: u64,
receiver_id_ptr: u64,
method_names_len: u64,
method_names_ptr: u64,
) {
self.logic
.borrow_mut()
.promise_batch_action_add_key_with_function_call(
promise_index,
public_key_len,
public_key_ptr,
nonce,
allowance_ptr,
receiver_id_len,
receiver_id_ptr,
method_names_len,
method_names_ptr,
)
.unwrap()
}
unsafe fn promise_batch_action_delete_key(
&self,
promise_index: u64,
public_key_len: u64,
public_key_ptr: u64,
) {
self.logic
.borrow_mut()
.promise_batch_action_delete_key(promise_index, public_key_len, public_key_ptr)
.unwrap()
}
unsafe fn promise_batch_action_delete_account(
&self,
promise_index: u64,
beneficiary_id_len: u64,
beneficiary_id_ptr: u64,
) {
self.logic
.borrow_mut()
.promise_batch_action_delete_account(
promise_index,
beneficiary_id_len,
beneficiary_id_ptr,
)
.unwrap()
}
unsafe fn promise_results_count(&self) -> u64 {
self.logic.borrow_mut().promise_results_count().unwrap()
}
unsafe fn promise_result(&self, result_idx: u64, register_id: u64) -> u64 {
self.logic.borrow_mut().promise_result(result_idx, register_id).unwrap()
}
unsafe fn promise_return(&self, promise_id: u64) {
self.logic.borrow_mut().promise_return(promise_id).unwrap()
}
unsafe fn storage_write(
&self,
key_len: u64,
key_ptr: u64,
value_len: u64,
value_ptr: u64,
register_id: u64,
) -> u64 {
self.logic
.borrow_mut()
.storage_write(key_len, key_ptr, value_len, value_ptr, register_id)
.unwrap()
}
unsafe fn storage_read(&self, key_len: u64, key_ptr: u64, register_id: u64) -> u64 {
self.logic.borrow_mut().storage_read(key_len, key_ptr, register_id).unwrap()
}
unsafe fn storage_remove(&self, key_len: u64, key_ptr: u64, register_id: u64) -> u64 {
self.logic.borrow_mut().storage_remove(key_len, key_ptr, register_id).unwrap()
}
unsafe fn storage_has_key(&self, key_len: u64, key_ptr: u64) -> u64 {
self.logic.borrow_mut().storage_has_key(key_len, key_ptr).unwrap()
}
unsafe fn storage_iter_prefix(&self, prefix_len: u64, prefix_ptr: u64) -> u64 {
self.logic.borrow_mut().storage_iter_prefix(prefix_len, prefix_ptr).unwrap()
}
unsafe fn storage_iter_range(
&self,
start_len: u64,
start_ptr: u64,
end_len: u64,
end_ptr: u64,
) -> u64 {
self.logic.borrow_mut().storage_iter_range(start_len, start_ptr, end_len, end_ptr).unwrap()
}
unsafe fn storage_iter_next(
&self,
iterator_id: u64,
key_register_id: u64,
value_register_id: u64,
) -> u64 {
self.logic
.borrow_mut()
.storage_iter_next(iterator_id, key_register_id, value_register_id)
.unwrap()
}
fn as_mut_mocked_blockchain(&mut self) -> Option<&mut MockedBlockchain> {
Some(self)
}
}
|
//! A registry of values, available both internally to Way Cooler
//! and its clients.
//!
//! The registry is divided into "categories", which gives the values some
//! semblance of structure (e.g window properties are part of the "windows"
//! category) while also allowing fine grain permissions for clients
//! (e.g most clients can read properties about windows,
//! but cannot modify them)
//!
//! Once a category has been created, you cannot overwrite it. However, you can
//! overwrite the data within the category assuming you have write permissions
//! for that category.
//!
//! Access is controlled by the `registry::Access` struct, which ensures
//! that the user of the registry can actually access the values its
//! trying to access
use std::collections::hash_map::{Entry, HashMap};
use std::sync::{RwLockReadGuard, RwLockWriteGuard, LockResult};
use uuid::Uuid;
use super::category::Category;
use super::client::{Client, ClientErr, ClientResult, Permissions};
use super::REGISTRY;
/// The result of doing an operation on the registry.
pub type RegistryResult<T> = Result<T, RegistryErr>;
/// Ways accessing of accessing the registry incorrectly
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum RegistryErr {
/// The category already exists, you cannot overwrite it.
CategoryExists(String),
/// The category does not exist, it needs to be created.
CategoryDoesNotExist(String)
}
/// The main store for the registry values. It tracks category names with
/// their associated `Category`s which holds the actual data.
///
/// Permissions are NOT tracked from here, that is done with `registry::Access`.
///
/// All public access of the registry should go through an `registry::Access`
/// object, to ensure that permissions are upheld.
pub struct Registry {
map: HashMap<String, Category>
}
impl Registry {
/// Makes a new registry, with no categories or data.
pub fn new() -> Self {
Registry { map: HashMap::new() }
}
/// Looks up a category by its canonical name immutably.
pub fn category(&self, category: String) -> RegistryResult<&Category> {
self.map.get(&category)
.ok_or_else(|| RegistryErr::CategoryDoesNotExist(category))
}
/// Looks up a category by its canonical name mutably.
pub fn category_mut(&mut self, category: String)
-> RegistryResult<&mut Category> {
self.map.get_mut(&category)
.ok_or_else(|| RegistryErr::CategoryDoesNotExist(category))
}
/// Adds a new category to the registry. Fails if it already exists.
pub fn add_category(&mut self, category: String)
-> RegistryResult<()> {
match self.map.entry(category.clone()) {
Entry::Occupied(_) =>
Err(RegistryErr::CategoryExists(category.into())),
Entry::Vacant(entry) => {
entry.insert(Category::new(category));
Ok(())
}
}
}
}
/// A handle for accessing the registry behind a read lock.
/// Holds the lock and a reference to the client who is using the
/// handle to access the registry.
pub struct ReadHandle<'lock> {
handle: LockResult<RwLockReadGuard<'lock, Registry>>,
client: &'lock Client
}
impl<'lock> ReadHandle<'lock> {
/// Makes a new handle to the registry with the given permissions.
pub fn new(client: &'lock Client) -> Self {
ReadHandle {
handle: REGISTRY.read(),
client: client
}
}
/// Attempts to access the data behind the category.
pub fn read(&self, category: String) -> ClientResult<&Category> {
if !self.client.categories().any(|permission| *permission.0 == category) {
if self.client.id() != Uuid::nil() {
return Err(ClientErr::DoesNotExist(category))
}
}
// if we have it in our permissions, we automatically can read it.
let handle = self.handle.as_ref().expect("handle.was poisoned!");
handle.category(category.clone())
.or(Err(ClientErr::DoesNotExist(category)))
}
}
/// A handle for accessing the registry behind a write lock.
/// Holds the lock and a reference to the client who is using the
/// handle to access the registry.
pub struct WriteHandle<'lock> {
handle: LockResult<RwLockWriteGuard<'lock, Registry>>,
client: &'lock Client
}
impl<'lock> WriteHandle<'lock> {
/// Makes a new handle to the registry with the given permissions.
pub fn new(client: &'lock Client) -> Self {
WriteHandle {
handle: REGISTRY.write(),
client: client
}
}
/// Writes to the data behind a category.
///
/// If the category does not exist, it is automatically created.
pub fn write(&mut self, category: String) -> ClientResult<&mut Category> {
let mut categories = self.client.categories();
if self.client.id() != Uuid::nil() {
try!(categories.find(|cat| *cat.0 == category)
.ok_or_else(|| ClientErr::DoesNotExist(category.clone()))
.and_then(|category| {
if *category.1 != Permissions::Write {
Err(ClientErr::InsufficientPermissions)
} else {
Ok(())
}
}));
}
let handle = self.handle.as_mut().expect("handle.was poisoned!");
if !self.client.categories().any(|permission| *permission.0 == category) {
handle.add_category(category.clone()).ok();
}
handle.category_mut(category.clone())
.or(Err(ClientErr::DoesNotExist(category)))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_basic_category_manipulation() {
let mut reg = Registry::new();
reg.add_category("Test".into()).unwrap();
assert_eq!(reg.add_category("Test".into()), Err(RegistryErr::CategoryExists("Test".into())));
assert!(reg.category("Test".into()).is_ok());
assert!(reg.category_mut("Test".into()).is_ok());
assert_eq!(reg.category("test".into()),
Err(RegistryErr::CategoryDoesNotExist("test".into())));
assert_eq!(reg.category_mut("test".into()),
Err(RegistryErr::CategoryDoesNotExist("test".into())));
assert_eq!(reg.category("whatever".into()),
Err(RegistryErr::CategoryDoesNotExist("whatever".into())));
assert_eq!(reg.category_mut("whatever".into()),
Err(RegistryErr::CategoryDoesNotExist("whatever".into())));
}
}
|
use super::Command;
use clap::ArgMatches;
use log::info;
pub fn run(matches: &ArgMatches, commands: &mut Vec<Command>) {
info!("Running NEW subcommand");
let command = matches.value_of("command").unwrap().to_owned();
let keywords: Vec<String> = matches
.values_of("keywords")
.unwrap()
.map(|k| k.to_owned())
.collect();
info!("Command: {}", command);
info!("Keywords: {}", keywords.join(" "));
commands.push(Command {
id: commands.len(),
command,
keywords,
});
}
|
use std;
use std::collections::HashMap;
use csv;
use lazy_static::lazy_static;
use pbr::ProgressBar;
use std::error;
use std::error::Error;
use std::fmt;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::str::FromStr;
use x86::cpuid;
use x86::perfcnt::intel::{events, Counter, EventDescription, MSRIndex, PebsType, Tuple};
use super::util::*;
use log::*;
lazy_static! {
/// Check if HT is enabled on this CPU (if HT is disabled it doubles the amount of available
/// performance counters on a core).
static ref HT_AVAILABLE: bool = {
let cpuid = cpuid::CpuId::new();
cpuid.get_extended_topology_info().unwrap().any(|t| {
t.level_type() == cpuid::TopologyType::SMT
})
};
/// For every MonitoringUnit try to figure out how many counters we support.
/// This is handled through a config file since Linux doesn't export this information in
/// it's PMU devices (but probably should)...
static ref PMU_COUNTERS: HashMap<MonitoringUnit, usize> = {
let cpuid = cpuid::CpuId::new();
let cpu_counter = cpuid.get_performance_monitoring_info().map_or(0, |info| info.number_of_counters()) as usize;
let mut res = HashMap::with_capacity(11);
res.insert(MonitoringUnit::CPU, cpu_counter);
let (family, model) = cpuid.get_feature_info().map_or((0,0), |fi| (fi.family_id(), ((fi.extended_model_id() as u8) << 4) | fi.model_id() as u8));
let ctr_config = include_str!("counters.toml");
let mut parser = toml::Parser::new(ctr_config);
let doc = match parser.parse() {
Some(doc) => doc,
None => {
error!("Can't parse the counter configuration file:\n{:?}", parser.errors);
std::process::exit(9);
}
};
trace!("Trying to find architecture for family = {:#x} model = {:#x}", family, model);
let mut found: bool = false;
for (name, architecture) in doc {
let architecture = architecture.as_table().expect("counters.toml architectures must be a table");
let cfamily = &architecture["family"];
for cmodel in architecture["models"].as_slice().expect("counters.toml models must be a list.") {
let cfamily = cfamily.as_integer().expect("Family must be int.") as u8;
let cmodel = cmodel.as_integer().expect("Model must be int.") as u8;
if family == cfamily && model == cmodel {
trace!("Running on {}, reading MonitoringUnit limits from config", name);
found = true;
// TODO: We should ideally get both, prgrammable and fixed counters:
for (unit, limit) in architecture["programmable_counters"].as_table().expect("programmable_counters must be a table") {
let unit = MonitoringUnit::new(unit.as_str());
let limit = limit.as_integer().expect("Counter limit should be an integer");
res.insert(unit, limit as usize);
}
}
}
}
if !found {
warn!("Didn't recogize this architecture so we can't infer #counters for MonitoringUnit (Please update counters.toml for family = {:#x} model = {:#x})", family, model);
res.insert(MonitoringUnit::UBox, 4);
res.insert(MonitoringUnit::HA, 4);
res.insert(MonitoringUnit::IRP, 4);
res.insert(MonitoringUnit::PCU, 4);
res.insert(MonitoringUnit::R2PCIe, 4);
res.insert(MonitoringUnit::R3QPI, 4);
res.insert(MonitoringUnit::QPI, 4);
res.insert(MonitoringUnit::CBox, 2);
res.insert(MonitoringUnit::IMC, 4);
res.insert(MonitoringUnit::Arb, 2);
res.insert(MonitoringUnit::M2M, 4);
res.insert(MonitoringUnit::CHA, 4);
res.insert(MonitoringUnit::M3UPI, 4);
res.insert(MonitoringUnit::IIO, 4);
res.insert(MonitoringUnit::UPI_LL, 4);
}
res
};
/// Find the linux PMU devices that we need to program through perf
static ref PMU_DEVICES: Vec<String> = {
let paths = fs::read_dir("/sys/bus/event_source/devices/").expect("Can't read devices directory.");
let mut devices = Vec::with_capacity(15);
for p in paths {
let path = p.expect("Is not a path.");
let file_name = path.file_name().into_string().expect("Is valid UTF-8 string.");
devices.push(file_name);
}
devices
};
/// Bogus or clocks that we don't want to measure or tend to break things
static ref IGNORE_EVENTS: HashMap<&'static str, bool> = {
let mut ignored = HashMap::with_capacity(1);
ignored.insert("UNC_CLOCK.SOCKET", true); // Just says 'fixed' and does not name which counter :/
ignored.insert("UNC_M_CLOCKTICKS_F", true);
ignored.insert("UNC_U_CLOCKTICKS", true);
ignored
};
/// Which events should be measured in isolation on this architecture.
static ref ISOLATE_EVENTS: Vec<&'static str> = {
let cpuid = cpuid::CpuId::new();
let (family, model) = cpuid.get_feature_info().map_or((0,0), |fi| (fi.family_id(), ((fi.extended_model_id() as u8) << 4) | fi.model_id() as u8));
// Sometimes the perfmon data is missing the errata information
// as is the case for IvyBridge where MEM_LOAD* things can't be measured
// together with other things.
if family == 0x6 && (model == 62 || model == 58) {
vec![ "MEM_UOPS_RETIRED.ALL_STORES",
"MEM_LOAD_UOPS_RETIRED.L1_MISS",
"MEM_LOAD_UOPS_RETIRED.HIT_LFB",
"MEM_LOAD_UOPS_LLC_HIT_RETIRED.XSNP_HITM",
"MEM_LOAD_UOPS_RETIRED.L2_HIT",
"MEM_UOPS_RETIRED.SPLIT_LOADS",
"MEM_UOPS_RETIRED.ALL_LOADS",
"MEM_LOAD_UOPS_LLC_MISS_RETIRED.LOCAL_DRAM",
"MEM_LOAD_UOPS_LLC_HIT_RETIRED.XSNP_NONE",
"MEM_LOAD_UOPS_RETIRED.L1_HIT",
"MEM_UOPS_RETIRED.STLB_MISS_STORES",
"MEM_LOAD_UOPS_LLC_HIT_RETIRED.XSNP_HIT",
"MEM_LOAD_UOPS_RETIRED.LLC_MISS",
"MEM_LOAD_UOPS_RETIRED.L2_MISS",
"MEM_LOAD_UOPS_LLC_HIT_RETIRED.XSNP_MISS",
"MEM_UOPS_RETIRED.STLB_MISS_LOADS",
"MEM_UOPS_RETIRED.LOCK_LOADS",
"MEM_LOAD_UOPS_RETIRED.LLC_HIT",
"MEM_UOPS_RETIRED.SPLIT_STORES",
// Those are IvyBridge-EP events:
"MEM_LOAD_UOPS_LLC_MISS_RETIRED.REMOTE_DRAM",
"MEM_LOAD_UOPS_LLC_MISS_RETIRED.REMOTE_HITM",
"MEM_LOAD_UOPS_LLC_MISS_RETIRED.REMOTE_FWD"]
}
else {
vec![]
}
};
}
fn execute_perf(
perf: &mut Command,
cmd: &Vec<String>,
counters: &Vec<String>,
datafile: &Path,
dryrun: bool,
) -> (String, String, String) {
assert!(cmd.len() >= 1);
let perf = perf.arg("-o").arg(datafile.as_os_str());
let events: Vec<String> = counters.iter().map(|c| format!("-e {}", c)).collect();
let perf = perf.args(events.as_slice());
let perf = perf.args(cmd.as_slice());
let perf_cmd_str: String = format!("{:?}", perf).replace("\"", "");
let (stdout, stderr) = if !dryrun {
match perf.output() {
Ok(out) => {
let stdout =
String::from_utf8(out.stdout).unwrap_or(String::from("Unable to read stdout!"));
let stderr =
String::from_utf8(out.stderr).unwrap_or(String::from("Unable to read stderr!"));
if out.status.success() {
trace!("stdout:\n{:?}", stdout);
trace!("stderr:\n{:?}", stderr);
} else if !out.status.success() {
error!(
"perf command: {} got unknown exit status was: {}",
perf_cmd_str, out.status
);
debug!("stdout:\n{}", stdout);
debug!("stderr:\n{}", stderr);
}
if !datafile.exists() {
error!(
"perf command: {} succeeded but did not produce the required file {:?} \
(you should file a bug report!)",
perf_cmd_str, datafile
);
}
(stdout, stderr)
}
Err(err) => {
error!("Executing {} failed : {}", perf_cmd_str, err);
(String::new(), String::new())
}
}
} else {
warn!("Dry run mode -- would execute: {}", perf_cmd_str);
(String::new(), String::new())
};
(perf_cmd_str, stdout, stderr)
}
pub fn create_out_directory(out_dir: &Path) {
if !out_dir.exists() {
std::fs::create_dir(out_dir).expect("Can't create `out` directory");
}
}
pub fn get_known_events<'a>() -> Vec<&'a EventDescription<'static>> {
events()
.expect("No performance events found?")
.values()
.collect()
}
#[allow(non_camel_case_types)]
#[derive(Hash, Eq, PartialEq, Debug, Copy, Clone, PartialOrd, Ord)]
pub enum MonitoringUnit {
/// Devices
CPU,
/// Memory stuff
Arb,
/// The CBox manages the interface between the core and the LLC, so
/// the instances of uncore CBox is equal to number of cores
CBox,
/// ???
SBox,
/// ???
UBox,
/// QPI Stuff
QPI,
/// Ring to QPI
R3QPI,
/// IIO Coherency
IRP,
/// Ring to PCIe
R2PCIe,
/// Memory Controller
IMC,
/// Home Agent
HA,
/// Power Control Unit
PCU,
/// XXX
M2M,
/// XXX
CHA,
/// XXX
M3UPI,
/// XXX
IIO,
/// XXX
UPI_LL,
/// Types we don't know how to handle...
Unknown,
}
impl fmt::Display for MonitoringUnit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
MonitoringUnit::CPU => write!(f, "CPU"),
MonitoringUnit::Arb => write!(f, "Arb"),
MonitoringUnit::CBox => write!(f, "CBox"),
MonitoringUnit::SBox => write!(f, "SBox"),
MonitoringUnit::UBox => write!(f, "UBox"),
MonitoringUnit::QPI => write!(f, "QPI"),
MonitoringUnit::R3QPI => write!(f, "R3QPI"),
MonitoringUnit::IRP => write!(f, "IRP"),
MonitoringUnit::R2PCIe => write!(f, "R2PCIe"),
MonitoringUnit::IMC => write!(f, "IMC"),
MonitoringUnit::HA => write!(f, "HA"),
MonitoringUnit::PCU => write!(f, "PCU"),
MonitoringUnit::M2M => write!(f, "M2M"),
MonitoringUnit::CHA => write!(f, "CHA"),
MonitoringUnit::M3UPI => write!(f, "M3UPI"),
MonitoringUnit::IIO => write!(f, "IIO"),
MonitoringUnit::UPI_LL => write!(f, "UPI LL"),
MonitoringUnit::Unknown => write!(f, "Unknown"),
}
}
}
impl MonitoringUnit {
fn new<'a>(unit: &'a str) -> MonitoringUnit {
match unit.to_lowercase().as_str() {
"cpu" => MonitoringUnit::CPU,
"cbo" => MonitoringUnit::CBox,
"qpi_ll" => MonitoringUnit::QPI,
"sbo" => MonitoringUnit::SBox,
"imph-u" => MonitoringUnit::Arb,
"arb" => MonitoringUnit::Arb,
"r3qpi" => MonitoringUnit::R3QPI,
"qpi ll" => MonitoringUnit::QPI,
"irp" => MonitoringUnit::IRP,
"r2pcie" => MonitoringUnit::R2PCIe,
"imc" => MonitoringUnit::IMC,
"ha" => MonitoringUnit::HA,
"pcu" => MonitoringUnit::PCU,
"ubox" => MonitoringUnit::UBox,
"m2m" => MonitoringUnit::M2M,
"cha" => MonitoringUnit::CHA,
"m3upi" => MonitoringUnit::M3UPI,
"iio" => MonitoringUnit::IIO,
"upi ll" => MonitoringUnit::UPI_LL,
"upi" => MonitoringUnit::UPI_LL,
"ubo" => MonitoringUnit::UBox,
"qpi" => MonitoringUnit::QPI,
_ => {
error!("Don't support MonitoringUnit {}", unit);
MonitoringUnit::Unknown
}
}
}
pub fn to_intel_event_description(&self) -> Option<&'static str> {
match *self {
MonitoringUnit::CPU => None,
MonitoringUnit::CBox => Some("CBO"),
MonitoringUnit::QPI => Some("QPI_LL"),
MonitoringUnit::SBox => Some("SBO"),
MonitoringUnit::Arb => Some("ARB"),
MonitoringUnit::R3QPI => Some("R3QPI"),
MonitoringUnit::IRP => Some("IRP"),
MonitoringUnit::R2PCIe => Some("R2PCIE"),
MonitoringUnit::IMC => Some("IMC"),
MonitoringUnit::HA => Some("HA"),
MonitoringUnit::PCU => Some("PCU"),
MonitoringUnit::UBox => Some("UBOX"),
MonitoringUnit::M2M => Some("M2M"),
MonitoringUnit::CHA => Some("CHA"),
MonitoringUnit::M3UPI => Some("M3UPI"),
MonitoringUnit::IIO => Some("IIO"),
MonitoringUnit::UPI_LL => Some("UPI LL"),
MonitoringUnit::Unknown => None,
}
}
/// Return the perf prefix for selecting the right PMU unit in case of uncore counters.
pub fn to_perf_prefix(&self) -> Option<&'static str> {
let res = match *self {
MonitoringUnit::CPU => Some("cpu"),
MonitoringUnit::CBox => Some("uncore_cbox"),
MonitoringUnit::QPI => Some("uncore_qpi"),
MonitoringUnit::SBox => Some("uncore_sbox"),
MonitoringUnit::Arb => Some("uncore_arb"),
MonitoringUnit::R3QPI => Some("uncore_r3qpi"), // Adds postfix value
MonitoringUnit::IRP => Some("uncore_irp"), // According to libpfm4 (lib/pfmlib_intel_ivbep_unc_irp.c)
MonitoringUnit::R2PCIe => Some("uncore_r2pcie"),
MonitoringUnit::IMC => Some("uncore_imc"), // Adds postfix value
MonitoringUnit::HA => Some("uncore_ha"), // Adds postfix value
MonitoringUnit::PCU => Some("uncore_pcu"),
MonitoringUnit::UBox => Some("uncore_ubox"),
MonitoringUnit::M2M => Some("uncore_m2m"), // Adds postfix value
MonitoringUnit::CHA => Some("uncore_cha"), // Adds postfix value
MonitoringUnit::M3UPI => Some("uncore_m3upi"), // Adds postfix value
MonitoringUnit::IIO => Some("uncore_iio"), // Adds postfix value
MonitoringUnit::UPI_LL => Some("uncore_upi"), // Adds postfix value
MonitoringUnit::Unknown => None,
};
// Note: If anything here does not return uncore_ as a prefix, you need to update extract.rs!
res.map(|string| assert!(string.starts_with("uncore_") || string.starts_with("cpu")));
res
}
}
#[derive(Debug)]
pub struct PerfEvent<'a, 'b>(pub &'a EventDescription<'b>)
where
'b: 'a;
impl<'a, 'b> PerfEvent<'a, 'b> {
/// Returns all possible configurations of the event.
/// This is a two vector tuple containing devices and configs:
///
/// * Devices are a subset of the ones listed in `/sys/bus/event_source/devices/`
/// Usually just `cpu` but uncore events can be measured on multiple devices.
/// * Configs are all possible combinations of attributes for this event.
/// Usually one but offcore events have two.
///
/// # Note
/// The assumption of the return type is that we can always match any
/// device with any config. Let's see how long this assumption will remain valid...
///
pub fn perf_configs(&self) -> (Vec<String>, Vec<Vec<String>>) {
let mut devices = Vec::with_capacity(1);
let mut configs = Vec::with_capacity(2);
let typ = self.unit();
// XXX: Horrible vector transformation:
let matched_devices: Vec<String> = PMU_DEVICES
.iter()
.filter(|d| typ.to_perf_prefix().map_or(false, |t| d.starts_with(t)))
.map(|d| d.clone())
.collect();
devices.extend(matched_devices);
// We can have no devices if we don't understand how to match the unit name to perf names:
if devices.len() == 0 {
debug!(
"Unit {:?} is not available to measure '{}'.",
self.unit(),
self,
);
}
for args in self.perf_args() {
configs.push(args);
}
(devices, configs)
}
/// Does this event use the passed code?
pub fn uses_event_code(&self, event_code: u8) -> bool {
match self.0.event_code {
Tuple::One(e1) => e1 == event_code,
Tuple::Two(e1, e2) => e1 == event_code || e2 == event_code,
}
}
/// Does this event use the passed code?
pub fn uses_umask(&self, umask: u8) -> bool {
match self.0.umask {
Tuple::One(m1) => m1 == umask,
Tuple::Two(m1, m2) => m1 == umask || m2 == umask,
}
}
/// Is this event an uncore event?
pub fn is_uncore(&self) -> bool {
self.0.unit.is_some()
}
pub fn unit(&self) -> MonitoringUnit {
self.0
.unit
.map_or(MonitoringUnit::CPU, |u| MonitoringUnit::new(u))
}
/// Is this event an offcore event?
pub fn is_offcore(&self) -> bool {
match self.0.event_code {
Tuple::One(_) => {
assert!(!self.0.offcore);
false
}
Tuple::Two(_, _) => {
assert!(self.0.event_name.contains("OFFCORE"));
// The OR is because there is this weird meta-event OFFCORE_RESPONSE
// in the data files. It has offcore == false and is not really a proper event :/
assert!(self.0.offcore || self.0.event_name == "OFFCORE_RESPONSE");
true
}
}
}
/// Get the correct counter mask
pub fn counter(&self) -> Counter {
if *HT_AVAILABLE || self.is_uncore() {
self.0.counter
} else {
self.0.counter_ht_off.expect("A bug in JSON?") // Ideally, all CPU events should have this attribute
}
}
fn push_arg(configs: &mut Vec<Vec<String>>, value: String) {
for config in configs.iter_mut() {
config.push(value.clone());
}
}
/// Returns a set of attributes used to build the perf event description.
///
/// # Arguments
/// * try_alternative: Can give a different event encoding (for offcore events).
fn perf_args(&self) -> Vec<Vec<String>> {
// OFFCORE_RESPONSE_0 and OFFCORE_RESPONSE_1 provide identical functionality. The reason
// that there are two of them is that these events are associated with a separate MSR that is
// used to program the types of requests/responses that you want to count (instead of being
// able to include this information in the Umask field of the PERFEVT_SELx MSR). The
// performance counter event OFFCORE_RESPONSE_0 (Event 0xB7) is associated with MSR 0x1A6,
// while the performance counter event OFFCORE_RESPONSE_1 (Event 0xBB) is associated with MSR
// 0x1A7.
// So having two events (with different associated MSRs) allows you to count two different
// offcore response events at the same time.
// Source: https://software.intel.com/en-us/forums/software-tuning-performance-optimization-platform-monitoring/topic/559227
let two_configs: bool = match self.0.event_code {
Tuple::One(_) => false,
Tuple::Two(_, _) => true,
};
let mut ret: Vec<Vec<String>> = vec![Vec::with_capacity(7)];
if two_configs {
ret.push(Vec::with_capacity(7));
}
PerfEvent::push_arg(&mut ret, format!("name={}", self.0.event_name));
let is_pcu = self.0.unit.map_or(false, |u| {
return MonitoringUnit::new(u) == MonitoringUnit::PCU;
});
match self.0.event_code {
Tuple::One(ev) => {
// PCU events have umasks defined but they're OR'd with event (wtf)
let pcu_umask = if is_pcu {
match self.0.umask {
Tuple::One(mask) => mask,
Tuple::Two(_m1, _m2) => unreachable!(),
}
} else {
0x0
};
ret[0].push(format!("event=0x{:x}", ev | pcu_umask));
}
Tuple::Two(e1, e2) => {
assert!(two_configs);
assert!(!is_pcu);
ret[0].push(format!("event=0x{:x}", e1));
ret[1].push(format!("event=0x{:x}", e2));
}
};
if !is_pcu {
match self.0.umask {
Tuple::One(mask) => {
PerfEvent::push_arg(&mut ret, format!("umask=0x{:x}", mask));
}
Tuple::Two(m1, m2) => {
assert!(two_configs);
ret[0].push(format!("umask=0x{:x}", m1));
ret[1].push(format!("umask=0x{:x}", m2));
}
};
}
if self.0.counter_mask != 0 {
PerfEvent::push_arg(&mut ret, format!("cmask=0x{:x}", self.0.counter_mask));
}
if self.0.fc_mask != 0 {
PerfEvent::push_arg(&mut ret, format!("fc_mask=0x{:x}", self.0.fc_mask));
}
if self.0.port_mask != 0 {
PerfEvent::push_arg(&mut ret, format!("ch_mask=0x{:x}", self.0.port_mask));
}
if self.0.offcore {
PerfEvent::push_arg(&mut ret, format!("offcore_rsp=0x{:x}", self.0.msr_value));
} else {
match self.0.msr_index {
MSRIndex::One(0x3F6) => {
PerfEvent::push_arg(&mut ret, format!("ldlat=0x{:x}", self.0.msr_value));
}
MSRIndex::One(0x1A6) => {
PerfEvent::push_arg(&mut ret, format!("offcore_rsp=0x{:x}", self.0.msr_value));
}
MSRIndex::One(0x1A7) => {
PerfEvent::push_arg(&mut ret, format!("offcore_rsp=0x{:x}", self.0.msr_value));
}
MSRIndex::One(0x3F7) => {
PerfEvent::push_arg(&mut ret, format!("frontend=0x{:x}", self.0.msr_value));
}
MSRIndex::One(a) => {
unreachable!("Unknown MSR value {}, check linux/latest/source/tools/perf/pmu-events/jevents.c", a)
}
MSRIndex::Two(_, _) => {
unreachable!("Should not have non offcore events with two MSR index values.")
}
MSRIndex::None => {
// ignored, not a load latency event
}
};
}
if self.0.invert {
PerfEvent::push_arg(&mut ret, String::from("inv=1"));
}
if self.0.edge_detect {
PerfEvent::push_arg(&mut ret, String::from("edge=1"));
}
if self.0.any_thread {
PerfEvent::push_arg(&mut ret, String::from("any=1"));
}
if self.match_filter("CBoFilter0[23:17]") {
PerfEvent::push_arg(&mut ret, String::from("filter_state=0x1f"));
}
if self.match_filter("CBoFilter1[15:0]") {
// TODO: Include both sockets by default -- we should probably be smarter...
PerfEvent::push_arg(&mut ret, String::from("filter_nid=0x3"));
}
if self.match_filter("CBoFilter1[28:20]") {
// TOR events requires filter_opc
// Set to: 0x192 PrefData Prefetch Data into LLC but donโt pass to L2. Includes Hints
PerfEvent::push_arg(&mut ret, String::from("filter_opc=0x192"));
}
ret
}
pub fn perf_qualifiers(&self) -> String {
let qualifiers = String::from("S");
if self.0.pebs == PebsType::PebsOrRegular {
// Adding 'p' for PebsOrRegular event doesnt seem to work
// for many events in perf that Intel regards as PEBS capable events
// (see issue #2)
} else if self.0.pebs == PebsType::PebsOnly {
// Adding a 'p' here seems counterproducive (perf won't measure the events then)
// so we do nothing
}
qualifiers
}
fn filters(&self) -> Vec<&str> {
self.0.filter.map_or(Vec::new(), |value| {
value
.split(",")
.map(|x| x.trim())
.filter(|x| x.len() > 0)
.collect()
})
}
pub fn match_filter(&self, filter: &str) -> bool {
self.filters().contains(&filter)
}
}
impl<'a, 'b> fmt::Display for PerfEvent<'a, 'b> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0.event_name)
}
}
/// Adding a new event to a group of existing events (that can be measured
/// together) can fail for a variety of reasons which are encoded in this type.
#[derive(Debug)]
pub enum AddEventError {
/// We couldn't measure any more offcore events
OffcoreCapacityReached,
/// We don't have more counters left on this monitoring unit
UnitCapacityReached(MonitoringUnit),
/// We have a constraint that we can't measure the new event together with
/// an existing event in the group
CounterConstraintConflict,
/// We have a conflict with filters
FilterConstraintConflict,
/// The errata specifies an issue with this event (we tend to isolate these)
ErrataConflict,
/// This counter must be measured alone
TakenAloneConflict,
/// This is one of these events that we manually specified to be isolated
IsolatedEventConflict,
}
impl fmt::Display for AddEventError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
AddEventError::OffcoreCapacityReached => write!(f, "Offcore event limit reached."),
AddEventError::UnitCapacityReached(u) => {
write!(f, "Unit '{}' capacity for reached.", u)
}
AddEventError::CounterConstraintConflict => write!(f, "Counter constraints conflict."),
AddEventError::FilterConstraintConflict => write!(f, "Filter constraints conflict."),
AddEventError::ErrataConflict => write!(f, "Errata conflict."),
AddEventError::TakenAloneConflict => write!(f, "Group contains a taken alone counter."),
AddEventError::IsolatedEventConflict => write!(f, "Group contains an isolated event."),
}
}
}
impl error::Error for AddEventError {
fn description(&self) -> &str {
match *self {
AddEventError::OffcoreCapacityReached => "Offcore event limit reached.",
AddEventError::UnitCapacityReached(_) => "Unit capacity reached.",
AddEventError::CounterConstraintConflict => "Counter constraints conflict.",
AddEventError::FilterConstraintConflict => "Filter constraints conflict.",
AddEventError::ErrataConflict => "Errata conflict.",
AddEventError::TakenAloneConflict => "Group contains a taken alone counter.",
AddEventError::IsolatedEventConflict => "Group contains an isolated event.",
}
}
}
#[derive(Debug)]
pub struct PerfEventGroup<'a, 'b>
where
'b: 'a,
{
events: Vec<PerfEvent<'a, 'b>>,
limits: &'a HashMap<MonitoringUnit, usize>,
}
impl<'a, 'b> PerfEventGroup<'a, 'b> {
/// Make a new performance event group.
pub fn new(unit_sizes: &'a HashMap<MonitoringUnit, usize>) -> PerfEventGroup {
PerfEventGroup {
events: Default::default(),
limits: unit_sizes,
}
}
/// Returns how many offcore events are in the group.
fn offcore_events(&self) -> usize {
self.events.iter().filter(|e| e.is_offcore()).count()
}
/// Returns how many uncore events are in the group for a given unit.
fn events_by_unit(&self, unit: MonitoringUnit) -> Vec<&PerfEvent> {
self.events.iter().filter(|e| e.unit() == unit).collect()
}
/// Backtracking algorithm to find assigment of events to available counters
/// while respecting the counter constraints every event has.
/// The events passed here should all have the same counter type
/// (i.e., either all programmable or all fixed) and the same unit.
///
/// Returns a possible placement or None if no assignment was possible.
fn find_counter_assignment(
level: usize,
max_level: usize,
events: Vec<&'a PerfEvent<'a, 'b>>,
assignment: Vec<&'a PerfEvent<'a, 'b>>,
) -> Option<Vec<&'a PerfEvent<'a, 'b>>> {
// Are we done yet?
if events.len() == 0 {
return Some(assignment);
}
// Are we too deep?
if level >= max_level {
return None;
}
for (idx, event) in events.iter().enumerate() {
let mask: usize = match event.counter() {
Counter::Programmable(mask) => mask as usize,
Counter::Fixed(mask) => mask as usize,
};
let mut assignment = assignment.clone();
let mut events = events.clone();
// If event supports counter, let's assign it to this counter and go deeper
if (mask & (1 << level)) > 0 {
assignment.push(event);
events.remove(idx);
let ret = PerfEventGroup::find_counter_assignment(
level + 1,
max_level,
events,
assignment,
);
if ret.is_some() {
return ret;
}
}
// Otherwise let's not assign the event at this level and go deeper (for groups that
// don't use all counters)
else {
let ret = PerfEventGroup::find_counter_assignment(
level + 1,
max_level,
events,
assignment,
);
if ret.is_some() {
return ret;
}
}
// And finally, just try with the next event in the list
}
None
}
/// Check if this event conflicts with the counter requirements
/// of events already in this group
fn has_counter_constraint_conflicts(&self, new_event: &PerfEvent) -> bool {
let unit = new_event.unit();
let unit_limit = *self.limits.get(&unit).unwrap_or(&0);
//error!("unit = {:?} unit_limit {:?}", unit, unit_limit);
// Get all the events that share the same counters as new_event:
let mut events: Vec<&PerfEvent> = self
.events_by_unit(unit)
.into_iter()
.filter(|c| match (c.counter(), new_event.counter()) {
(Counter::Programmable(_), Counter::Programmable(_)) => true,
(Counter::Fixed(_), Counter::Fixed(_)) => true,
_ => false,
})
.collect();
events.push(new_event);
PerfEventGroup::find_counter_assignment(0, unit_limit, events, Vec::new()).is_none()
}
/// Check if this events conflicts with the filter requirements of
/// events already in this group
fn has_filter_constraint_conflicts(&self, new_event: &PerfEvent) -> bool {
let unit = new_event.unit();
let events: Vec<&PerfEvent> = self.events_by_unit(unit);
for event in events.iter() {
for filter in event.filters() {
if new_event.filters().contains(&filter) {
return true;
}
}
}
false
}
/// Try to add an event to an event group.
///
/// Returns true if the event can be added to the group, false if we would be Unable
/// to measure the event in the same group (given the PMU limitations).
///
/// Things we consider correctly right now:
/// * Fixed amount of counters per monitoring unit (so we don't multiplex).
/// * Some events can only use some counters.
/// * Taken alone attribute of the events.
///
/// Things we consider not entirely correct right now:
/// * Event Erratas this is not complete in the JSON files, and we just run them in isolation
///
pub fn add_event(&mut self, event: PerfEvent<'a, 'b>) -> Result<(), AddEventError> {
// 1. Can't measure more than two offcore events:
if event.is_offcore() && self.offcore_events() == 2 {
return Err(AddEventError::OffcoreCapacityReached);
}
// 2. Check we don't measure more events than we have counters
// for on the repspective units
let unit = event.unit();
let unit_limit = *self.limits.get(&unit).unwrap_or(&0);
if self.events_by_unit(unit).len() >= unit_limit {
return Err(AddEventError::UnitCapacityReached(unit));
}
// 3. Now, consider the counter <-> event mapping constraints:
// Try to see if there is any event already in the group
// that would conflict when running together with the new `event`:
if self.has_counter_constraint_conflicts(&event) {
return Err(AddEventError::CounterConstraintConflict);
}
if self.has_filter_constraint_conflicts(&event) {
return Err(AddEventError::FilterConstraintConflict);
}
// 4. Isolate things that have erratas to not screw other events (see HSW30)
let errata = self.events.iter().any(|cur| cur.0.errata.is_some());
if errata || event.0.errata.is_some() && self.events.len() != 0 {
return Err(AddEventError::ErrataConflict);
}
// 5. If an event has the taken alone attribute set it needs to be measured alone
let already_have_taken_alone_event = self.events.iter().any(|cur| cur.0.taken_alone);
if already_have_taken_alone_event || event.0.taken_alone && self.events.len() != 0 {
return Err(AddEventError::TakenAloneConflict);
}
// 6. If our own isolate event list contains the name we also run them alone:
let already_have_isolated_event = self.events.get(0).map_or(false, |e| {
ISOLATE_EVENTS.iter().any(|cur| *cur == e.0.event_name)
});
if already_have_isolated_event
|| ISOLATE_EVENTS.iter().any(|cur| *cur == event.0.event_name) && self.events.len() != 0
{
return Err(AddEventError::IsolatedEventConflict);
}
self.events.push(event);
Ok(())
}
/// Find the right config to use for every event in the group.
///
/// * We need to make sure we use the correct config if we have two offcore events in the same group.
pub fn get_perf_config(&self) -> Vec<String> {
let mut event_strings: Vec<String> = Vec::with_capacity(2);
let mut have_one_offcore = false; // Have we already added one offcore event?
for event in self.events.iter() {
let (devices, mut configs) = event.perf_configs();
if devices.len() == 0 || configs.len() == 0 {
error!(
"Event {} supported by hardware, but your Linux does not allow you to measure it (available PMU devices = {:?})",
event, devices
);
continue;
}
// TODO: handle fixed counters
// fixed_counters = {
// "inst_retired.any": (0xc0, 0, 0),
// "cpu_clk_unhalted.thread": (0x3c, 0, 0),
// "cpu_clk_unhalted.thread_any": (0x3c, 0, 1),
// }
// Adding offcore event:
if event.is_offcore() {
assert!(devices.len() == 1);
assert!(configs.len() == 2);
assert!(devices[0] == "cpu");
let config = match have_one_offcore {
false => configs.get(0).unwrap(), // Ok, always has at least one config
true => configs.get(1).unwrap(), // Ok, as offcore implies two configs
};
event_strings.push(format!(
"{}/{}/{}",
devices[0],
config.join(","),
event.perf_qualifiers()
));
have_one_offcore = true;
}
// Adding uncore event:
else if event.is_uncore() {
assert!(configs.len() == 1);
// If we have an uncore event we just go ahead and measure it on all possible devices:
for device in devices {
// Patch name in config so we know where this event was running
// `perf stat` just reports CPU 0 for uncore events :-(
configs[0][0] = format!("name={}.{}", device, event.0.event_name);
event_strings.push(format!(
"{}/{}/{}",
device,
configs[0].join(","),
event.perf_qualifiers()
));
}
}
// Adding normal event:
else {
assert!(devices.len() == 1);
assert!(configs.len() == 1);
assert!(devices[0] == "cpu");
event_strings.push(format!(
"{}/{}/{}",
devices[0],
configs[0].join(","),
event.perf_qualifiers()
));
}
}
event_strings
}
/// Returns a list of events as strings that can be passed to perf-record using
/// the -e arguments.
pub fn get_perf_config_strings(&self) -> Vec<String> {
self.get_perf_config()
}
/// Returns a list of event names in this group.
///
/// The order of the list of names matches with the order
/// returned by `get_perf_config_strings` or `get_perf_config`.
pub fn get_event_names(&self) -> Vec<&'b str> {
self.events.iter().map(|event| event.0.event_name).collect()
}
}
/// Given a list of events, create a list of event groups that can be measured together.
pub fn schedule_events<'a, 'b>(events: Vec<&'a EventDescription<'b>>) -> Vec<PerfEventGroup<'a, 'b>>
where
'b: 'a,
{
let mut groups: Vec<PerfEventGroup> = Vec::with_capacity(42);
for event in events {
if IGNORE_EVENTS.contains_key(event.event_name) {
continue;
}
let perf_event: PerfEvent = PerfEvent(event);
let mut added: Result<(), AddEventError> = Err(AddEventError::ErrataConflict);
match perf_event.unit() {
MonitoringUnit::Unknown => {
info!("Ignoring event with unknown unit '{}'", event);
continue;
}
_ => (),
};
// Try to add the event to an existing group:
for group in groups.iter_mut() {
let perf_event: PerfEvent = PerfEvent(event);
added = group.add_event(perf_event);
if added.is_ok() {
break;
}
}
// Unable to add event to any existing group, make a new group instead:
if !added.is_ok() {
let mut pg = PerfEventGroup::new(&*PMU_COUNTERS);
let perf_event: PerfEvent = PerfEvent(event);
let added = pg.add_event(perf_event);
match added {
Err(e) => {
let perf_event: PerfEvent = PerfEvent(event);
panic!(
"Can't add a new event {:?} to an empty group: {:?}",
perf_event, e
);
}
Ok(_) => (),
};
groups.push(pg);
}
}
// println!("{:?}", groups);
groups
}
pub fn get_perf_command(
cmd_working_dir: &str,
_output_path: &Path,
env: &Vec<(String, String)>,
breakpoints: &Vec<String>,
record: bool,
) -> Command {
let mut perf = Command::new("perf");
perf.current_dir(cmd_working_dir);
let _filename: String;
if !record {
perf.arg("stat");
perf.arg("-aA");
perf.arg("-I 250");
perf.arg("-x ;");
} else {
perf.arg("record");
perf.arg("--group");
perf.arg("-F 4");
perf.arg("-a");
perf.arg("--raw-samples");
}
// Ensure we use dots as number separators in csv output (see issue #1):
perf.env("LC_NUMERIC", "C");
// Add the environment variables:
for &(ref key, ref value) in env.iter() {
perf.env(key, value);
}
let breakpoint_args: Vec<String> = breakpoints.iter().map(|s| format!("-e \\{}", s)).collect();
perf.args(breakpoint_args.as_slice());
perf
}
pub fn profile<'a, 'b>(
output_path: &Path,
cmd_working_dir: &str,
cmd: Vec<String>,
env: Vec<(String, String)>,
breakpoints: Vec<String>,
record: bool,
events: Option<Vec<&'a EventDescription<'b>>>,
dryrun: bool,
) where
'b: 'a,
{
let event_groups = match events {
Some(evts) => schedule_events(evts),
None => schedule_events(get_known_events()),
};
// Is this run already done (in case we restart):
let mut completed_file: PathBuf = output_path.to_path_buf();
completed_file.push("completed");
if completed_file.exists() {
warn!(
"Run {} already completed, skipping.",
output_path.to_string_lossy()
);
return;
}
create_out_directory(output_path);
if !dryrun {
check_for_perf();
let ret = check_for_perf_permissions()
|| check_for_disabled_nmi_watchdog()
|| check_for_perf_paranoia();
if !ret {
std::process::exit(3);
}
let _ = save_numa_topology(&output_path).expect("Can't save NUMA topology");
let _ = save_cpu_topology(&output_path).expect("Can't save CPU topology");
let _ = save_lstopo(&output_path).expect("Can't save lstopo information");
let _ = save_cpuid(&output_path).expect("Can't save CPUID information");
let _ = save_likwid_topology(&output_path).expect("Can't save likwid information");
}
assert!(cmd.len() >= 1);
let mut perf_log = PathBuf::new();
perf_log.push(output_path);
perf_log.push("perf.csv");
let mut wtr = csv::Writer::from_file(perf_log).unwrap();
let r = wtr.encode((
"command",
"event_names",
"perf_events",
"breakpoints",
"datafile",
"perf_command",
"stdout",
"stdin",
));
assert!(r.is_ok());
// For warm-up do a dummy run of the program with perf
let record_path = Path::new("/dev/null");
let mut perf = get_perf_command(cmd_working_dir, output_path, &env, &breakpoints, record);
perf.arg("-n"); // null run - donโt start any counters
let (_, _, _) = execute_perf(&mut perf, &cmd, &Vec::new(), &record_path, dryrun);
debug!("Warmup complete, let's start measuring.");
let mut pb = ProgressBar::new(event_groups.len() as u64);
for (idx, group) in event_groups.iter().enumerate() {
if !dryrun {
pb.inc();
}
let event_names: Vec<&str> = group.get_event_names();
let counters: Vec<String> = group.get_perf_config_strings();
let mut record_path = PathBuf::new();
let filename = match record {
false => format!("{}_stat.csv", idx + 1),
true => format!("{}_perf.data", idx + 1),
};
record_path.push(output_path);
record_path.push(&filename);
let mut perf = get_perf_command(cmd_working_dir, output_path, &env, &breakpoints, record);
let (executed_cmd, stdout, stdin) =
execute_perf(&mut perf, &cmd, &counters, record_path.as_path(), dryrun);
if !dryrun {
let r = wtr.encode(vec![
cmd.join(" "),
event_names.join(","),
counters.join(","),
String::new(),
filename,
executed_cmd,
stdout,
stdin,
]);
assert!(r.is_ok());
let r = wtr.flush();
assert!(r.is_ok());
}
}
// Mark this run as completed:
let _ = File::create(completed_file.as_path()).unwrap();
}
pub fn check_for_perf() {
match Command::new("perf").output() {
Ok(out) => {
if out.status.code() != Some(1) {
error!("'perf' seems to have some problems?");
debug!("perf exit status was: {}", out.status);
error!("{}", String::from_utf8_lossy(&out.stderr));
error!(
"You may require a restart after fixing this so \
`/sys/bus/event_source/devices` is updated!"
);
std::process::exit(2);
}
}
Err(_) => {
error!(
"'perf' does not seem to be executable? You may need to install it (Ubuntu: \
`sudo apt-get install linux-tools-common`)."
);
error!(
"You may require a restart after fixing this so \
`/sys/bus/event_source/devices` is updated!"
);
std::process::exit(2);
}
}
}
pub fn check_for_perf_permissions() -> bool {
let path = Path::new("/proc/sys/kernel/kptr_restrict");
let mut file = File::open(path).expect("kptr_restrict file does not exist?");
let mut s = String::new();
match file.read_to_string(&mut s) {
Ok(_) => {
match s.trim() {
"1" => {
error!(
"kptr restriction is enabled. You can either run autoperf as root or \
do:"
);
error!("\tsudo sh -c 'echo 0 >> {}'", path.display());
error!("to disable.");
return false;
}
"0" => {
// debug!("kptr_restrict is already disabled (good).");
}
_ => {
warn!(
"Unkown content read from '{}': {}. Proceeding anyways...",
path.display(),
s.trim()
);
}
}
}
Err(why) => {
error!("Couldn't read {}: {}", path.display(), why.description());
std::process::exit(3);
}
}
true
}
pub fn check_for_disabled_nmi_watchdog() -> bool {
let path = Path::new("/proc/sys/kernel/nmi_watchdog");
let mut file = File::open(path).expect("nmi_watchdog file does not exist?");
let mut s = String::new();
match file.read_to_string(&mut s) {
Ok(_) => {
match s.trim() {
"1" => {
error!(
"nmi_watchdog is enabled. This can lead to counters not read (<not \
counted>). Execute"
);
error!("\tsudo sh -c 'echo 0 > {}'", path.display());
error!("to disable.");
return false;
}
"0" => {
// debug!("nmi_watchdog is already disabled (good).");
}
_ => {
warn!(
"Unkown content read from '{}': {}. Proceeding anyways...",
path.display(),
s.trim()
);
}
}
}
Err(why) => {
error!("Couldn't read {}: {}", path.display(), why.description());
std::process::exit(4);
}
}
true
}
pub fn check_for_perf_paranoia() -> bool {
let path = Path::new("/proc/sys/kernel/perf_event_paranoid");
let mut file = File::open(path).expect("perf_event_paranoid file does not exist?");
let mut s = String::new();
let res = match file.read_to_string(&mut s) {
Ok(_) => {
let digit = i64::from_str(s.trim()).unwrap_or_else(|_op| {
warn!(
"Unkown content read from '{}': {}. Proceeding anyways...",
path.display(),
s.trim()
);
1
});
if digit >= 0 {
error!(
"perf_event_paranoid is enabled. This means we can't collect system wide \
stats. Execute"
);
error!("\tsudo sh -c 'echo -1 > {}'", path.display());
error!("to disable.");
false
} else {
true
}
}
Err(why) => {
error!("Couldn't read {}: {}", path.display(), why.description());
std::process::exit(4);
}
};
res
}
|
// Copyright 2020 IOTA Stiftung
//
// 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.
#![cfg(feature = "serde1")]
mod common;
use self::common::*;
use bee_ternary::{raw::*, *};
use serde::{de::DeserializeOwned, *};
fn serialize_generic<T: raw::RawEncodingBuf>()
where
<T::Slice as RawEncoding>::Trit: Serialize,
{
let (a, a_i8) = gen_buf::<T>(0..1000);
assert_eq!(
serde_json::to_string(&a).unwrap(),
format!("[{}]", a_i8.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(",")),
);
}
fn serialize_generic_unbalanced<T: raw::RawEncodingBuf>()
where
<T::Slice as RawEncoding>::Trit: Serialize,
{
let (a, a_i8) = gen_buf_unbalanced::<T>(0..1000);
assert_eq!(
serde_json::to_string(&a).unwrap(),
format!("[{}]", a_i8.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(",")),
);
}
fn deserialize_generic<T: raw::RawEncodingBuf>()
where
<T::Slice as RawEncoding>::Trit: DeserializeOwned,
{
let (a, a_i8) = gen_buf::<T>(0..1000);
assert_eq!(
serde_json::from_str::<TritBuf<T>>(&format!(
"[{}]",
a_i8.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(",")
))
.unwrap(),
a,
);
}
fn deserialize_generic_unbalanced<T: raw::RawEncodingBuf>()
where
<T::Slice as RawEncoding>::Trit: DeserializeOwned,
{
let (a, a_i8) = gen_buf_unbalanced::<T>(0..1000);
assert_eq!(
serde_json::from_str::<TritBuf<T>>(&format!(
"[{}]",
a_i8.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(",")
))
.unwrap(),
a,
);
}
#[test]
fn serialize() {
serialize_generic::<T1B1Buf<Btrit>>();
serialize_generic_unbalanced::<T1B1Buf<Utrit>>();
serialize_generic::<T2B1Buf>();
serialize_generic::<T3B1Buf>();
serialize_generic::<T4B1Buf>();
serialize_generic::<T5B1Buf>();
}
#[test]
fn deserialize() {
deserialize_generic::<T1B1Buf<Btrit>>();
deserialize_generic_unbalanced::<T1B1Buf<Utrit>>();
deserialize_generic::<T2B1Buf>();
deserialize_generic::<T3B1Buf>();
deserialize_generic::<T4B1Buf>();
deserialize_generic::<T5B1Buf>();
}
|
pub mod item;
pub mod quest;
pub mod entity;
pub mod game_local;
pub mod game;
pub mod gamesys;
pub mod player;
pub mod multiplayer_game;
|
//
// model.rs
// Spose
//
// Author: Wess (me@wess.io)
// Created: 12/08/2020
//
// Copywrite (c) 2020 Wess.io
//
use serde::{Serialize};
use mongodb::bson::{
to_bson,
Bson,
oid::ObjectId
};
pub trait Model : Serialize {
fn id(&self) -> Option<ObjectId> {
let b = self.to_bson();
let d = b.as_document().unwrap();
Some(
d.get("_id")
.unwrap()
.as_object_id()
.unwrap()
.clone()
)
}
fn to_bson(&self) -> Bson {
to_bson(self).unwrap()
}
}
|
use futures::TryStreamExt;
use sqlx::postgres::{PgPool, PgQueryAs, PgRow};
use sqlx::{Connection, Cursor, Executor, Postgres, Row};
use sqlx_test::new;
use std::time::Duration;
// TODO: As soon as I tried to deserialize a json value in a function, inferance for this test stopped working. I am at a loss as to how to resolve this.
#[cfg(not(feature = "json"))]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
async fn it_connects() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let value = sqlx::query("select 1 + 1")
.try_map(|row: PgRow| row.try_get::<i32, _>(0))
.fetch_one(&mut conn)
.await?;
assert_eq!(2i32, value);
Ok(())
}
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
async fn it_executes() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let _ = conn
.execute(
r#"
CREATE TEMPORARY TABLE users (id INTEGER PRIMARY KEY);
"#,
)
.await?;
for index in 1..=10_i32 {
let cnt = sqlx::query("INSERT INTO users (id) VALUES ($1)")
.bind(index)
.execute(&mut conn)
.await?;
assert_eq!(cnt, 1);
}
let sum: i32 = sqlx::query("SELECT id FROM users")
.try_map(|row: PgRow| row.try_get::<i32, _>(0))
.fetch(&mut conn)
.try_fold(0_i32, |acc, x| async move { Ok(acc + x) })
.await?;
assert_eq!(sum, 55);
Ok(())
}
// https://github.com/launchbadge/sqlx/issues/104
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
async fn it_can_return_interleaved_nulls_issue_104() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let tuple = sqlx::query("SELECT NULL, 10::INT, NULL, 20::INT, NULL, 40::INT, NULL, 80::INT")
.try_map(|row: PgRow| {
Ok((
row.get::<Option<i32>, _>(0),
row.get::<Option<i32>, _>(1),
row.get::<Option<i32>, _>(2),
row.get::<Option<i32>, _>(3),
row.get::<Option<i32>, _>(4),
row.get::<Option<i32>, _>(5),
row.get::<Option<i32>, _>(6),
row.get::<Option<i32>, _>(7),
))
})
.fetch_one(&mut conn)
.await?;
assert_eq!(tuple.0, None);
assert_eq!(tuple.1, Some(10));
assert_eq!(tuple.2, None);
assert_eq!(tuple.3, Some(20));
assert_eq!(tuple.4, None);
assert_eq!(tuple.5, Some(40));
assert_eq!(tuple.6, None);
assert_eq!(tuple.7, Some(80));
Ok(())
}
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
async fn it_can_work_with_transactions() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
conn.execute("CREATE TABLE IF NOT EXISTS _sqlx_users_1922 (id INTEGER PRIMARY KEY)")
.await?;
conn.execute("TRUNCATE _sqlx_users_1922").await?;
// begin .. rollback
let mut tx = conn.begin().await?;
sqlx::query("INSERT INTO _sqlx_users_1922 (id) VALUES ($1)")
.bind(10_i32)
.execute(&mut tx)
.await?;
conn = tx.rollback().await?;
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_1922")
.fetch_one(&mut conn)
.await?;
assert_eq!(count, 0);
// begin .. commit
let mut tx = conn.begin().await?;
sqlx::query("INSERT INTO _sqlx_users_1922 (id) VALUES ($1)")
.bind(10_i32)
.execute(&mut tx)
.await?;
conn = tx.commit().await?;
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_1922")
.fetch_one(&mut conn)
.await?;
assert_eq!(count, 1);
// begin .. (drop)
{
let mut tx = conn.begin().await?;
sqlx::query("INSERT INTO _sqlx_users_1922 (id) VALUES ($1)")
.bind(20_i32)
.execute(&mut tx)
.await?;
}
conn = new::<Postgres>().await?;
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_1922")
.fetch_one(&mut conn)
.await?;
assert_eq!(count, 1);
Ok(())
}
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
async fn it_can_work_with_nested_transactions() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
conn.execute("CREATE TABLE IF NOT EXISTS _sqlx_users_2523 (id INTEGER PRIMARY KEY)")
.await?;
conn.execute("TRUNCATE _sqlx_users_2523").await?;
// begin
let mut tx = conn.begin().await?;
// insert a user
sqlx::query("INSERT INTO _sqlx_users_2523 (id) VALUES ($1)")
.bind(50_i32)
.execute(&mut tx)
.await?;
// begin once more
let mut tx = tx.begin().await?;
// insert another user
sqlx::query("INSERT INTO _sqlx_users_2523 (id) VALUES ($1)")
.bind(10_i32)
.execute(&mut tx)
.await?;
// never mind, rollback
let mut tx = tx.rollback().await?;
// did we really?
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_2523")
.fetch_one(&mut tx)
.await?;
assert_eq!(count, 1);
// actually, commit
let mut conn = tx.commit().await?;
// did we really?
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_2523")
.fetch_one(&mut conn)
.await?;
assert_eq!(count, 1);
Ok(())
}
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
async fn it_can_rollback_nested_transactions() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
conn.execute("CREATE TABLE IF NOT EXISTS _sqlx_users_512412 (id INTEGER PRIMARY KEY)")
.await?;
conn.execute("TRUNCATE _sqlx_users_512412").await?;
// begin
let mut tx = conn.begin().await?;
// insert a user
sqlx::query("INSERT INTO _sqlx_users_512412 (id) VALUES ($1)")
.bind(50_i32)
.execute(&mut tx)
.await?;
// begin once more
let mut tx = tx.begin().await?;
// insert another user
sqlx::query("INSERT INTO _sqlx_users_512412 (id) VALUES ($1)")
.bind(10_i32)
.execute(&mut tx)
.await?;
// stop the phone, drop the entire transaction
tx.close().await?;
// did we really?
let mut conn = new::<Postgres>().await?;
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_512412")
.fetch_one(&mut conn)
.await?;
assert_eq!(count, 0);
Ok(())
}
// run with `cargo test --features postgres -- --ignored --nocapture pool_smoke_test`
#[ignore]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
async fn pool_smoke_test() -> anyhow::Result<()> {
#[cfg(feature = "runtime-tokio")]
use tokio::{task::spawn, time::delay_for as sleep, time::timeout};
#[cfg(feature = "runtime-async-std")]
use async_std::{future::timeout, task::sleep, task::spawn};
eprintln!("starting pool");
let pool = PgPool::builder()
.connect_timeout(Duration::from_secs(5))
.min_size(5)
.max_size(10)
.build(&dotenv::var("DATABASE_URL")?)
.await?;
// spin up more tasks than connections available, and ensure we don't deadlock
for i in 0..20 {
let pool = pool.clone();
spawn(async move {
loop {
if let Err(e) = sqlx::query("select 1 + 1").execute(&pool).await {
eprintln!("pool task {} dying due to {}", i, e);
break;
}
}
});
}
for _ in 0..5 {
let pool = pool.clone();
spawn(async move {
while !pool.is_closed() {
// drop acquire() futures in a hot loop
// https://github.com/launchbadge/sqlx/issues/83
drop(pool.acquire());
}
});
}
eprintln!("sleeping for 30 seconds");
sleep(Duration::from_secs(30)).await;
assert_eq!(pool.size(), 10);
eprintln!("closing pool");
timeout(Duration::from_secs(30), pool.close()).await?;
eprintln!("pool closed successfully");
Ok(())
}
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
async fn test_invalid_query() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
conn.execute("definitely not a correct query")
.await
.unwrap_err();
let mut cursor = conn.fetch("select 1");
let row = cursor.next().await?.unwrap();
assert_eq!(row.get::<i32, _>(0), 1i32);
Ok(())
}
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
async fn test_describe() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let _ = conn
.execute(
r#"
CREATE TEMP TABLE describe_test (
id SERIAL primary key,
name text not null,
hash bytea
)
"#,
)
.await?;
let describe = conn
.describe("select nt.*, false from describe_test nt")
.await?;
assert_eq!(describe.result_columns[0].non_null, Some(true));
assert_eq!(
describe.result_columns[0]
.type_info
.as_ref()
.unwrap()
.to_string(),
"INT4"
);
assert_eq!(describe.result_columns[1].non_null, Some(true));
assert_eq!(
describe.result_columns[1]
.type_info
.as_ref()
.unwrap()
.to_string(),
"TEXT"
);
assert_eq!(describe.result_columns[2].non_null, Some(false));
assert_eq!(
describe.result_columns[2]
.type_info
.as_ref()
.unwrap()
.to_string(),
"BYTEA"
);
assert_eq!(describe.result_columns[3].non_null, None);
assert_eq!(
describe.result_columns[3]
.type_info
.as_ref()
.unwrap()
.to_string(),
"BOOL"
);
Ok(())
}
|
pub mod time_util;
pub mod xml_loader;
pub mod print_util;
pub mod string_util;
pub mod value_util;
pub mod bencher;
pub mod join_in;
pub mod error_util;
pub mod array_util; |
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright ยฉ 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
/// Host Identity Protocol (`HIP`) resource record data.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct HostIdentityProtocol<'a>
{
/// Host identitiy tag (HIT).
pub host_identity_tag: &'a [u8],
/// Public key.
pub public_key: Option<PublicKey<'a>>,
/// At least one rendezvous server is present.
pub first_rendezvous_server_domain_name: WithoutCompressionParsedName<'a>,
/// May be empty.
///
/// Recipients *SHOULD* parse this to make sure the names are valid.
pub remaining_rendezvous_server_domain_names: &'a [u8],
}
|
use thiserror::Error;
use tokio::task::JoinError;
use tokio::time::error::Elapsed;
#[derive(Error, Debug)]
pub enum DlmError {
#[error("the input file is empty")]
EmptyInputFile,
#[error("connection closed")]
ConnectionClosed,
#[error("connection timeout")]
ConnectionTimeout,
#[error("response body error")]
ResponseBodyError,
#[error("deadline elapsed timeout")]
DeadLineElapsedTimeout,
#[error("response status not success - {status_code:?}")]
ResponseStatusNotSuccess { status_code: String },
#[error("URL decode error - {message:?}")]
UrlDecodeError { message: String },
#[error("standard I/O error - {e}")]
StdIoError { e: std::io::Error },
#[error("task error - {e}")]
TaskError { e: JoinError },
#[error("channel error - {e}")]
ChannelError { e: async_channel::RecvError },
#[error("CLI argument error - {message:?}")]
CliArgumentError { message: String },
#[error("CLI argument error ({e})")]
ClapError { e: clap::Error },
#[error("other error - {message:?}")]
Other { message: String },
}
const CONNECTION_CLOSED: &str = "connection closed before message completed";
const CONNECTION_TIMEOUT: &str = "error trying to connect: operation timed out";
const BODY_ERROR: &str = "error reading a body from connection";
impl From<reqwest::Error> for DlmError {
fn from(e: reqwest::Error) -> Self {
//TODO use Reqwest's types instead of guessing from strings https://github.com/seanmonstar/reqwest/issues/757
let e_string = e.to_string();
if e_string.contains(BODY_ERROR) {
DlmError::ResponseBodyError
} else if e_string.contains(CONNECTION_CLOSED) {
DlmError::ConnectionClosed
} else if e_string.contains(CONNECTION_TIMEOUT) {
DlmError::ConnectionTimeout
} else {
DlmError::Other { message: e_string }
}
}
}
impl From<std::io::Error> for DlmError {
fn from(e: std::io::Error) -> Self {
DlmError::StdIoError { e }
}
}
impl From<Elapsed> for DlmError {
fn from(_: Elapsed) -> Self {
DlmError::DeadLineElapsedTimeout
}
}
impl From<JoinError> for DlmError {
fn from(e: JoinError) -> Self {
DlmError::TaskError { e }
}
}
impl From<async_channel::RecvError> for DlmError {
fn from(e: async_channel::RecvError) -> Self {
DlmError::ChannelError { e }
}
}
impl From<clap::Error> for DlmError {
fn from(e: clap::Error) -> Self {
DlmError::ClapError { e }
}
}
|
use midi_message::MidiMessage;
use color::Color;
use color_strip::ColorStrip;
use effects::effect::Effect;
// http://www.roxlu.com/downloads/scholar/001.fluid.height_field_simulation.pdf
pub struct Ripple {
u: Vec<f64>,
v: Vec<f64>,
}
impl Ripple {
pub fn new(led_count: usize) -> Ripple {
Ripple {
u: vec![0.0; led_count],
v: vec![0.0; led_count],
}
}
pub fn on_note(&mut self, note: u8) {
let i = (i32::from(note)) % self.u.len() as i32;
self.u[i as usize] = 1256.0;
}
}
fn wrap_index(i: usize, delta: i32, l: usize) -> usize {
((i as i32 + delta + l as i32) % l as i32) as usize
}
impl Effect for Ripple {
fn paint(&mut self, color_strip: &mut ColorStrip) {
for (i, &height) in self.u.iter().enumerate() {
let light = f64::min(height, 255.0) as u8;
color_strip.pixel[i] += if light < 128 {
Color::new(0, 0, 128 + light)
} else {
Color::new((light - 128) * 2, (light - 128) * 2, 255)
};
}
}
fn tick(&mut self) {
let l = self.u.len();
for i in 0..l {
let new_v = (self.u[wrap_index(i, -1, l)] + self.u[wrap_index(i, 1, l)]) / 2.0 -
self.u[i];
self.v[i] = new_v * 0.999;
}
for i in 0..l {
self.u[i] = f64::max(self.u[i] + self.v[i] * 1.0 - 2.0, 0.0);
}
}
fn on_midi_message(&mut self, midi_message: MidiMessage) {
if let MidiMessage::NoteOn(_, note, _) = midi_message {
self.on_note(note)
}
}
} |
use input_i_scanner::{scan_with, InputIScanner};
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
let (a, b, c) = scan_with!(_i_i, (u32, u32, u32));
for x in a..=b {
if x % c == 0 {
println!("{}", x);
return;
}
}
println!("-1");
}
|
use std::cell::RefCell;
use std::rc::Rc;
use nom::character::complete::char as nom_char;
use nom::combinator::recognize;
use nom::error::Error;
use nom::sequence::pair;
use nom::IResult;
use nom::Parser;
type InputType<'a> = &'a str;
type NomError<'a> = Error<InputType<'a>>;
type DynParser<'a> = dyn FnMut(InputType<'a>) -> IResult<InputType<'a>, InputType<'a>> + 'a;
type BoxedParser<'a> = Box<DynParser<'a>>;
struct NomParserWrapper<F> {
f: Rc<RefCell<F>>,
}
impl<F> Clone for NomParserWrapper<F> {
fn clone(&self) -> Self {
NomParserWrapper { f: self.f.clone() }
}
}
impl<F> NomParserWrapper<F> {
fn new(f: F) -> Self {
NomParserWrapper {
f: Rc::new(RefCell::new(f)),
}
}
}
impl<I, O1, E, F: Parser<I, O1, E>> Parser<I, O1, E> for NomParserWrapper<F> {
fn parse(&mut self, i: I) -> IResult<I, O1, E> {
self.f.borrow_mut().parse(i)
}
}
fn nom_parser_wrapper_new<'a, F>(f: F) -> NomParserWrapper<F>
where
F: Parser<InputType<'a>, InputType<'a>, NomError<'a>>,
{
NomParserWrapper::new(f)
}
fn main() {
let char_parser = nom_char('3');
let char_parser_rc = NomParserWrapper::new(char_parser);
let recognize_parser = recognize(char_parser_rc);
let mut recognize_parser_rc = nom_parser_wrapper_new(recognize_parser);
let mut recognize_parser_rc_2 = recognize_parser_rc.clone();
let parsed = recognize_parser_rc.parse("3");
dbg!(parsed.is_ok());
let parsed = recognize_parser_rc_2.parse("a");
dbg!(parsed.is_err());
let char_parser = || recognize(nom_char('c'));
let first_wrapper = NomParserWrapper::new(char_parser());
let mut parser_accumulator: BoxedParser = Box::new(recognize(first_wrapper));
for _ in 1..3 {
parser_accumulator = Box::new(recognize(pair(parser_accumulator, char_parser())));
}
let mut compunded_parser = nom_parser_wrapper_new(parser_accumulator);
let parsed = compunded_parser.parse("cccc");
dbg!(parsed.is_ok());
}
|
//! Utilities for testing `cam_geom` implementations.
use super::*;
use nalgebra::{
base::{dimension::Dyn, VecStorage},
convert,
};
pub(crate) fn generate_uv_raw<R: RealField>(
width: usize,
height: usize,
step: usize,
border: usize,
) -> Pixels<R, Dyn, VecStorage<R, Dyn, U2>> {
let mut uv_raws: Vec<[R; 2]> = Vec::new();
for row in num_iter::range_step(border, height - border, step) {
for col in num_iter::range_step(border, width - border, step) {
uv_raws.push([convert(col as f64), convert(row as f64)]);
}
}
let mut data = nalgebra::OMatrix::<R, Dyn, U2>::from_element(uv_raws.len(), convert(0.0));
for i in 0..uv_raws.len() {
for j in 0..2 {
data[(i, j)] = uv_raws[i][j].clone();
}
}
Pixels { data }
}
/// Test roundtrip projection from pixels to camera rays for an intrinsic camera model.
///
/// Generate pixel coordinates, project them to rays, convert to points on the
/// rays, convert the points back to pixels, and then compare with the original
/// pixel coordinates.
pub fn roundtrip_intrinsics<R, CAM>(
cam: &CAM,
width: usize,
height: usize,
step: usize,
border: usize,
eps: R,
) where
R: RealField,
CAM: IntrinsicParameters<R>,
CAM::BundleType: Bundle<R>,
{
let pixels = generate_uv_raw(width, height, step, border);
let camcoords = cam.pixel_to_camera(&pixels);
let camera_coords_points = camcoords.point_on_ray();
// project back to pixel coordinates
let pixel_actual = cam.camera_to_pixel(&camera_coords_points);
approx::assert_abs_diff_eq!(pixels.data, pixel_actual.data, epsilon = convert(eps));
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_exception::Result;
use crate::optimizer::group::Group;
use crate::optimizer::m_expr::MExpr;
use crate::optimizer::memo::Memo;
use crate::optimizer::SExpr;
/// A helper to extract `SExpr`s from `Memo` that match the given pattern.
pub struct PatternExtractor {}
impl PatternExtractor {
pub fn create() -> Self {
PatternExtractor {}
}
pub fn extract(&mut self, memo: &Memo, m_expr: &MExpr, pattern: &SExpr) -> Result<Vec<SExpr>> {
if !m_expr.match_pattern(memo, pattern) {
return Ok(vec![]);
}
if pattern.is_pattern() {
// Pattern operator is `Pattern`, we can return current operator.
return Ok(vec![SExpr::create(
m_expr.plan.clone(),
vec![],
Some(m_expr.group_index),
Some(memo.group(m_expr.group_index)?.relational_prop.clone()),
)]);
}
let pattern_children = pattern.children();
if m_expr.arity() != pattern_children.len() {
return Ok(vec![]);
}
let mut children_results = vec![];
for (i, child) in m_expr.children.iter().enumerate().take(m_expr.arity()) {
let pattern = &pattern_children[i];
let child_group = memo.group(*child)?;
let result = self.extract_group(memo, child_group, pattern)?;
children_results.push(result);
}
Self::generate_expression_with_children(memo, m_expr, children_results)
}
fn extract_group(&mut self, memo: &Memo, group: &Group, pattern: &SExpr) -> Result<Vec<SExpr>> {
let mut results = vec![];
for m_expr in group.m_exprs.iter() {
let result = self.extract(memo, m_expr, pattern)?;
results.extend(result.into_iter());
}
Ok(results)
}
fn generate_expression_with_children(
memo: &Memo,
m_expr: &MExpr,
candidates: Vec<Vec<SExpr>>,
) -> Result<Vec<SExpr>> {
let mut results = vec![];
// Initialize cursors
let mut cursors: Vec<usize> = vec![];
for candidate in candidates.iter() {
if candidate.is_empty() {
// Every child should have at least one candidate
return Ok(results);
}
cursors.push(0);
}
if cursors.is_empty() {
results.push(SExpr::create(
m_expr.plan.clone(),
vec![],
Some(m_expr.group_index),
Some(memo.group(m_expr.group_index)?.relational_prop.clone()),
));
return Ok(results);
}
'LOOP: loop {
let mut children: Vec<SExpr> = vec![];
for (index, cursor) in cursors.iter().enumerate() {
children.push(candidates[index][*cursor].clone());
}
results.push(SExpr::create(
m_expr.plan.clone(),
children,
Some(m_expr.group_index),
Some(memo.group(m_expr.group_index)?.relational_prop.clone()),
));
let mut shifted = false;
// Shift cursor
for i in (0..cursors.len()).rev() {
if !shifted {
// Shift cursor
cursors[i] += 1;
shifted = true;
}
if i == 0 && cursors[0] > candidates[0].len() - 1 {
// Candidates are exhausted
break 'LOOP;
} else if i > 0 && cursors[i] > candidates[i].len() - 1 {
// Shift previous children
cursors[i] = 0;
cursors[i - 1] += 1;
continue;
} else {
break;
}
}
}
Ok(results)
}
}
|
use std::fs::File;
use std::string::String;
use std::io::prelude::*;
use std::char;
fn main() {
let mut box_ids = String::new();
File::open("./../input.txt")
.expect("Unable to read from input.txt")
.read_to_string(&mut box_ids)
.expect("Unable to feed contents to string");
let mut common_id: String = String::from("");
'outer: for box_id in box_ids.lines() {
for other_box_id in box_ids.lines() {
let mut diff_count = 0;
common_id.clear();
for (first, second) in box_id.trim().chars().zip(other_box_id.trim().chars()) {
if first == second {
common_id.push(first);
} else {
diff_count += 1;
}
}
if diff_count == 1 {
break 'outer;
}
}
}
println!("Common Box ID: {}", common_id);
}
|
use crate::geom::{Point, Vector};
pub struct Inertia {
pub position: Point,
pub prev: Point,
}
impl Inertia {
pub fn step() -> f32 {
0.01
}
pub fn new(position: Point) -> Inertia {
let prev = position;
Inertia { position, prev }
}
pub fn integrate(&mut self) {
let inertia = self.inertia();
self.prev = self.position;
self.position = self.position + inertia
}
pub fn inertia(&self) -> Point {
self.position - self.prev
}
pub fn force(&mut self, force: Vector) {
self.prev = self.prev - (force * Self::step());
}
}
impl std::fmt::Debug for Inertia {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}->{:?}", self.position, self.inertia())
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "Media_Capture_Core")]
pub mod Core;
#[cfg(feature = "Media_Capture_Frames")]
pub mod Frames;
#[link(name = "windows")]
extern "system" {}
pub type AdvancedCapturedPhoto = *mut ::core::ffi::c_void;
pub type AdvancedPhotoCapture = *mut ::core::ffi::c_void;
pub type AppBroadcastBackgroundService = *mut ::core::ffi::c_void;
pub type AppBroadcastBackgroundServiceSignInInfo = *mut ::core::ffi::c_void;
pub type AppBroadcastBackgroundServiceStreamInfo = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppBroadcastCameraCaptureState(pub i32);
impl AppBroadcastCameraCaptureState {
pub const Stopped: Self = Self(0i32);
pub const Started: Self = Self(1i32);
pub const Failed: Self = Self(2i32);
}
impl ::core::marker::Copy for AppBroadcastCameraCaptureState {}
impl ::core::clone::Clone for AppBroadcastCameraCaptureState {
fn clone(&self) -> Self {
*self
}
}
pub type AppBroadcastCameraCaptureStateChangedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppBroadcastCameraOverlayLocation(pub i32);
impl AppBroadcastCameraOverlayLocation {
pub const TopLeft: Self = Self(0i32);
pub const TopCenter: Self = Self(1i32);
pub const TopRight: Self = Self(2i32);
pub const MiddleLeft: Self = Self(3i32);
pub const MiddleCenter: Self = Self(4i32);
pub const MiddleRight: Self = Self(5i32);
pub const BottomLeft: Self = Self(6i32);
pub const BottomCenter: Self = Self(7i32);
pub const BottomRight: Self = Self(8i32);
}
impl ::core::marker::Copy for AppBroadcastCameraOverlayLocation {}
impl ::core::clone::Clone for AppBroadcastCameraOverlayLocation {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct AppBroadcastCameraOverlaySize(pub i32);
impl AppBroadcastCameraOverlaySize {
pub const Small: Self = Self(0i32);
pub const Medium: Self = Self(1i32);
pub const Large: Self = Self(2i32);
}
impl ::core::marker::Copy for AppBroadcastCameraOverlaySize {}
impl ::core::clone::Clone for AppBroadcastCameraOverlaySize {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct AppBroadcastCaptureTargetType(pub i32);
impl AppBroadcastCaptureTargetType {
pub const AppView: Self = Self(0i32);
pub const EntireDisplay: Self = Self(1i32);
}
impl ::core::marker::Copy for AppBroadcastCaptureTargetType {}
impl ::core::clone::Clone for AppBroadcastCaptureTargetType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct AppBroadcastExitBroadcastModeReason(pub i32);
impl AppBroadcastExitBroadcastModeReason {
pub const NormalExit: Self = Self(0i32);
pub const UserCanceled: Self = Self(1i32);
pub const AuthorizationFail: Self = Self(2i32);
pub const ForegroundAppActivated: Self = Self(3i32);
}
impl ::core::marker::Copy for AppBroadcastExitBroadcastModeReason {}
impl ::core::clone::Clone for AppBroadcastExitBroadcastModeReason {
fn clone(&self) -> Self {
*self
}
}
pub type AppBroadcastGlobalSettings = *mut ::core::ffi::c_void;
pub type AppBroadcastHeartbeatRequestedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppBroadcastMicrophoneCaptureState(pub i32);
impl AppBroadcastMicrophoneCaptureState {
pub const Stopped: Self = Self(0i32);
pub const Started: Self = Self(1i32);
pub const Failed: Self = Self(2i32);
}
impl ::core::marker::Copy for AppBroadcastMicrophoneCaptureState {}
impl ::core::clone::Clone for AppBroadcastMicrophoneCaptureState {
fn clone(&self) -> Self {
*self
}
}
pub type AppBroadcastMicrophoneCaptureStateChangedEventArgs = *mut ::core::ffi::c_void;
pub type AppBroadcastPlugIn = *mut ::core::ffi::c_void;
pub type AppBroadcastPlugInManager = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppBroadcastPlugInState(pub i32);
impl AppBroadcastPlugInState {
pub const Unknown: Self = Self(0i32);
pub const Initialized: Self = Self(1i32);
pub const MicrosoftSignInRequired: Self = Self(2i32);
pub const OAuthSignInRequired: Self = Self(3i32);
pub const ProviderSignInRequired: Self = Self(4i32);
pub const InBandwidthTest: Self = Self(5i32);
pub const ReadyToBroadcast: Self = Self(6i32);
}
impl ::core::marker::Copy for AppBroadcastPlugInState {}
impl ::core::clone::Clone for AppBroadcastPlugInState {
fn clone(&self) -> Self {
*self
}
}
pub type AppBroadcastPlugInStateChangedEventArgs = *mut ::core::ffi::c_void;
pub type AppBroadcastPreview = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppBroadcastPreviewState(pub i32);
impl AppBroadcastPreviewState {
pub const Started: Self = Self(0i32);
pub const Stopped: Self = Self(1i32);
pub const Failed: Self = Self(2i32);
}
impl ::core::marker::Copy for AppBroadcastPreviewState {}
impl ::core::clone::Clone for AppBroadcastPreviewState {
fn clone(&self) -> Self {
*self
}
}
pub type AppBroadcastPreviewStateChangedEventArgs = *mut ::core::ffi::c_void;
pub type AppBroadcastPreviewStreamReader = *mut ::core::ffi::c_void;
pub type AppBroadcastPreviewStreamVideoFrame = *mut ::core::ffi::c_void;
pub type AppBroadcastPreviewStreamVideoHeader = *mut ::core::ffi::c_void;
pub type AppBroadcastProviderSettings = *mut ::core::ffi::c_void;
pub type AppBroadcastServices = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppBroadcastSignInResult(pub i32);
impl AppBroadcastSignInResult {
pub const Success: Self = Self(0i32);
pub const AuthenticationFailed: Self = Self(1i32);
pub const Unauthorized: Self = Self(2i32);
pub const ServiceUnavailable: Self = Self(3i32);
pub const Unknown: Self = Self(4i32);
}
impl ::core::marker::Copy for AppBroadcastSignInResult {}
impl ::core::clone::Clone for AppBroadcastSignInResult {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct AppBroadcastSignInState(pub i32);
impl AppBroadcastSignInState {
pub const NotSignedIn: Self = Self(0i32);
pub const MicrosoftSignInInProgress: Self = Self(1i32);
pub const MicrosoftSignInComplete: Self = Self(2i32);
pub const OAuthSignInInProgress: Self = Self(3i32);
pub const OAuthSignInComplete: Self = Self(4i32);
}
impl ::core::marker::Copy for AppBroadcastSignInState {}
impl ::core::clone::Clone for AppBroadcastSignInState {
fn clone(&self) -> Self {
*self
}
}
pub type AppBroadcastSignInStateChangedEventArgs = *mut ::core::ffi::c_void;
pub type AppBroadcastState = *mut ::core::ffi::c_void;
pub type AppBroadcastStreamAudioFrame = *mut ::core::ffi::c_void;
pub type AppBroadcastStreamAudioHeader = *mut ::core::ffi::c_void;
pub type AppBroadcastStreamReader = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppBroadcastStreamState(pub i32);
impl AppBroadcastStreamState {
pub const Initializing: Self = Self(0i32);
pub const StreamReady: Self = Self(1i32);
pub const Started: Self = Self(2i32);
pub const Paused: Self = Self(3i32);
pub const Terminated: Self = Self(4i32);
}
impl ::core::marker::Copy for AppBroadcastStreamState {}
impl ::core::clone::Clone for AppBroadcastStreamState {
fn clone(&self) -> Self {
*self
}
}
pub type AppBroadcastStreamStateChangedEventArgs = *mut ::core::ffi::c_void;
pub type AppBroadcastStreamVideoFrame = *mut ::core::ffi::c_void;
pub type AppBroadcastStreamVideoHeader = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppBroadcastTerminationReason(pub i32);
impl AppBroadcastTerminationReason {
pub const NormalTermination: Self = Self(0i32);
pub const LostConnectionToService: Self = Self(1i32);
pub const NoNetworkConnectivity: Self = Self(2i32);
pub const ServiceAbort: Self = Self(3i32);
pub const ServiceError: Self = Self(4i32);
pub const ServiceUnavailable: Self = Self(5i32);
pub const InternalError: Self = Self(6i32);
pub const UnsupportedFormat: Self = Self(7i32);
pub const BackgroundTaskTerminated: Self = Self(8i32);
pub const BackgroundTaskUnresponsive: Self = Self(9i32);
}
impl ::core::marker::Copy for AppBroadcastTerminationReason {}
impl ::core::clone::Clone for AppBroadcastTerminationReason {
fn clone(&self) -> Self {
*self
}
}
pub type AppBroadcastTriggerDetails = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppBroadcastVideoEncodingBitrateMode(pub i32);
impl AppBroadcastVideoEncodingBitrateMode {
pub const Custom: Self = Self(0i32);
pub const Auto: Self = Self(1i32);
}
impl ::core::marker::Copy for AppBroadcastVideoEncodingBitrateMode {}
impl ::core::clone::Clone for AppBroadcastVideoEncodingBitrateMode {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct AppBroadcastVideoEncodingResolutionMode(pub i32);
impl AppBroadcastVideoEncodingResolutionMode {
pub const Custom: Self = Self(0i32);
pub const Auto: Self = Self(1i32);
}
impl ::core::marker::Copy for AppBroadcastVideoEncodingResolutionMode {}
impl ::core::clone::Clone for AppBroadcastVideoEncodingResolutionMode {
fn clone(&self) -> Self {
*self
}
}
pub type AppBroadcastViewerCountChangedEventArgs = *mut ::core::ffi::c_void;
pub type AppCapture = *mut ::core::ffi::c_void;
pub type AppCaptureAlternateShortcutKeys = *mut ::core::ffi::c_void;
pub type AppCaptureDurationGeneratedEventArgs = *mut ::core::ffi::c_void;
pub type AppCaptureFileGeneratedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppCaptureHistoricalBufferLengthUnit(pub i32);
impl AppCaptureHistoricalBufferLengthUnit {
pub const Megabytes: Self = Self(0i32);
pub const Seconds: Self = Self(1i32);
}
impl ::core::marker::Copy for AppCaptureHistoricalBufferLengthUnit {}
impl ::core::clone::Clone for AppCaptureHistoricalBufferLengthUnit {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct AppCaptureMetadataPriority(pub i32);
impl AppCaptureMetadataPriority {
pub const Informational: Self = Self(0i32);
pub const Important: Self = Self(1i32);
}
impl ::core::marker::Copy for AppCaptureMetadataPriority {}
impl ::core::clone::Clone for AppCaptureMetadataPriority {
fn clone(&self) -> Self {
*self
}
}
pub type AppCaptureMetadataWriter = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppCaptureMicrophoneCaptureState(pub i32);
impl AppCaptureMicrophoneCaptureState {
pub const Stopped: Self = Self(0i32);
pub const Started: Self = Self(1i32);
pub const Failed: Self = Self(2i32);
}
impl ::core::marker::Copy for AppCaptureMicrophoneCaptureState {}
impl ::core::clone::Clone for AppCaptureMicrophoneCaptureState {
fn clone(&self) -> Self {
*self
}
}
pub type AppCaptureMicrophoneCaptureStateChangedEventArgs = *mut ::core::ffi::c_void;
pub type AppCaptureRecordOperation = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppCaptureRecordingState(pub i32);
impl AppCaptureRecordingState {
pub const InProgress: Self = Self(0i32);
pub const Completed: Self = Self(1i32);
pub const Failed: Self = Self(2i32);
}
impl ::core::marker::Copy for AppCaptureRecordingState {}
impl ::core::clone::Clone for AppCaptureRecordingState {
fn clone(&self) -> Self {
*self
}
}
pub type AppCaptureRecordingStateChangedEventArgs = *mut ::core::ffi::c_void;
pub type AppCaptureServices = *mut ::core::ffi::c_void;
pub type AppCaptureSettings = *mut ::core::ffi::c_void;
pub type AppCaptureState = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppCaptureVideoEncodingBitrateMode(pub i32);
impl AppCaptureVideoEncodingBitrateMode {
pub const Custom: Self = Self(0i32);
pub const High: Self = Self(1i32);
pub const Standard: Self = Self(2i32);
}
impl ::core::marker::Copy for AppCaptureVideoEncodingBitrateMode {}
impl ::core::clone::Clone for AppCaptureVideoEncodingBitrateMode {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct AppCaptureVideoEncodingFrameRateMode(pub i32);
impl AppCaptureVideoEncodingFrameRateMode {
pub const Standard: Self = Self(0i32);
pub const High: Self = Self(1i32);
}
impl ::core::marker::Copy for AppCaptureVideoEncodingFrameRateMode {}
impl ::core::clone::Clone for AppCaptureVideoEncodingFrameRateMode {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct AppCaptureVideoEncodingResolutionMode(pub i32);
impl AppCaptureVideoEncodingResolutionMode {
pub const Custom: Self = Self(0i32);
pub const High: Self = Self(1i32);
pub const Standard: Self = Self(2i32);
}
impl ::core::marker::Copy for AppCaptureVideoEncodingResolutionMode {}
impl ::core::clone::Clone for AppCaptureVideoEncodingResolutionMode {
fn clone(&self) -> Self {
*self
}
}
pub type CameraCaptureUI = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct CameraCaptureUIMaxPhotoResolution(pub i32);
impl CameraCaptureUIMaxPhotoResolution {
pub const HighestAvailable: Self = Self(0i32);
pub const VerySmallQvga: Self = Self(1i32);
pub const SmallVga: Self = Self(2i32);
pub const MediumXga: Self = Self(3i32);
pub const Large3M: Self = Self(4i32);
pub const VeryLarge5M: Self = Self(5i32);
}
impl ::core::marker::Copy for CameraCaptureUIMaxPhotoResolution {}
impl ::core::clone::Clone for CameraCaptureUIMaxPhotoResolution {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct CameraCaptureUIMaxVideoResolution(pub i32);
impl CameraCaptureUIMaxVideoResolution {
pub const HighestAvailable: Self = Self(0i32);
pub const LowDefinition: Self = Self(1i32);
pub const StandardDefinition: Self = Self(2i32);
pub const HighDefinition: Self = Self(3i32);
}
impl ::core::marker::Copy for CameraCaptureUIMaxVideoResolution {}
impl ::core::clone::Clone for CameraCaptureUIMaxVideoResolution {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct CameraCaptureUIMode(pub i32);
impl CameraCaptureUIMode {
pub const PhotoOrVideo: Self = Self(0i32);
pub const Photo: Self = Self(1i32);
pub const Video: Self = Self(2i32);
}
impl ::core::marker::Copy for CameraCaptureUIMode {}
impl ::core::clone::Clone for CameraCaptureUIMode {
fn clone(&self) -> Self {
*self
}
}
pub type CameraCaptureUIPhotoCaptureSettings = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct CameraCaptureUIPhotoFormat(pub i32);
impl CameraCaptureUIPhotoFormat {
pub const Jpeg: Self = Self(0i32);
pub const Png: Self = Self(1i32);
pub const JpegXR: Self = Self(2i32);
}
impl ::core::marker::Copy for CameraCaptureUIPhotoFormat {}
impl ::core::clone::Clone for CameraCaptureUIPhotoFormat {
fn clone(&self) -> Self {
*self
}
}
pub type CameraCaptureUIVideoCaptureSettings = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct CameraCaptureUIVideoFormat(pub i32);
impl CameraCaptureUIVideoFormat {
pub const Mp4: Self = Self(0i32);
pub const Wmv: Self = Self(1i32);
}
impl ::core::marker::Copy for CameraCaptureUIVideoFormat {}
impl ::core::clone::Clone for CameraCaptureUIVideoFormat {
fn clone(&self) -> Self {
*self
}
}
pub type CapturedFrame = *mut ::core::ffi::c_void;
pub type CapturedFrameControlValues = *mut ::core::ffi::c_void;
pub type CapturedPhoto = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct ForegroundActivationArgument(pub i32);
impl ForegroundActivationArgument {
pub const SignInRequired: Self = Self(0i32);
pub const MoreSettings: Self = Self(1i32);
}
impl ::core::marker::Copy for ForegroundActivationArgument {}
impl ::core::clone::Clone for ForegroundActivationArgument {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct GameBarCommand(pub i32);
impl GameBarCommand {
pub const OpenGameBar: Self = Self(0i32);
pub const RecordHistoricalBuffer: Self = Self(1i32);
pub const ToggleStartStopRecord: Self = Self(2i32);
pub const StartRecord: Self = Self(3i32);
pub const StopRecord: Self = Self(4i32);
pub const TakeScreenshot: Self = Self(5i32);
pub const StartBroadcast: Self = Self(6i32);
pub const StopBroadcast: Self = Self(7i32);
pub const PauseBroadcast: Self = Self(8i32);
pub const ResumeBroadcast: Self = Self(9i32);
pub const ToggleStartStopBroadcast: Self = Self(10i32);
pub const ToggleMicrophoneCapture: Self = Self(11i32);
pub const ToggleCameraCapture: Self = Self(12i32);
pub const ToggleRecordingIndicator: Self = Self(13i32);
}
impl ::core::marker::Copy for GameBarCommand {}
impl ::core::clone::Clone for GameBarCommand {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct GameBarCommandOrigin(pub i32);
impl GameBarCommandOrigin {
pub const ShortcutKey: Self = Self(0i32);
pub const Cortana: Self = Self(1i32);
pub const AppCommand: Self = Self(2i32);
}
impl ::core::marker::Copy for GameBarCommandOrigin {}
impl ::core::clone::Clone for GameBarCommandOrigin {
fn clone(&self) -> Self {
*self
}
}
pub type GameBarServices = *mut ::core::ffi::c_void;
pub type GameBarServicesCommandEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct GameBarServicesDisplayMode(pub i32);
impl GameBarServicesDisplayMode {
pub const Windowed: Self = Self(0i32);
pub const FullScreenExclusive: Self = Self(1i32);
}
impl ::core::marker::Copy for GameBarServicesDisplayMode {}
impl ::core::clone::Clone for GameBarServicesDisplayMode {
fn clone(&self) -> Self {
*self
}
}
pub type GameBarServicesManager = *mut ::core::ffi::c_void;
pub type GameBarServicesManagerGameBarServicesCreatedEventArgs = *mut ::core::ffi::c_void;
pub type GameBarServicesTargetInfo = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct GameBarTargetCapturePolicy(pub i32);
impl GameBarTargetCapturePolicy {
pub const EnabledBySystem: Self = Self(0i32);
pub const EnabledByUser: Self = Self(1i32);
pub const NotEnabled: Self = Self(2i32);
pub const ProhibitedBySystem: Self = Self(3i32);
pub const ProhibitedByPublisher: Self = Self(4i32);
}
impl ::core::marker::Copy for GameBarTargetCapturePolicy {}
impl ::core::clone::Clone for GameBarTargetCapturePolicy {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct KnownVideoProfile(pub i32);
impl KnownVideoProfile {
pub const VideoRecording: Self = Self(0i32);
pub const HighQualityPhoto: Self = Self(1i32);
pub const BalancedVideoAndPhoto: Self = Self(2i32);
pub const VideoConferencing: Self = Self(3i32);
pub const PhotoSequence: Self = Self(4i32);
pub const HighFrameRate: Self = Self(5i32);
pub const VariablePhotoSequence: Self = Self(6i32);
pub const HdrWithWcgVideo: Self = Self(7i32);
pub const HdrWithWcgPhoto: Self = Self(8i32);
pub const VideoHdr8: Self = Self(9i32);
pub const CompressedCamera: Self = Self(10i32);
}
impl ::core::marker::Copy for KnownVideoProfile {}
impl ::core::clone::Clone for KnownVideoProfile {
fn clone(&self) -> Self {
*self
}
}
pub type LowLagMediaRecording = *mut ::core::ffi::c_void;
pub type LowLagPhotoCapture = *mut ::core::ffi::c_void;
pub type LowLagPhotoSequenceCapture = *mut ::core::ffi::c_void;
pub type MediaCapture = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct MediaCaptureDeviceExclusiveControlStatus(pub i32);
impl MediaCaptureDeviceExclusiveControlStatus {
pub const ExclusiveControlAvailable: Self = Self(0i32);
pub const SharedReadOnlyAvailable: Self = Self(1i32);
}
impl ::core::marker::Copy for MediaCaptureDeviceExclusiveControlStatus {}
impl ::core::clone::Clone for MediaCaptureDeviceExclusiveControlStatus {
fn clone(&self) -> Self {
*self
}
}
pub type MediaCaptureDeviceExclusiveControlStatusChangedEventArgs = *mut ::core::ffi::c_void;
pub type MediaCaptureFailedEventArgs = *mut ::core::ffi::c_void;
pub type MediaCaptureFailedEventHandler = *mut ::core::ffi::c_void;
pub type MediaCaptureFocusChangedEventArgs = *mut ::core::ffi::c_void;
pub type MediaCaptureInitializationSettings = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct MediaCaptureMemoryPreference(pub i32);
impl MediaCaptureMemoryPreference {
pub const Auto: Self = Self(0i32);
pub const Cpu: Self = Self(1i32);
}
impl ::core::marker::Copy for MediaCaptureMemoryPreference {}
impl ::core::clone::Clone for MediaCaptureMemoryPreference {
fn clone(&self) -> Self {
*self
}
}
pub type MediaCapturePauseResult = *mut ::core::ffi::c_void;
pub type MediaCaptureRelativePanelWatcher = *mut ::core::ffi::c_void;
pub type MediaCaptureSettings = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct MediaCaptureSharingMode(pub i32);
impl MediaCaptureSharingMode {
pub const ExclusiveControl: Self = Self(0i32);
pub const SharedReadOnly: Self = Self(1i32);
}
impl ::core::marker::Copy for MediaCaptureSharingMode {}
impl ::core::clone::Clone for MediaCaptureSharingMode {
fn clone(&self) -> Self {
*self
}
}
pub type MediaCaptureStopResult = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct MediaCaptureThermalStatus(pub i32);
impl MediaCaptureThermalStatus {
pub const Normal: Self = Self(0i32);
pub const Overheated: Self = Self(1i32);
}
impl ::core::marker::Copy for MediaCaptureThermalStatus {}
impl ::core::clone::Clone for MediaCaptureThermalStatus {
fn clone(&self) -> Self {
*self
}
}
pub type MediaCaptureVideoProfile = *mut ::core::ffi::c_void;
pub type MediaCaptureVideoProfileMediaDescription = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct MediaCategory(pub i32);
impl MediaCategory {
pub const Other: Self = Self(0i32);
pub const Communications: Self = Self(1i32);
pub const Media: Self = Self(2i32);
pub const GameChat: Self = Self(3i32);
pub const Speech: Self = Self(4i32);
pub const FarFieldSpeech: Self = Self(5i32);
pub const UniformSpeech: Self = Self(6i32);
pub const VoiceTyping: Self = Self(7i32);
}
impl ::core::marker::Copy for MediaCategory {}
impl ::core::clone::Clone for MediaCategory {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct MediaStreamType(pub i32);
impl MediaStreamType {
pub const VideoPreview: Self = Self(0i32);
pub const VideoRecord: Self = Self(1i32);
pub const Audio: Self = Self(2i32);
pub const Photo: Self = Self(3i32);
pub const Metadata: Self = Self(4i32);
}
impl ::core::marker::Copy for MediaStreamType {}
impl ::core::clone::Clone for MediaStreamType {
fn clone(&self) -> Self {
*self
}
}
pub type OptionalReferencePhotoCapturedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhotoCaptureSource(pub i32);
impl PhotoCaptureSource {
pub const Auto: Self = Self(0i32);
pub const VideoPreview: Self = Self(1i32);
pub const Photo: Self = Self(2i32);
}
impl ::core::marker::Copy for PhotoCaptureSource {}
impl ::core::clone::Clone for PhotoCaptureSource {
fn clone(&self) -> Self {
*self
}
}
pub type PhotoCapturedEventArgs = *mut ::core::ffi::c_void;
pub type PhotoConfirmationCapturedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PowerlineFrequency(pub i32);
impl PowerlineFrequency {
pub const Disabled: Self = Self(0i32);
pub const FiftyHertz: Self = Self(1i32);
pub const SixtyHertz: Self = Self(2i32);
pub const Auto: Self = Self(3i32);
}
impl ::core::marker::Copy for PowerlineFrequency {}
impl ::core::clone::Clone for PowerlineFrequency {
fn clone(&self) -> Self {
*self
}
}
pub type RecordLimitationExceededEventHandler = *mut ::core::ffi::c_void;
pub type ScreenCapture = *mut ::core::ffi::c_void;
pub type SourceSuspensionChangedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct StreamingCaptureMode(pub i32);
impl StreamingCaptureMode {
pub const AudioAndVideo: Self = Self(0i32);
pub const Audio: Self = Self(1i32);
pub const Video: Self = Self(2i32);
}
impl ::core::marker::Copy for StreamingCaptureMode {}
impl ::core::clone::Clone for StreamingCaptureMode {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct VideoDeviceCharacteristic(pub i32);
impl VideoDeviceCharacteristic {
pub const AllStreamsIndependent: Self = Self(0i32);
pub const PreviewRecordStreamsIdentical: Self = Self(1i32);
pub const PreviewPhotoStreamsIdentical: Self = Self(2i32);
pub const RecordPhotoStreamsIdentical: Self = Self(3i32);
pub const AllStreamsIdentical: Self = Self(4i32);
}
impl ::core::marker::Copy for VideoDeviceCharacteristic {}
impl ::core::clone::Clone for VideoDeviceCharacteristic {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct VideoRotation(pub i32);
impl VideoRotation {
pub const None: Self = Self(0i32);
pub const Clockwise90Degrees: Self = Self(1i32);
pub const Clockwise180Degrees: Self = Self(2i32);
pub const Clockwise270Degrees: Self = Self(3i32);
}
impl ::core::marker::Copy for VideoRotation {}
impl ::core::clone::Clone for VideoRotation {
fn clone(&self) -> Self {
*self
}
}
pub type VideoStreamConfiguration = *mut ::core::ffi::c_void;
#[repr(C)]
pub struct WhiteBalanceGain {
pub R: f64,
pub G: f64,
pub B: f64,
}
impl ::core::marker::Copy for WhiteBalanceGain {}
impl ::core::clone::Clone for WhiteBalanceGain {
fn clone(&self) -> Self {
*self
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_datavalues::DataValue;
use ordered_float::OrderedFloat;
use crate::Scalar;
pub fn scalar_to_datavalue(scalar: &Scalar) -> DataValue {
match scalar {
Scalar::Null => DataValue::Null,
Scalar::EmptyArray => DataValue::Null,
Scalar::Number(ty) => match ty {
crate::types::number::NumberScalar::UInt8(x) => DataValue::UInt64(*x as u64),
crate::types::number::NumberScalar::UInt16(x) => DataValue::UInt64(*x as u64),
crate::types::number::NumberScalar::UInt32(x) => DataValue::UInt64(*x as u64),
crate::types::number::NumberScalar::UInt64(x) => DataValue::UInt64(*x),
crate::types::number::NumberScalar::Int8(x) => DataValue::Int64(*x as i64),
crate::types::number::NumberScalar::Int16(x) => DataValue::Int64(*x as i64),
crate::types::number::NumberScalar::Int32(x) => DataValue::Int64(*x as i64),
crate::types::number::NumberScalar::Int64(x) => DataValue::Int64(*x),
crate::types::number::NumberScalar::Float32(x) => {
DataValue::Float64(<OrderedFloat<f32> as Into<f32>>::into(*x) as f64)
}
crate::types::number::NumberScalar::Float64(x) => DataValue::Float64((*x).into()),
},
Scalar::Decimal(_) => unimplemented!("decimal type is not supported"),
Scalar::Timestamp(x) => DataValue::Int64(*x),
Scalar::Date(x) => DataValue::Int64(*x as i64),
Scalar::Boolean(x) => DataValue::Boolean(*x),
Scalar::String(x) | Scalar::Variant(x) => DataValue::String(x.clone()),
Scalar::Array(x) => {
let values = (0..x.len())
.map(|idx| scalar_to_datavalue(&x.index(idx).unwrap().to_owned()))
.collect();
DataValue::Array(values)
}
Scalar::Tuple(x) => {
let values = x.iter().map(scalar_to_datavalue).collect();
DataValue::Struct(values)
}
Scalar::EmptyMap | Scalar::Map(_) => unimplemented!(),
}
}
|
use super::{InlineObject, InlineObjectTrait};
use crate::{
heap::{
object_heap::HeapObject, symbol_table::impl_ord_with_symbol_table_via_ord, Heap, Int, Tag,
},
utils::{impl_debug_display_via_debugdisplay, impl_eq_hash_ord_via_get, DebugDisplay},
};
use derive_more::Deref;
use extension_trait::extension_trait;
use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::Signed;
use rustc_hash::FxHashMap;
use std::{
cmp::Ordering,
fmt::{self, Formatter},
num::NonZeroU64,
ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Rem, Shl, Shr, Sub},
};
#[derive(Clone, Copy, Deref)]
pub struct InlineInt(InlineObject);
impl InlineInt {
const VALUE_SHIFT: usize = 3;
pub fn new_unchecked(object: InlineObject) -> Self {
Self(object)
}
pub fn fits(value: i64) -> bool {
(value << Self::VALUE_SHIFT) >> Self::VALUE_SHIFT == value
}
pub fn from_unchecked(value: i64) -> Self {
debug_assert_eq!(
(value << Self::VALUE_SHIFT) >> Self::VALUE_SHIFT,
value,
"Integer is too large.",
);
let header_word = InlineObject::KIND_INT | ((value as u64) << Self::VALUE_SHIFT);
let header_word = unsafe { NonZeroU64::new_unchecked(header_word) };
Self(InlineObject(header_word))
}
pub fn get(self) -> i64 {
self.raw_word().get() as i64 >> Self::VALUE_SHIFT
}
pub fn try_get<T: TryFrom<i64>>(&self) -> Option<T> {
self.get().try_into().ok()
}
operator_fn!(add, i64::checked_add, Add::add);
operator_fn!(subtract, i64::checked_sub, Sub::sub);
operator_fn!(multiply, i64::checked_mul, Mul::mul);
operator_fn!(int_divide_truncating, i64::checked_div, Div::div);
operator_fn!(remainder, i64::checked_rem, Rem::rem);
pub fn modulo(self, heap: &mut Heap, rhs: Self) -> Int {
let lhs = self.get();
let rhs = rhs.get();
lhs.checked_rem_euclid(rhs)
.map(|it| Int::create(heap, true, it))
.unwrap_or_else(|| {
Int::create_from_bigint(heap, true, BigInt::from(lhs).mod_floor(&rhs.into()))
})
}
pub fn compare_to(self, rhs: Int) -> Tag {
let ordering = match rhs {
Int::Inline(rhs) => self.get().cmp(&rhs.get()),
Int::Heap(rhs) => {
if rhs.get().is_negative() {
Ordering::Greater
} else {
Ordering::Less
}
}
};
Tag::create_ordering(ordering)
}
shift_fn!(shift_left, i64::checked_shl, Shl::shl);
shift_fn!(shift_right, i64::checked_shr, Shr::shr);
pub fn bit_length(self) -> Self {
// SAFETY: The `bit_length` can be at most 61 since that's how large an [InlineInt] can get.
Self::from_unchecked(self.get().bit_length().into())
}
operator_fn_closed!(bitwise_and, BitAnd::bitand);
operator_fn_closed!(bitwise_or, BitOr::bitor);
operator_fn_closed!(bitwise_xor, BitXor::bitxor);
}
macro_rules! operator_fn {
($name:ident, $inline_operation:expr, $bigint_operation:expr) => {
pub fn $name(self, heap: &mut Heap, rhs: Int) -> Int {
let lhs = self.get();
match rhs {
Int::Inline(rhs) => rhs
.try_get()
.and_then(|rhs| $inline_operation(lhs, rhs))
.map(|it| Int::create(heap, true, it))
.unwrap_or_else(|| {
Int::create_from_bigint(
heap,
true,
$bigint_operation(BigInt::from(lhs), rhs.get()),
)
}),
Int::Heap(rhs) => Int::create_from_bigint(
heap,
true,
$bigint_operation(BigInt::from(lhs), rhs.get()),
),
}
}
};
}
macro_rules! shift_fn {
($name:ident, $inline_operation:expr, $bigint_operation:expr) => {
pub fn $name(self, heap: &mut Heap, rhs: InlineInt) -> Int {
let lhs = self.get();
rhs.try_get()
.and_then(|rhs| $inline_operation(lhs, rhs))
.map(|it| Int::create(heap, true, it))
.unwrap_or_else(|| {
Int::create_from_bigint(
heap,
true,
$bigint_operation(BigInt::from(lhs), rhs.get()),
)
})
}
};
}
macro_rules! operator_fn_closed {
($name:ident, $operation:expr) => {
pub fn $name(self, rhs: Self) -> Self {
// SAFETY: The new number can't exceed the input number of bits.
Self::from_unchecked($operation(self.get(), rhs.get()))
}
};
}
use {operator_fn, operator_fn_closed, shift_fn};
impl DebugDisplay for InlineInt {
fn fmt(&self, f: &mut Formatter, _is_debug: bool) -> fmt::Result {
write!(f, "{}", self.get())
}
}
impl_debug_display_via_debugdisplay!(InlineInt);
impl_eq_hash_ord_via_get!(InlineInt);
impl TryFrom<&BigInt> for InlineInt {
type Error = ();
fn try_from(value: &BigInt) -> Result<Self, Self::Error> {
i64::try_from(value)
.map_err(|_| ())
.and_then(|value| value.try_into())
}
}
impl TryFrom<i64> for InlineInt {
type Error = ();
fn try_from(value: i64) -> Result<Self, Self::Error> {
if InlineInt::fits(value) {
Ok(InlineInt::from_unchecked(value))
} else {
Err(())
}
}
}
impl InlineObjectTrait for InlineInt {
fn clone_to_heap_with_mapping(
self,
_heap: &mut Heap,
_address_map: &mut FxHashMap<HeapObject, HeapObject>,
) -> Self {
self
}
}
impl_ord_with_symbol_table_via_ord!(InlineInt);
#[extension_trait]
pub impl I64BitLength for i64 {
fn bit_length(self) -> u32 {
i64::BITS - self.unsigned_abs().leading_zeros()
}
}
|
use core::slice::{Iter, IterMut};
use std::ops::{Index, IndexMut};
#[derive(Debug)]
pub struct VkMappedMemory<'a, T>
where
T: Clone,
{
data: &'a mut [T],
}
impl<'a, T: Clone> VkMappedMemory<'a, T> {
pub(crate) fn new(data: &'a mut [T]) -> VkMappedMemory<'a, T> {
VkMappedMemory { data }
}
pub fn copy(&mut self, data: &[T]) {
self.data.clone_from_slice(data);
}
pub fn iter(&self) -> Iter<'_, T> {
self.data.iter()
}
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
self.data.iter_mut()
}
}
impl<'a, T: Clone> Index<usize> for VkMappedMemory<'a, T> {
type Output = T;
fn index(&self, index: usize) -> &T {
&self.data[index]
}
}
impl<'a, T: Clone> IndexMut<usize> for VkMappedMemory<'a, T> {
fn index_mut(&mut self, index: usize) -> &mut T {
&mut self.data[index]
}
}
|
use cortex_m::asm::bkpt;
use cortex_m;
use nrf51;
use boards::nrf51dk::PERIPH;
use Kernel;
use boards::peripherals::timers::Timer;
#[derive(PartialEq, Clone)]
pub enum PendingInterrupt {
Button1,
Button2,
Button3,
Button4
}
pub struct Interrupt {
pub pending_interrupt: Option<PendingInterrupt>
}
impl Interrupt {
pub fn new() -> Interrupt {
Interrupt { pending_interrupt: None }
}
#[allow(non_snake_case)]
pub fn GPIOTE_IRQHandler(&mut self) {
cortex_m::interrupt::free(|cs| {
if let Some(p) = PERIPH.borrow(cs).borrow().as_ref() {
// TODO we should be referencing the buttons array
for i in 0..4 {
let button = p.GPIOTE.events_in[i].read().bits() != 0;
if button {
//print("button pressed");
self.set_button_pending_interrupt(i);
}
// clear the events
p.GPIOTE.events_in[i].write(|w| unsafe { w.bits(0) });
}
}
});
}
fn set_button_pending_interrupt(&mut self, button_index: usize) {
let button_interrupts = [
PendingInterrupt::Button1,
PendingInterrupt::Button2,
PendingInterrupt::Button3,
PendingInterrupt::Button4
];
self.pending_interrupt = Some(button_interrupts[button_index].clone());
}
pub fn consume_if_pending_interrupt(&mut self) -> Option<PendingInterrupt> {
let mut maybe_interrupt = None;
cortex_m::interrupt::free(|_cs| {
if let Some(ref interrupt) = self.pending_interrupt {
maybe_interrupt = Some(interrupt.clone());
}
self.pending_interrupt = None;
});
return maybe_interrupt;
}
// TODO timers should be using the new timer struct
#[allow(non_snake_case)]
pub fn TIMER0_IRQHandler(&self) {
cortex_m::interrupt::free(|_cs| {
// Get an instance of timer 0
let timer0 = Timer::new(0, 1000000);
// update the current time
Kernel::os_update_time(timer0.get_value());
// clear the registers
timer0.clear();
timer0.clear_event();
});
}
#[allow(non_snake_case)]
pub fn TIMER1_IRQHandler() {
cortex_m::interrupt::free(|_cs| {
/*Do Something*/
unsafe {
// clear the register
(*nrf51::TIMER1::ptr()).tasks_clear.write(|w| w.bits(1));
// clear the event
(*nrf51::TIMER1::ptr()).events_compare[1].write(|w| w.bits(0));
}
bkpt();
});
}
#[allow(non_snake_case)]
pub fn TIMER2_IRQHandler() {
cortex_m::interrupt::free(|_cs| {
/*Do Something*/
unsafe {
// clear the register
(*nrf51::TIMER2::ptr()).tasks_clear.write(|w| w.bits(1));
// clear the event
(*nrf51::TIMER2::ptr()).events_compare[2].write(|w| w.bits(0));
}
bkpt();
});
}
} |
/// The basic macro for making a union of entities.
///
/// This macro is the most generic version.
/// You can find more specific versions in `shape`, `material` and `object` modules.
///
/// You can read more about the technique [here](https://clay-rs.github.io/knowledge/#objects).
#[macro_export]
macro_rules! instance_select {
($Select:ident: $Base:path: $Class:ty { $( $Enum:ident($Param:ident = $Instance:ty) ),+ $(,)? }) => {
pub enum $Select<
$( $Param:
$crate::Pack +
$crate::Instance<$Class> +
$Base
= $Instance
),+
> {
$( $Enum($Param), )+
}
impl $Select {
#[allow(unused_assignments)]
fn index(&self) -> u32 {
let mut i = 0;
$(
if let $Select::$Enum(_) = self {
return i;
}
i += 1;
)+
unreachable!()
}
#[allow(unused_assignments)]
fn method_source(method: &str) -> String {
use $crate::class::*;
let cpref = format!(
"{}_{}",
<$Class>::name(),
method,
).to_uppercase();
let mut cases = Vec::new();
let mut i = 0;
$(
let inst_name = <$Instance as $crate::Instance<$Class>>::inst_name();
cases.push([
format!("\tif (sel_idx == {}) {{", i),
format!(
"\t\treturn {}_{}({}_ARGS_B(1, 0));",
inst_name, method, cpref,
),
"\t}".to_string(),
].join("\n"));
i += 1;
)+
let cases_text = cases.join(" else\n");
[
&format!(
"{}_RET {}_{}({}_ARGS_DEF) {{",
cpref, Self::inst_name(), method, cpref,
),
"\tint sel_idx = ibuf[0];",
&cases_text,
&format!("\treturn {}_RET_BAD;", cpref),
"}",
].join("\n")
}
}
impl $crate::Instance<$Class> for $Select {
fn source(cache: &mut std::collections::HashSet<u64>) -> String {
use $crate::{TypeHash, class::*};
if !cache.insert(Self::type_hash()) {
return String::new()
}
let mut ms = Vec::new();
for method in <$Class>::methods().into_iter() {
ms.push(Self::method_source(&method));
}
[
$( <$Instance as $crate::Instance<$Class>>::source(cache), )+
ms.join("\n"),
].join("\n")
}
fn inst_name() -> String {
use $crate::TypeHash;
format!("__select_{:x}", Self::type_hash())
}
}
impl $crate::Pack for $Select {
fn size_int() -> usize {
let sizes = [
$( <$Instance>::size_int(), )+
];
1 + *sizes.iter().max().unwrap()
}
fn size_float() -> usize {
let sizes = [
$( <$Instance>::size_float(), )+
];
*sizes.iter().max().unwrap()
}
fn pack_to(&self, mut buffer_int: &mut [i32], buffer_float: &mut [f32]) {
use $crate::pack::*;
self.index().pack_int_to(buffer_int);
buffer_int = &mut buffer_int[1..];
match self {
$( $Select::$Enum(x) => x.pack_to(buffer_int, buffer_float), )+
}
}
}
$(
impl From<$Instance> for $Select {
fn from(origin: $Instance) -> Self {
$Select::$Enum(origin)
}
}
)+
};
}
#[cfg(test)]
mod check {
use crate::{
shape::{
Shape, ShapeClass,
test::TestShape,
},
instance_select,
};
instance_select!(
TestSelect: Shape: ShapeClass {
Shape1(T1 = TestShape<i32>),
Shape2(T2 = TestShape<f32>),
}
);
}
|
/*
tree!{
sum => {
mul => { a, c },
b
}
};
******
sum(mul(a, c), b)
*/
#[derive(Debug)]
struct My {
a: i32,
b: i32
}
fn procedure<'res, 'a: 'res, 'b: 'res>(
a: &'a My, b: &'b My) -> &'res My
{
if a.a > b.b { a } else { b }
}
fn main() {
let a = My { a: 13, b: -1 };
let b = My { a: 10, b: 6 };
let x = procedure(&a, &b);
println!("{:?}", x);
}
|
use crate::errors::ServiceError;
use actix_web::{client::Client, http::StatusCode};
use failure::Error;
use qrcode::QrCode;
use redis::{Commands, RedisError};
pub struct QREncoder {
username: String,
github_url: String,
redis_url: String,
redis_ttl: usize,
}
impl QREncoder {
pub fn new(
username: &String,
github_url: &String,
redis_url: &String,
redis_ttl: &usize,
) -> Self {
QREncoder {
username: username.clone(),
github_url: github_url.clone(),
redis_url: redis_url.clone(),
redis_ttl: *redis_ttl,
}
}
pub async fn encode(&self) -> Result<Vec<String>, Error> {
let api_client = ApiClient::new(&self.github_url, &self.username);
let redis_client = RedisClient::new(self.redis_url.clone(), self.redis_ttl, &self.username);
if !regex::Regex::new(r"\A[a-z0-9-]+\z")
.unwrap()
.is_match(&self.username)
{
return Err(ServiceError::InvalidUsername(self.username.clone()).into());
}
let value_in_redis: Vec<u8>;
match redis_client.get() {
Err(e) => return Err(ServiceError::RedisError(e).into()),
Ok(v) => value_in_redis = v,
}
if value_in_redis.len() > 0 {
let pair = value_in_redis
.split(|num| num == &b':')
.collect::<Vec<&[u8]>>();
let etag_in_redis = pair[0].to_vec();
let public_keys_in_redis = pair[1].to_vec();
api_client
.send_request(Some(etag_in_redis))
.await
.and_then(move |response_data| match response_data.status_code {
StatusCode::NOT_MODIFIED => {
log::info!("ETag matched");
Ok(public_keys_in_redis)
}
StatusCode::OK => {
log::info!("ETag not matched");
let body = response_data.body;
match redis_client.set(&response_data.etag[..], &body[..]) {
Err(e) => return Err(ServiceError::RedisError(e).into()),
Ok(_) => {}
}
Ok(body)
}
_ => Err(ServiceError::UnexpectedStatusCode(response_data.status_code).into()),
})
} else {
api_client
.send_request(None)
.await
.and_then(move |response_data| {
let body = response_data.body;
match redis_client.set(&response_data.etag[..], &body[..]) {
Err(e) => return Err(ServiceError::RedisError(e).into()),
Ok(_) => {}
}
Ok(body)
})
}
.map(|public_keys| {
public_keys
.split(|num| num == &10u8)
.collect::<Vec<&[u8]>>()
.iter()
.map(|public_key| {
QrCode::new(&public_key)
.expect(&format!(
"failed to initialize QRCode. [public_key: {:?}]",
public_key
))
.render::<qrcode::render::svg::Color>()
.quiet_zone(true)
.build()
})
.collect()
})
}
}
struct ApiClient<'a> {
github_url: &'a str,
username: &'a str,
}
impl<'a> ApiClient<'a> {
fn new(github_url: &'a str, username: &'a str) -> Self {
ApiClient {
github_url,
username,
}
}
async fn send_request(&self, etag: Option<Vec<u8>>) -> Result<ResponseData, Error> {
let mut client_request = Client::default().get(&self.github_endpoint());
if let Some(etag) = etag {
client_request = client_request.header("If-None-Match", etag)
}
client_request
.send()
.await
.map_err(|e| ServiceError::SendRequest(format!("{}", e)).into())
.and_then(|mut response| {
let resp_status = response.status();
if resp_status == StatusCode::NOT_MODIFIED {
Ok(ResponseData::new(resp_status, None, None))
} else {
futures::executor::block_on(response.body())
.map_err(|e| ServiceError::GetResponseBody(format!("{}", e)).into())
.and_then(move |bytes| {
let mut vec_u8 = bytes.to_vec();
if vec_u8.pop() != Some(10u8) {
return Err(ServiceError::NoTrailingNewline(
String::from_utf8(vec_u8).unwrap(),
)
.into());
}
let etag = match response.headers().get("ETag") {
Some(etag) => etag.as_bytes().to_vec(),
None => vec![],
};
Ok(ResponseData::new(resp_status, etag, vec_u8))
})
}
})
}
fn github_endpoint(&self) -> String {
format!("{}{}.keys", self.github_url, self.username)
}
}
struct ResponseData {
status_code: StatusCode,
etag: Vec<u8>,
body: Vec<u8>,
}
impl ResponseData {
fn new(
status_code: StatusCode,
etag: impl Into<Option<Vec<u8>>>,
body: impl Into<Option<Vec<u8>>>,
) -> Self {
Self {
status_code,
etag: etag.into().unwrap_or(vec![]),
body: body.into().unwrap_or(vec![]),
}
}
}
struct RedisClient {
redis_url: String,
redis_ttl: usize,
redis_key: String,
}
impl<'a> RedisClient {
fn new(redis_url: String, redis_ttl: usize, username: &'a str) -> Self {
Self {
redis_url,
redis_ttl,
redis_key: format!("username:{}", username),
}
}
fn get(&self) -> Result<Vec<u8>, RedisError> {
let value = self.get_connection()?.get(&self.redis_key);
log::info!("Got data from redis. [key: {}]", &self.redis_key,);
value
}
fn set(&self, etag: &[u8], public_keys: &[u8]) -> Result<(), RedisError> {
let value = self.build_value(etag, public_keys);
let mut conn = self.get_connection()?;
conn.set(&self.redis_key, value)?;
conn.expire(&self.redis_key, self.redis_ttl)?;
log::info!("Set data to redis. [key: {}]", &self.redis_key,);
Ok(())
}
fn get_connection(&self) -> Result<redis::Connection, RedisError> {
redis::Client::open(self.redis_url.as_str())?.get_connection()
}
fn build_value(&self, etag: &[u8], public_keys: &[u8]) -> Vec<u8> {
[etag, b":", public_keys].concat()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_send_request() {
let response_data = actix_rt::System::new("test").block_on(async {
ApiClient::new("https://github.com/", "hioki")
.send_request(None)
.await
.unwrap()
});
assert_eq!(response_data.status_code, StatusCode::OK);
assert_eq!(
String::from_utf8(response_data.etag).unwrap(),
String::from("W/\"db8b4393a051570a5bf3ac92f784c086\"")
);
assert_eq!(
String::from_utf8(response_data.body).unwrap(),
String::from(
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGrql7jpTfbW48HzUluCwddwPwg4+UNNIqI3ntPBFOPg"
)
);
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Operating mode Register"]
pub mtlomr: MTLOMR,
_reserved1: [u8; 28usize],
#[doc = "0x20 - Interrupt status Register"]
pub mtlisr: MTLISR,
_reserved2: [u8; 220usize],
#[doc = "0x100 - Tx queue operating mode Register"]
pub mtltx_qomr: MTLTXQOMR,
#[doc = "0x104 - Tx queue underflow register"]
pub mtltx_qur: MTLTXQUR,
#[doc = "0x108 - Tx queue debug Register"]
pub mtltx_qdr: MTLTXQDR,
_reserved5: [u8; 32usize],
#[doc = "0x12c - Queue interrupt control status Register"]
pub mtlqicsr: MTLQICSR,
#[doc = "0x130 - Rx queue operating mode register"]
pub mtlrx_qomr: MTLRXQOMR,
#[doc = "0x134 - Rx queue missed packet and overflow counter register"]
pub mtlrx_qmpocr: MTLRXQMPOCR,
#[doc = "0x138 - Rx queue debug register"]
pub mtlrx_qdr: MTLRXQDR,
}
#[doc = "Operating mode Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mtlomr](mtlomr) module"]
pub type MTLOMR = crate::Reg<u32, _MTLOMR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MTLOMR;
#[doc = "`read()` method returns [mtlomr::R](mtlomr::R) reader structure"]
impl crate::Readable for MTLOMR {}
#[doc = "`write(|w| ..)` method takes [mtlomr::W](mtlomr::W) writer structure"]
impl crate::Writable for MTLOMR {}
#[doc = "Operating mode Register"]
pub mod mtlomr;
#[doc = "Interrupt status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mtlisr](mtlisr) module"]
pub type MTLISR = crate::Reg<u32, _MTLISR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MTLISR;
#[doc = "`read()` method returns [mtlisr::R](mtlisr::R) reader structure"]
impl crate::Readable for MTLISR {}
#[doc = "`write(|w| ..)` method takes [mtlisr::W](mtlisr::W) writer structure"]
impl crate::Writable for MTLISR {}
#[doc = "Interrupt status Register"]
pub mod mtlisr;
#[doc = "Tx queue operating mode Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mtltx_qomr](mtltx_qomr) module"]
pub type MTLTXQOMR = crate::Reg<u32, _MTLTXQOMR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MTLTXQOMR;
#[doc = "`read()` method returns [mtltx_qomr::R](mtltx_qomr::R) reader structure"]
impl crate::Readable for MTLTXQOMR {}
#[doc = "`write(|w| ..)` method takes [mtltx_qomr::W](mtltx_qomr::W) writer structure"]
impl crate::Writable for MTLTXQOMR {}
#[doc = "Tx queue operating mode Register"]
pub mod mtltx_qomr;
#[doc = "Tx queue underflow register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mtltx_qur](mtltx_qur) module"]
pub type MTLTXQUR = crate::Reg<u32, _MTLTXQUR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MTLTXQUR;
#[doc = "`read()` method returns [mtltx_qur::R](mtltx_qur::R) reader structure"]
impl crate::Readable for MTLTXQUR {}
#[doc = "`write(|w| ..)` method takes [mtltx_qur::W](mtltx_qur::W) writer structure"]
impl crate::Writable for MTLTXQUR {}
#[doc = "Tx queue underflow register"]
pub mod mtltx_qur;
#[doc = "Tx queue debug Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mtltx_qdr](mtltx_qdr) module"]
pub type MTLTXQDR = crate::Reg<u32, _MTLTXQDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MTLTXQDR;
#[doc = "`read()` method returns [mtltx_qdr::R](mtltx_qdr::R) reader structure"]
impl crate::Readable for MTLTXQDR {}
#[doc = "`write(|w| ..)` method takes [mtltx_qdr::W](mtltx_qdr::W) writer structure"]
impl crate::Writable for MTLTXQDR {}
#[doc = "Tx queue debug Register"]
pub mod mtltx_qdr;
#[doc = "Queue interrupt control status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mtlqicsr](mtlqicsr) module"]
pub type MTLQICSR = crate::Reg<u32, _MTLQICSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MTLQICSR;
#[doc = "`read()` method returns [mtlqicsr::R](mtlqicsr::R) reader structure"]
impl crate::Readable for MTLQICSR {}
#[doc = "`write(|w| ..)` method takes [mtlqicsr::W](mtlqicsr::W) writer structure"]
impl crate::Writable for MTLQICSR {}
#[doc = "Queue interrupt control status Register"]
pub mod mtlqicsr;
#[doc = "Rx queue operating mode register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mtlrx_qomr](mtlrx_qomr) module"]
pub type MTLRXQOMR = crate::Reg<u32, _MTLRXQOMR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MTLRXQOMR;
#[doc = "`read()` method returns [mtlrx_qomr::R](mtlrx_qomr::R) reader structure"]
impl crate::Readable for MTLRXQOMR {}
#[doc = "`write(|w| ..)` method takes [mtlrx_qomr::W](mtlrx_qomr::W) writer structure"]
impl crate::Writable for MTLRXQOMR {}
#[doc = "Rx queue operating mode register"]
pub mod mtlrx_qomr;
#[doc = "Rx queue missed packet and overflow counter register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mtlrx_qmpocr](mtlrx_qmpocr) module"]
pub type MTLRXQMPOCR = crate::Reg<u32, _MTLRXQMPOCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MTLRXQMPOCR;
#[doc = "`read()` method returns [mtlrx_qmpocr::R](mtlrx_qmpocr::R) reader structure"]
impl crate::Readable for MTLRXQMPOCR {}
#[doc = "`write(|w| ..)` method takes [mtlrx_qmpocr::W](mtlrx_qmpocr::W) writer structure"]
impl crate::Writable for MTLRXQMPOCR {}
#[doc = "Rx queue missed packet and overflow counter register"]
pub mod mtlrx_qmpocr;
#[doc = "Rx queue debug register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mtlrx_qdr](mtlrx_qdr) module"]
pub type MTLRXQDR = crate::Reg<u32, _MTLRXQDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MTLRXQDR;
#[doc = "`read()` method returns [mtlrx_qdr::R](mtlrx_qdr::R) reader structure"]
impl crate::Readable for MTLRXQDR {}
#[doc = "`write(|w| ..)` method takes [mtlrx_qdr::W](mtlrx_qdr::W) writer structure"]
impl crate::Writable for MTLRXQDR {}
#[doc = "Rx queue debug register"]
pub mod mtlrx_qdr;
|
/*
* __ __ _ _ _
* | \/ | ___ ___ __ _| | (_)_ __ | | __
* | |\/| |/ _ \/ __|/ _` | | | | '_ \| |/ /
* | | | | __/\__ \ (_| | |___| | | | | <
* |_| |_|\___||___/\__,_|_____|_|_| |_|_|\_\
*
* Copyright (c) 2017-2018, The MesaLink Authors.
* All rights reserved.
*
* This work is licensed under the terms of the BSD 3-Clause License.
* For a copy, see the LICENSE file.
*
*/
/// Implementations of OpenSSL BIO APIs.
/// Please also refer to the header file at mesalink/openssl/bio.h
pub mod bio;
/// Implementations of OpenSSL EVP APIs.
/// Please also refer to the header file at mesalink/openssl/evp.h
pub mod evp;
/// Implementations of OpenSSL PEM APIs.
/// Please also refer to the header file at mesalink/openssl/evp.h
pub mod pem;
use libc::c_int;
pub(self) const CRYPTO_FAILURE: c_int = 0;
pub(self) const CRYPTO_SUCCESS: c_int = 1;
|
/// ```rust,ignore
/// 43. ๅญ็ฌฆไธฒ็ธไน
///
/// ็ปๅฎไธคไธชไปฅๅญ็ฌฆไธฒๅฝขๅผ่กจ็คบ็้่ดๆดๆฐ num1 ๅ num2๏ผ่ฟๅ num1 ๅ num2 ็ไน็งฏ๏ผๅฎไปฌ็ไน็งฏไน่กจ็คบไธบๅญ็ฌฆไธฒๅฝขๅผใ
///
/// ็คบไพ 1:
///
/// ่พๅ
ฅ: num1 = "2", num2 = "3"
/// ่พๅบ: "6"
///
/// ็คบไพ 2:
///
/// ่พๅ
ฅ: num1 = "123", num2 = "456"
/// ่พๅบ: "56088"
///
/// ่ฏดๆ๏ผ
///
/// num1 ๅ num2 ็้ฟๅบฆๅฐไบ110ใ
/// num1 ๅ num2 ๅชๅ
ๅซๆฐๅญ 0-9ใ
/// num1 ๅ num2 ๅไธไปฅ้ถๅผๅคด๏ผ้ค้ๆฏๆฐๅญ 0 ๆฌ่บซใ
/// ไธ่ฝไฝฟ็จไปปไฝๆ ๅๅบ็ๅคงๆฐ็ฑปๅ๏ผๆฏๅฆ BigInteger๏ผๆ็ดๆฅๅฐ่พๅ
ฅ่ฝฌๆขไธบๆดๆฐๆฅๅค็ใ
///
/// ๆฅๆบ๏ผๅๆฃ๏ผLeetCode๏ผ
/// ้พๆฅ๏ผhttps://leetcode-cn.com/problems/multiply-strings
/// ่ไฝๆๅฝ้ขๆฃ็ฝ็ปๆๆใๅไธ่ฝฌ่ฝฝ่ฏท่็ณปๅฎๆนๆๆ๏ผ้ๅไธ่ฝฌ่ฝฝ่ฏทๆณจๆๅบๅคใ
/// ```
pub fn multiply(num1: String, num2: String) -> String {
let bytes1 = num1.into_bytes();
let bytes2 = num2.into_bytes();
let (mut nb1, mut nb2) = (bytes1.len() - 1, bytes2.len() - 1);
let (mut a, mut b) = (0 as i128, 0 as i128);
for i in bytes1 {
a += ((i as i128) - ('0' as i128)) * ((10 as f64).powi((nb1) as i32) as i128);
if nb1 == 0 {
break;
}
nb1 -= 1;
}
for i in bytes2 {
b += ((i as i128) - ('0' as i128)) * ((10 as f64).powi((nb2) as i32) as i128);
if nb2 == 0 {
break;
}
nb2 -= 1;
}
(a * b).to_string()
}
#[cfg(test)]
mod test
{
use super::multiply;
#[test]
fn test_multiply()
{
assert_eq!(multiply("2".to_string(), "3".to_string()), "6".to_string());
// assert_eq!(multiply("401716832807512840963".to_string(), "167141802233061013023557397451289113296441069".to_string()), "67143675422804947379429215144664313370120390398055713625298709447".to_string());
}
}
|
//! Inlets
use std::ffi::c_void;
///Callback method for Float inlet
pub type FloatCB<T> = Box<dyn Fn(&T, f64)>;
///Callback method for Int inletk
pub type IntCB<T> = Box<dyn Fn(&T, max_sys::t_atom_long)>;
/// Inlets for Max objects
pub enum MaxInlet<T> {
Float(FloatCB<T>),
Int(IntCB<T>),
Proxy,
}
/// Inlets for MSP objects
pub enum MSPInlet<T> {
Float(FloatCB<T>),
Int(IntCB<T>),
Proxy,
Signal,
}
/// Encapsulation of a Max Proxy inlet
pub struct Proxy {
inner: *mut c_void,
}
impl Proxy {
pub fn new(owner: *mut max_sys::t_object, id: usize) -> Self {
Self {
inner: unsafe { max_sys::proxy_new(owner as _, id as _, std::ptr::null_mut()) },
}
}
pub fn get_inlet<I: Into<*mut max_sys::t_object>>(owner: I) -> usize {
unsafe { max_sys::proxy_getinlet(owner.into()) as _ }
}
}
impl Drop for Proxy {
fn drop(&mut self) {
unsafe {
max_sys::object_free(self.inner);
}
}
}
|
use neqo_future::*;
use std::panic::{ catch_unwind, AssertUnwindSafe };
use std::ffi::CStr;
use std::thread::LocalKey;
use std::cell::RefCell;
use async_std::task::JoinHandle;
use async_std::task;
use futures::{AsyncWriteExt, AsyncReadExt};
type ConnectionInfo = (JoinHandle<Option<u64>>, Connection);
pub enum StreamInfo {
FullStream(QuicSendStream, QuicRecvStream),
HalfStreamSend(QuicSendStream),
HalfStreamRecv(QuicRecvStream),
}
pub unsafe fn to_string(p_str: *const i8) -> String {
String::from_utf8_unchecked(CStr::from_ptr(p_str).to_bytes().to_vec())
}
// ------------------------------
// ERROR HELPERS
// ------------------------------
#[no_mangle]
unsafe fn qf_last_error() -> &'static LocalKey<RefCell<Option<QuicError>>> {
thread_local! {
pub static THREAD_ERROR: RefCell<Option<QuicError>> = RefCell::new(None)
}
return &THREAD_ERROR;
}
unsafe fn qf_pop_error() {
qf_last_error().with(|e| {
let mut emut = e.borrow_mut();
*emut = None;
});
}
unsafe fn qf_set_error(error: QuicError) {
qf_last_error().with(|e| {
let mut emut = e.borrow_mut();
assert!(emut.is_some(), "bad error state!");
*emut = Some(error);
});
}
// ------------------------------
// CRYPTO HELPERS
// ------------------------------
#[no_mangle]
pub unsafe extern fn qf_init(nss_dir: *const i8) -> i64 {
qf_pop_error();
return match catch_unwind(|| {
if nss_dir == std::ptr::null() {
neqo_crypto::init();
neqo_crypto::assert_initialized();
return;
}
neqo_crypto::init_db(to_string(nss_dir));
}) { Ok (_) => 0, Err(e) => { qf_set_error(QuicError::FatalError(e)); return -1; } };
}
// ------------------------------
// QUIC WRAPPERS (NONE-ASYNC)
// ------------------------------
#[no_mangle]
pub unsafe extern fn qf_connect(conn_addr: *const i8, config: Box<client::ClientConfig>) -> Option<Box<ConnectionInfo>> {
qf_pop_error();
return match catch_unwind(|| {
task::block_on(async {
let conn_addr = to_string(conn_addr);
let result = client::connect(conn_addr.parse().unwrap(), *config).await;
if let Err(v) = result {
qf_set_error(v);
return None;
}
return Some(Box::new(result.unwrap()));
})
}) { Ok(v) => v, Err(e) => { qf_set_error(QuicError::FatalError(e)); return None } };
}
#[no_mangle]
pub unsafe extern fn qf_stream_listen(info: &mut ConnectionInfo) -> Option<Box<StreamInfo>> {
qf_pop_error();
return match catch_unwind(AssertUnwindSafe(|| {
if let Some((tx, rx)) = task::block_on(info.1.listen_stream()) {
return Some(Box::new(StreamInfo::FullStream(tx, rx)));
}
return None;
})) { Ok(v) => v, Err(e) => { qf_set_error(QuicError::FatalError(e)); return None } };
}
#[no_mangle]
pub unsafe extern fn qf_stream_create_half(info: &mut ConnectionInfo) -> Option<Box<StreamInfo>> {
qf_pop_error();
return match catch_unwind(AssertUnwindSafe(|| {
if let Some(v) = task::block_on(info.1.create_stream_half()) {
return Some(Box::new(StreamInfo::HalfStreamSend(v)));
}
return None;
})) { Ok(v) => v, Err(e) => { qf_set_error(QuicError::FatalError(e)); return None } };
}
#[no_mangle]
pub unsafe extern fn qf_stream_create_full(info: &mut ConnectionInfo) -> Option<Box<StreamInfo>> {
qf_pop_error();
return match catch_unwind(AssertUnwindSafe(|| {
if let Some((tx, rx)) = task::block_on(info.1.create_stream_full()) {
return Some(Box::new(StreamInfo::FullStream(tx, rx)));
}
return None;
})) { Ok(v) => v, Err(e) => { qf_set_error(QuicError::FatalError(e)); return None } };
}
#[no_mangle]
pub unsafe extern fn qf_stream_send(info: &mut StreamInfo, buf: *mut u8, len: i64) -> i64 {
qf_pop_error();
let buffer = std::slice::from_raw_parts(buf, len as usize);
return match catch_unwind(AssertUnwindSafe(|| {
let result = task::block_on(async {
if let StreamInfo::FullStream(tx, _) | StreamInfo::HalfStreamSend(tx) = info {
return tx.write(buffer).await;
}
panic!("bad stream type!");
});
if let Err(e) = result {
qf_set_error(QuicError::IoError(e));
return -1;
}
return result.unwrap() as i64;
})) { Ok(v) => v, Err(e) => { qf_set_error(QuicError::FatalError(e)); return -1 } };
}
#[no_mangle]
pub unsafe extern fn qf_stream_send_exact(info: &mut StreamInfo, buf: *mut u8, len: i64) -> bool {
qf_pop_error();
let buffer = std::slice::from_raw_parts(buf, len as usize);
return match catch_unwind(AssertUnwindSafe(|| {
let result = task::block_on(async {
if let StreamInfo::FullStream(tx, _) | StreamInfo::HalfStreamSend(tx) = info {
return tx.write_all(buffer).await;
}
panic!("bad stream type!");
});
if let Err(e) = result {
qf_set_error(QuicError::IoError(e));
return false;
}
return true;
})) { Ok(v) => v, Err(e) => { qf_set_error(QuicError::FatalError(e)); return false } };
}
#[no_mangle]
pub unsafe extern fn qf_stream_recv(info: &mut StreamInfo, buf: *mut u8, len: i64) -> i64 {
qf_pop_error();
let buffer = std::slice::from_raw_parts_mut(buf, len as usize);
return match catch_unwind(AssertUnwindSafe(|| {
let result = task::block_on(async {
if let StreamInfo::FullStream(_, rx) | StreamInfo::HalfStreamRecv(rx) = info {
return rx.read(buffer).await;
}
panic!("bad stream type!");
});
if let Err(e) = result {
qf_set_error(QuicError::IoError(e));
return -1;
}
return result.unwrap() as i64;
})) { Ok(v) => v, Err(e) => { qf_set_error(QuicError::FatalError(e)); return -1 } };
}
#[no_mangle]
pub unsafe extern fn qf_stream_recv_exact(info: &mut StreamInfo, buf: *mut u8, len: i64) -> bool {
qf_pop_error();
let buffer = std::slice::from_raw_parts_mut(buf, len as usize);
return match catch_unwind(AssertUnwindSafe(|| {
let result = task::block_on(async {
if let StreamInfo::FullStream(_, rx) | StreamInfo::HalfStreamRecv(rx) = info {
return rx.read_exact(buffer).await;
}
panic!("bad stream type!");
});
if let Err(e) = result {
qf_set_error(QuicError::IoError(e));
return false;
}
return true;
})) { Ok(v) => v, Err(e) => { qf_set_error(QuicError::FatalError(e)); return false } };
}
#[no_mangle]
pub unsafe extern fn qf_stream_close(info: &mut StreamInfo) -> bool {
qf_pop_error();
return match catch_unwind(AssertUnwindSafe(|| {
let result = task::block_on(async {
if let StreamInfo::FullStream(tx, _) | StreamInfo::HalfStreamSend(tx) = info {
return tx.close().await;
}
panic!("bad stream type!");
});
if let Err(e) = result {
qf_set_error(QuicError::IoError(e));
return false;
}
return true;
})) { Ok(v) => v, Err(e) => { qf_set_error(QuicError::FatalError(e)); return false } };
}
#[no_mangle]
pub unsafe extern fn qf_stream_reset(info: &mut StreamInfo, err: u64) -> bool {
qf_pop_error();
return match catch_unwind(AssertUnwindSafe(|| {
task::block_on(async {
match info {
StreamInfo::FullStream(tx, _) => tx.reset(err),
StreamInfo::HalfStreamRecv(tx) => tx.reset(err),
StreamInfo::HalfStreamSend(rx) => rx.reset(err)
}
});
return true;
})) { Ok(v) => v, Err(e) => { qf_set_error(QuicError::FatalError(e)); return false } };
} |
extern crate atoi;
extern crate bincode;
extern crate byteorder;
extern crate hex;
extern crate openssl;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate log;
pub enum Command {
PING,
SET(Vec<u8>),
GET(Vec<u8>),
NOTSUPPORTED,
}
pub mod server;
pub mod storage;
|
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn CoGetInstanceFromFile ( pserverinfo : *const super:: COSERVERINFO , pclsid : *const :: windows_sys::core::GUID , punkouter : :: windows_sys::core::IUnknown , dwclsctx : super:: CLSCTX , grfmode : u32 , pwszname : :: windows_sys::core::PCWSTR , dwcount : u32 , presults : *mut super:: MULTI_QI ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn CoGetInstanceFromIStorage ( pserverinfo : *const super:: COSERVERINFO , pclsid : *const :: windows_sys::core::GUID , punkouter : :: windows_sys::core::IUnknown , dwclsctx : super:: CLSCTX , pstg : IStorage , dwcount : u32 , presults : *mut super:: MULTI_QI ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn CoGetInterfaceAndReleaseStream ( pstm : super:: IStream , iid : *const :: windows_sys::core::GUID , ppv : *mut *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"] fn CreateILockBytesOnHGlobal ( hglobal : isize , fdeleteonrelease : super::super::super::Foundation:: BOOL , pplkbyt : *mut ILockBytes ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"] fn CreateStreamOnHGlobal ( hglobal : isize , fdeleteonrelease : super::super::super::Foundation:: BOOL , ppstm : *mut super:: IStream ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn FmtIdToPropStgName ( pfmtid : *const :: windows_sys::core::GUID , oszname : :: windows_sys::core::PWSTR ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"] fn FreePropVariantArray ( cvariants : u32 , rgvars : *mut PROPVARIANT ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn GetConvertStg ( pstg : IStorage ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn GetHGlobalFromILockBytes ( plkbyt : ILockBytes , phglobal : *mut isize ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn GetHGlobalFromStream ( pstm : super:: IStream , phglobal : *mut isize ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn OleConvertIStorageToOLESTREAM ( pstg : IStorage , lpolestream : *mut OLESTREAM ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Graphics_Gdi")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Graphics_Gdi\"`*"] fn OleConvertIStorageToOLESTREAMEx ( pstg : IStorage , cfformat : u16 , lwidth : i32 , lheight : i32 , dwsize : u32 , pmedium : *const super:: STGMEDIUM , polestm : *mut OLESTREAM ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn OleConvertOLESTREAMToIStorage ( lpolestream : *const OLESTREAM , pstg : IStorage , ptd : *const super:: DVTARGETDEVICE ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Graphics_Gdi")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Graphics_Gdi\"`*"] fn OleConvertOLESTREAMToIStorageEx ( polestm : *const OLESTREAM , pstg : IStorage , pcfformat : *mut u16 , plwwidth : *mut i32 , plheight : *mut i32 , pdwsize : *mut u32 , pmedium : *mut super:: STGMEDIUM ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn PropStgNameToFmtId ( oszname : :: windows_sys::core::PCWSTR , pfmtid : *mut :: windows_sys::core::GUID ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"] fn PropVariantClear ( pvar : *mut PROPVARIANT ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"] fn PropVariantCopy ( pvardest : *mut PROPVARIANT , pvarsrc : *const PROPVARIANT ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn ReadClassStg ( pstg : IStorage , pclsid : *mut :: windows_sys::core::GUID ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn ReadClassStm ( pstm : super:: IStream , pclsid : *mut :: windows_sys::core::GUID ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn ReadFmtUserTypeStg ( pstg : IStorage , pcf : *mut u16 , lplpszusertype : *mut :: windows_sys::core::PWSTR ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"] fn SetConvertStg ( pstg : IStorage , fconvert : super::super::super::Foundation:: BOOL ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"] fn StgConvertPropertyToVariant ( pprop : *const SERIALIZEDPROPERTYVALUE , codepage : u16 , pvar : *mut PROPVARIANT , pma : *const PMemoryAllocator ) -> super::super::super::Foundation:: BOOLEAN );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"] fn StgConvertVariantToProperty ( pvar : *const PROPVARIANT , codepage : u16 , pprop : *mut SERIALIZEDPROPERTYVALUE , pcb : *mut u32 , pid : u32 , freserved : super::super::super::Foundation:: BOOLEAN , pcindirect : *mut u32 ) -> *mut SERIALIZEDPROPERTYVALUE );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgCreateDocfile ( pwcsname : :: windows_sys::core::PCWSTR , grfmode : super:: STGM , reserved : u32 , ppstgopen : *mut IStorage ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgCreateDocfileOnILockBytes ( plkbyt : ILockBytes , grfmode : super:: STGM , reserved : u32 , ppstgopen : *mut IStorage ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgCreatePropSetStg ( pstorage : IStorage , dwreserved : u32 , pppropsetstg : *mut IPropertySetStorage ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgCreatePropStg ( punk : :: windows_sys::core::IUnknown , fmtid : *const :: windows_sys::core::GUID , pclsid : *const :: windows_sys::core::GUID , grfflags : u32 , dwreserved : u32 , pppropstg : *mut IPropertyStorage ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Security")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Security\"`*"] fn StgCreateStorageEx ( pwcsname : :: windows_sys::core::PCWSTR , grfmode : super:: STGM , stgfmt : STGFMT , grfattrs : u32 , pstgoptions : *mut STGOPTIONS , psecuritydescriptor : super::super::super::Security:: PSECURITY_DESCRIPTOR , riid : *const :: windows_sys::core::GUID , ppobjectopen : *mut *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "propsys.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"] fn StgDeserializePropVariant ( pprop : *const SERIALIZEDPROPERTYVALUE , cbmax : u32 , ppropvar : *mut PROPVARIANT ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgGetIFillLockBytesOnFile ( pwcsname : :: windows_sys::core::PCWSTR , ppflb : *mut IFillLockBytes ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgGetIFillLockBytesOnILockBytes ( pilb : ILockBytes , ppflb : *mut IFillLockBytes ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgIsStorageFile ( pwcsname : :: windows_sys::core::PCWSTR ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgIsStorageILockBytes ( plkbyt : ILockBytes ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgOpenAsyncDocfileOnIFillLockBytes ( pflb : IFillLockBytes , grfmode : u32 , asyncflags : u32 , ppstgopen : *mut IStorage ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "dflayout.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgOpenLayoutDocfile ( pwcsdfname : :: windows_sys::core::PCWSTR , grfmode : u32 , reserved : u32 , ppstgopen : *mut IStorage ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgOpenPropStg ( punk : :: windows_sys::core::IUnknown , fmtid : *const :: windows_sys::core::GUID , grfflags : u32 , dwreserved : u32 , pppropstg : *mut IPropertyStorage ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgOpenStorage ( pwcsname : :: windows_sys::core::PCWSTR , pstgpriority : IStorage , grfmode : super:: STGM , snbexclude : *const *const u16 , reserved : u32 , ppstgopen : *mut IStorage ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Security")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Security\"`*"] fn StgOpenStorageEx ( pwcsname : :: windows_sys::core::PCWSTR , grfmode : super:: STGM , stgfmt : STGFMT , grfattrs : u32 , pstgoptions : *mut STGOPTIONS , psecuritydescriptor : super::super::super::Security:: PSECURITY_DESCRIPTOR , riid : *const :: windows_sys::core::GUID , ppobjectopen : *mut *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgOpenStorageOnILockBytes ( plkbyt : ILockBytes , pstgpriority : IStorage , grfmode : super:: STGM , snbexclude : *const *const u16 , reserved : u32 , ppstgopen : *mut IStorage ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn StgPropertyLengthAsVariant ( pprop : *const SERIALIZEDPROPERTYVALUE , cbprop : u32 , codepage : u16 , breserved : u8 ) -> u32 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "propsys.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"] fn StgSerializePropVariant ( ppropvar : *const PROPVARIANT , ppprop : *mut *mut SERIALIZEDPROPERTYVALUE , pcb : *mut u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"] fn StgSetTimes ( lpszname : :: windows_sys::core::PCWSTR , pctime : *const super::super::super::Foundation:: FILETIME , patime : *const super::super::super::Foundation:: FILETIME , pmtime : *const super::super::super::Foundation:: FILETIME ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn WriteClassStg ( pstg : IStorage , rclsid : *const :: windows_sys::core::GUID ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn WriteClassStm ( pstm : super:: IStream , rclsid : *const :: windows_sys::core::GUID ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "ole32.dll""system" #[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"] fn WriteFmtUserTypeStg ( pstg : IStorage , cf : u16 , lpszusertype : :: windows_sys::core::PCWSTR ) -> :: windows_sys::core::HRESULT );
pub type IDirectWriterLock = *mut ::core::ffi::c_void;
pub type IEnumSTATPROPSETSTG = *mut ::core::ffi::c_void;
pub type IEnumSTATPROPSTG = *mut ::core::ffi::c_void;
pub type IEnumSTATSTG = *mut ::core::ffi::c_void;
pub type IFillLockBytes = *mut ::core::ffi::c_void;
pub type ILayoutStorage = *mut ::core::ffi::c_void;
pub type ILockBytes = *mut ::core::ffi::c_void;
pub type IPersistStorage = *mut ::core::ffi::c_void;
pub type IPropertyBag = *mut ::core::ffi::c_void;
pub type IPropertyBag2 = *mut ::core::ffi::c_void;
pub type IPropertySetStorage = *mut ::core::ffi::c_void;
pub type IPropertyStorage = *mut ::core::ffi::c_void;
pub type IRootStorage = *mut ::core::ffi::c_void;
pub type IStorage = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const CCH_MAX_PROPSTG_NAME: u32 = 31u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const CWCSTORAGENAME: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDI_THUMBNAIL: i32 = 2i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_BYTECOUNT: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_CATEGORY: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_COMPANY: u32 = 15u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_DOCPARTS: u32 = 13u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_HEADINGPAIR: u32 = 12u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_HIDDENCOUNT: u32 = 9u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_LINECOUNT: u32 = 5u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_LINKSDIRTY: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_MANAGER: u32 = 14u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_MMCLIPCOUNT: u32 = 10u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_NOTECOUNT: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_PARCOUNT: u32 = 6u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_PRESFORMAT: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_SCALE: u32 = 11u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDDSI_SLIDECOUNT: u32 = 7u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_COPYRIGHT: i32 = 11i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_EDITOR: i32 = 2i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_OWNER: i32 = 8i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_PRODUCTION: i32 = 10i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_PROJECT: i32 = 6i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_RATING: i32 = 9i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_SEQUENCE_NO: i32 = 5i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_SOURCE: i32 = 4i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_STATUS: i32 = 7i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_SUPPLIER: i32 = 3i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_APPNAME: i32 = 18i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_AUTHOR: i32 = 4i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_CHARCOUNT: i32 = 16i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_COMMENTS: i32 = 6i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_CREATE_DTM: i32 = 12i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_DOC_SECURITY: i32 = 19i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_EDITTIME: i32 = 10i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_KEYWORDS: i32 = 5i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_LASTAUTHOR: i32 = 8i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_LASTPRINTED: i32 = 11i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_LASTSAVE_DTM: i32 = 13i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_PAGECOUNT: i32 = 14i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_REVNUMBER: i32 = 9i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_SUBJECT: i32 = 3i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_TEMPLATE: i32 = 7i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_THUMBNAIL: i32 = 17i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_TITLE: i32 = 2i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDSI_WORDCOUNT: i32 = 15i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PID_BEHAVIOR: u32 = 2147483651u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PID_CODEPAGE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PID_DICTIONARY: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PID_FIRST_NAME_DEFAULT: u32 = 4095u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PID_FIRST_USABLE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PID_ILLEGAL: u32 = 4294967295u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PID_LOCALE: u32 = 2147483648u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PID_MAX_READONLY: u32 = 3221225471u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PID_MIN_READONLY: u32 = 2147483648u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PID_MODIFY_TIME: u32 = 2147483649u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PID_SECURITY: u32 = 2147483650u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PROPSETFLAG_ANSI: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PROPSETFLAG_CASE_SENSITIVE: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PROPSETFLAG_DEFAULT: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PROPSETFLAG_NONSIMPLE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PROPSETFLAG_UNBUFFERED: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PROPSETHDR_OSVERSION_UNKNOWN: u32 = 4294967295u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PROPSET_BEHAVIOR_CASE_SENSITIVE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PRSPEC_INVALID: u32 = 4294967295u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const STGOPTIONS_VERSION: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub type PIDMSI_STATUS_VALUE = i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_STATUS_NORMAL: PIDMSI_STATUS_VALUE = 0i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_STATUS_NEW: PIDMSI_STATUS_VALUE = 1i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_STATUS_PRELIM: PIDMSI_STATUS_VALUE = 2i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_STATUS_DRAFT: PIDMSI_STATUS_VALUE = 3i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_STATUS_INPROGRESS: PIDMSI_STATUS_VALUE = 4i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_STATUS_EDIT: PIDMSI_STATUS_VALUE = 5i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_STATUS_REVIEW: PIDMSI_STATUS_VALUE = 6i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_STATUS_PROOF: PIDMSI_STATUS_VALUE = 7i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_STATUS_FINAL: PIDMSI_STATUS_VALUE = 8i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PIDMSI_STATUS_OTHER: PIDMSI_STATUS_VALUE = 32767i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub type PROPSPEC_KIND = u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PRSPEC_LPWSTR: PROPSPEC_KIND = 0u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const PRSPEC_PROPID: PROPSPEC_KIND = 1u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub type STGFMT = u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const STGFMT_STORAGE: STGFMT = 0u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const STGFMT_NATIVE: STGFMT = 1u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const STGFMT_FILE: STGFMT = 3u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const STGFMT_ANY: STGFMT = 4u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const STGFMT_DOCFILE: STGFMT = 5u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const STGFMT_DOCUMENT: STGFMT = 0u32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub type STGMOVE = i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const STGMOVE_MOVE: STGMOVE = 0i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const STGMOVE_COPY: STGMOVE = 1i32;
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub const STGMOVE_SHALLOWCOPY: STGMOVE = 2i32;
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct BSTRBLOB {
pub cbSize: u32,
pub pData: *mut u8,
}
impl ::core::marker::Copy for BSTRBLOB {}
impl ::core::clone::Clone for BSTRBLOB {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct CABOOL {
pub cElems: u32,
pub pElems: *mut super::super::super::Foundation::VARIANT_BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for CABOOL {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for CABOOL {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CABSTR {
pub cElems: u32,
pub pElems: *mut ::windows_sys::core::BSTR,
}
impl ::core::marker::Copy for CABSTR {}
impl ::core::clone::Clone for CABSTR {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CABSTRBLOB {
pub cElems: u32,
pub pElems: *mut BSTRBLOB,
}
impl ::core::marker::Copy for CABSTRBLOB {}
impl ::core::clone::Clone for CABSTRBLOB {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CAC {
pub cElems: u32,
pub pElems: ::windows_sys::core::PSTR,
}
impl ::core::marker::Copy for CAC {}
impl ::core::clone::Clone for CAC {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CACLIPDATA {
pub cElems: u32,
pub pElems: *mut CLIPDATA,
}
impl ::core::marker::Copy for CACLIPDATA {}
impl ::core::clone::Clone for CACLIPDATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CACLSID {
pub cElems: u32,
pub pElems: *mut ::windows_sys::core::GUID,
}
impl ::core::marker::Copy for CACLSID {}
impl ::core::clone::Clone for CACLSID {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CACY {
pub cElems: u32,
pub pElems: *mut super::CY,
}
impl ::core::marker::Copy for CACY {}
impl ::core::clone::Clone for CACY {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CADATE {
pub cElems: u32,
pub pElems: *mut f64,
}
impl ::core::marker::Copy for CADATE {}
impl ::core::clone::Clone for CADATE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CADBL {
pub cElems: u32,
pub pElems: *mut f64,
}
impl ::core::marker::Copy for CADBL {}
impl ::core::clone::Clone for CADBL {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct CAFILETIME {
pub cElems: u32,
pub pElems: *mut super::super::super::Foundation::FILETIME,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for CAFILETIME {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for CAFILETIME {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CAFLT {
pub cElems: u32,
pub pElems: *mut f32,
}
impl ::core::marker::Copy for CAFLT {}
impl ::core::clone::Clone for CAFLT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CAH {
pub cElems: u32,
pub pElems: *mut i64,
}
impl ::core::marker::Copy for CAH {}
impl ::core::clone::Clone for CAH {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CAI {
pub cElems: u32,
pub pElems: *mut i16,
}
impl ::core::marker::Copy for CAI {}
impl ::core::clone::Clone for CAI {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CAL {
pub cElems: u32,
pub pElems: *mut i32,
}
impl ::core::marker::Copy for CAL {}
impl ::core::clone::Clone for CAL {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CALPSTR {
pub cElems: u32,
pub pElems: *mut ::windows_sys::core::PSTR,
}
impl ::core::marker::Copy for CALPSTR {}
impl ::core::clone::Clone for CALPSTR {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CALPWSTR {
pub cElems: u32,
pub pElems: *mut ::windows_sys::core::PWSTR,
}
impl ::core::marker::Copy for CALPWSTR {}
impl ::core::clone::Clone for CALPWSTR {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct CAPROPVARIANT {
pub cElems: u32,
pub pElems: *mut PROPVARIANT,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for CAPROPVARIANT {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for CAPROPVARIANT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CASCODE {
pub cElems: u32,
pub pElems: *mut i32,
}
impl ::core::marker::Copy for CASCODE {}
impl ::core::clone::Clone for CASCODE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CAUB {
pub cElems: u32,
pub pElems: *mut u8,
}
impl ::core::marker::Copy for CAUB {}
impl ::core::clone::Clone for CAUB {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CAUH {
pub cElems: u32,
pub pElems: *mut u64,
}
impl ::core::marker::Copy for CAUH {}
impl ::core::clone::Clone for CAUH {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CAUI {
pub cElems: u32,
pub pElems: *mut u16,
}
impl ::core::marker::Copy for CAUI {}
impl ::core::clone::Clone for CAUI {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CAUL {
pub cElems: u32,
pub pElems: *mut u32,
}
impl ::core::marker::Copy for CAUL {}
impl ::core::clone::Clone for CAUL {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct CLIPDATA {
pub cbSize: u32,
pub ulClipFmt: i32,
pub pClipData: *mut u8,
}
impl ::core::marker::Copy for CLIPDATA {}
impl ::core::clone::Clone for CLIPDATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct OLESTREAM {
pub lpstbl: *mut OLESTREAMVTBL,
}
impl ::core::marker::Copy for OLESTREAM {}
impl ::core::clone::Clone for OLESTREAM {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct OLESTREAMVTBL {
pub Get: isize,
pub Put: isize,
}
impl ::core::marker::Copy for OLESTREAMVTBL {}
impl ::core::clone::Clone for OLESTREAMVTBL {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct PMemoryAllocator(pub u8);
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct PROPBAG2 {
pub dwType: u32,
pub vt: super::VARENUM,
pub cfType: u16,
pub dwHint: u32,
pub pstrName: ::windows_sys::core::PWSTR,
pub clsid: ::windows_sys::core::GUID,
}
impl ::core::marker::Copy for PROPBAG2 {}
impl ::core::clone::Clone for PROPBAG2 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct PROPSPEC {
pub ulKind: PROPSPEC_KIND,
pub Anonymous: PROPSPEC_0,
}
impl ::core::marker::Copy for PROPSPEC {}
impl ::core::clone::Clone for PROPSPEC {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub union PROPSPEC_0 {
pub propid: u32,
pub lpwstr: ::windows_sys::core::PWSTR,
}
impl ::core::marker::Copy for PROPSPEC_0 {}
impl ::core::clone::Clone for PROPSPEC_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct PROPVARIANT {
pub Anonymous: PROPVARIANT_0,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PROPVARIANT {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PROPVARIANT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub union PROPVARIANT_0 {
pub Anonymous: PROPVARIANT_0_0,
pub decVal: super::super::super::Foundation::DECIMAL,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PROPVARIANT_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PROPVARIANT_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct PROPVARIANT_0_0 {
pub vt: super::VARENUM,
pub wReserved1: u16,
pub wReserved2: u16,
pub wReserved3: u16,
pub Anonymous: PROPVARIANT_0_0_0,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PROPVARIANT_0_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PROPVARIANT_0_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub union PROPVARIANT_0_0_0 {
pub cVal: super::super::super::Foundation::CHAR,
pub bVal: u8,
pub iVal: i16,
pub uiVal: u16,
pub lVal: i32,
pub ulVal: u32,
pub intVal: i32,
pub uintVal: u32,
pub hVal: i64,
pub uhVal: u64,
pub fltVal: f32,
pub dblVal: f64,
pub boolVal: super::super::super::Foundation::VARIANT_BOOL,
pub __OBSOLETE__VARIANT_BOOL: super::super::super::Foundation::VARIANT_BOOL,
pub scode: i32,
pub cyVal: super::CY,
pub date: f64,
pub filetime: super::super::super::Foundation::FILETIME,
pub puuid: *mut ::windows_sys::core::GUID,
pub pclipdata: *mut CLIPDATA,
pub bstrVal: ::windows_sys::core::BSTR,
pub bstrblobVal: BSTRBLOB,
pub blob: super::BLOB,
pub pszVal: ::windows_sys::core::PSTR,
pub pwszVal: ::windows_sys::core::PWSTR,
pub punkVal: ::windows_sys::core::IUnknown,
pub pdispVal: super::IDispatch,
pub pStream: super::IStream,
pub pStorage: IStorage,
pub pVersionedStream: *mut VERSIONEDSTREAM,
pub parray: *mut super::SAFEARRAY,
pub cac: CAC,
pub caub: CAUB,
pub cai: CAI,
pub caui: CAUI,
pub cal: CAL,
pub caul: CAUL,
pub cah: CAH,
pub cauh: CAUH,
pub caflt: CAFLT,
pub cadbl: CADBL,
pub cabool: CABOOL,
pub cascode: CASCODE,
pub cacy: CACY,
pub cadate: CADATE,
pub cafiletime: CAFILETIME,
pub cauuid: CACLSID,
pub caclipdata: CACLIPDATA,
pub cabstr: CABSTR,
pub cabstrblob: CABSTRBLOB,
pub calpstr: CALPSTR,
pub calpwstr: CALPWSTR,
pub capropvar: CAPROPVARIANT,
pub pcVal: ::windows_sys::core::PSTR,
pub pbVal: *mut u8,
pub piVal: *mut i16,
pub puiVal: *mut u16,
pub plVal: *mut i32,
pub pulVal: *mut u32,
pub pintVal: *mut i32,
pub puintVal: *mut u32,
pub pfltVal: *mut f32,
pub pdblVal: *mut f64,
pub pboolVal: *mut super::super::super::Foundation::VARIANT_BOOL,
pub pdecVal: *mut super::super::super::Foundation::DECIMAL,
pub pscode: *mut i32,
pub pcyVal: *mut super::CY,
pub pdate: *mut f64,
pub pbstrVal: *mut ::windows_sys::core::BSTR,
pub ppunkVal: *mut ::windows_sys::core::IUnknown,
pub ppdispVal: *mut super::IDispatch,
pub pparray: *mut *mut super::SAFEARRAY,
pub pvarVal: *mut PROPVARIANT,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PROPVARIANT_0_0_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PROPVARIANT_0_0_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct RemSNB {
pub ulCntStr: u32,
pub ulCntChar: u32,
pub rgString: [u16; 1],
}
impl ::core::marker::Copy for RemSNB {}
impl ::core::clone::Clone for RemSNB {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct SERIALIZEDPROPERTYVALUE {
pub dwType: u32,
pub rgb: [u8; 1],
}
impl ::core::marker::Copy for SERIALIZEDPROPERTYVALUE {}
impl ::core::clone::Clone for SERIALIZEDPROPERTYVALUE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct STATPROPSETSTG {
pub fmtid: ::windows_sys::core::GUID,
pub clsid: ::windows_sys::core::GUID,
pub grfFlags: u32,
pub mtime: super::super::super::Foundation::FILETIME,
pub ctime: super::super::super::Foundation::FILETIME,
pub atime: super::super::super::Foundation::FILETIME,
pub dwOSVersion: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for STATPROPSETSTG {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for STATPROPSETSTG {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct STATPROPSTG {
pub lpwstrName: ::windows_sys::core::PWSTR,
pub propid: u32,
pub vt: super::VARENUM,
}
impl ::core::marker::Copy for STATPROPSTG {}
impl ::core::clone::Clone for STATPROPSTG {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct STGOPTIONS {
pub usVersion: u16,
pub reserved: u16,
pub ulSectorSize: u32,
pub pwcsTemplateFile: ::windows_sys::core::PCWSTR,
}
impl ::core::marker::Copy for STGOPTIONS {}
impl ::core::clone::Clone for STGOPTIONS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_StructuredStorage\"`*"]
pub struct VERSIONEDSTREAM {
pub guidVersion: ::windows_sys::core::GUID,
pub pStream: super::IStream,
}
impl ::core::marker::Copy for VERSIONEDSTREAM {}
impl ::core::clone::Clone for VERSIONEDSTREAM {
fn clone(&self) -> Self {
*self
}
}
|
use std::io::{Read, Result as IOResult};
use crate::lump_data::{LumpData, LumpType};
use crate::PrimitiveRead;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct LeafBrush {
pub index: u16
}
impl LumpData for LeafBrush {
fn lump_type() -> LumpType {
LumpType::LeafBrushes
}
fn lump_type_hdr() -> Option<LumpType> {
None
}
fn element_size(_version: i32) -> usize {
2
}
fn read(reader: &mut dyn Read, _version: i32) -> IOResult<Self> {
let brush = reader.read_u16()?;
Ok(Self {
index: brush
})
}
}
|
use log::error;
use std::env;
use std::result::Result;
use thiserror::Error;
use crate::common;
#[derive(Error, Debug)]
enum CurrentCommandError {
#[error("reading .rpilot file failed. Make sure this project is initialised properly.")]
NotInitialized,
#[error("the specified profile name does not exists for this project. Please make sure that you are passing the correvt name.")]
NotExists,
#[error(
"no profile has been applied yet. Please use apply command to use the certain profile"
)]
NoProfileIsApplied,
#[error("Failed at reading the config")]
ConfigReadError,
#[error("external library failed")]
ExternalFail(#[from] std::io::Error),
}
pub fn execute() {
match _execute() {
Ok(_) => (),
Err(e) => {
error!("{}", e);
}
}
}
fn _execute() -> Result<(), CurrentCommandError> {
let pwd = env::current_dir()?;
let project_dir = common::get_data_dir()?;
let project_id = common::get_project_id(&pwd);
if project_id.is_none() {
return Err(CurrentCommandError::NotInitialized);
}
let project_id = project_id.unwrap();
let (_, project) = common::read_config(&project_dir, &project_id)
.map_err(|_| CurrentCommandError::ConfigReadError)?;
if project.current_profile.as_ref().is_none() {
return Err(CurrentCommandError::NoProfileIsApplied);
}
let empty_name = "".to_string();
let current_profile = project
.current_profile
.as_ref()
.as_ref()
.unwrap_or(&empty_name);
let profile = common::select_profile(&project, current_profile)
.map_err(|_| CurrentCommandError::NotExists)?;
let (_, env) = common::read_env(&project_dir, &project_id, &profile.id);
println!("The current profile is {}", current_profile);
println!("---------------------------");
println!("{}", env.unwrap_or_else(|| "".to_string()));
Ok(())
}
|
#[test]
fn mock_test() {
assert!(true);
}
|
use super::Money;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct LineItem {
number: usize,
description: String,
quantity: usize,
unit_price: Money,
}
|
// Copyright 2020, The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::{message::MessageTag, peer_manager::NodeId};
use bytes::Bytes;
use futures::channel::oneshot;
use std::{
fmt,
fmt::{Error, Formatter},
};
pub type MessagingReplyTx = oneshot::Sender<Result<(), ()>>;
pub type MessagingReplyRx = oneshot::Receiver<Result<(), ()>>;
/// Contains details required to build a message envelope and send a message to a peer. OutboundMessage will not copy
/// the body bytes when cloned and is 'cheap to clone(tm)'.
#[derive(Debug)]
pub struct OutboundMessage {
pub tag: MessageTag,
pub peer_node_id: NodeId,
pub body: Bytes,
pub reply_tx: Option<MessagingReplyTx>,
}
impl OutboundMessage {
pub fn new(peer_node_id: NodeId, body: Bytes) -> Self {
Self {
tag: MessageTag::new(),
peer_node_id,
body,
reply_tx: None,
}
}
pub fn reply_fail(&mut self) {
self.oneshot_reply(Err(()));
}
pub fn reply_success(&mut self) {
self.oneshot_reply(Ok(()));
}
#[inline]
fn oneshot_reply(&mut self, result: Result<(), ()>) {
if let Some(reply_tx) = self.reply_tx.take() {
let _ = reply_tx.send(result);
}
}
}
impl Drop for OutboundMessage {
fn drop(&mut self) {
self.reply_fail();
}
}
impl fmt::Display for OutboundMessage {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(
f,
"OutboundMessage (tag: {}, {} bytes) for peer '{}'",
self.tag,
self.body.len(),
self.peer_node_id.short_str()
)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn with_tag() {
static TEST_MSG: Bytes = Bytes::from_static(b"The ghost brigades");
let node_id = NodeId::new();
let tag = MessageTag::new();
let subject = OutboundMessage {
tag,
peer_node_id: node_id.clone(),
reply_tx: None,
body: TEST_MSG.clone(),
};
assert_eq!(tag, subject.tag);
assert_eq!(subject.body, TEST_MSG);
assert_eq!(subject.peer_node_id, node_id);
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_exception::Result;
use common_expression::types::number::NumberScalar;
use common_expression::types::DataType;
use common_expression::types::NumberDataType;
use common_expression::BlockEntry;
use common_expression::DataBlock;
use common_expression::Scalar;
use common_expression::Value;
use common_sql::plans::ExistsTablePlan;
use crate::interpreters::Interpreter;
use crate::pipelines::PipelineBuildResult;
use crate::sessions::QueryContext;
use crate::sessions::TableContext;
pub struct ExistsTableInterpreter {
ctx: Arc<QueryContext>,
plan: ExistsTablePlan,
}
impl ExistsTableInterpreter {
pub fn try_create(ctx: Arc<QueryContext>, plan: ExistsTablePlan) -> Result<Self> {
Ok(ExistsTableInterpreter { ctx, plan })
}
}
#[async_trait::async_trait]
impl Interpreter for ExistsTableInterpreter {
fn name(&self) -> &str {
"ExistsTableInterpreter"
}
async fn execute2(&self) -> Result<PipelineBuildResult> {
let catalog = self.plan.catalog.as_str();
let database = self.plan.database.as_str();
let table = self.plan.table.as_str();
let exists = self.ctx.get_table(catalog, database, table).await.is_ok();
let result = match exists {
true => 1u8,
false => 0u8,
};
PipelineBuildResult::from_blocks(vec![DataBlock::new(
vec![BlockEntry {
data_type: DataType::Number(NumberDataType::UInt8),
value: Value::Scalar(Scalar::Number(NumberScalar::UInt8(result))),
}],
1,
)])
}
}
|
#[doc = "Reader of register CSR"]
pub type R = crate::R<u32, super::CSR>;
#[doc = "Writer for register CSR"]
pub type W = crate::W<u32, super::CSR>;
#[doc = "Register CSR `reset()`'s with value 0"]
impl crate::ResetValue for super::CSR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "LSI oscillator enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LSION_A {
#[doc = "0: LSI oscillator Off"]
OFF = 0,
#[doc = "1: LSI oscillator On"]
ON = 1,
}
impl From<LSION_A> for bool {
#[inline(always)]
fn from(variant: LSION_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LSION`"]
pub type LSION_R = crate::R<bool, LSION_A>;
impl LSION_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LSION_A {
match self.bits {
false => LSION_A::OFF,
true => LSION_A::ON,
}
}
#[doc = "Checks if the value of the field is `OFF`"]
#[inline(always)]
pub fn is_off(&self) -> bool {
*self == LSION_A::OFF
}
#[doc = "Checks if the value of the field is `ON`"]
#[inline(always)]
pub fn is_on(&self) -> bool {
*self == LSION_A::ON
}
}
#[doc = "Write proxy for field `LSION`"]
pub struct LSION_W<'a> {
w: &'a mut W,
}
impl<'a> LSION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LSION_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "LSI oscillator Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(LSION_A::OFF)
}
#[doc = "LSI oscillator On"]
#[inline(always)]
pub fn on(self) -> &'a mut W {
self.variant(LSION_A::ON)
}
#[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 = "LSI oscillator ready\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LSIRDY_A {
#[doc = "0: LSI oscillator not ready"]
NOTREADY = 0,
#[doc = "1: LSI oscillator ready"]
READY = 1,
}
impl From<LSIRDY_A> for bool {
#[inline(always)]
fn from(variant: LSIRDY_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LSIRDY`"]
pub type LSIRDY_R = crate::R<bool, LSIRDY_A>;
impl LSIRDY_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LSIRDY_A {
match self.bits {
false => LSIRDY_A::NOTREADY,
true => LSIRDY_A::READY,
}
}
#[doc = "Checks if the value of the field is `NOTREADY`"]
#[inline(always)]
pub fn is_not_ready(&self) -> bool {
*self == LSIRDY_A::NOTREADY
}
#[doc = "Checks if the value of the field is `READY`"]
#[inline(always)]
pub fn is_ready(&self) -> bool {
*self == LSIRDY_A::READY
}
}
#[doc = "Write proxy for field `LSIRDY`"]
pub struct LSIRDY_W<'a> {
w: &'a mut W,
}
impl<'a> LSIRDY_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LSIRDY_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "LSI oscillator not ready"]
#[inline(always)]
pub fn not_ready(self) -> &'a mut W {
self.variant(LSIRDY_A::NOTREADY)
}
#[doc = "LSI oscillator ready"]
#[inline(always)]
pub fn ready(self) -> &'a mut W {
self.variant(LSIRDY_A::READY)
}
#[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
}
}
impl R {
#[doc = "Bit 0 - LSI oscillator enable"]
#[inline(always)]
pub fn lsion(&self) -> LSION_R {
LSION_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - LSI oscillator ready"]
#[inline(always)]
pub fn lsirdy(&self) -> LSIRDY_R {
LSIRDY_R::new(((self.bits >> 1) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - LSI oscillator enable"]
#[inline(always)]
pub fn lsion(&mut self) -> LSION_W {
LSION_W { w: self }
}
#[doc = "Bit 1 - LSI oscillator ready"]
#[inline(always)]
pub fn lsirdy(&mut self) -> LSIRDY_W {
LSIRDY_W { w: self }
}
}
|
// https://leetcode.com/problems/matrix-diagonal-sum/
impl Solution {
pub fn diagonal_sum(mat: Vec<Vec<i32>>) -> i32 {
let mut diagonal_sum = 0;
for i in 0..mat.len() {
diagonal_sum += mat[i][i] + mat[mat.len()-i-1][i];
}
if (mat.len()%2 == 1) {
diagonal_sum -= mat[mat.len()/2][mat.len()/2];
}
diagonal_sum
}
} |
use nalgebra::Vector3;
use crate::{LumpType, LumpData};
use crate::PrimitiveRead;
use std::io::{Read, Result as IOResult};
pub struct DispVert {
pub vec: Vector3<f32>,
pub dist: f32,
pub alpha: f32
}
impl LumpData for DispVert {
fn lump_type() -> LumpType {
LumpType::DisplacementVertices
}
fn lump_type_hdr() -> Option<LumpType> {
None
}
fn element_size(_version: i32) -> usize {
20
}
fn read(read: &mut dyn Read, _version: i32) -> IOResult<Self> {
let vec = Vector3::new(read.read_f32()?, read.read_f32()?, read.read_f32()?);
let dist = read.read_f32()?;
let alpha = read.read_f32()?;
Ok(Self {
vec,
dist,
alpha
})
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use bitfield::bitfield;
use byteorder::{LittleEndian, WriteBytesExt};
use std::io;
#[cfg(test)]
use byteorder::ReadBytesExt;
// IEEE Std 802.11-2016, 9.2.4.1.3 Table 9-1
#[derive(Clone, Copy, Debug)]
pub enum FrameControlType {
Mgmt = 0b00,
#[cfg(test)]
Data = 0b10,
}
#[derive(Clone, Copy, Debug)]
pub enum MgmtSubtype {
AssociationRequest = 0b0000,
AssociationResponse = 0b0001,
Beacon = 0b1000,
Authentication = 0b1011,
#[cfg(test)]
Action = 0b1101,
}
#[cfg(test)]
#[derive(Clone, Copy, Debug)]
pub enum DataSubtype {
Data = 0b0000,
}
// IEEE Std 802.11-2016, 9.4.1.9, Table 9-46
#[derive(Clone, Copy, Debug)]
pub enum StatusCode {
Success = 0,
}
// IEEE Std 802.11-2016, 9.4.1.1
#[derive(Clone, Copy, Debug)]
pub enum AuthAlgorithm {
OpenSystem = 0,
}
bitfield! {
#[derive(Clone, Copy, Debug)]
pub struct FrameControl(u16);
pub protocol_ver, set_protocol_ver: 1, 0;
pub typ, set_typ: 3, 2;
pub subtype, set_subtype: 7, 4;
pub to_ds, set_to_ds: 8;
pub from_ds, set_from_ds: 9;
pub more_frags, set_more_frags: 10;
pub retry, set_retry: 11;
pub power_mgmt, set_power_mgmt: 12;
pub more_data, set_more_data: 13;
pub protected_frame, set_protected_frame: 14;
pub htc_order, set_htc_order: 15;
}
// IEEE Std 802.11-2016, 9.4.1.4
bitfield! {
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CapabilityInfo(u16);
pub ess, set_ess: 0;
pub ibss, set_ibss: 1;
pub cf_pollable, set_cf_pollable: 2;
pub cf_pll_req, set_cf_poll_req: 3;
pub privacy, set_privacy: 4;
pub short_preamble, set_short_preamble: 5;
// bit 6-7 reserved
pub spectrum_mgmt, set_spectrum_mgmt: 8;
pub qos, set_qos: 9;
pub short_slot_time, set_short_slot_time: 10;
pub apsd, set_apsd: 11;
pub radio_msmt, set_radio_msmt: 12;
// bit 13 reserved
pub delayed_block_ack, set_delayed_block_ack: 14;
pub immediate_block_ack, set_immediate_block_ack: 15;
}
// IEEE Std 802.11-2016, 9.2.4.4
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SeqControl {
pub frag_num: u16,
pub seq_num: u16,
}
impl SeqControl {
#[cfg(test)]
fn decode(num: u16) -> Self {
Self { frag_num: num & 0x0F, seq_num: num >> 4 }
}
fn encode(&self) -> u16 {
self.frag_num | (self.seq_num << 4)
}
}
// IEEE Std 802.11-2016, 9.3.2.1
#[derive(Clone, Copy, Debug)]
pub struct DataHeader {
pub frame_control: FrameControl,
pub duration: u16,
pub addr1: [u8; 6],
pub addr2: [u8; 6],
pub addr3: [u8; 6],
pub seq_control: SeqControl,
pub addr4: Option<[u8; 6]>,
pub qos_control: Option<u16>,
pub ht_control: Option<u32>,
}
#[cfg(test)]
impl DataHeader {
pub fn from_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
const DATA_SUBTYPE_QOS_BIT: u16 = 0b1000;
let frame_control = FrameControl(reader.read_u16::<LittleEndian>()?);
let duration = reader.read_u16::<LittleEndian>()?;
let mut addr1 = [0u8; 6];
reader.read(&mut addr1)?;
let mut addr2 = [0u8; 6];
reader.read(&mut addr2)?;
let mut addr3 = [0u8; 6];
reader.read(&mut addr3)?;
let seq_control = SeqControl::decode(reader.read_u16::<LittleEndian>()?);
let addr4 = match frame_control.to_ds() & frame_control.from_ds() {
true => {
let mut addr4 = [0u8; 6];
reader.read(&mut addr4)?;
Some(addr4)
}
false => None,
};
let qos_control = if (frame_control.subtype() & DATA_SUBTYPE_QOS_BIT) != 0 {
Some(reader.read_u16::<LittleEndian>()?)
} else {
None
};
let ht_control =
if frame_control.htc_order() { Some(reader.read_u32::<LittleEndian>()?) } else { None };
Ok(Self {
frame_control,
duration,
addr1,
addr2,
addr3,
seq_control,
addr4,
qos_control,
ht_control,
})
}
}
// IEEE Std 802.2-1998, 3.2
// IETF RFC 1042
#[derive(Clone, Copy, Debug)]
pub struct LlcHeader {
pub dsap: u8,
pub ssap: u8,
pub control: u8,
pub oui: [u8; 3],
pub protocol_id: u16,
}
#[cfg(test)]
impl LlcHeader {
pub fn from_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
let dsap = reader.read_u8()?;
let ssap = reader.read_u8()?;
let control = reader.read_u8()?;
let mut oui = [0u8; 3];
reader.read(&mut oui)?;
let protocol_id = reader.read_u16::<LittleEndian>()?;
Ok(Self { dsap, ssap, control, oui, protocol_id })
}
}
// IEEE Std 802.11-2016, 9.3.3.2
#[derive(Clone, Copy, Debug)]
pub struct MgmtHeader {
pub frame_control: FrameControl,
pub duration: u16,
pub addr1: [u8; 6],
pub addr2: [u8; 6],
pub addr3: [u8; 6],
pub seq_control: SeqControl,
pub ht_control: Option<u32>,
}
#[cfg(test)]
impl MgmtHeader {
pub fn from_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
let frame_control = FrameControl(reader.read_u16::<LittleEndian>()?);
let duration = reader.read_u16::<LittleEndian>()?;
let mut addr1 = [0u8; 6];
reader.read(&mut addr1)?;
let mut addr2 = [0u8; 6];
reader.read(&mut addr2)?;
let mut addr3 = [0u8; 6];
reader.read(&mut addr3)?;
let seq_control = SeqControl::decode(reader.read_u16::<LittleEndian>()?);
let ht_control =
if frame_control.htc_order() { Some(reader.read_u32::<LittleEndian>()?) } else { None };
Ok(Self { frame_control, duration, addr1, addr2, addr3, seq_control, ht_control })
}
}
// IEEE Std 802.11-2016, 9.3.3.3
#[derive(Clone, Copy, Debug)]
pub struct BeaconFields {
pub timestamp: u64, // IEEE Std 802.11-2016, 9.4.1.10
pub beacon_interval: u16, // IEEE Std 802.11-2016, 9.4.1.3
pub capability_info: CapabilityInfo, // IEEE Std 802.11-2016, 9.4.1.4
}
// IEEE Std 802.11-2016, 9.3.3.12
pub struct AuthenticationFields {
pub auth_algorithm_number: u16, // 9.4.1.1
pub auth_txn_seq_number: u16, // 9.4.1.2
pub status_code: u16, // 9.4.1.9
}
#[cfg(test)]
impl AuthenticationFields {
pub fn from_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
let auth_algorithm_number = reader.read_u16::<LittleEndian>()?;
let auth_txn_seq_number = reader.read_u16::<LittleEndian>()?;
let status_code = reader.read_u16::<LittleEndian>()?;
Ok(Self { auth_algorithm_number, auth_txn_seq_number, status_code })
}
}
// IEEE Std 802.11-2016, 9.3.3.7
pub struct AssociationResponseFields {
pub capability_info: CapabilityInfo, // 9.4.1.4
pub status_code: u16, // 9.4.1.9
pub association_id: u16, // 9.4.1.8
}
#[cfg(test)]
impl AssociationResponseFields {
pub fn from_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
let capability_info = CapabilityInfo(reader.read_u16::<LittleEndian>()?);
let status_code = reader.read_u16::<LittleEndian>()?;
let association_id = reader.read_u16::<LittleEndian>()?;
Ok(Self { capability_info, status_code, association_id })
}
}
pub const BROADCAST_ADDR: [u8; 6] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
// IEEE Std 802.11-2016, 9.4.2.1
enum ElementId {
Ssid = 0,
SupportedRates = 1,
DsssParameterSet = 3,
ExtendedSupportedRates = 50,
}
pub struct MacFrameWriter<W: io::Write> {
w: W,
}
impl<W: io::Write> MacFrameWriter<W> {
pub fn new(w: W) -> Self {
MacFrameWriter { w }
}
pub fn beacon(
mut self,
header: &MgmtHeader,
beacon: &BeaconFields,
) -> io::Result<ElementWriter<W>> {
self.write_mgmt_header(header, MgmtSubtype::Beacon)?;
self.w.write_u64::<LittleEndian>(beacon.timestamp)?;
self.w.write_u16::<LittleEndian>(beacon.beacon_interval)?;
self.w.write_u16::<LittleEndian>(beacon.capability_info.0 as u16)?;
Ok(ElementWriter { w: self.w })
}
pub fn authentication(
mut self,
header: &MgmtHeader,
auth: &AuthenticationFields,
) -> io::Result<ElementWriter<W>> {
self.write_mgmt_header(header, MgmtSubtype::Authentication)?;
self.w.write_u16::<LittleEndian>(auth.auth_algorithm_number)?;
self.w.write_u16::<LittleEndian>(auth.auth_txn_seq_number)?;
self.w.write_u16::<LittleEndian>(auth.status_code)?;
Ok(ElementWriter { w: self.w })
}
pub fn association_response(
mut self,
header: &MgmtHeader,
assoc: &AssociationResponseFields,
) -> io::Result<ElementWriter<W>> {
self.write_mgmt_header(header, MgmtSubtype::AssociationResponse)?;
self.w.write_u16::<LittleEndian>(assoc.capability_info.0 as u16)?;
self.w.write_u16::<LittleEndian>(assoc.status_code)?;
self.w.write_u16::<LittleEndian>(assoc.association_id)?;
Ok(ElementWriter { w: self.w })
}
fn write_mgmt_header(&mut self, header: &MgmtHeader, subtype: MgmtSubtype) -> io::Result<()> {
let mut frame_control = header.frame_control;
frame_control.set_typ(FrameControlType::Mgmt as u16);
frame_control.set_subtype(subtype as u16);
frame_control.set_htc_order(header.ht_control.is_some());
self.w.write_u16::<LittleEndian>(frame_control.0)?;
self.w.write_u16::<LittleEndian>(header.duration)?;
self.w.write_all(&header.addr1)?;
self.w.write_all(&header.addr2)?;
self.w.write_all(&header.addr3)?;
self.w.write_u16::<LittleEndian>(header.seq_control.encode())?;
if let Some(ht_control) = header.ht_control {
self.w.write_u32::<LittleEndian>(ht_control)?;
}
Ok(())
}
#[cfg(test)]
pub fn data(
mut self,
data_header: &DataHeader,
llc_header: &LlcHeader,
payload: &[u8],
) -> io::Result<Self> {
self.write_data_header(data_header, DataSubtype::Data)?;
self.write_llc_header(llc_header)?;
self.w.write_all(payload)?;
Ok(self)
}
#[cfg(test)]
fn write_data_header(&mut self, header: &DataHeader, subtype: DataSubtype) -> io::Result<()> {
let mut frame_control = header.frame_control;
frame_control.set_typ(FrameControlType::Data as u16);
frame_control.set_subtype(subtype as u16);
frame_control.set_htc_order(header.ht_control.is_some());
self.w.write_u16::<LittleEndian>(frame_control.0)?;
self.w.write_u16::<LittleEndian>(header.duration)?;
self.w.write_all(&header.addr1)?;
self.w.write_all(&header.addr2)?;
self.w.write_all(&header.addr3)?;
self.w.write_u16::<LittleEndian>(header.seq_control.encode())?;
if let Some(addr4) = header.addr4 {
self.w.write_all(&addr4)?;
}
if let Some(qos_control) = header.qos_control {
self.w.write_u16::<LittleEndian>(qos_control)?;
};
if let Some(ht_control) = header.ht_control {
self.w.write_u32::<LittleEndian>(ht_control)?;
};
Ok(())
}
#[cfg(test)]
fn write_llc_header(&mut self, header: &LlcHeader) -> io::Result<()> {
self.w.write_u8(header.dsap)?;
self.w.write_u8(header.ssap)?;
self.w.write_u8(header.control)?;
self.w.write_all(&header.oui)?;
self.w.write_u16::<LittleEndian>(header.protocol_id)?;
Ok(())
}
#[cfg(test)]
pub fn into_writer(self) -> W {
self.w
}
}
pub struct ElementWriter<W: io::Write> {
w: W,
}
impl<W: io::Write> ElementWriter<W> {
pub fn ssid(mut self, ssid: &[u8]) -> io::Result<Self> {
self.write_header(ElementId::Ssid, ssid.len() as u8)?;
self.w.write_all(ssid)?;
Ok(self)
}
pub fn supported_rates(mut self, rates: &[u8]) -> io::Result<Self> {
self.write_header(ElementId::SupportedRates, rates.len() as u8)?;
self.w.write_all(rates)?;
Ok(self)
}
pub fn dsss_parameter_set(mut self, current_channel: u8) -> io::Result<Self> {
self.write_header(ElementId::DsssParameterSet, 1)?;
self.w.write_u8(current_channel)?;
Ok(self)
}
pub fn extended_supported_rates(mut self, rates: &[u8]) -> io::Result<Self> {
self.write_header(ElementId::ExtendedSupportedRates, rates.len() as u8)?;
self.w.write_all(rates)?;
Ok(self)
}
#[cfg(test)]
pub fn into_writer(self) -> W {
self.w
}
fn write_header(&mut self, element_id: ElementId, length: u8) -> io::Result<()> {
self.w.write_u8(element_id as u8)?;
self.w.write_u8(length)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn simple_beacon() {
let frame = MacFrameWriter::new(vec![])
.beacon(
&MgmtHeader {
frame_control: FrameControl(0),
duration: 0x9765,
addr1: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06],
addr2: [0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C],
addr3: [0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12],
seq_control: SeqControl { frag_num: 5, seq_num: 0xABC },
ht_control: None,
},
&BeaconFields {
timestamp: 0x1122334455667788u64,
beacon_interval: 0xBEAC,
capability_info: CapabilityInfo(0xCAFE),
},
)
.unwrap()
.ssid(&[0xAA, 0xBB, 0xCC, 0xDD, 0xEE])
.unwrap()
.into_writer();
#[rustfmt::skip]
let expected_frame: &[u8] = &[
// Framectl Duration Address 1
0x80, 0x00, 0x65, 0x97, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
// Address 2 Address 3
0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12,
// Seq ctl Timestamp
0xC5, 0xAB, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11,
// Interval Cap info SSID element
0xAC, 0xBE, 0xFE, 0xCA, 0x00, 0x05, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE
];
assert_eq!(expected_frame, &frame[..]);
}
#[test]
fn parse_auth_frame() {
#[rustfmt::skip]
let mut bytes: &[u8] = &[
// Framectl Duration Address 1
0xb0, 0x00, 0x76, 0x98, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
// Address 2 Address 3
0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12,
// Seq ctl Algo num Seq num Status
0xC5, 0xAB, 0xB2, 0xA1, 0xAB, 0x23, 0xD4, 0xC3,
];
let hdr = MgmtHeader::from_reader(&mut bytes).expect("reading mgmt header");
assert_eq!(hdr.frame_control.typ(), FrameControlType::Mgmt as u16);
assert_eq!(hdr.frame_control.subtype(), MgmtSubtype::Authentication as u16);
assert_eq!(hdr.duration, 0x9876);
assert_eq!(hdr.addr1, [0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
assert_eq!(hdr.addr2, [0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C]);
assert_eq!(hdr.addr3, [0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12]);
assert_eq!(hdr.seq_control, SeqControl { frag_num: 5, seq_num: 0xABC });
assert_eq!(hdr.ht_control, None);
let body = AuthenticationFields::from_reader(&mut bytes).expect("reading auth fields");
assert_eq!(body.auth_algorithm_number, 0xA1B2);
assert_eq!(body.auth_txn_seq_number, 0x23AB);
assert_eq!(body.status_code, 0xC3D4);
}
#[test]
fn simple_auth() {
let frame = MacFrameWriter::new(vec![])
.authentication(
&MgmtHeader {
frame_control: FrameControl(0),
duration: 0x9876,
addr1: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06],
addr2: [0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C],
addr3: [0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12],
seq_control: SeqControl { frag_num: 5, seq_num: 0xABC },
ht_control: None,
},
&AuthenticationFields {
auth_algorithm_number: 0xA1B2,
auth_txn_seq_number: 0x23AB,
status_code: 0xC3D4,
},
)
.unwrap()
.into_writer();
#[rustfmt::skip]
let expected_frame: &[u8] = &[
// Framectl Duration Address 1
0xb0, 0x00, 0x76, 0x98, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
// Address 2 Address 3
0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12,
// Seq ctl Algo num Seq num Status
0xC5, 0xAB, 0xB2, 0xA1, 0xAB, 0x23, 0xD4, 0xC3,
];
assert_eq!(expected_frame, &frame[..]);
}
#[test]
fn parse_assoc_frame() {
let mut bytes: &[u8] = &[
// Framectl Duration Address 1
0x10, 0x00, 0x65, 0x87, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
// Address 2 Address 3
0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12,
// Seq ctl Cap info Status code Assoc id
0xF6, 0xDE, 0xDE, 0xBC, 0x76, 0x98, 0x43, 0x65,
];
let hdr = MgmtHeader::from_reader(&mut bytes).expect("reading mgmt header");
assert_eq!(hdr.frame_control.typ(), FrameControlType::Mgmt as u16);
assert_eq!(hdr.frame_control.subtype(), MgmtSubtype::AssociationResponse as u16);
assert_eq!(hdr.duration, 0x8765);
assert_eq!(hdr.addr1, [0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
assert_eq!(hdr.addr2, [0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C]);
assert_eq!(hdr.addr3, [0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12]);
assert_eq!(hdr.seq_control, SeqControl { frag_num: 6, seq_num: 0xDEF });
assert_eq!(hdr.ht_control, None);
let body = AssociationResponseFields::from_reader(&mut bytes).expect("reading assoc resp");
assert_eq!(body.capability_info, CapabilityInfo(0xBCDE));
assert_eq!(body.status_code, 0x9876);
assert_eq!(body.association_id, 0x6543);
}
#[test]
fn simple_assoc() {
let frame = MacFrameWriter::new(vec![])
.association_response(
&MgmtHeader {
frame_control: FrameControl(0),
duration: 0x8765,
addr1: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06],
addr2: [0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C],
addr3: [0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12],
seq_control: SeqControl { frag_num: 6, seq_num: 0xDEF },
ht_control: None,
},
&AssociationResponseFields {
capability_info: CapabilityInfo(0xBCDE),
status_code: 0x9876,
association_id: 0x6543,
},
)
.unwrap()
.into_writer();
#[rustfmt::skip]
let expected_frame: &[u8] = &[
// Framectl Duration Address 1
0x10, 0x00, 0x65, 0x87, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
// Address 2 Address 3
0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12,
// Seq ctl Cap info Status code Assoc id
0xF6, 0xDE, 0xDE, 0xBC, 0x76, 0x98, 0x43, 0x65,
];
assert_eq!(expected_frame, &frame[..]);
}
#[test]
fn parse_data_frame() {
let mut bytes = &[
8u8, 1, // FrameControl
0, 0, // Duration
101, 116, 104, 110, 101, 116, // Addr1
103, 98, 111, 110, 105, 107, // Addr2
98, 115, 115, 98, 115, 115, // Addr3
48, 0, // SeqControl
// LLC Header
170, 170, 3, // dsap, ssap and control
0, 0, 0, // OUI
0, 8, // protocol ID
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, // payload
] as &[u8];
let data_header = DataHeader::from_reader(&mut bytes).expect("reading data header");
assert_eq!(data_header.frame_control.typ(), FrameControlType::Data as u16);
assert_eq!(data_header.frame_control.subtype(), DataSubtype::Data as u16);
assert_eq!(data_header.addr1, [0x65, 0x74, 0x68, 0x6e, 0x65, 0x74]);
assert_eq!(data_header.addr2, [0x67, 0x62, 0x6f, 0x6e, 0x69, 0x6b]);
assert_eq!(data_header.addr3, [0x62, 0x73, 0x73, 0x62, 0x73, 0x73]);
assert_eq!(data_header.seq_control.seq_num, 3);
assert!(data_header.addr4.is_none());
assert!(data_header.qos_control.is_none());
assert!(data_header.ht_control.is_none());
let llc_header = LlcHeader::from_reader(&mut bytes).expect("reading llc header");
assert_eq!(llc_header.oui, [0, 0, 0]);
let mut payload = vec![];
let bytes_read = io::Read::read_to_end(&mut bytes, &mut payload).expect("reading payload");
assert_eq!(bytes_read, 15);
assert_eq!(&payload[..], &[1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
}
#[test]
fn simple_data() {
let frame = MacFrameWriter::new(vec![])
.data(
&DataHeader {
frame_control: FrameControl(0), // will be overwritten
duration: 0x8765,
addr1: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06],
addr2: [0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C],
addr3: [0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12],
seq_control: SeqControl { frag_num: 6, seq_num: 0xDEF },
addr4: None,
qos_control: None,
ht_control: None,
},
&LlcHeader {
dsap: 123,
ssap: 234,
control: 111,
oui: [0xff, 0xfe, 0xfd],
protocol_id: 0x3456,
},
&[11, 12, 13, 14, 15, 16, 17],
)
.unwrap()
.into_writer();
#[rustfmt::skip]
let expected_frame: &[u8] = &[
8u8, 0, // FrameControl (overwritten)
0x65, 0x87, // Duration
1, 2, 3, 4, 5, 6, // Addr1
7, 8, 9, 10, 11, 12, // Addr2
13, 14, 15, 16, 17, 18, // Addr3
0xf6, 0xde, // SeqControl
// LLC Header
123, 234, 111, // dsap, ssap and control
0xff, 0xfe, 0xfd, // OUI
0x56, 0x34, // protocol ID
// payload
11, 12, 13, 14, 15, 16, 17,
];
assert_eq!(expected_frame, &frame[..]);
}
}
|
use crate::hitable::*;
use crate::ray::*;
use crate::sphere::*;
use crate::vec3::*;
use rand::Rng;
use rand::distributions::{Distribution, Standard};
// One trait to rule them all
pub trait Material {
fn scatter(&self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3) -> Option<Ray>;
}
// Use an enum as type of material
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MaterialType {
Dielectric(Dielectric),
Lambertian(Lambertian),
Metal(Metal),
}
// So we can use Material with rand::random::<Material>()
impl Distribution<MaterialType> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> MaterialType {
// Weighted random material. 80% Diffuse, 15% Metal, 5% Glass
let mat_type: f32 = rng.gen();
match mat_type {
x if x < 0.8 => {
MaterialType::Lambertian(Lambertian::from((rng.gen(), rng.gen(), rng.gen())))
},
x if x < 0.95 => {
MaterialType::Metal(Metal::from(((rng.gen(), rng.gen(), rng.gen()), rng.gen())))
},
_ => {
let rnd: f32 = rng.gen();
MaterialType::Dielectric(Dielectric::from(rnd))
},
}
}
}
impl Material for MaterialType {
fn scatter(&self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3) -> Option<Ray> {
use MaterialType::*;
match self {
Dielectric(d) => d.scatter(r_in, rec, attenuation),
Lambertian(l) => l.scatter(r_in, rec, attenuation),
Metal(m) => m.scatter(r_in, rec, attenuation),
}
}
}
// =================================================================================
/// DIELECTRIC MATERIAL
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Dielectric {
pub ref_idx: f32,
}
impl Dielectric {
pub fn schlick(cosine: f32, ref_idx: f32) -> f32 {
let mut r0 = (1.0 - ref_idx) / (1.0 + ref_idx);
r0 *= r0;
r0 + (1.0 - r0) * (1.0 - cosine).powf(5.0)
}
}
impl From<f32> for Dielectric {
fn from(ref_idx: f32) -> Self {
Self {
ref_idx
}
}
}
impl Material for Dielectric {
fn scatter(&self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3) -> Option<Ray> {
let mut outward_normal: Vec3;
let reflected = r_in.direction.reflect(rec.normal);
let ni_over_nt: f32;
let reflect_prob: f32;
let cosine: f32;
*attenuation = Vec3::from((1.0, 1.0, 1.0));
if r_in.direction.dot(rec.normal) > 0.0 {
outward_normal = -rec.normal;
ni_over_nt = self.ref_idx;
cosine = self.ref_idx * r_in.direction.dot(rec.normal) / r_in.direction.length();
} else {
outward_normal = rec.normal;
ni_over_nt = 1.0 / self.ref_idx;
cosine = -r_in.direction.dot(rec.normal) / r_in.direction.length();
}
let refracted = r_in.direction.refract(outward_normal, ni_over_nt);
if refracted.is_some() {
reflect_prob = Dielectric::schlick(cosine, self.ref_idx);
} else {
reflect_prob = 1.0;
}
// Result randomly chosen between reflected and refracted
if rand::random::<f32>() < reflect_prob {
Some(Ray::from((rec.p, reflected)))
} else {
Some(Ray::from((rec.p, refracted.unwrap())))
}
}
}
// =================================================================================
// =================================================================================
/// LAMBERTIAN MATERIAL
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Lambertian {
pub albedo: Vec3,
}
impl From<(f32, f32, f32)> for Lambertian {
fn from(tuple: (f32, f32, f32)) -> Self {
Self {
albedo: Vec3::from(tuple)
}
}
}
impl From<Vec3> for Lambertian {
fn from(albedo: Vec3) -> Self {
Self {
albedo
}
}
}
impl Material for Lambertian {
fn scatter(&self, _r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3) -> Option<Ray> {
let target = rec.p + rec.normal + Sphere::random_in_unit_sphere();
*attenuation = self.albedo;
Some(Ray::from((rec.p, target - rec.p)))
}
}
// =================================================================================
// =================================================================================
/// METAL MATERIAL
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Metal {
pub albedo: Vec3,
pub fuzz: f32,
}
// This from is for Vec3 from 3 f32s tupled with a f32 for fuzz
impl From<((f32, f32, f32), f32)> for Metal {
fn from(tuple: ((f32, f32, f32), f32)) -> Self {
Self {
albedo: Vec3::from(tuple.0),
fuzz: tuple.1,
}
}
}
impl From<(Vec3, f32)> for Metal {
fn from(tuple: (Vec3, f32)) -> Self {
Self {
albedo: Vec3::from(tuple.0),
fuzz: tuple.1,
}
}
}
impl Material for Metal {
fn scatter(&self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3) -> Option<Ray> {
let reflected = r_in.direction.unit_vector().reflect(rec.normal);
let scattered = Ray::from((rec.p, reflected + self.fuzz * Sphere::random_in_unit_sphere()));
*attenuation = self.albedo;
// Result:
if scattered.direction.dot(rec.normal) > 0.0 {
Some(scattered)
} else {
None
}
}
}
// ================================================================================= |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::string::String;
use alloc::vec::Vec;
use alloc::sync::Arc;
pub use xmas_elf::program::{Flags, ProgramHeader, ProgramHeader64};
pub use xmas_elf::sections::Rela;
pub use xmas_elf::symbol_table::{Entry, Entry64};
pub use xmas_elf::{P32, P64};
pub use xmas_elf::header::HeaderPt2;
use super::super::asm::*;
use super::super::loader::loader::*;
use super::super::taskMgr::*;
use super::super::task::*;
use super::super::SignalDef::*;
use super::super::vcpu::*;
use super::super::qlib::LoadAddr;
use super::super::qlib::common::*;
use super::super::qlib::linux_def::*;
use super::super::syscalls::syscalls::*;
use super::super::kernel::cpuset::*;
use super::super::threadmgr::thread::*;
use super::super::threadmgr::task_exit::*;
use super::super::threadmgr::task_exec::*;
use super::super::threadmgr::task_clone::*;
use super::super::threadmgr::task_sched::*;
use super::super::memmgr::mm::*;
use super::super::SHARESPACE;
#[derive(Default, Debug)]
pub struct ElfInfo {
pub interpreter: String,
pub entry: u64,
pub start: u64,
pub end: u64,
pub phdrAddr: u64,
pub phdrSize: usize,
pub phdrNum: usize,
pub addrs: Vec<LoadAddr>
}
// Getppid implements linux syscall getppid(2).
pub fn SysGetPpid(task: &mut Task, _args: &SyscallArguments) -> Result<i64> {
let t = task.Thread();
let parent = match t.Parent() {
None => return Ok(0),
Some(p) => p,
};
let pidns = t.PIDNamespace();
let ptg = parent.ThreadGroup();
let pid = pidns.IDOfThreadGroup(&ptg);
return Ok(pid as i64)
}
// Getpid implements linux syscall getpid(2).
pub fn SysGetPid(task: &mut Task, _args: &SyscallArguments) -> Result<i64> {
let pid = task.Thread().ThreadGroup().ID();
return Ok(pid as i64)
}
// Gettid implements linux syscall gettid(2).
pub fn SysGetTid(task: &mut Task, _args: &SyscallArguments) -> Result<i64> {
let tid = task.Thread().ThreadID();
return Ok(tid as i64)
}
pub fn SysSetRobustList(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let robust_list_head = args.arg0 as u64;
let robust_list_len = args.arg1 as i64;
if robust_list_len as u64 != ROBUST_LIST_LEN {
return Err(Error::SysError(SysErr::EINVAL));
}
let thread = task.Thread();
thread.lock().robust_list_head = robust_list_head;
return Ok(0);
}
pub fn SysGetRobustList(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let tid = args.arg0 as i32;
let headAddr = args.arg1 as u64;
let lenAddr = args.arg2 as u64;
let thread = if tid == 0 {
task.Thread()
} else {
match task.Thread().PIDNamespace().TaskWithID(tid) {
None => return Err(Error::SysError(SysErr::ESRCH)),
Some(t) => t,
}
};
// todo: check whether the current thread has permission to get the RobustList from target thread
//*task.GetTypeMut::<u64>(headAddr)? = thread.lock().robust_list_head;
//*task.GetTypeMut::<i64>(lenAddr)? = ROBUST_LIST_LEN as i64;
task.CopyOutObj(&(thread.lock().robust_list_head as u64), headAddr)?;
task.CopyOutObj(&(ROBUST_LIST_LEN as i64), lenAddr)?;
return Ok(0);
}
// ExecMaxTotalSize is the maximum length of all argv and envv entries.
//
// N.B. The behavior here is different than Linux. Linux provides a limit on
// individual arguments of 32 pages, and an aggregate limit of at least 32 pages
// but otherwise bounded by min(stack size / 4, 8 MB * 3 / 4). We don't implement
// any behavior based on the stack size, and instead provide a fixed hard-limit of
// 2 MB (which should work well given that 8 MB stack limits are common).
const EXEC_MAX_TOTAL_SIZE: usize = 2 * 1024 * 1024;
// ExecMaxElemSize is the maximum length of a single argv or envv entry.
const EXEC_MAX_ELEM_SIZE: usize = 32 * MemoryDef::PAGE_SIZE as usize;
pub fn SysExecve(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let filenameAddr = args.arg0 as u64;
let argvAddr = args.arg1 as u64;
let envvAddr = args.arg2 as u64;
let (fileName, err) = task.CopyInString(filenameAddr, PATH_MAX);
match err {
Err(e) => return Err(e),
_ => ()
}
info!("SysExecve file name is {}", &fileName);
let mut argv = task.CopyInVector(argvAddr, EXEC_MAX_ELEM_SIZE, EXEC_MAX_TOTAL_SIZE as i32)?;
let envv = task.CopyInVector(envvAddr, EXEC_MAX_ELEM_SIZE, EXEC_MAX_TOTAL_SIZE as i32)?;
//todo: handle SysExecve gracelly
info!("SysExecve workaround, will handle gracefully");
let mut cmd = format!("");
for arg in &argv {
cmd += &arg;
cmd += " ";
}
let mut envs = format!("");
for env in &envv {
envs += &env;
envs += " ";
}
info!("in the execve: the cmd is {} \n envs is {:?}", &cmd, &envs);
let fileName = {
let fscontex = task.fsContext.clone();
let cwd = fscontex.lock().cwd.clone();
let root = fscontex.lock().root.clone();
let mut remainingTraversals = 40;
let d = task.mountNS.FindInode(task, &root, Some(cwd), &fileName, &mut remainingTraversals)?;
d.MyFullName()
};
let (entry, usersp, kernelsp) = {
{
let t = task.Thread().clone();
let tg = t.lock().tg.clone();
let pidns = tg.PIDNamespace();
let owner = pidns.lock().owner.clone();
let signallock = tg.lock().signalLock.clone();
{
let ol = owner.WriteLock();
let sl = signallock.lock();
let exiting = tg.lock().exiting;
let execing = tg.lock().execing.Upgrade();
if exiting || execing.is_some() {
// We lost to a racing group-exit, kill, or exec from another thread
// and should just exit.
return Err(Error::SysError(SysErr::EINTR))
}
// Cancel any racing group stops.
tg.lock().endGroupStopLocked(false);
// If the task has any siblings, they have to exit before the exec can
// continue.
tg.lock().execing = t.Downgrade();
let taskCnt = tg.lock().tasks.len();
if taskCnt != 1 {
// "[All] other threads except the thread group leader report death as
// if they exited via _exit(2) with exit code 0." - ptrace(2)
let tasks : Vec<_> = tg.lock().tasks.iter().cloned().collect();
for sibling in &tasks {
if t != sibling.clone() {
sibling.lock().killLocked();
}
}
// The last sibling to exit will wake t.
t.lock().beginInternalStopLocked(&Arc::new(ExecStop {}));
core::mem::drop(sl);
core::mem::drop(ol);
task.DoStop();
}
}
let mut its = Vec::new();
{
let _l = owner.WriteLock();
tg.lock().execing = ThreadWeak::default();
if t.lock().killed() {
//return (*runInterrupt)(nil)
return Err(Error::SysError(SysErr::EINTR))
}
t.promoteLocked();
// "POSIX timers are not preserved (timer_create(2))." - execve(2). Handle
// this first since POSIX timers are protected by the signal mutex, which
// we're about to change. Note that we have to stop and destroy timers
// without holding any mutexes to avoid circular lock ordering.
{
let _s = signallock.lock();
for (_, it) in &tg.lock().timers {
its.push(it.clone());
}
tg.lock().timers.clear();
}
}
for it in its {
it.DestroyTimer();
}
{
let _l = owner.WriteLock();
let sh = tg.lock().signalHandlers.clone();
// "During an execve(2), the dispositions of handled signals are reset to
// the default; the dispositions of ignored signals are left unchanged. ...
// [The] signal mask is preserved across execve(2). ... [The] pending
// signal set is preserved across an execve(2)." - signal(7)
//
// Details:
//
// - If the thread group is sharing its signal handlers with another thread
// group via CLONE_SIGHAND, execve forces the signal handlers to be copied
// (see Linux's fs/exec.c:de_thread). We're not reference-counting signal
// handlers, so we always make a copy.
//
// - "Disposition" only means sigaction::sa_handler/sa_sigaction; flags,
// restorer (if present), and mask are always reset. (See Linux's
// fs/exec.c:setup_new_exec => kernel/signal.c:flush_signal_handlers.)
tg.lock().signalHandlers = sh.CopyForExec();
// "Any alternate signal stack is not preserved (sigaltstack(2))." - execve(2)
t.lock().signalStack = SignalStack::default();
task.signalStack = SignalStack::default();
// "The termination signal is reset to SIGCHLD (see clone(2))."
tg.lock().terminationSignal = Signal(Signal::SIGCHLD);
// execed indicates that the process can no longer join a process group
// in some scenarios (namely, the parent call setpgid(2) on the child).
// See the JoinProcessGroup function in sessions.go for more context.
tg.lock().execed = true;
}
let fdtbl = t.lock().fdTbl.clone();
fdtbl.lock().RemoveCloseOnExec();
t.ExitRobustList(task);
t.lock().updateCredsForExecLocked();
t.UnstopVforkParent();
SetFs(0);
task.context.fs = 0;
let newMM = MemoryManager::Init(false);
let oldMM = task.mm.clone();
task.mm = newMM.clone();
task.futexMgr = task.futexMgr.Fork();
task.Thread().lock().memoryMgr = newMM;
if !SHARESPACE.config.KernelPagetable {
task.SwitchPageTable();
}
// make the old mm exist before switch pagetable
core::mem::drop(oldMM);
}
Load(task, &fileName, &mut argv, &envv, &Vec::new())?
};
//need to clean object on stack before enter_user as the stack will be destroyed
task.AccountTaskEnter(SchedState::RunningApp);
EnterUser(entry, usersp, kernelsp);
//won't reach here
return Ok(0)
}
pub fn SysExit(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let exitcode = args.arg0 as i32;
let exitStatus = ExitStatus::New(exitcode as i32, 0);
task.Thread().PrepareExit(exitStatus);
return Err(Error::SysCallRetCtrl(TaskRunState::RunThreadExit));
}
pub fn SysExitThreadGroup(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let exitcode = args.arg0 as i32;
let exitStatus = ExitStatus::New(exitcode as i32, 0);
task.Thread().PrepareGroupExit(exitStatus);
return Err(Error::SysCallRetCtrl(TaskRunState::RunExit));
}
// Clone implements linux syscall clone(2).
// sys_clone has so many flavors. We implement the default one in linux 3.11
// x86_64:
// sys_clone(clone_flags, newsp, parent_tidptr, child_tidptr, tls_val)
pub fn SysClone(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let flags = args.arg0;
let cStack = args.arg1;
let pTid = args.arg2;
let cTid = args.arg3;
let tls = args.arg4;
let pid = task.Clone(flags, cStack, pTid, cTid, tls)?;
return Ok(pid as i64)
}
// Fork implements Linux syscall fork(2).
pub fn SysFork(task: &mut Task, _args: &SyscallArguments) -> Result<i64> {
let pid = task.Clone(Signal::SIGCHLD as u64, 0, 0, 0, 0)?;
return Ok(pid as i64)
}
pub fn SysVfork(task: &mut Task, _args: &SyscallArguments) -> Result<i64> {
let pid = task.Clone(LibcConst::CLONE_VM | LibcConst::CLONE_VFORK |Signal::SIGCHLD as u64, 0, 0, 0, 0)?;
return Ok(pid as i64)
}
// Wait4 implements linux syscall wait4(2).
pub fn SysWait4(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let pid = args.arg0;
let status = args.arg1;
let option = args.arg2 as u32;
let rusage = args.arg3;
return wait4(task, pid as i32, status, option, rusage);
}
// Waitid implements linux syscall waitid(2).
pub fn SysWaitid(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let idtype = args.arg0 as i32;
let id = args.arg1 as i32;
let infop = args.arg2;
let options = args.arg3 as u32;
let _rusageAddr = args.arg4;
if options & !(WaitOption::WNOHANG |
WaitOption::WEXITED |
WaitOption::WSTOPPED |
WaitOption::WCONTINUED |
WaitOption::WNOWAIT |
WaitOption::WNOTHREAD |
WaitOption::WALL |
WaitOption::WCLONE
) != 0 {
return Err(Error::SysError(SysErr::EINVAL))
}
if options & (WaitOption::WEXITED | WaitOption::WSTOPPED | WaitOption::WCONTINUED) == 0 {
return Err(Error::SysError(SysErr::EINVAL))
}
let mut wopts = WaitOptions {
Events: TaskEvent::TRACE_STOP as EventMask,
ConsumeEvent: options & WaitOption::WNOWAIT == 0,
..Default::default()
};
match idtype {
IDType::P_ALL | IDType::P_PID => {
wopts.SpecificTID = id;
}
IDType::P_PGID => {
wopts.SpecificPGID = id;
}
_ => {
return Err(Error::SysError(SysErr::EINVAL))
}
}
parseCommonWaitOptions(&mut wopts, options)?;
if options & WaitOption::WEXITED != 0 {
wopts.Events |= EVENT_EXIT;
}
if options & WaitOption::WSTOPPED != 0 {
wopts.Events |= EVENT_CHILD_GROUP_STOP;
}
let wr = match task.Wait(&wopts) {
Err(Error::ErrNoWaitableEvent) => {
// "If WNOHANG was specified in options and there were no children
// in a waitable state, then waitid() returns 0 immediately and the
// state of the siginfo_t structure pointed to by infop is
// unspecified." - waitid(2). But Linux's waitid actually zeroes
// out the fields it would set for a successful waitid in this case
// as well.
if infop != 0 {
let si = SignalInfo::default();
task.CopyOutObj(&si, infop)?;
}
return Ok(0)
}
Err(e) => return Err(e),
Ok(wr) => wr,
};
//todo: handle rusageAddr
/*if rusageAddr != 0 {
}*/
if infop == 0 {
return Ok(0)
}
let mut si = SignalInfo {
Signo: Signal::SIGCHLD,
..Default::default()
};
let sigChld = si.SigChld();
sigChld.pid = wr.TID;
sigChld.uid = wr.UID.0;
// TODO: convert kernel.ExitStatus to functions and make
// WaitResult.Status a linux.WaitStatus
let mut siCode = 0;
let s = WaitStatus(wr.Status);
if s.Exited() {
siCode = SignalInfo::CLD_EXITED;
sigChld.status = s.ExitStatus();
} else if s.Signaled() {
siCode = SignalInfo::CLD_KILLED;
sigChld.status = s.Signal();
} else if s.CoreDump() {
siCode = SignalInfo::CLD_DUMPED;
sigChld.status = s.Signal();
} else if s.Stopped() {
if wr.Event == EVENT_TRACEE_STOP {
siCode = SignalInfo::CLD_TRAPPED;
sigChld.status = s.TrapCause();
} else {
siCode = SignalInfo::CLD_TRAPPED;
sigChld.status = s.StopSignal();
}
} else if s.Continued() {
siCode = SignalInfo::CLD_CONTINUED;
sigChld.status = Signal::SIGCONT;
} else {
info!("waitid got incomprehensible wait status {:b}", s.0)
}
si.Code = siCode;
task.CopyOutObj(&si, infop)?;
return Ok(0)
}
pub fn wait4(task: &Task, pid: i32, statusAddr: u64, options: u32, _rusage: u64) -> Result<i64> {
if options & !(WaitOption::WNOHANG | WaitOption::WUNTRACED | WaitOption::WCONTINUED | WaitOption::WNOTHREAD | WaitOption::WALL | WaitOption::WCLONE) != 0 {
return Err(Error::SysError(SysErr::EINVAL))
}
let mut wopts = WaitOptions {
Events: (TaskEvent::EXIT | TaskEvent::TRACE_STOP) as u64,
ConsumeEvent: true,
..Default::default()
};
// There are four cases to consider:
//
// pid < -1 any child process whose process group ID is equal to the absolute value of pid
// pid == -1 any child process
// pid == 0 any child process whose process group ID is equal to that of the calling process
// pid > 0 the child whose process ID is equal to the value of pid
if pid < -1 {
wopts.SpecificPGID = -pid;
} else if pid == -1 {
// Any process is the default.
} else if pid == 0 {
let pg = task.Thread().ThreadGroup().ProcessGroup();
let pidns = task.Thread().PIDNamespace();
wopts.SpecificPGID = pidns.IDOfProcessGroup(&pg.unwrap());
} else {
wopts.SpecificTID = pid;
}
parseCommonWaitOptions(&mut wopts, options)?;
if options & WaitOption::WUNTRACED != 0 {
wopts.Events |= EVENT_CHILD_GROUP_STOP;
}
let wr = match task.Wait(&wopts) {
Err(Error::ErrNoWaitableEvent) => return Ok(0),
Err(e) => return Err(e),
Ok(wr) => wr,
};
if statusAddr != 0 {
//task.CopyInObject(statusAddr, &wr.Status as * const _ as u64, 4)?;
task.CopyOutObj(&wr.Status, statusAddr)?;
}
//todo: handle rusageAddr
/*if rusageAddr != 0 {
}*/
return Ok(wr.TID as i64)
}
pub fn parseCommonWaitOptions(wopts: &mut WaitOptions, options: u32) -> Result<()> {
let tmp = options & (WaitOption::WCLONE | WaitOption::WALL);
if tmp == 0 {
wopts.NonCloneTasks = true;
} else if tmp == WaitOption::WCLONE {
wopts.CloneTasks = true;
} else if tmp == WaitOption::WALL {
wopts.CloneTasks = true;
wopts.NonCloneTasks = true;
} else {
return Err(Error::SysError(SysErr::EINVAL))
}
if options & WaitOption::WCONTINUED != 0 {
wopts.Events |= TaskEvent::GROUP_CONTINUE as u64;
}
if options & WaitOption::WNOHANG == 0 {
wopts.BlockInterruptErr = Some(Error::SysError(SysErr::ERESTARTSYS));
}
if options & WaitOption::WNOTHREAD == 0 {
wopts.SiblingChildren = true;
}
return Ok(())
}
// SetTidAddress implements linux syscall set_tid_address(2).
pub fn SysSetTidAddr(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let addr = args.arg0 as u64;
task.SetClearTID(addr);
let tid = task.Thread().ThreadID();
return Ok(tid as i64);
}
// Unshare implements linux syscall unshare(2).
pub fn SysUnshare(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let flags = args.arg0 as i32;
let mut opts = SharingOptions {
NewAddressSpace: flags & CloneOp::CLONE_VM == CloneOp::CLONE_VM,
NewSignalHandlers: flags & CloneOp::CLONE_SIGHAND == CloneOp::CLONE_SIGHAND,
NewThreadGroup: flags & CloneOp::CLONE_THREAD == CloneOp::CLONE_THREAD,
NewPIDNamespace: flags & CloneOp::CLONE_NEWPID == CloneOp::CLONE_NEWPID,
NewUserNamespace: flags & CloneOp::CLONE_NEWUSER == CloneOp::CLONE_NEWUSER,
NewNetworkNamespace: flags & CloneOp::CLONE_NEWNET == CloneOp::CLONE_NEWNET,
NewFiles: flags & CloneOp::CLONE_FILES == CloneOp::CLONE_FILES,
NewFSContext: flags & CloneOp::CLONE_FS == CloneOp::CLONE_FS,
NewUTSNamespace: flags & CloneOp::CLONE_NEWUTS == CloneOp::CLONE_NEWUTS,
NewIPCNamespace: flags & CloneOp::CLONE_NEWIPC == CloneOp::CLONE_NEWIPC,
..Default::default()
};
// "CLONE_NEWPID automatically implies CLONE_THREAD as well." - unshare(2)
if opts.NewPIDNamespace {
opts.NewThreadGroup = true;
}
// "... specifying CLONE_NEWUSER automatically implies CLONE_THREAD. Since
// Linux 3.9, CLONE_NEWUSER also automatically implies CLONE_FS."
if opts.NewUserNamespace {
opts.NewThreadGroup = true;
opts.NewFSContext = true;
panic!("Doesn't support create new usernamespace...");
}
task.Unshare(&opts)?;
return Ok(0);
}
// SchedYield implements linux syscall sched_yield(2).
pub fn SysScheduleYield(_task: &mut Task, _args: &SyscallArguments) -> Result<i64> {
Yield();
return Ok(0)
}
// SchedSetaffinity implements linux syscall sched_setaffinity(2).
pub fn SysSchedSetaffinity(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let tid = args.arg0 as i32;
let mut size = args.arg1 as usize;
let maskAddr = args.arg2 as u64;
let t = if tid == 0 {
task.Thread().clone()
} else {
let pidns = task.Thread().PIDNamespace();
match pidns.TaskWithID(tid) {
None => return Err(Error::SysError(SysErr::ESRCH)),
Some(t) => t,
}
};
let mut mask = CPUSet::New(task.Thread().lock().k.ApplicationCores() as usize);
if size > mask.Size() {
size = mask.Size();
}
let arr = task.CopyInVec::<u8>(maskAddr, size)?;
for i in 0..size {
mask.0[i] = arr[0];
}
t.SetCPUMask(mask)?;
return Ok(0)
}
// SchedGetaffinity implements linux syscall sched_getaffinity(2).
pub fn SysSchedGetaffinity(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let tid = args.arg0 as i32;
let size = args.arg1 as usize;
let maskAddr = args.arg2 as u64;
// This limitation is because linux stores the cpumask
// in an array of "unsigned long" so the buffer needs to
// be a multiple of the word size.
if size & (8 - 1) > 0 {
return Err(Error::SysError(SysErr::EINVAL));
}
let t = if tid == 0 {
task.Thread()
} else {
let pidns = task.Thread().PIDNamespace();
match pidns.TaskWithID(tid) {
None => return Err(Error::SysError(SysErr::ESRCH)),
Some(t) => t,
}
};
let mask = t.CPUMask();
// The buffer needs to be big enough to hold a cpumask with
// all possible cpus.
if size < mask.Size() {
return Err(Error::SysError(SysErr::EINVAL));
}
// info!("SysSchedGetaffinity cpu count is {}", mask.NumCPUs());
task.CopyOutSlice(&mask.0[..], maskAddr, mask.0.len())?;
// NOTE: The syscall interface is slightly different than the glibc
// interface. The raw sched_getaffinity syscall returns the number of
// bytes used to represent a cpu mask.
return Ok(mask.Size() as i64)
}
// Getcpu implements linux syscall getcpu(2).
pub fn SysGetcpu(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let cpu = args.arg0 as u64;
let node = args.arg1 as u64;
// third argument to this system call is nowadays unused.
if cpu != 0 {
let id = task.CPU();
//*task.GetTypeMut(cpu)? = id;
task.CopyOutObj(&id, cpu)?;
}
if node != 0 {
let val: u32 = 0;
//*task.GetTypeMut(node)? = val;
task.CopyOutObj(&val, node)?;
}
return Ok(0);
}
// Setpgid implements the linux syscall setpgid(2).
pub fn SysSetpgid(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
// Note that throughout this function, pgid is interpreted with respect
// to t's namespace, not with respect to the selected ThreadGroup's
// namespace (which may be different).
let pid = args.arg0 as i32;
let mut pgid = args.arg1 as i32;
// "If pid is zero, then the process ID of the calling process is used."
let mut tg = task.Thread().ThreadGroup();
let pidns = tg.PIDNamespace();
if pid != 0 {
let ot = match pidns.TaskWithID(pid) {
None => return Err(Error::SysError(SysErr::ESRCH)),
Some(t) => t,
};
tg = ot.ThreadGroup();
let tgLeader = tg.Leader().unwrap();
if tgLeader != ot {
return Err(Error::SysError(SysErr::EINVAL));
}
// Setpgid only operates on child threadgroups.
if tg != task.Thread().ThreadGroup() &&
(tgLeader.Parent().is_none() || tgLeader.Parent().unwrap().ThreadGroup() != task.Thread().ThreadGroup()) {
return Err(Error::SysError(SysErr::EINVAL));
}
}
// "If pgid is zero, then the PGID of the process specified by pid is made
// the same as its process ID."
let defaultPGID = pidns.IDOfThreadGroup(&tg);
if pgid == 0 {
pgid = defaultPGID;
} else if pgid < 0 {
return Err(Error::SysError(SysErr::EINVAL));
}
// If the pgid is the same as the group, then create a new one. Otherwise,
// we attempt to join an existing process group.
if pgid == defaultPGID {
// For convenience, errors line up with Linux syscall API.
match tg.CreateProcessGroup() {
Err(e) => {
let pg = tg.ProcessGroup().unwrap();
if pidns.IDOfProcessGroup(&pg) == defaultPGID {
return Ok(0)
}
return Err(e)
}
_ => (),
}
} else {
let localtg = task.Thread().ThreadGroup();
match tg.JoinProcessGroup(&pidns, pgid, tg != localtg) {
Err(e) => {
let pg = tg.ProcessGroup().unwrap();
if pidns.IDOfProcessGroup(&pg) == pgid {
return Ok(0)
}
return Err(e)
}
Ok(_) => ()
}
}
// Success.
return Ok(0)
}
// Getpgrp implements the linux syscall getpgrp(2).
pub fn SysGetpgrp(task: &mut Task, _args: &SyscallArguments) -> Result<i64> {
let pidns = task.Thread().PIDNamespace();
let tg = task.Thread().ThreadGroup();
let pg = tg.ProcessGroup().unwrap();
let pgid = pidns.IDOfProcessGroup(&pg);
return Ok(pgid as i64)
}
// Getpgid implements the linux syscall getpgid(2).
pub fn SysGetpgid(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let tid = args.arg0 as i32;
if tid == 0 {
return SysGetpgrp(task, args)
}
let pidns = task.Thread().PIDNamespace();
let target = match pidns.TaskWithID(tid) {
None => return Err(Error::SysError(SysErr::ESRCH)),
Some(t) => t,
};
let tg = target.ThreadGroup();
let pg = tg.ProcessGroup().unwrap();
let id = pidns.IDOfProcessGroup(&pg);
return Ok(id as i64)
}
// Setsid implements the linux syscall setsid(2).
pub fn SysSetsid(task: &mut Task, _args: &SyscallArguments) -> Result<i64> {
let tg = task.Thread().ThreadGroup();
tg.CreateSessoin()?;
return Ok(0)
}
// Getsid implements the linux syscall getsid(2).
pub fn SysGetsid(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let tid = args.arg0 as i32;
let pidns = task.Thread().PIDNamespace();
if tid == 0 {
let tg = task.Thread().ThreadGroup();
let session = tg.Session().unwrap();
return Ok(pidns.IDOfSession(&session) as i64);
}
let target = match pidns.TaskWithID(tid) {
None => return Err(Error::SysError(SysErr::ESRCH)),
Some(t) => t,
};
let tg = target.ThreadGroup();
let session = tg.Session().unwrap();
return Ok(pidns.IDOfSession(&session) as i64);
}
// Getpriority pretends to implement the linux syscall getpriority(2).
//
// This is a stub; real priorities require a full scheduler.
pub fn SysGetpriority(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let which = args.arg0 as i32;
let who = args.arg1 as i32;
match which as u64 {
LibcConst::PRIO_PROCESS => {
let t = if who == 0 {
task.Thread()
} else {
let pidns = task.Thread().PIDNamespace();
match pidns.TaskWithID(who) {
None => return Err(Error::SysError(SysErr::ESRCH)),
Some(t) => t,
}
};
return Ok((20 - t.Niceness()) as i64);
}
LibcConst::PRIO_USER | LibcConst::PRIO_PGRP => {
// PRIO_USER and PRIO_PGRP have no further implementation yet.
return Ok(0);
}
_ => {
return Err(Error::SysError(SysErr::EINVAL));
}
}
}
// Setpriority pretends to implement the linux syscall setpriority(2).
//
// This is a stub; real priorities require a full scheduler.
pub fn SysSetpriority(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let which = args.arg0 as i32;
let who = args.arg1 as i32;
let mut niceval = args.arg2 as i32;
// In the kernel's implementation, values outside the range
// of [-20, 19] are truncated to these minimum and maximum
// values.
if niceval < -20 /* min niceval */ {
niceval = -20
} else if niceval > 19 /* max niceval */ {
niceval = 19
}
match which as u64 {
LibcConst::PRIO_PROCESS => {
let t = if who == 0 {
task.Thread().clone()
} else {
let pidns = task.Thread().PIDNamespace();
match pidns.TaskWithID(who) {
None => return Err(Error::SysError(SysErr::ESRCH)),
Some(t) => t,
}
};
t.SetNiceness(niceval);
return Ok(0);
}
LibcConst::PRIO_USER | LibcConst::PRIO_PGRP => {
// PRIO_USER and PRIO_PGRP have no further implementation yet.
return Ok(0);
}
_ => {
return Err(Error::SysError(SysErr::EINVAL));
}
}
}
|
extern crate proc_macro;
use proc_macro::TokenStream;
#[proc_macro_derive(Command, attributes(test_attr))]
pub fn derive_command_fn(_item: TokenStream) -> TokenStream {
"fn command() { let meme = 21; println!(\"I purchased {} watermelons today\", meme); }"
.parse()
.unwrap()
}
#[proc_macro_derive(Event, attributes(test_attr))]
pub fn derive_event_fn(_item: TokenStream) -> TokenStream {
"fn event() { let meme = 9999; println!(\"event {}\", meme); }"
.parse()
.unwrap()
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.