text stringlengths 8 4.13M |
|---|
#![deny(missing_docs, warnings)]
#![no_std]
//! `panic!()` in debug builds, optimization hint in release.
extern crate unreachable;
#[doc(hidden)]
pub use unreachable::unreachable as __unreachable;
#[macro_export]
/// `panic!()` in debug builds, optimization hint in release.
macro_rules! debug_unreachable {
() => { debug_unreachable!("entered unreachable code") };
($e:expr) => {
if cfg!(debug_assertions) {
panic!($e);
} else {
$crate::__unreachable()
}
}
}
|
pub fn run() {
// Simple print
println!("Hello from the print.rs file");
// Basic formating
println!("{} if from {}", "Brad", "Mass");
// Positional arguments
println!("{0} is from {1} and {0} likes to {2}", "Brad", "Mass", "code");
// Named arguments
println!("{name} likes to play {activity}", name="John", activity="Baseball");
// Placeholder traits
println!("Binary: {:b} Hex: {:x} Octal: {:o}", 10, 10, 10);
// Placeholder for debug trait
println!("{:?}", (12, true, "hello"));
// Basic math
println!("10 + 10 = {}", 10 + 10);
//Basic Print on PR for Hacktoberfest!!!
println!("{0} like to {1} together for {2}", "friends", "pull request", "Hacktoberfest")
} |
use crate::days::day2::{Row, default_input, parse_input};
pub fn run() {
let input = default_input();
println!("{}", password_validator_str(input).unwrap());
}
pub fn password_validator_str(input : &str) -> Result<usize, ()> {
password_validator(parse_input(input))
}
pub fn password_validator(rows: Vec<Row>) -> Result<usize, ()> {
Ok(rows.iter().filter(|r| {r.is_valid2()}).count())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part2_answer() {
assert_eq!(249, password_validator_str(default_input()).unwrap())
}
} |
use crate::AddAsHeader;
use http::request::Builder;
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
pub struct SequenceNumber(u64);
impl SequenceNumber {
pub fn new(max_results: u64) -> Self {
Self(max_results)
}
}
impl From<u64> for SequenceNumber {
fn from(max_results: u64) -> Self {
Self::new(max_results)
}
}
impl AddAsHeader for SequenceNumber {
fn add_as_header(&self, builder: Builder) -> Builder {
builder.header(crate::BLOB_SEQUENCE_NUMBER, &format!("{}", self.0))
}
fn add_as_header2(
&self,
request: &mut crate::Request,
) -> Result<(), crate::errors::HTTPHeaderError> {
request.headers_mut().append(
crate::BLOB_SEQUENCE_NUMBER,
http::HeaderValue::from_str(&format!("{}", self.0))?,
);
Ok(())
}
}
|
use super::RwLock;
use failure_derive::Fail;
use rayon::ThreadPool;
use std::{collections::HashMap, hash::Hash, sync::Weak};
pub mod dispatcher;
pub mod parallel_dispatcher;
pub mod priority_dispatcher;
pub use dispatcher::Dispatcher;
pub use parallel_dispatcher::ParallelDispatcher;
pub use priority_dispatcher::PriorityDispatcher;
type EventFunction<T> = Vec<Box<dyn Fn(&T) -> Option<SyncDispatcherRequest> + Send + Sync>>;
type ListenerMap<T> = HashMap<T, FnsAndTraits<T>>;
type ParallelListenerMap<T> = HashMap<T, ParallelFnsAndTraits<T>>;
type ParallelEventFunction<T> =
Vec<Box<dyn Fn(&T) -> Option<ParallelDispatcherRequest> + Send + Sync>>;
/// An `enum` returning a request from a listener to its `sync` event-dispatcher.
/// This `enum` is not restricted to dispatcher residing in the `sync`-module.
/// A request will be processed by the event-dispatcher depending on the variant:
///
/// `StopListening` will remove your listener from the event-dispatcher.
///
/// `StopPropagation` will stop dispatching of the current `Event` instance.
/// Therefore, a listener issuing this is the last receiver.
///
/// `StopListeningAndPropagation` a combination of first `StopListening`
/// and then `StopPropagation`.
#[derive(Debug)]
pub enum SyncDispatcherRequest {
StopListening,
StopPropagation,
StopListeningAndPropagation,
}
/// When `execute_sync_dispatcher_requests` returns,
/// this `enum` informs on whether the return is early
/// and thus forcefully stopped or finished on its own.
#[derive(Debug)]
pub(crate) enum ExecuteRequestsResult {
Finished,
Stopped,
}
/// Every event-receiver needs to implement this trait
/// in order to receive dispatched events.
/// `T` being the type you use for events, e.g. an `Enum`.
pub trait Listener<T>
where
T: PartialEq + Eq + Hash + Clone + 'static,
{
/// This function will be called once a listened
/// event-type `T` has been dispatched.
fn on_event(&mut self, event: &T) -> Option<SyncDispatcherRequest>;
}
/// Iterates over the passed `vec` and applies `function` to each element.
/// `function`'s returned [`SyncDispatcherRequest`] will instruct
/// a procedure depending on its variant:
///
/// `StopListening`: Removes item from `vec`.
/// `StopPropagation`: Stops further dispatching to other elements
/// in `vec`.
/// `StopListeningAndPropagation`: Execute `StopListening`,
/// then execute `StopPropagation`.
///
/// **Note**: When `StopListening` is being executed,
/// removal of items from `vec` will result use a swap of elements,
/// resulting in an alteration of the order items were originally
/// inserted into `vec`.
///
/// **Note**: Unlike [`retain`], `execute_sync_dispatcher_requests`
/// can break the current iteration and is able to match [`SyncDispatcherRequest`]
/// and perform actions based on variants.
///
/// [`retain`]: https://doc.rust-lang.org/alloc/vec/struct.Vec.html#method.retain
/// [`SyncDispatcherRequest`]: enum.SyncDispatcherRequest.html
pub(crate) fn execute_sync_dispatcher_requests<T, F>(
vec: &mut Vec<T>,
mut function: F,
) -> ExecuteRequestsResult
where
F: FnMut(&T) -> Option<SyncDispatcherRequest>,
{
let mut index = 0;
loop {
if index < vec.len() {
match function(&vec[index]) {
None => index += 1,
Some(SyncDispatcherRequest::StopListening) => {
vec.swap_remove(index);
}
Some(SyncDispatcherRequest::StopPropagation) => {
return ExecuteRequestsResult::Stopped
}
Some(SyncDispatcherRequest::StopListeningAndPropagation) => {
vec.swap_remove(index);
return ExecuteRequestsResult::Stopped;
}
}
} else {
return ExecuteRequestsResult::Finished;
}
}
}
/// Yields closures and trait-objects.
struct FnsAndTraits<T>
where
T: PartialEq + Eq + Hash + Clone + Send + Sync + 'static,
{
traits: Vec<Weak<RwLock<dyn Listener<T> + Send + Sync + 'static>>>,
fns: EventFunction<T>,
}
impl<T> FnsAndTraits<T>
where
T: PartialEq + Eq + Hash + Clone + Send + Sync + 'static,
{
fn new_with_traits(
trait_objects: Vec<Weak<RwLock<dyn Listener<T> + Send + Sync + 'static>>>,
) -> Self {
FnsAndTraits {
traits: trait_objects,
fns: vec![],
}
}
fn new_with_fns(fns: EventFunction<T>) -> Self {
FnsAndTraits {
traits: vec![],
fns,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(test)]
mod execute_sync_dispatcher_requests {
use super::*;
fn map_usize_to_request(x: &usize) -> Option<SyncDispatcherRequest> {
match *x {
0 => Some(SyncDispatcherRequest::StopListening),
1 => Some(SyncDispatcherRequest::StopPropagation),
2 => Some(SyncDispatcherRequest::StopListeningAndPropagation),
_ => None,
}
}
#[test]
fn stop_listening() {
let mut vec = vec![0, 0, 0, 1, 1, 1, 1];
execute_sync_dispatcher_requests(&mut vec, map_usize_to_request);
assert_eq!(vec, [1, 0, 0, 1, 1, 1]);
}
#[test]
fn empty_vec() {
let mut vec = Vec::new();
execute_sync_dispatcher_requests(&mut vec, map_usize_to_request);
assert!(vec.is_empty());
}
#[test]
fn removing_all() {
let mut vec = vec![0, 0, 0, 0, 0, 0, 0];
execute_sync_dispatcher_requests(&mut vec, map_usize_to_request);
assert!(vec.is_empty());
}
#[test]
fn remove_one_element_and_stop() {
let mut vec = vec![2, 0];
execute_sync_dispatcher_requests(&mut vec, map_usize_to_request);
assert_eq!(vec, [0]);
}
}
}
/// An `enum` returning a request from a [`Listener`] to its parallel event-dispatcher.
///
/// `StopListening` will remove your [`Listener`] from the
/// event-dispatcher.
///
/// **Note**:
/// Opposed to `SyncDispatcherRequest` a [`Listener`] cannot
/// stop propagation as the propagation is happening parallel.
///
/// [`Listener`]: trait.Listener.html
#[derive(Debug)]
pub enum ParallelDispatcherRequest {
StopListening,
}
/// Yields `Send` and `Sync` closures and trait-objects.
struct ParallelFnsAndTraits<T>
where
T: PartialEq + Eq + Hash + Clone + Send + Sync + 'static,
{
traits: Vec<Weak<RwLock<dyn ParallelListener<T> + Send + Sync + 'static>>>,
fns: ParallelEventFunction<T>,
}
impl<T> ParallelFnsAndTraits<T>
where
T: PartialEq + Eq + Hash + Clone + Send + Sync + 'static,
{
fn new_with_traits(
trait_objects: Vec<Weak<RwLock<dyn ParallelListener<T> + Send + Sync + 'static>>>,
) -> Self {
ParallelFnsAndTraits {
traits: trait_objects,
fns: vec![],
}
}
fn new_with_fns(fns: ParallelEventFunction<T>) -> Self {
ParallelFnsAndTraits {
traits: vec![],
fns,
}
}
}
/// Every event-receiver needs to implement this trait
/// in order to receive dispatched events.
/// `T` being the type you use for events, e.g. an `Enum`.
pub trait ParallelListener<T>
where
T: PartialEq + Eq + Hash + Clone + Send + Sync + 'static,
{
/// This function will be called once a listened
/// event-type `T` has been dispatched.
fn on_event(&mut self, event: &T) -> Option<ParallelDispatcherRequest>;
}
/// Errors for ThreadPool-building related failures.
#[derive(Fail, Debug)]
pub enum BuildError {
#[fail(display = "Internal error on trying to build thread-pool: {:?}", _0)]
NumThreads(String),
}
|
#[doc = "Reader of register BREG[%s]"]
pub type R = crate::R<u32, super::BREG>;
#[doc = "Writer for register BREG[%s]"]
pub type W = crate::W<u32, super::BREG>;
#[doc = "Register BREG[%s] `reset()`'s with value 0"]
impl crate::ResetValue for super::BREG {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `BREG`"]
pub type BREG_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `BREG`"]
pub struct BREG_W<'a> {
w: &'a mut W,
}
impl<'a> BREG_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:31 - Backup memory that contains application-specific data. Memory is retained on vbackup supply."]
#[inline(always)]
pub fn breg(&self) -> BREG_R {
BREG_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31 - Backup memory that contains application-specific data. Memory is retained on vbackup supply."]
#[inline(always)]
pub fn breg(&mut self) -> BREG_W {
BREG_W { w: self }
}
}
|
pub mod shapes;
pub mod tools;
use crate::{
terminal::{Terminal, SIZE},
util::{Color, Point, Size},
};
pub struct Canvas {
pub cells: Vec<Cell>, //[Cell; (SIZE::MAX as usize).pow(2)],
terminal: Terminal,
}
#[derive(Clone, PartialEq, Debug)]
pub struct Cell {
pub upper_block: Option<Color>,
pub lower_block: Option<Color>,
pub upper_point: Point,
pub lower_point: Point,
}
impl Default for Cell {
fn default() -> Self {
Self {
upper_block: Default::default(),
lower_block: Default::default(),
upper_point: Default::default(),
lower_point: Default::default(),
}
}
}
impl Canvas {
pub fn new() -> Self {
// (terminal.size.width, terminal.size.height);
Self {
cells: vec![Default::default(); (SIZE::MAX as usize).pow(2)],
terminal: Terminal::new(),
}
}
pub fn resize_terminal(&mut self, size: Size) {
self.terminal.size = size;
}
fn get_position(point: Point) -> usize {
point.x as usize + SIZE::MAX as usize * (point.y as usize / 2)
}
pub fn get_cell(&self, point: Point) -> &Cell {
let position = Self::get_position(point);
self.cells
.get(position)
.unwrap_or_else(|| panic!("cell at {} is out of range", point))
}
fn get_mut_cell(&mut self, point: Point) -> &mut Cell {
let position = Self::get_position(point);
self.cells
.get_mut(position)
.unwrap_or_else(|| panic!("cell at {} is out of range", point))
}
fn get_color(&self, point: Point) -> Color {
let cell = self.get_cell(point);
if point.y % 2 == 0 {
if let Some(color) = cell.upper_block {
return color;
}
} else {
if let Some(color) = cell.lower_block {
return color;
}
}
Color::default()
}
pub fn clear(&mut self) {
self.cells.fill_with(Cell::default)
}
/// Draws a half block. This method is exposed publicly in a higher level method [`Canvas::block`].
fn half_block(&mut self, point: Point, color: Color) {
let current_cell = self.get_cell(point);
if point.y % 2 == 0 {
if let Some(lower_block_color) = current_cell.lower_block {
self.terminal.set_background_color(lower_block_color);
}
self.terminal.write("▀");
let current_cell = self.get_mut_cell(point); // TODO: can a second `get` be avoided?
*current_cell = Cell {
upper_block: Some(color),
upper_point: point,
..*current_cell
};
} else {
if let Some(upper_block_color) = current_cell.upper_block {
self.terminal.set_background_color(upper_block_color);
}
self.terminal.write("▄");
let current_cell = self.get_mut_cell(point); // TODO: can a second `get` be avoided?
*current_cell = Cell {
lower_block: Some(color),
lower_point: point,
..*current_cell
}
}
}
pub fn redraw(&mut self) {
for cell in &self.cells.clone() {
self.redraw_cell(cell);
}
}
pub fn redraw_cell(&mut self, cell: &Cell) {
if let Some(upper_block_color) = cell.upper_block {
self.block(cell.upper_point, upper_block_color);
}
if let Some(lower_block_color) = cell.lower_block {
self.block(cell.lower_point, lower_block_color);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_point() {
let mut canvas = Canvas::new();
let point = Point { x: 0, y: 0 };
let color = Color::Red;
canvas.half_block(point, color);
assert_eq!(canvas.get_color(point), color);
assert_ne!(canvas.get_color(Point { x: 1, y: 0 }), color);
assert_ne!(canvas.get_color(Point { x: 0, y: 1 }), color);
canvas.clear();
let point = Point { x: 0, y: 1 };
let color = Color::Green;
canvas.half_block(point, color);
assert_eq!(canvas.get_color(point), color);
assert_ne!(canvas.get_color(Point { x: 0, y: 0 }), color);
assert_ne!(canvas.get_color(Point { x: 0, y: 2 }), color);
canvas.clear();
let point = Point { x: 5, y: 3 };
let color = Color::Blue;
canvas.half_block(point, color);
assert_eq!(canvas.get_color(point), color);
assert_ne!(canvas.get_color(Point { x: 5, y: 2 }), color);
assert_ne!(canvas.get_color(Point { x: 5, y: 4 }), color);
}
}
|
use ws;
use json;
use gamestate::{GameState};
use network::{Connection, Connections};
use std::sync::mpsc::{channel, Sender};
use messages::Message;
use std::sync::{Arc, Mutex};
pub struct Server {
tx_to_game_state: Sender<Message>,
connections: Arc<Mutex<Connections>>,
}
impl Server {
pub fn new() -> Server {
use std::{thread, time};
let (tx_to_server, rx) = channel();
let mut game_state = GameState::new(tx_to_server);
let tx_to_game_state = game_state.get_sender();
let sixty_hertz = time::Duration::from_millis(100);
thread::Builder::new().name("update".to_string()).spawn(move || {
loop {
game_state.update().unwrap();
thread::sleep(sixty_hertz);
}
}).unwrap();
let connections = Arc::new(Mutex::new(Connections::new()));
let thread_cons = Arc::clone(&connections);
thread::Builder::new().name("connection sink".to_string()).spawn(move || {
loop {
// Does the server have anything to say?
// Should be done in _t0 really?
let msg = rx.recv().unwrap();
let mut unlocked = thread_cons.lock().unwrap();
let msg_str = json::from(&msg).to_string();
if msg.id == 0 {
// TODO handle error!
let _res = unlocked.broadcast(msg_str);
} else {
// TODO handle error!
let _res = unlocked.send(msg.id, msg_str);
}
}
}).unwrap();
Server {
tx_to_game_state,connections,
}
}
}
impl ws::Factory for Server {
type Handler = Connection;
fn connection_made(&mut self, out: ws::Sender) -> Connection {
use messages::{Payload, Message};
let id = {
let mut unlocked = self.connections.lock().unwrap();
unlocked.add(out.clone())
};
let msg = Message::new(Payload::MadeConnection, id, 0);
self.tx_to_game_state.send(msg).unwrap();
Connection::new(id, self.tx_to_game_state.clone())
}
}
pub fn listen(host : &str, port : u32 ) -> ws::Result<ws::WebSocket<Server>> {
let server = Server::new();
let con_str = format!("{}:{}", host, port);
let ws = ws::WebSocket::new(server)?.bind(con_str)?;
info!("Bound to {:?}", ws.local_addr());
Ok(ws)
}
|
pub enum TokenType {
NUMBER,
PLUS,
MINUS,
STAR,
SLASH,
LPAREN,
RPAREN
}
pub struct Token<'a> {
pub value: &'a str,
pub toktype: TokenType
}
impl<'a> ::std::fmt::Show for Token<'a> {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", self.value)
}
}
impl<'a> Token<'a> {
pub fn is_terminal(&self) -> bool {
return match self.toktype {
NUMBER => true,
LPAREN => true,
RPAREN => true,
_ => false
}
}
}
|
use super::HdrVal;
use http::header::{self, GetAll, HeaderValue};
use std::option;
/// An encoded header value.
///
/// A single header value can be represented in multiple fields. In this case,
/// the value is equivalent to a comma separated list of all the fields.
pub trait Encoded: for<'a> Iterable<'a> {
/// Returns true if the encoded header value is empty.
fn is_empty(&self) -> bool {
self.iter().next().is_none()
}
}
/// Iterate header values
pub trait Iterable<'a> {
type Iter: Iterator<Item = &'a HdrVal>;
fn iter(&'a self) -> Self::Iter;
}
pub struct ValueIter<'a> {
inner: header::ValueIter<'a, HeaderValue>,
}
// ==== impl HeaderValue =====
impl Encoded for HeaderValue {
}
impl<'a> Iterable<'a> for HeaderValue {
type Iter = option::IntoIter<&'a HdrVal>;
fn iter(&'a self) -> Self::Iter {
Some(self.as_ref()).into_iter()
}
}
// ==== impl &HeaderValue =====
impl<'a> Encoded for &'a HeaderValue {
}
impl<'a, 'b> Iterable<'a> for &'b HeaderValue {
type Iter = option::IntoIter<&'a HdrVal>;
fn iter(&'a self) -> Self::Iter {
Some(self.as_ref()).into_iter()
}
}
// ===== impl GetAll =====
impl<'a> Encoded for GetAll<'a, HeaderValue> {
}
impl<'a, 'b> Iterable<'a> for GetAll<'b, HeaderValue> {
type Iter = ValueIter<'a>;
fn iter(&'a self) -> Self::Iter {
let inner = GetAll::iter(self);
ValueIter { inner }
}
}
// ===== impl ValueIter =====
impl<'a> Iterator for ValueIter<'a> {
type Item = &'a HdrVal;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(AsRef::as_ref)
}
}
|
table! {
grades (id) {
id -> Int4,
grade -> Float4,
student_id -> Int4,
}
}
table! {
users (id) {
id -> Int4,
username -> Varchar,
password -> Varchar,
role -> Varchar,
}
}
joinable!(grades -> users (student_id));
allow_tables_to_appear_in_same_query!(
grades,
users,
);
|
use std::collections::HashMap;
use actix_http::ResponseBuilder;
use actix_web::{error, http::header, http::StatusCode, HttpResponse};
use serde::Serialize;
use common::error::{Error, ErrorKind};
#[derive(Debug, Clone, Serialize)]
pub struct PublicError {
kind: String,
path: String,
code: String,
status: Option<u32>,
message: Option<String>,
context: HashMap<String, String>,
cause: Option<Box<PublicError>>,
}
impl std::fmt::Display for PublicError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl std::error::Error for PublicError {}
impl From<Error> for PublicError {
fn from(err: Error) -> Self {
if let ErrorKind::Internal = err.kind() {
return PublicError {
kind: ErrorKind::Application.to_string(),
code: "internal_server".to_owned(),
path: "error".to_owned(),
status: Some(500),
message: None,
context: HashMap::new(),
cause: None,
};
}
let cause = match err.cause() {
Some(err) => {
if let ErrorKind::Application = err.kind() {
Some(Box::new(Self::from(err.clone())))
} else {
None
}
}
_ => None,
};
PublicError {
kind: err.kind().to_string(),
code: err.code().to_string(),
path: err.path().to_string(),
status: err.status(),
message: err.message().cloned(),
context: err.context().clone(),
cause,
}
}
}
impl error::ResponseError for PublicError {
fn error_response(&self) -> HttpResponse {
ResponseBuilder::new(self.status_code())
.set_header(header::CONTENT_TYPE, "application/json")
.body(serde_json::to_string(self).unwrap())
}
fn status_code(&self) -> StatusCode {
match self.status {
Some(status) => {
if let Ok(status) = StatusCode::from_u16(status as u16) {
status
} else {
StatusCode::BAD_REQUEST
}
}
None => StatusCode::BAD_REQUEST,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::error;
use std::fmt;
#[derive(Debug, Clone)]
struct StringError {
error: String,
}
impl fmt::Display for StringError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.error)
}
}
impl error::Error for StringError {}
fn err() -> Error {
Error::new("one", "one")
.set_message("message")
.set_status(404)
.add_context("k1", "v1")
.add_context("k2", "v2")
.add_context("k2", "v3")
.wrap(
Error::new("two", "two")
.add_context("prop1", "invalid")
.wrap(
Error::internal("three", "three")
.wrap(
Error::new("four", "prop2_invalid")
.wrap(
Error::internal("five", "five")
.wrap_raw(StringError {
error: "INSERT failed".to_owned(),
})
.build(),
)
.build(),
)
.build(),
)
.build(),
)
.build()
}
// TODO: test internal error without application
#[test]
fn without_internal_errors() {
let err = err();
let public_err = PublicError::from(err);
assert_eq!(public_err.kind, "application");
assert_eq!(public_err.path, "one");
assert_eq!(public_err.code, "one");
let two = public_err.cause.unwrap();
assert_eq!(two.kind, "application");
assert_eq!(two.path, "two");
assert_eq!(two.code, "two");
assert!(two.cause.is_none());
}
}
|
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(feature = "std")]
use std::error::Error as StdError;
#[cfg(feature = "std")]
use std::fmt;
#[derive(Debug, PartialEq, Eq, Clone)]
/// Error for trie node decoding.
pub enum Error {
/// Bad format.
BadFormat,
/// Decoding error.
Decode(codec::Error),
}
impl From<codec::Error> for Error {
fn from(x: codec::Error) -> Self {
Error::Decode(x)
}
}
#[cfg(feature = "std")]
impl StdError for Error {
fn description(&self) -> &str {
match self {
Error::BadFormat => "Bad format error",
Error::Decode(_) => "Decoding error",
}
}
}
#[cfg(feature = "std")]
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Decode(e) => write!(f, "Decode error: {}", e.what()),
Error::BadFormat => write!(f, "Bad format"),
}
}
}
|
/// A continer backed by a Vec with a cursor that always points to a valid element,
/// and therefore it is always possible to get the current element.
/// The backing container must never be empty.
pub struct CursorVec<T> {
index: usize,
vec: Vec<T>,
}
impl<T> CursorVec<T> {
/// Construct a CursorVec from a single element
pub fn new(first: T) -> CursorVec<T> {
Self {
index: 0,
vec: vec![first],
}
}
pub fn get(&self) -> &T {
unsafe { self.vec.get_unchecked(self.index) }
}
pub fn get_mut(&mut self) -> &mut T {
unsafe { self.vec.get_unchecked_mut(self.index) }
}
pub fn next(&mut self) {
self.index = self.index.wrapping_add(1);
if self.index >= self.vec.len() {
self.index = 0;
}
}
pub fn prev(&mut self) {
if self.index == 0 {
self.index = self.vec.len().saturating_sub(1);
} else {
// Doesn't matter what we use here, because it's always > 0
self.index = self.index.saturating_sub(1);
}
}
pub fn get_first_mut(&mut self) -> &mut T {
unsafe { self.vec.get_unchecked_mut(0) }
}
pub fn push(&mut self, item: T) {
self.vec.push(item)
}
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.vec.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
self.vec.iter_mut()
}
pub fn tell(&self) -> usize {
self.index
}
pub fn len(&self) -> usize {
self.vec.len()
}
pub fn sort_by_key<K, F>(&mut self, f: F)
where
F: FnMut(&T) -> K,
K: Ord,
{
self.vec.sort_by_key(f);
}
}
|
//! # URL Locator
//!
//! This library provides a streaming parser for locating URLs.
//!
//! Instead of returning the URL itself, this library will only return the length of the URL and
//! the offset from the current parsing position.
//!
//! The length and offset counts follow the example of Rust's standard library's [`char`] type and
//! are based on unicode scalar values instead of graphemes.
//!
//! # Usage
//!
//! This crate is available on [crates.io](https://crates.io/crates/urlocator) and can be used by
//! adding `urlocator` to your dependencies in your project's Cargo.toml:
//!
//! ```toml
//! [dependencies]
//! urlocator = "0.1.4"
//! ```
//!
//! # Example: URL boundaries
//!
//! By keeping track of the current parser position, it is possible to locate the boundaries of a
//! URL in a character stream:
//!
//! ```rust
//! # use urlocator::{UrlLocator, UrlLocation};
//! // Boundaries: 10-v v-28
//! let input = "[example](https://example.org)";
//!
//! let mut locator = UrlLocator::new();
//!
//! let (mut start, mut end) = (0, 0);
//!
//! for (i, c) in input.chars().enumerate() {
//! if let UrlLocation::Url(length, end_offset) = locator.advance(c) {
//! start = 1 + i - length as usize;
//! end = i - end_offset as usize;
//! }
//! }
//!
//! assert_eq!(start, 10);
//! assert_eq!(end, 28);
//! ```
//!
//! # Examlpe: Counting URLs
//!
//! By checking for the return state of the parser, it is possible to determine exactly when a URL
//! has been broken. Using this, you can count the number of URLs in a stream:
//!
//! ```rust
//! # use urlocator::{UrlLocator, UrlLocation};
//! let input = "https://example.org/1 https://rust-lang.org/二 https://example.com/Ⅲ";
//!
//! let mut locator = UrlLocator::new();
//!
//! let mut url_count = 0;
//! let mut reset = true;
//!
//! for c in input.chars() {
//! match locator.advance(c) {
//! UrlLocation::Url(..) if reset => {
//! url_count += 1;
//! reset = false;
//! },
//! UrlLocation::Reset => reset = true,
//! _ => (),
//! }
//! }
//!
//! assert_eq!(url_count, 3);
//! ```
#![cfg_attr(all(test, feature = "nightly"), feature(test))]
#![cfg_attr(not(test), no_std)]
mod scheme;
#[cfg(test)]
mod tests;
use scheme::SchemeState;
/// Position of the URL parser.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum UrlLocation {
/// Current location is the end of a valid URL.
Url(u16, u16),
/// Current location is possibly a URL scheme.
Scheme,
/// Last advancement has reset the URL parser.
Reset,
}
/// URL parser positional state.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum State {
/// Parsing the URL scheme.
Scheme(SchemeState),
/// Parsing a valid URL.
Url,
}
impl Default for State {
#[inline]
fn default() -> Self {
State::Scheme(SchemeState::default())
}
}
/// URL parser.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct UrlLocator {
state: State,
illegal_end_chars: u16,
len: u16,
open_parentheses: u8,
open_brackets: u8,
}
impl UrlLocator {
/// Create a new parser.
#[inline]
pub fn new() -> Self {
Self::default()
}
/// Advance the parser by one char.
///
/// # Example
///
/// ```rust
/// # use urlocator::{UrlLocator, UrlLocation};
/// let mut locator = UrlLocator::new();
///
/// let location = locator.advance('h');
///
/// assert_eq!(location, UrlLocation::Scheme);
/// ```
#[inline]
pub fn advance(&mut self, c: char) -> UrlLocation {
self.len += 1;
match self.state {
State::Scheme(state) => self.advance_scheme(state, c),
State::Url => self.advance_url(c),
}
}
#[inline]
fn advance_scheme(&mut self, state: SchemeState, c: char) -> UrlLocation {
self.state = match state.advance(c) {
SchemeState::RESET => return self.reset(),
SchemeState::COMPLETE => State::Url,
state => State::Scheme(state),
};
UrlLocation::Scheme
}
#[inline]
fn advance_url(&mut self, c: char) -> UrlLocation {
if Self::is_illegal_at_end(c) {
self.illegal_end_chars += 1;
} else {
self.illegal_end_chars = 0;
}
self.url(c)
}
#[inline]
fn url(&mut self, c: char) -> UrlLocation {
match c {
'(' => self.open_parentheses += 1,
'[' => self.open_brackets += 1,
')' => {
if self.open_parentheses == 0 {
return self.reset();
} else {
self.open_parentheses -= 1;
}
},
']' => {
if self.open_brackets == 0 {
return self.reset();
} else {
self.open_brackets -= 1;
}
},
// Illegal URL characters
'\u{00}'..='\u{1F}'
| '\u{7F}'..='\u{9F}'
| '<'
| '>'
| '"'
| ' '
| '{'..='}'
| '\\'
| '^'
| '⟨'
| '⟩'
| '`' => return self.reset(),
_ => (),
}
self.state = State::Url;
UrlLocation::Url(self.len - self.illegal_end_chars, self.illegal_end_chars)
}
#[inline]
fn is_illegal_at_end(c: char) -> bool {
match c {
'.' | ',' | ':' | ';' | '?' | '!' | '(' | '[' | '\'' => true,
_ => false,
}
}
#[inline]
fn reset(&mut self) -> UrlLocation {
*self = Self::default();
UrlLocation::Reset
}
}
|
use radius_parser::*;
static RADIUS_ACCESS_REQ: &'static [u8] = include_bytes!("../assets/radius_access-request.bin");
#[test]
fn test_access_request() {
let (rem, acces_req) = parse_radius_data(RADIUS_ACCESS_REQ).expect("could not parse data");
assert!(rem.is_empty());
println!("{:?}", acces_req);
assert_eq!(acces_req.code, RadiusCode(1));
}
|
// This file is part of Substrate.
// Copyright (C) 2019-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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(test)]
// Do not complain about unused `dispatch` and `dispatch_aux`.
#[allow(dead_code)]
mod tests {
use codec::{Decode, Encode, EncodeLike};
use frame_support::metadata::*;
use sp_io::TestExternalities;
use std::marker::PhantomData;
frame_support::decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin, system=self {}
}
pub trait Trait {
type Origin: Encode + Decode + EncodeLike + std::default::Default;
type BlockNumber;
}
frame_support::decl_storage! {
trait Store for Module<T: Trait> as TestStorage {
// non-getters: pub / $default
/// Hello, this is doc!
U32: Option<u32>;
pub PUBU32: Option<u32>;
U32MYDEF: Option<u32>;
pub PUBU32MYDEF: Option<u32>;
// getters: pub / $default
// we need at least one type which uses T, otherwise GenesisConfig will complain.
GETU32 get(fn u32_getter): T::Origin;
pub PUBGETU32 get(fn pub_u32_getter): u32;
GETU32WITHCONFIG get(fn u32_getter_with_config) config(): u32;
pub PUBGETU32WITHCONFIG get(fn pub_u32_getter_with_config) config(): u32;
GETU32MYDEF get(fn u32_getter_mydef): Option<u32>;
pub PUBGETU32MYDEF get(fn pub_u32_getter_mydef) config(): u32 = 3;
GETU32WITHCONFIGMYDEF get(fn u32_getter_with_config_mydef) config(): u32 = 2;
pub PUBGETU32WITHCONFIGMYDEF get(fn pub_u32_getter_with_config_mydef) config(): u32 = 1;
PUBGETU32WITHCONFIGMYDEFOPT get(fn pub_u32_getter_with_config_mydef_opt) config(): Option<u32>;
GetU32WithBuilder get(fn u32_with_builder) build(|_| 1): u32;
GetOptU32WithBuilderSome get(fn opt_u32_with_builder_some) build(|_| Some(1)): Option<u32>;
GetOptU32WithBuilderNone get(fn opt_u32_with_builder_none) build(|_| None): Option<u32>;
// map non-getters: pub / $default
MAPU32: map hasher(blake2_128_concat) u32 => Option<String>;
pub PUBMAPU32: map hasher(blake2_128_concat) u32 => Option<String>;
MAPU32MYDEF: map hasher(blake2_128_concat) u32 => Option<String>;
pub PUBMAPU32MYDEF: map hasher(blake2_128_concat) u32 => Option<String>;
// map getters: pub / $default
GETMAPU32 get(fn map_u32_getter): map hasher(blake2_128_concat) u32 => String;
pub PUBGETMAPU32 get(fn pub_map_u32_getter): map hasher(blake2_128_concat) u32 => String;
GETMAPU32MYDEF get(fn map_u32_getter_mydef):
map hasher(blake2_128_concat) u32 => String = "map".into();
pub PUBGETMAPU32MYDEF get(fn pub_map_u32_getter_mydef):
map hasher(blake2_128_concat) u32 => String = "pubmap".into();
COMPLEXTYPE1: ::std::vec::Vec<<T as Trait>::Origin>;
COMPLEXTYPE2: (Vec<Vec<(u16, Box<()>)>>, u32);
COMPLEXTYPE3: [u32; 25];
}
add_extra_genesis {
build(|_| {});
}
}
struct TraitImpl {}
impl Trait for TraitImpl {
type Origin = u32;
type BlockNumber = u32;
}
const EXPECTED_METADATA: StorageMetadata = StorageMetadata {
prefix: DecodeDifferent::Encode("TestStorage"),
entries: DecodeDifferent::Encode(&[
StorageEntryMetadata {
name: DecodeDifferent::Encode("U32"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructU32(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[" Hello, this is doc!"]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("PUBU32"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructPUBU32(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("U32MYDEF"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructU32MYDEF(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("PUBU32MYDEF"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructPUBU32MYDEF(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GETU32"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("T::Origin")),
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructGETU32(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("PUBGETU32"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructPUBGETU32(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GETU32WITHCONFIG"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructGETU32WITHCONFIG(PhantomData::<TraitImpl>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("PUBGETU32WITHCONFIG"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructPUBGETU32WITHCONFIG(PhantomData::<TraitImpl>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GETU32MYDEF"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructGETU32MYDEF(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("PUBGETU32MYDEF"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructPUBGETU32MYDEF(PhantomData::<TraitImpl>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GETU32WITHCONFIGMYDEF"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructGETU32WITHCONFIGMYDEF(PhantomData::<TraitImpl>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("PUBGETU32WITHCONFIGMYDEF"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructPUBGETU32WITHCONFIGMYDEF(PhantomData::<TraitImpl>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("PUBGETU32WITHCONFIGMYDEFOPT"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructPUBGETU32WITHCONFIGMYDEFOPT(PhantomData::<TraitImpl>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GetU32WithBuilder"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructGetU32WithBuilder(PhantomData::<TraitImpl>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GetOptU32WithBuilderSome"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructGetOptU32WithBuilderSome(PhantomData::<TraitImpl>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GetOptU32WithBuilderNone"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("u32")),
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructGetOptU32WithBuilderNone(PhantomData::<TraitImpl>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("MAPU32"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Map {
hasher: StorageHasher::Blake2_128Concat,
key: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("String"),
unused: false,
},
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructMAPU32(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("PUBMAPU32"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Map {
hasher: StorageHasher::Blake2_128Concat,
key: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("String"),
unused: false,
},
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructPUBMAPU32(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("MAPU32MYDEF"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Map {
hasher: StorageHasher::Blake2_128Concat,
key: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("String"),
unused: false,
},
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructMAPU32MYDEF(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("PUBMAPU32MYDEF"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Map {
hasher: StorageHasher::Blake2_128Concat,
key: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("String"),
unused: false,
},
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructPUBMAPU32MYDEF(PhantomData::<TraitImpl>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GETMAPU32"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map {
hasher: StorageHasher::Blake2_128Concat,
key: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("String"),
unused: false,
},
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructGETMAPU32(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("PUBGETMAPU32"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map {
hasher: StorageHasher::Blake2_128Concat,
key: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("String"),
unused: false,
},
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructPUBGETMAPU32(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GETMAPU32MYDEF"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map {
hasher: StorageHasher::Blake2_128Concat,
key: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("String"),
unused: false,
},
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructGETMAPU32MYDEF(PhantomData::<TraitImpl>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("PUBGETMAPU32MYDEF"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map {
hasher: StorageHasher::Blake2_128Concat,
key: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("String"),
unused: false,
},
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructPUBGETMAPU32MYDEF(PhantomData::<TraitImpl>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("COMPLEXTYPE1"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Plain(DecodeDifferent::Encode(
"::std::vec::Vec<<T as Trait>::Origin>",
)),
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructCOMPLEXTYPE1(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("COMPLEXTYPE2"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Plain(DecodeDifferent::Encode(
"(Vec<Vec<(u16, Box<()>)>>, u32)",
)),
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructCOMPLEXTYPE2(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("COMPLEXTYPE3"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Plain(DecodeDifferent::Encode("[u32; 25]")),
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructCOMPLEXTYPE3(
PhantomData::<TraitImpl>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
]),
};
#[test]
fn store_metadata() {
let metadata = Module::<TraitImpl>::storage_metadata();
pretty_assertions::assert_eq!(EXPECTED_METADATA, metadata);
}
#[test]
fn check_genesis_config() {
let config = GenesisConfig::default();
assert_eq!(config.u32_getter_with_config, 0u32);
assert_eq!(config.pub_u32_getter_with_config, 0u32);
assert_eq!(config.pub_u32_getter_mydef, 3u32);
assert_eq!(config.u32_getter_with_config_mydef, 2u32);
assert_eq!(config.pub_u32_getter_with_config_mydef, 1u32);
assert_eq!(config.pub_u32_getter_with_config_mydef_opt, 0u32);
}
#[test]
fn check_builder_config() {
let config = GenesisConfig::default();
let storage = config.build_storage().unwrap();
TestExternalities::from(storage).execute_with(|| {
assert_eq!(Module::<TraitImpl>::u32_with_builder(), 1);
assert_eq!(Module::<TraitImpl>::opt_u32_with_builder_some(), Some(1));
assert_eq!(Module::<TraitImpl>::opt_u32_with_builder_none(), None);
})
}
}
#[cfg(test)]
#[allow(dead_code)]
mod test2 {
pub trait Trait {
type Origin;
type BlockNumber;
}
frame_support::decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin, system=self {}
}
type PairOf<T> = (T, T);
frame_support::decl_storage! {
trait Store for Module<T: Trait> as TestStorage {
SingleDef : u32;
PairDef : PairOf<u32>;
Single : Option<u32>;
Pair : (u32, u32);
}
add_extra_genesis {
config(_marker) : ::std::marker::PhantomData<T>;
config(extra_field) : u32 = 32;
build(|_| {});
}
}
struct TraitImpl {}
impl Trait for TraitImpl {
type Origin = u32;
type BlockNumber = u32;
}
}
#[cfg(test)]
#[allow(dead_code)]
mod test3 {
pub trait Trait {
type Origin;
type BlockNumber;
}
frame_support::decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin, system=self {}
}
frame_support::decl_storage! {
trait Store for Module<T: Trait> as Test {
Foo get(fn foo) config(initial_foo): u32;
}
}
type PairOf<T> = (T, T);
struct TraitImpl {}
impl Trait for TraitImpl {
type Origin = u32;
type BlockNumber = u32;
}
}
#[cfg(test)]
#[allow(dead_code)]
mod test_append_and_len {
use codec::{Decode, Encode};
use sp_io::TestExternalities;
pub trait Trait {
type Origin;
type BlockNumber;
}
frame_support::decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin, system=self {}
}
#[derive(PartialEq, Eq, Clone, Encode, Decode)]
struct NoDef(u32);
frame_support::decl_storage! {
trait Store for Module<T: Trait> as Test {
NoDefault: Option<NoDef>;
JustVec: Vec<u32>;
JustVecWithDefault: Vec<u32> = vec![6, 9];
OptionVec: Option<Vec<u32>>;
MapVec: map hasher(blake2_128_concat) u32 => Vec<u32>;
MapVecWithDefault: map hasher(blake2_128_concat) u32 => Vec<u32> = vec![6, 9];
OptionMapVec: map hasher(blake2_128_concat) u32 => Option<Vec<u32>>;
DoubleMapVec: double_map hasher(blake2_128_concat) u32, hasher(blake2_128_concat) u32 => Vec<u32>;
DoubleMapVecWithDefault: double_map hasher(blake2_128_concat) u32, hasher(blake2_128_concat) u32 => Vec<u32> = vec![6, 9];
OptionDoubleMapVec: double_map hasher(blake2_128_concat) u32, hasher(blake2_128_concat) u32 => Option<Vec<u32>>;
}
}
struct Test {}
impl Trait for Test {
type Origin = u32;
type BlockNumber = u32;
}
#[test]
fn default_for_option() {
TestExternalities::default().execute_with(|| {
assert_eq!(OptionVec::get(), None);
assert!(JustVec::get().is_empty());
});
}
#[test]
fn append_works() {
TestExternalities::default().execute_with(|| {
for val in &[1, 2, 3, 4, 5] {
MapVec::append(1, val);
}
assert_eq!(MapVec::get(1), vec![1, 2, 3, 4, 5]);
MapVec::remove(1);
MapVec::append(1, 1);
assert_eq!(MapVec::get(1), vec![1]);
for val in &[1, 2, 3, 4, 5] {
JustVec::append(val);
}
assert_eq!(JustVec::get(), vec![1, 2, 3, 4, 5]);
JustVec::kill();
JustVec::append(1);
assert_eq!(JustVec::get(), vec![1]);
});
}
#[test]
fn append_overwrites_invalid_data() {
TestExternalities::default().execute_with(|| {
let key = JustVec::hashed_key();
// Set it to some invalid value.
frame_support::storage::unhashed::put_raw(&key, &*b"1");
assert!(JustVec::get().is_empty());
assert_eq!(frame_support::storage::unhashed::get_raw(&key), Some(b"1".to_vec()));
JustVec::append(1);
JustVec::append(2);
assert_eq!(JustVec::get(), vec![1, 2]);
});
}
#[test]
fn append_overwrites_default() {
TestExternalities::default().execute_with(|| {
assert_eq!(JustVecWithDefault::get(), vec![6, 9]);
JustVecWithDefault::append(1);
assert_eq!(JustVecWithDefault::get(), vec![1]);
assert_eq!(MapVecWithDefault::get(0), vec![6, 9]);
MapVecWithDefault::append(0, 1);
assert_eq!(MapVecWithDefault::get(0), vec![1]);
assert_eq!(OptionVec::get(), None);
OptionVec::append(1);
assert_eq!(OptionVec::get(), Some(vec![1]));
});
}
#[test]
fn len_works() {
TestExternalities::default().execute_with(|| {
JustVec::put(&vec![1, 2, 3, 4]);
OptionVec::put(&vec![1, 2, 3, 4, 5]);
MapVec::insert(1, &vec![1, 2, 3, 4, 5, 6]);
DoubleMapVec::insert(0, 1, &vec![1, 2]);
assert_eq!(JustVec::decode_len().unwrap(), 4);
assert_eq!(OptionVec::decode_len().unwrap(), 5);
assert_eq!(MapVec::decode_len(1).unwrap(), 6);
assert_eq!(DoubleMapVec::decode_len(0, 1).unwrap(), 2);
});
}
// `decode_len` should always return `None` for default assigments
// in `decl_storage!`.
#[test]
fn len_works_ignores_default_assignment() {
TestExternalities::default().execute_with(|| {
// vec
assert!(JustVec::get().is_empty());
assert_eq!(JustVec::decode_len(), None);
assert_eq!(JustVecWithDefault::get(), vec![6, 9]);
assert_eq!(JustVecWithDefault::decode_len(), None);
assert_eq!(OptionVec::get(), None);
assert_eq!(OptionVec::decode_len(), None);
// map
assert!(MapVec::get(0).is_empty());
assert_eq!(MapVec::decode_len(0), None);
assert_eq!(MapVecWithDefault::get(0), vec![6, 9]);
assert_eq!(MapVecWithDefault::decode_len(0), None);
assert_eq!(OptionMapVec::get(0), None);
assert_eq!(OptionMapVec::decode_len(0), None);
// Double map
assert!(DoubleMapVec::get(0, 0).is_empty());
assert_eq!(DoubleMapVec::decode_len(0, 1), None);
assert_eq!(DoubleMapVecWithDefault::get(0, 0), vec![6, 9]);
assert_eq!(DoubleMapVecWithDefault::decode_len(0, 1), None);
assert_eq!(OptionDoubleMapVec::get(0, 0), None);
assert_eq!(OptionDoubleMapVec::decode_len(0, 1), None);
});
}
}
|
use super::razer_report::{Color, RazerMatrixEffectId, RazerReport, RazerVarstore};
use super::{Device, DeviceFactory};
use errors::Result;
use hidapi::HidDevice;
#[derive(Clone, Debug)]
pub struct MatrixKeyboardFactory {
name: &'static str,
led_ids: &'static [u8],
}
impl MatrixKeyboardFactory {
pub fn new(name: &'static str, led_ids: &'static [u8]) -> Box<MatrixKeyboardFactory> {
Box::new(MatrixKeyboardFactory { name, led_ids })
}
}
impl DeviceFactory for MatrixKeyboardFactory {
fn name(&self) -> &'static str {
self.name
}
fn open(&self, hid_device: HidDevice) -> Box<Device> {
Box::new(MatrixKeyboard {
name: self.name,
led_ids: self.led_ids,
hid_device,
})
}
}
pub struct MatrixKeyboard {
name: &'static str,
led_ids: &'static [u8],
hid_device: HidDevice,
}
impl Device for MatrixKeyboard {
fn name(&self) -> &'static str {
self.name
}
fn hid_device<'a>(&'a self) -> &'a HidDevice {
&self.hid_device
}
fn get_brightness(&self) -> Result<u8> {
self.send_report(RazerReport::standard_get_led_brightness(
RazerVarstore::Store,
self.led_ids[0],
))?;
Ok(0)
}
fn set_brightness(&self, brightness: u8) -> Result<()> {
for led_id in self.led_ids {
self.send_report(RazerReport::standard_set_led_brightness(
RazerVarstore::Store,
*led_id,
brightness,
))?;
}
Ok(())
}
fn set_color(&self, color: Color) -> Result<()> {
let mut report = RazerReport::standard_matrix_effect(RazerMatrixEffectId::Static);
report.arguments[1] = color.red;
report.arguments[2] = color.green;
report.arguments[3] = color.blue;
self.send_report(report)?;
Ok(())
}
}
|
use std::fs::File;
use std::io::{BufReader, BufRead};
use std::collections::{HashSet, HashMap};
fn create_path(line: &Vec<String>) -> Vec<[i32; 3]> {
let mut x = 0;
let mut y = 0;
let mut d = 0;
let mut path: Vec<[i32; 3]> = Vec::new();
for mvt in line {
let dir = mvt.chars().next().unwrap();
let value: u32 = mvt[1..].parse().unwrap();
match dir {
'L' | 'R' | 'U' | 'D' => {
for _ in 0..value {
d += 1;
if dir == 'L' { x -= 1 }
else if dir == 'R' { x += 1 }
else if dir == 'U' { y += 1 }
else { y -= 1 };
path.push([x, y, d]);
}
},
_ => panic!("Got unexpected character!")
}
}
path
}
fn find_cross(path1: Vec<[i32; 3]>, path2: Vec<[i32; 3]>) -> Vec<[i32; 3]> {
let mut set1: HashSet<[i32; 2]> = HashSet::new();
let mut set2: HashSet<[i32; 2]> = HashSet::new();
let mut map1 = HashMap::new();
let mut map2 = HashMap::new();
for x in &path1 {
set1.insert([x[0], x[1]]);
map1.insert([x[0], x[1]], x.clone());
}
for x in &path2 {
set2.insert([x[0], x[1]]);
map2.insert([x[0], x[1]], x.clone());
}
set1.intersection(&set2)
.map(|x| {
let x1 = map1.get(x).unwrap();
let x2 = map2.get(x).unwrap();
[x1[0], x1[1], x1[2] + x2[2]]
})
.collect()
}
fn nearest_cross(points: Vec<[i32; 3]>) -> u32 {
let mut distances: Vec<i32> = points.iter().map(|x| x[0].abs() + x[1].abs()).collect();
distances.sort_by(|a, b| a.partial_cmp(b).unwrap());
distances[0] as u32
}
fn best_cross(points: Vec<[i32; 3]>) -> u32 {
let mut distances: Vec<i32> = points.iter().map(|x| x[2]).collect();
distances.sort_by(|a, b| a.partial_cmp(b).unwrap());
distances[0] as u32
}
fn main() {
let file = File::open("inputs.txt").expect("got an error opening the file");
let buffer = BufReader::new(file);
let lines: Vec<Vec<String>> = buffer
.lines()
.map(|x| x.unwrap().parse().unwrap())
.map(|x: String| x.trim().to_string())
.map(|x| x.split(",").map(|s| s.to_string()).collect())
.collect();
let mut maps: Vec<Vec<[i32; 3]>> = Vec::new();
for line in lines {
maps.push(create_path(&line));
}
let points = find_cross(maps[0].clone(), maps[1].clone());
let nearest = nearest_cross(points.clone());
println!("{}", nearest);
// part 2
let best = best_cross(points);
println!("{}", best);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_map() {
let line = vec!["R8", "U5", "L5", "D3"];
let line: Vec<String> = line.into_iter().map(|x| x.to_string()).collect();
let map = create_path(&line);
assert_eq!(map[map.len() - 1], [3, 2, 21]);
let line = vec!["U7", "R6", "D4", "L4"];
let line: Vec<String> = line.into_iter().map(|x| x.to_string()).collect();
let map = create_path(&line);
assert_eq!(map[map.len() - 1], [2, 3, 21]);
}
#[test]
fn test_find_nearest_cross() {
let map1 = vec!(
[1, 0, 1], [2, 0, 2], [3, 0, 3], [4, 0, 4], [5, 0, 5], [6, 0, 6], [7, 0, 7], [8, 0, 8], [8, 1, 9], [8, 2, 10],
[8, 3, 11], [8, 4, 12], [8, 5, 13], [7, 5, 14], [6, 5, 15], [5, 5, 16], [4, 5, 17], [3, 5, 18], [3, 4, 19], [3, 3, 20], [3, 2, 21]
);
let map2 = vec!(
[0, 1, 1], [0, 2, 2], [0, 3, 3], [0, 4, 4], [0, 5, 5], [0, 6, 6], [0, 7, 7], [1, 7, 8], [2, 7, 9], [3, 7, 10],
[4, 7, 11], [5, 7, 12], [6, 7, 13], [6, 6, 14], [6, 5, 15], [6, 4, 16], [6, 3, 17], [5, 3, 18], [4, 3, 19], [3, 3, 20], [2, 3, 21]
);
let points = find_cross(map1, map2);
let nearest = nearest_cross(points);
assert_eq!(nearest, 6);
}
#[test]
fn test_find_best_cross() {
let line1 = vec!["R75", "D30", "R83", "U83", "L12", "D49", "R71", "U7", "L72"];
let line1: Vec<String> = line1.into_iter().map(|x| x.to_string()).collect();
let line2 = vec!["U62", "R66", "U55", "R34", "D71", "R55", "D58", "R83"];
let line2: Vec<String> = line2.into_iter().map(|x| x.to_string()).collect();
let map1 = create_path(&line1);
let map2 = create_path(&line2);
let points = find_cross(map1, map2);
let best = best_cross(points);
assert_eq!(best, 610);
}
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::DMACFG {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct DMAPWROFFR {
bits: bool,
}
impl DMAPWROFFR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Possible values of the field `DMAPRI`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DMAPRIR {
#[doc = "Low Priority (service as best effort) value."]
LOW,
#[doc = "High Priority (service immediately) value."]
HIGH,
#[doc = "Auto Priority (priority raised once TX FIFO empties or RX FIFO fills) value."]
AUTO,
#[doc = r" Reserved"]
_Reserved(u8),
}
impl DMAPRIR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
DMAPRIR::LOW => 0,
DMAPRIR::HIGH => 1,
DMAPRIR::AUTO => 2,
DMAPRIR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> DMAPRIR {
match value {
0 => DMAPRIR::LOW,
1 => DMAPRIR::HIGH,
2 => DMAPRIR::AUTO,
i => DMAPRIR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `LOW`"]
#[inline]
pub fn is_low(&self) -> bool {
*self == DMAPRIR::LOW
}
#[doc = "Checks if the value of the field is `HIGH`"]
#[inline]
pub fn is_high(&self) -> bool {
*self == DMAPRIR::HIGH
}
#[doc = "Checks if the value of the field is `AUTO`"]
#[inline]
pub fn is_auto(&self) -> bool {
*self == DMAPRIR::AUTO
}
}
#[doc = "Possible values of the field `DMADIR`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DMADIRR {
#[doc = "Peripheral to Memory (SRAM) transaction value."]
P2M,
#[doc = "Memory to Peripheral transaction value."]
M2P,
}
impl DMADIRR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
DMADIRR::P2M => false,
DMADIRR::M2P => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> DMADIRR {
match value {
false => DMADIRR::P2M,
true => DMADIRR::M2P,
}
}
#[doc = "Checks if the value of the field is `P2M`"]
#[inline]
pub fn is_p2m(&self) -> bool {
*self == DMADIRR::P2M
}
#[doc = "Checks if the value of the field is `M2P`"]
#[inline]
pub fn is_m2p(&self) -> bool {
*self == DMADIRR::M2P
}
}
#[doc = "Possible values of the field `DMAEN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DMAENR {
#[doc = "Disable DMA Function value."]
DIS,
#[doc = "Enable HW controlled DMA Function to manage DMA to flash devices. HW will automatically handle issuance of instruction/address bytes based on settings in the FLASH register. value."]
EN,
#[doc = r" Reserved"]
_Reserved(u8),
}
impl DMAENR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
DMAENR::DIS => 0,
DMAENR::EN => 3,
DMAENR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> DMAENR {
match value {
0 => DMAENR::DIS,
3 => DMAENR::EN,
i => DMAENR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == DMAENR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == DMAENR::EN
}
}
#[doc = r" Proxy"]
pub struct _DMAPWROFFW<'a> {
w: &'a mut W,
}
impl<'a> _DMAPWROFFW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 18;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `DMAPRI`"]
pub enum DMAPRIW {
#[doc = "Low Priority (service as best effort) value."]
LOW,
#[doc = "High Priority (service immediately) value."]
HIGH,
#[doc = "Auto Priority (priority raised once TX FIFO empties or RX FIFO fills) value."]
AUTO,
}
impl DMAPRIW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
DMAPRIW::LOW => 0,
DMAPRIW::HIGH => 1,
DMAPRIW::AUTO => 2,
}
}
}
#[doc = r" Proxy"]
pub struct _DMAPRIW<'a> {
w: &'a mut W,
}
impl<'a> _DMAPRIW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: DMAPRIW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Low Priority (service as best effort) value."]
#[inline]
pub fn low(self) -> &'a mut W {
self.variant(DMAPRIW::LOW)
}
#[doc = "High Priority (service immediately) value."]
#[inline]
pub fn high(self) -> &'a mut W {
self.variant(DMAPRIW::HIGH)
}
#[doc = "Auto Priority (priority raised once TX FIFO empties or RX FIFO fills) value."]
#[inline]
pub fn auto(self) -> &'a mut W {
self.variant(DMAPRIW::AUTO)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `DMADIR`"]
pub enum DMADIRW {
#[doc = "Peripheral to Memory (SRAM) transaction value."]
P2M,
#[doc = "Memory to Peripheral transaction value."]
M2P,
}
impl DMADIRW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
DMADIRW::P2M => false,
DMADIRW::M2P => true,
}
}
}
#[doc = r" Proxy"]
pub struct _DMADIRW<'a> {
w: &'a mut W,
}
impl<'a> _DMADIRW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: DMADIRW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Peripheral to Memory (SRAM) transaction value."]
#[inline]
pub fn p2m(self) -> &'a mut W {
self.variant(DMADIRW::P2M)
}
#[doc = "Memory to Peripheral transaction value."]
#[inline]
pub fn m2p(self) -> &'a mut W {
self.variant(DMADIRW::M2P)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `DMAEN`"]
pub enum DMAENW {
#[doc = "Disable DMA Function value."]
DIS,
#[doc = "Enable HW controlled DMA Function to manage DMA to flash devices. HW will automatically handle issuance of instruction/address bytes based on settings in the FLASH register. value."]
EN,
}
impl DMAENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
DMAENW::DIS => 0,
DMAENW::EN => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _DMAENW<'a> {
w: &'a mut W,
}
impl<'a> _DMAENW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: DMAENW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Disable DMA Function value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(DMAENW::DIS)
}
#[doc = "Enable HW controlled DMA Function to manage DMA to flash devices. HW will automatically handle issuance of instruction/address bytes based on settings in the FLASH register. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(DMAENW::EN)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 18 - Power off MSPI domain upon completion of DMA operation."]
#[inline]
pub fn dmapwroff(&self) -> DMAPWROFFR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 18;
((self.bits >> OFFSET) & MASK as u32) != 0
};
DMAPWROFFR { bits }
}
#[doc = "Bits 3:4 - Sets the Priority of the DMA request"]
#[inline]
pub fn dmapri(&self) -> DMAPRIR {
DMAPRIR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 2 - Direction"]
#[inline]
pub fn dmadir(&self) -> DMADIRR {
DMADIRR::_from({
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 0:1 - DMA Enable. Setting this bit to EN will start the DMA operation"]
#[inline]
pub fn dmaen(&self) -> DMAENR {
DMAENR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 18 - Power off MSPI domain upon completion of DMA operation."]
#[inline]
pub fn dmapwroff(&mut self) -> _DMAPWROFFW {
_DMAPWROFFW { w: self }
}
#[doc = "Bits 3:4 - Sets the Priority of the DMA request"]
#[inline]
pub fn dmapri(&mut self) -> _DMAPRIW {
_DMAPRIW { w: self }
}
#[doc = "Bit 2 - Direction"]
#[inline]
pub fn dmadir(&mut self) -> _DMADIRW {
_DMADIRW { w: self }
}
#[doc = "Bits 0:1 - DMA Enable. Setting this bit to EN will start the DMA operation"]
#[inline]
pub fn dmaen(&mut self) -> _DMAENW {
_DMAENW { w: self }
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - control register 1"]
pub cr1: CR1,
#[doc = "0x04 - control register 2"]
pub cr2: CR2,
_reserved2: [u8; 0x04],
#[doc = "0x0c - TAMP filter control register"]
pub fltcr: FLTCR,
_reserved3: [u8; 0x1c],
#[doc = "0x2c - TAMP interrupt enable register"]
pub ier: IER,
#[doc = "0x30 - TAMP status register"]
pub sr: SR,
#[doc = "0x34 - TAMP masked interrupt status register"]
pub misr: MISR,
_reserved6: [u8; 0x04],
#[doc = "0x3c - TAMP status clear register"]
pub scr: SCR,
_reserved7: [u8; 0xc0],
#[doc = "0x100..0x114 - TAMP backup register"]
pub bkpr: [BKPR; 5],
_reserved8: [u8; 0x02d8],
#[doc = "0x3ec - TAMP hardware configuration register 2"]
pub hwcfgr2: HWCFGR2,
#[doc = "0x3f0 - TAMP hardware configuration register 1"]
pub hwcfgr1: HWCFGR1,
#[doc = "0x3f4 - EXTI IP Version register"]
pub verr: VERR,
#[doc = "0x3f8 - EXTI Identification register"]
pub ipidr: IPIDR,
#[doc = "0x3fc - EXTI Size ID register"]
pub sidr: SIDR,
}
#[doc = "CR1 (rw) register accessor: control register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr1`]
module"]
pub type CR1 = crate::Reg<cr1::CR1_SPEC>;
#[doc = "control register 1"]
pub mod cr1;
#[doc = "CR2 (rw) register accessor: control register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr2`]
module"]
pub type CR2 = crate::Reg<cr2::CR2_SPEC>;
#[doc = "control register 2"]
pub mod cr2;
#[doc = "FLTCR (rw) register accessor: TAMP filter control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fltcr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`fltcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`fltcr`]
module"]
pub type FLTCR = crate::Reg<fltcr::FLTCR_SPEC>;
#[doc = "TAMP filter control register"]
pub mod fltcr;
#[doc = "IER (rw) register accessor: TAMP interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ier::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ier`]
module"]
pub type IER = crate::Reg<ier::IER_SPEC>;
#[doc = "TAMP interrupt enable register"]
pub mod ier;
#[doc = "SR (r) register accessor: TAMP status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sr`]
module"]
pub type SR = crate::Reg<sr::SR_SPEC>;
#[doc = "TAMP status register"]
pub mod sr;
#[doc = "MISR (r) register accessor: TAMP masked interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`misr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`misr`]
module"]
pub type MISR = crate::Reg<misr::MISR_SPEC>;
#[doc = "TAMP masked interrupt status register"]
pub mod misr;
#[doc = "SCR (w) register accessor: TAMP status clear register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`scr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`scr`]
module"]
pub type SCR = crate::Reg<scr::SCR_SPEC>;
#[doc = "TAMP status clear register"]
pub mod scr;
#[doc = "BKPR (rw) register accessor: TAMP backup register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bkpr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`bkpr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`bkpr`]
module"]
pub type BKPR = crate::Reg<bkpr::BKPR_SPEC>;
#[doc = "TAMP backup register"]
pub mod bkpr;
#[doc = "HWCFGR2 (r) register accessor: TAMP hardware configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hwcfgr2::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hwcfgr2`]
module"]
pub type HWCFGR2 = crate::Reg<hwcfgr2::HWCFGR2_SPEC>;
#[doc = "TAMP hardware configuration register 2"]
pub mod hwcfgr2;
#[doc = "HWCFGR1 (r) register accessor: TAMP hardware configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hwcfgr1::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hwcfgr1`]
module"]
pub type HWCFGR1 = crate::Reg<hwcfgr1::HWCFGR1_SPEC>;
#[doc = "TAMP hardware configuration register 1"]
pub mod hwcfgr1;
#[doc = "VERR (r) register accessor: EXTI IP Version register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`verr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`verr`]
module"]
pub type VERR = crate::Reg<verr::VERR_SPEC>;
#[doc = "EXTI IP Version register"]
pub mod verr;
#[doc = "IPIDR (r) register accessor: EXTI Identification register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipidr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ipidr`]
module"]
pub type IPIDR = crate::Reg<ipidr::IPIDR_SPEC>;
#[doc = "EXTI Identification register"]
pub mod ipidr;
#[doc = "SIDR (r) register accessor: EXTI Size ID register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sidr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sidr`]
module"]
pub type SIDR = crate::Reg<sidr::SIDR_SPEC>;
#[doc = "EXTI Size ID register"]
pub mod sidr;
|
use svg::node::element::{path::Data, Element, Path, Title};
use crate::dirgraphsvg::{
nodes::{add_text, OFFSET_IDENTIFIER},
util::font::FontInfo,
};
use super::{Node, SizeContext, PADDING_HORIZONTAL, PADDING_VERTICAL};
const MODULE_TAB_HEIGHT: i32 = 10;
const UNDEVELOPED_DIAMOND: i32 = 5;
const CONTEXT_BUMP: i32 = 10;
pub(crate) enum BoxType {
Normal(i32),
Undeveloped(i32),
Module,
Context,
}
impl BoxType {
///
///
///
pub(super) fn get_minimum_size(&self) -> (i32, i32) {
let skew = if let BoxType::Normal(x) = self { *x } else { 0 };
(
PADDING_HORIZONTAL * 2 + 90 + skew * 2,
PADDING_VERTICAL * 2 + 30,
)
}
///
///
///
pub(super) fn calculate_size(
&self,
_font: &FontInfo,
min_width: i32,
min_height: i32,
size_context: &mut SizeContext,
) -> (i32, i32) {
let mut width = std::cmp::max(min_width, size_context.text_width + 2 * PADDING_HORIZONTAL);
let mut height = std::cmp::max(min_height, size_context.text_height + 2 * PADDING_VERTICAL);
match &self {
BoxType::Normal(_) => (),
BoxType::Undeveloped(_) => {
height += UNDEVELOPED_DIAMOND;
}
BoxType::Module => {
height += MODULE_TAB_HEIGHT;
}
BoxType::Context => {
width += CONTEXT_BUMP * 2;
}
}
(width, height)
}
///
///
///
///
pub(super) fn render(&self, node: &Node, font: &FontInfo, mut context: Element) -> Element {
let title = Title::new().add(svg::node::Text::new(&node.identifier));
use svg::Node;
context.append(title);
let data = match &self {
BoxType::Normal(skew) | BoxType::Undeveloped(skew) => Data::new()
.move_to((node.x - node.width / 2 + skew / 2, node.y - node.height / 2))
.line_to((node.x + node.width / 2 + skew / 2, node.y - node.height / 2))
.line_to((node.x + node.width / 2 - skew / 2, node.y + node.height / 2))
.line_to((node.x - node.width / 2 - skew / 2, node.y + node.height / 2))
.close(),
BoxType::Module => Data::new()
.move_to((node.x - node.width / 2, node.y - node.height / 2))
.horizontal_line_by(30)
.vertical_line_by(MODULE_TAB_HEIGHT)
.line_to((
node.x + node.width / 2,
node.y - node.height / 2 + MODULE_TAB_HEIGHT,
))
.line_to((node.x + node.width / 2, node.y + node.height / 2))
.line_to((node.x - node.width / 2, node.y + node.height / 2))
.close(),
BoxType::Context => Data::new()
.move_to((
node.x + CONTEXT_BUMP - node.width / 2,
node.y - node.height / 2,
))
.line_to((
node.x - CONTEXT_BUMP + node.width / 2,
node.y - node.height / 2,
))
.cubic_curve_to((
node.x + node.width / 2,
node.y - node.height / 2,
node.x + node.width / 2,
node.y + node.height / 2,
node.x + node.width / 2 - CONTEXT_BUMP,
node.y + node.height / 2,
))
.line_to((
node.x - node.width / 2 + CONTEXT_BUMP,
node.y + node.height / 2,
))
.cubic_curve_to((
node.x - node.width / 2,
node.y + node.height / 2,
node.x - node.width / 2,
node.y - node.height / 2,
node.x - node.width / 2 + CONTEXT_BUMP,
node.y - node.height / 2,
)),
};
let border = Path::new()
.set("fill", "none")
.set("stroke", "black")
.set("stroke-width", 1u32)
.set("d", data)
.set("class", "border");
context.append(border);
let skew = if let BoxType::Normal(x) = self { *x } else { 0 };
let mut x = node.x - (node.width - skew) / 2 + PADDING_HORIZONTAL;
if let BoxType::Context = self {
x += CONTEXT_BUMP;
}
let mut y = node.y - node.height / 2 + PADDING_VERTICAL;
if let BoxType::Module = self {
y += MODULE_TAB_HEIGHT;
}
y += font.size as i32;
context = add_text(context, &node.identifier, x, y, font, true);
y += OFFSET_IDENTIFIER;
for text in node.text.lines() {
y += font.size as i32;
context = add_text(context, text, x, y, font, false);
}
if let BoxType::Undeveloped(_) = self {
let data = Data::new()
.move_to((node.x, node.y + node.height / 2))
.line_by((UNDEVELOPED_DIAMOND, UNDEVELOPED_DIAMOND))
.line_by((-UNDEVELOPED_DIAMOND, UNDEVELOPED_DIAMOND))
.line_by((-UNDEVELOPED_DIAMOND, -UNDEVELOPED_DIAMOND))
.close();
let undeveloped_diamond = Path::new()
.set("fill", "none")
.set("stroke", "black")
.set("stroke-width", 1u32)
.set("d", data);
context.append(undeveloped_diamond);
}
context
}
}
|
use vector;
use std::vec::*;
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
/// PPM image container
#[allow(dead_code)]
pub struct PPM
{
width: u32,
height: u32,
data: Box<[u8]>,
}
#[allow(dead_code)]
impl PPM
{
pub fn new(height: u32, width: u32) -> PPM
{
let size = 3 * height * width;
let mut buffer: Vec<u8> = Vec::with_capacity(size as usize);
unsafe { buffer.set_len(size as usize); }
PPM{height: height, width: width, data: buffer.into_boxed_slice()}
}
fn buffer_size(&self) -> u32
{
3 * self.width * self.height
}
fn get_offset(&self, x: u32, y: u32) -> Option<u32>
{
let offset = (y * self.width * 3) + (x * 3);
if offset < self.buffer_size()
{ Some(offset) }
else
{ None }
}
/// Returns the pixels in floats
/// 1. => 255
/// .5 => 127
/// 0. => 0
pub fn get_pixel(&self, x:u32, y:u32) -> Option<vector::Vec3>
{
match self.get_offset(x, y)
{
Some(offset) =>
{
let r = self.data[offset as usize] as f32 / 255.;
let g = self.data[(offset + 1) as usize] as f32 / 255.;
let b = self.data[(offset + 2) as usize] as f32 / 255.;
Some(vector::Vec3::new(r, g, b))
},
None => None
}
}
/// Contents of color must be in floats
/// 1. => 255
/// .5 => 127
/// 0. => 0
pub fn set_pixel(&mut self, x: u32, y: u32, color: vector::Vec3) -> bool
{
match self.get_offset(x, y)
{
Some(offset) =>
{
self.data[offset as usize] = (color.x * 255.) as u8;
self.data[(offset + 1) as usize] = (color.y * 255.) as u8;
self.data[(offset + 2) as usize] = (color.z * 255.) as u8;
true
},
None => false
}
}
/// Writes contents of image to file
pub fn write_file(&self, filename: &Path) -> bool
{
let mut file = match File::create(&filename)
{
Ok(file) => file,
Err(e) => panic!("Failed to create {}: {}", filename.display(), e),
};
let header = format!("P3 {} {} 255\n", self.width, self.height);
file.write(header.as_bytes());
for y in 0..self.height
{
for x in 0..self.width
{
let color = match self.get_pixel(x, y)
{ Some(v) => v, None => vector::Vec3::new(0., 0., 0.), };
let write_str = format!("{} {} {}\n",
color.x * 255.,
color.y * 255.,
color.z * 255.);
let write = match file.write(write_str.as_bytes())
{ Ok(_) => true, Err(_) => false, };
}
}
true
}
}
|
mod position;
mod exercise_11;
mod read_csv;
fn main() {
let filename = "./matrix.csv";
let matrix = read_csv::read_matrix_from_file(&filename);
// matrix_printer(&matrix)
}
|
pub fn decode_utf8(src: &[u8]) -> Result<Vec<char>, DecodeUtf8Error> {
let mut result = Vec::new();
let mut index = 0;
while index < src.len() {
match decode_char(&src[index..]) {
Ok((ch, len)) => {
result.push(ch);
index += len;
}
Err(kind) => {
return Err(DecodeUtf8Error { src, index, kind });
}
}
}
Ok(result)
}
#[derive(Debug, Clone)]
pub struct DecodeUtf8Error<'a> {
pub src: &'a [u8],
pub index: usize,
pub kind: DecodeUtf8ErrorKind,
}
#[derive(Debug, Clone)]
pub enum DecodeUtf8ErrorKind {
MissingStartByte,
InvalidStartByte,
NotEnoughBytes,
InvalidTrailingByte,
}
const MAX_ONE_BYTE: u8 = 0b1000_0000;
const MAX_MID_BYTE: u8 = 0b1100_0000;
const MAX_TWO_START_BYTE: u8 = 0b1110_0000;
const MAX_THREE_START_BYTE: u8 = 0b1111_0000;
const MAX_FOUR_START_BYTE: u8 = 0b1111_1000;
const NON_START_BYTE_MASK: u8 = 0b0011_1111;
const TWO_MASK: u8 = 0b0001_1111;
const THREE_MASK: u8 = 0b0000_1111;
const FOUR_MASK: u8 = 0b0000_0111;
fn decode_char(src: &[u8]) -> Result<(char, usize), DecodeUtf8ErrorKind> {
let start = src[0];
if start < MAX_ONE_BYTE {
Ok((start as char, 1))
} else if start < MAX_MID_BYTE {
Err(DecodeUtf8ErrorKind::MissingStartByte)
} else if start < MAX_TWO_START_BYTE {
decode_multi_bytes(src, 2).map(|ch| (ch, 2))
} else if start < MAX_THREE_START_BYTE {
decode_multi_bytes(src, 3).map(|ch| (ch, 3))
} else if start < MAX_FOUR_START_BYTE {
decode_multi_bytes(src, 4).map(|ch| (ch, 4))
} else {
Err(DecodeUtf8ErrorKind::InvalidStartByte)
}
}
fn decode_multi_bytes(src: &[u8], len: usize) -> Result<char, DecodeUtf8ErrorKind> {
if src.len() < len {
return Err(DecodeUtf8ErrorKind::NotEnoughBytes);
}
let mask = match len {
2 => TWO_MASK,
3 => THREE_MASK,
4 => FOUR_MASK,
_ => unreachable!(),
};
let mut raw_char = (src[0] & mask) as u32;
for &byte in &src[1..len] {
if byte < MAX_ONE_BYTE || byte >= MAX_MID_BYTE {
return Err(DecodeUtf8ErrorKind::InvalidTrailingByte);
}
raw_char = (raw_char << 6) | (byte & NON_START_BYTE_MASK) as u32;
}
Ok(std::char::from_u32(raw_char).unwrap())
}
|
use actix::prelude::*;
#[path = "route_fragment.rs"]
pub mod route_fragment;
use std::collections::HashMap;
#[derive(Default)]
pub struct RouteFragmentRegistry {
route_fragments: HashMap<String, Addr<route_fragment::RouteFragment>>,
}
impl Actor for RouteFragmentRegistry {
type Context = Context<RouteFragmentRegistry>;
}
impl Supervised for RouteFragmentRegistry {}
impl ArbiterService for RouteFragmentRegistry {}
#[derive(Message)]
#[rtype(result = "Addr<route_fragment::RouteFragment>")]
pub struct GetRouteFragment {
id: String,
}
impl GetRouteFragment {
pub fn new(id: String) -> GetRouteFragment {
GetRouteFragment { id: id }
}
}
impl Handler<GetRouteFragment> for RouteFragmentRegistry {
type Result = Addr<route_fragment::RouteFragment>;
fn handle(
&mut self,
_msg: GetRouteFragment,
_ctx: &mut Context<Self>,
) -> Addr<route_fragment::RouteFragment> {
match self.route_fragments.get(&_msg.id) {
Some(trip) => trip.clone(),
None => {
println!("Creating new route fragment {}", _msg.id);
let id = String::from(&_msg.id);
let new_fragment = route_fragment::RouteFragment::create(|_| {
route_fragment::RouteFragment::new(String::from(_msg.id))
});
self.route_fragments.insert(id, new_fragment.clone());
new_fragment
}
}
}
}
|
#[doc = "Reader of register TAMP_CR1"]
pub type R = crate::R<u32, super::TAMP_CR1>;
#[doc = "Writer for register TAMP_CR1"]
pub type W = crate::W<u32, super::TAMP_CR1>;
#[doc = "Register TAMP_CR1 `reset()`'s with value 0xffff_0000"]
impl crate::ResetValue for super::TAMP_CR1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xffff_0000
}
}
#[doc = "Reader of field `TAMP1E`"]
pub type TAMP1E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TAMP1E`"]
pub struct TAMP1E_W<'a> {
w: &'a mut W,
}
impl<'a> TAMP1E_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `TAMP2E`"]
pub type TAMP2E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TAMP2E`"]
pub struct TAMP2E_W<'a> {
w: &'a mut W,
}
impl<'a> TAMP2E_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `TAMP3E`"]
pub type TAMP3E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TAMP3E`"]
pub struct TAMP3E_W<'a> {
w: &'a mut W,
}
impl<'a> TAMP3E_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `ITAMP1E`"]
pub type ITAMP1E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ITAMP1E`"]
pub struct ITAMP1E_W<'a> {
w: &'a mut W,
}
impl<'a> ITAMP1E_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `ITAMP2E`"]
pub type ITAMP2E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ITAMP2E`"]
pub struct ITAMP2E_W<'a> {
w: &'a mut W,
}
impl<'a> ITAMP2E_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `ITAMP3E`"]
pub type ITAMP3E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ITAMP3E`"]
pub struct ITAMP3E_W<'a> {
w: &'a mut W,
}
impl<'a> ITAMP3E_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `ITAMP4E`"]
pub type ITAMP4E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ITAMP4E`"]
pub struct ITAMP4E_W<'a> {
w: &'a mut W,
}
impl<'a> ITAMP4E_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Reader of field `ITAMP5E`"]
pub type ITAMP5E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ITAMP5E`"]
pub struct ITAMP5E_W<'a> {
w: &'a mut W,
}
impl<'a> ITAMP5E_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Reader of field `ITAMP8E`"]
pub type ITAMP8E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ITAMP8E`"]
pub struct ITAMP8E_W<'a> {
w: &'a mut W,
}
impl<'a> ITAMP8E_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
impl R {
#[doc = "Bit 0 - TAMP1E"]
#[inline(always)]
pub fn tamp1e(&self) -> TAMP1E_R {
TAMP1E_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - TAMP2E"]
#[inline(always)]
pub fn tamp2e(&self) -> TAMP2E_R {
TAMP2E_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - TAMP3E"]
#[inline(always)]
pub fn tamp3e(&self) -> TAMP3E_R {
TAMP3E_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 16 - ITAMP1E"]
#[inline(always)]
pub fn itamp1e(&self) -> ITAMP1E_R {
ITAMP1E_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - ITAMP2E"]
#[inline(always)]
pub fn itamp2e(&self) -> ITAMP2E_R {
ITAMP2E_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - ITAMP3E"]
#[inline(always)]
pub fn itamp3e(&self) -> ITAMP3E_R {
ITAMP3E_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - ITAMP4E"]
#[inline(always)]
pub fn itamp4e(&self) -> ITAMP4E_R {
ITAMP4E_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - ITAMP5E"]
#[inline(always)]
pub fn itamp5e(&self) -> ITAMP5E_R {
ITAMP5E_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 23 - ITAMP8E"]
#[inline(always)]
pub fn itamp8e(&self) -> ITAMP8E_R {
ITAMP8E_R::new(((self.bits >> 23) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - TAMP1E"]
#[inline(always)]
pub fn tamp1e(&mut self) -> TAMP1E_W {
TAMP1E_W { w: self }
}
#[doc = "Bit 1 - TAMP2E"]
#[inline(always)]
pub fn tamp2e(&mut self) -> TAMP2E_W {
TAMP2E_W { w: self }
}
#[doc = "Bit 2 - TAMP3E"]
#[inline(always)]
pub fn tamp3e(&mut self) -> TAMP3E_W {
TAMP3E_W { w: self }
}
#[doc = "Bit 16 - ITAMP1E"]
#[inline(always)]
pub fn itamp1e(&mut self) -> ITAMP1E_W {
ITAMP1E_W { w: self }
}
#[doc = "Bit 17 - ITAMP2E"]
#[inline(always)]
pub fn itamp2e(&mut self) -> ITAMP2E_W {
ITAMP2E_W { w: self }
}
#[doc = "Bit 18 - ITAMP3E"]
#[inline(always)]
pub fn itamp3e(&mut self) -> ITAMP3E_W {
ITAMP3E_W { w: self }
}
#[doc = "Bit 19 - ITAMP4E"]
#[inline(always)]
pub fn itamp4e(&mut self) -> ITAMP4E_W {
ITAMP4E_W { w: self }
}
#[doc = "Bit 20 - ITAMP5E"]
#[inline(always)]
pub fn itamp5e(&mut self) -> ITAMP5E_W {
ITAMP5E_W { w: self }
}
#[doc = "Bit 23 - ITAMP8E"]
#[inline(always)]
pub fn itamp8e(&mut self) -> ITAMP8E_W {
ITAMP8E_W { w: self }
}
}
|
// implements the morphology kernel submodule
pub enum ThresholdType {
Binary,
TruncateUpper,
TruncateLower,
}
pub fn erode(/*image: &Image, kernel: &Kernel*/) /*->Image*/ {
}
pub fn dilate(/*image: &Image, kernel: &Kernel*/) /*->Image*/ {
}
pub fn open(/*image: &Image, kernel: &Kernel*/) /*->Image*/ {
}
pub fn close(/*image: &Image, kernel: &Kernel*/) /*->Image*/ {
}
pub fn threshold(/*image: &Image, threshold: u8*/) /*->Image*/ {
}
|
// MIT License
//
// Copyright (c) 2019-2021 Tobias Pfeiffer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use {serde::{*, de::Error}, crate::xml::Body, self::RegistryElement::*, std::sync::atomic::AtomicBool};
pub static BITFIELDS: AtomicBool = AtomicBool::new(false);
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Api {
Vulkan,
OpenXr
}
pub struct Registry {
pub api: Api,
pub elements: Vec<RegistryElement>,
pub exts: Vec<(String, Vec<String>)>
}
#[derive(Debug)]
pub enum RegistryElement {
Type(KhrType),
Enums(KhrEnums),
Command(KhrCommand),
Macro { name: String, content: String },
Comment(String)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KhrRegistryVariant {
Comment(Body<String>),
Types(Vec<KhrTypesVariants>),
Enums(#[serde(deserialize_with = "deserialize_enums")] KhrEnums),
Commands(Vec<KhrCommandsVariant>),
Feature(KhrFeature),
Extensions(Vec<KhrExtensionsVariant>),
#[serde(other)]
Other
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KhrTypesVariants {
Type(KhrType),
Comment(CommentVariant)
}
#[derive(Debug)]
pub enum KhrType {
Alias(KhrTypeAlias),
Struct(KhrTypeStruct),
FuncPtr(KhrTypeFuncPtr),
Other
}
#[derive(Debug)]
pub struct KhrTypeAlias {
pub category: KhrTypeAliasCategory,
pub name: String,
pub alias: String,
pub body: String,
pub parent: Option<String>
}
#[derive(Debug)]
pub struct KhrTypeStruct {
pub category: KhrTypeStructCategory,
pub name: String,
pub members: Vec<KhrTypeStructMemberVariant>,
pub comment: Option<String>
}
#[derive(Debug)]
pub struct KhrTypeFuncPtr {
pub name: String,
pub comment: Option<String>,
pub result: String,
pub params: Vec<KhrCommandParam>
}
#[derive(Debug, Deserialize, Eq, PartialEq, Copy, Clone)]
#[serde(rename_all = "lowercase")]
pub enum KhrTypeAliasCategory {
Handle,
Enum,
Bitmask,
Basetype,
Struct
}
#[derive(Debug, Deserialize, Eq, PartialEq, Copy, Clone)]
#[serde(rename_all = "lowercase")]
pub enum KhrTypeStructCategory {
Struct,
Union
}
impl std::fmt::Display for KhrTypeStructCategory {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Struct => f.write_str("struct"),
Self::Union => f.write_str("union")
}
}
}
#[derive(Debug)]
pub enum KhrTypeStructMemberVariant {
Member(KhrTypeStructMember),
Comment(String)
}
#[derive(Debug)]
pub struct KhrTypeStructMember {
pub r#type: String,
pub name: String,
pub optional: Option<String>,
pub len: Option<String>,
pub comment: Option<String>
}
#[derive(Debug)]
pub struct KhrEnums {
pub name: String,
pub r#type: KhrEnumsType,
pub comment: Option<String>,
pub enums: Vec<KhrEnumsVariant>
}
#[derive(Debug, Deserialize, Eq, PartialEq, Copy, Clone)]
#[serde(rename_all = "lowercase")]
pub enum KhrEnumsType {
Enum,
Bitmask,
#[serde(other)]
None
}
impl Default for KhrEnumsType {
fn default() -> Self {
Self::None
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KhrEnumsVariant {
Enum {
name: String,
#[serde(flatten)]
value: KhrEnumValue,
comment: Option<String>
},
Comment(String),
#[serde(other)]
Other
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KhrEnumValue {
Value(#[serde(deserialize_with = "deserialize_value")] String),
BitPos(String),
Alias(String)
}
impl std::fmt::Display for KhrEnumValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Value(value) => f.write_str(value),
Self::BitPos(bit) => write!(f, "{:#x}", 1usize << bit.parse::<usize>().unwrap()),
Self::Alias(alias) => f.write_str(alias)
}
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KhrCommandsVariant {
Comment(String),
Command(KhrCommand)
}
#[derive(Debug, Clone)]
pub enum KhrCommand {
Alias {
name: String,
alias: String,
comment: Option<String>,
feature: Option<String>
},
Command {
proto: KhrCommandProto,
param: Vec<KhrCommandParam>,
comment: Option<String>,
feature: Option<String>
}
}
#[derive(Debug, Default, Clone)]
pub struct KhrCommandProto {
pub r#type: String,
pub name: String
}
#[derive(Debug, Default, Clone)]
pub struct KhrCommandParam {
pub r#type: String,
pub name: String,
pub optional: Option<String>,
pub len: Option<String>,
pub comment: Option<String>
}
#[derive(Debug)]
pub struct KhrFeature {
pub api: String,
pub name: String,
pub number: String,
pub comment: Option<String>,
pub require: Vec<Vec<KhrRequireVariant>>
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KhrExtensionsVariant {
Comment(String),
Extension(KhrExtension)
}
#[derive(Debug)]
pub struct KhrExtension {
pub name: String,
pub number: usize,
pub r#type: Option<String>,
pub supported: String,
pub requires: Vec<String>,
pub platform: Option<String>,
pub require: Vec<Vec<KhrRequireVariant>>
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KhrRequireVariant {
Enum {
name: String,
#[serde(flatten)]
value: Option<KhrRequireEnumVal>,
extends: Option<String>,
extnumber: Option<usize>,
comment: Option<String>,
dir: Option<String>
},
Type { name: String },
Command { name: String },
Comment(String),
#[serde(other)]
Other
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KhrRequireEnumVal {
Value(#[serde(deserialize_with = "deserialize_value")] String),
Offset(String),
Bitpos(String),
Alias(String)
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum CommentVariant {
Attr(String),
Body(Body<String>)
}
#[allow(clippy::from_over_into)]
impl Into<String> for CommentVariant {
fn into(self) -> String {
match self {
Self::Attr(v) => v,
Self::Body(v) => v.value
}
}
}
fn deserialize_value<'de, D: Deserializer<'de>>(de: D) -> Result<String, D::Error> {
String::deserialize(de).map(|s| convert_c_value(&s))
}
fn deserialize_list<'de, D: Deserializer<'de>>(de: D) -> Result<Vec<String>, D::Error> {
String::deserialize(de)
.map(|s| s.split(',').map(String::from).collect())
}
impl<'de> Deserialize<'de> for Registry {
#[allow(clippy::cognitive_complexity)]
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
use KhrRequireEnumVal::*;
let registry = Vec::<KhrRegistryVariant>::deserialize(deserializer)?;
let mut api = None;
let mut elements = Vec::new();
let mut consts = Vec::new();
let mut exts = Vec::new();
for e in registry {
match e {
KhrRegistryVariant::Comment(v) => elements.push(RegistryElement::Comment(v.value)),
KhrRegistryVariant::Types(types) => elements.extend(types.into_iter()
.map(|r#type| match r#type {
KhrTypesVariants::Comment(v) => RegistryElement::Comment(v.into()),
KhrTypesVariants::Type(r#type) => RegistryElement::Type(r#type)
})),
KhrRegistryVariant::Enums(mut enums) => {
if &enums.name == "API Constants" {
for e in &mut enums.enums {
if let KhrEnumsVariant::Enum { name, value: KhrEnumValue::Value(ref mut v), .. } = e {
if ["VK_TRUE", "VK_FALSE"].contains(&name.as_str()) {
api = Some(Api::Vulkan);
v.push_str("u32");
} else if ["XR_TRUE", "XR_FALSE"].contains(&name.as_str()) {
api = Some(Api::OpenXr);
v.push_str("u32");
}
}
}
}
elements.push(Enums(enums))
}
KhrRegistryVariant::Commands(commands) => elements.extend(
commands.iter().map(|e| match e {
KhrCommandsVariant::Command(KhrCommand::Alias { name, alias, comment, feature }) => {
let mut alias = alias;
'outer: loop {
for command in &commands {
match command {
KhrCommandsVariant::Command(KhrCommand::Command { proto, param, .. })
if *alias == proto.name => break 'outer Command(KhrCommand::Command {
proto: KhrCommandProto { r#type: proto.r#type.clone(), name: name.clone() },
param: param.clone(),
comment: comment.clone(),
feature: feature.clone()
}),
KhrCommandsVariant::Command(KhrCommand::Alias { name: name_, alias: alias2, .. })
if alias == name_ => {
alias = alias2;
continue 'outer;
}
_ => ()
}
}
panic!("failed to find command alias `{}` for command `{}`", alias, name)
}
}
KhrCommandsVariant::Command(v) => Command(v.clone()),
KhrCommandsVariant::Comment(v) => Comment(v.clone())
})),
KhrRegistryVariant::Extensions(mut extensions) => {
let extensions = extensions.iter_mut().filter_map(|e| match e {
KhrExtensionsVariant::Extension(e) if e.supported != "disabled" => Some(e),
_ => None
}).collect::<Vec<_>>();
extensions.iter()
.flat_map(|ext| ext.require.iter())
.flat_map(|req| req.iter())
.for_each(|e| if let KhrRequireVariant::Enum { name, value, extends: Option::None, .. } = e {
consts.push(KhrEnumsVariant::Enum {
name: name.clone(),
value: match value {
Some(Alias(v)) => KhrEnumValue::Alias(v.clone()),
Some(Value(v)) => KhrEnumValue::Value(v.clone()),
Some(Bitpos(v)) => KhrEnumValue::BitPos(v.clone()),
_ => return
},
comment: None
})
});
elements.iter_mut().for_each(|e| match e {
RegistryElement::Enums(ref mut enums) => extensions.iter()
.flat_map(|ext| ext.require.iter().map(move |e| (ext, e)))
.flat_map(|(ext, req)| req.iter().map(move |e| (ext, e)))
.for_each(|(ext, e)| match e {
KhrRequireVariant::Enum { name, value, dir, extends: Some(extends), extnumber, .. }
if extends == &enums.name && !enums.enums.iter()
.any(|v| if let KhrEnumsVariant::Enum { name: ref v, .. } = v { v == name } else { false })
=> enums.enums.push(KhrEnumsVariant::Enum {
name: name.clone(),
value: match value {
Some(Alias(v)) => KhrEnumValue::Alias(v.clone()),
Some(Value(v)) => KhrEnumValue::Value(v.clone()),
Some(Bitpos(v)) => KhrEnumValue::BitPos(v.clone()),
Some(Offset(offset)) => KhrEnumValue::Value(dir.clone().unwrap_or_default() + &(
1_000_000_000 + (extnumber.unwrap_or(ext.number) - 1)
* 1_000 + offset.parse::<usize>().unwrap()).to_string()),
_ => return
},
comment: None
}),
_ => ()
}),
RegistryElement::Command(KhrCommand::Command { feature: ref mut feat, proto: KhrCommandProto { name, .. }, .. })
| RegistryElement::Command(KhrCommand::Alias { feature: ref mut feat, name, .. }) => extensions.iter()
.flat_map(|ext| ext.require.iter().map(move |e| (ext, e)))
.flat_map(|(ext, req)| req.iter().map(move |e| (ext, e)))
.for_each(|(ext, e)| match e {
KhrRequireVariant::Command { name: feature_cmd_name } if feature_cmd_name == &*name => *feat = Some(ext.name.clone()),
_ => ()
}),
_ => ()
});
exts.extend(extensions.into_iter().map(|e| (e.name.clone(), e.requires.clone())));
}
KhrRegistryVariant::Feature(feature) => {
feature.require.iter()
.flat_map(|req| req.iter())
.for_each(|e| if let KhrRequireVariant::Enum { name, value, extends: Option::None, .. } = e {
consts.push(KhrEnumsVariant::Enum {
name: name.clone(),
value: match value {
Some(Alias(v)) => KhrEnumValue::Alias(v.clone()),
Some(Value(v)) => KhrEnumValue::Value(v.clone()),
Some(Bitpos(v)) => KhrEnumValue::BitPos(v.clone()),
_ => return
},
comment: None
})
});
elements.iter_mut().for_each(|e| match e {
RegistryElement::Enums(ref mut enums) => feature.require.iter()
.flat_map(|req| req.iter())
.for_each(|e| match e {
KhrRequireVariant::Enum { name, value, dir, extends: Some(extends), extnumber, .. }
if extends == &enums.name && !enums.enums.iter()
.any(|v| if let KhrEnumsVariant::Enum { name: ref v, .. } = v { v == name } else { false })
=> enums.enums.push(KhrEnumsVariant::Enum {
name: name.clone(),
value: match value {
Some(Alias(v)) => KhrEnumValue::Alias(v.clone()),
Some(Value(v)) => KhrEnumValue::Value(v.clone()),
Some(Bitpos(v)) => KhrEnumValue::BitPos(v.clone()),
Some(Offset(offset)) => KhrEnumValue::Value(dir.clone().unwrap_or_default() + &(
1_000_000_000 + (extnumber.unwrap() - 1)
* 1_000 + offset.parse::<usize>().unwrap()).to_string()),
_ => return
},
comment: None
}),
_ => ()
}),
RegistryElement::Command(KhrCommand::Command { feature: ref mut feat, proto: KhrCommandProto { name, .. }, .. })
| RegistryElement::Command(KhrCommand::Alias { feature: ref mut feat, name, .. }) => feature.require.iter()
.flat_map(|req| req.iter())
.for_each(|e| match e {
KhrRequireVariant::Command { name: feature_cmd_name } if feature_cmd_name == name => *feat = Some(feature.name.clone()),
_ => ()
}),
_ => ()
});
exts.push((feature.name, Vec::new()));
}
_ => ()
}
}
let api = api.expect("cannot determine API type");
// extension constants are handled like an enum
elements.push(Enums(KhrEnums {
name: "Extension Constants".to_string(),
r#type: KhrEnumsType::None,
comment: None,
enums: consts
}));
// HACK: Add registry elements that can not be parsed reliably manually
match api {
Api::Vulkan => elements.extend(get_vk_items().into_iter()),
Api::OpenXr => elements.extend(get_xr_items().into_iter())
}
Ok(Self { api, elements, exts })
}
}
impl<'de> Deserialize<'de> for KhrType {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum Val {
Category(Category),
Name(CommentVariant),
Member(KhrTypeStructMember),
#[serde(alias = "type")]
Alias(CommentVariant),
Parent(String),
Comment(CommentVariant),
#[serde(rename = "$value")]
Body(String),
#[serde(other)]
Other
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Category {
Struct(KhrTypeStructCategory),
Alias(KhrTypeAliasCategory),
Other(String)
}
let vec = Vec::<Val>::deserialize(deserializer);
let vec = vec?;
let body = vec.iter()
.filter_map(|e| match e { Val::Body(v) => Some(v.as_str()), _ => None })
.collect::<String>();
let mut category = None;
let mut name = None;
let mut alias = None;
let mut comment = None;
let mut parent = None;
let mut members = Vec::new();
for e in vec {
match e {
Val::Category(v) => category = Some(v),
Val::Name(v) => name = Some(v),
Val::Alias(v) => alias = Some(v.into()),
Val::Parent(v) => parent = Some(v),
Val::Comment(CommentVariant::Attr(v)) => comment = Some(v),
Val::Comment(CommentVariant::Body(v)) => members.push(KhrTypeStructMemberVariant::Comment(v.value)),
Val::Member(v) => members.push(KhrTypeStructMemberVariant::Member(v)),
_ => ()
}
}
Ok(match (category, name, alias) {
(
Some(Category::Struct(category)),
Some(CommentVariant::Attr(name)),
None
) => KhrType::Struct(KhrTypeStruct {
category,
name,
members,
comment
}),
(
Some(Category::Alias(category)),
Some(name),
Some(alias)
) => KhrType::Alias(KhrTypeAlias {
category,
name: name.into(),
alias,
body,
parent
}),
(
Some(Category::Struct(_)),
Some(name),
Some(alias)
) => KhrType::Alias(KhrTypeAlias {
category: KhrTypeAliasCategory::Struct,
name: name.into(),
alias,
body,
parent
}),
_ => KhrType::Other
})
}
}
impl<'de> Deserialize<'de> for KhrTypeStructMember {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum Val {
Type(Body<String>),
Name(Body<String>),
Comment(Body<String>),
#[serde(rename = "$value")]
Body(String),
Optional(String),
Len(String),
Enum(Body<String>),
#[serde(other)]
Other
}
let vec = Vec::<Val>::deserialize(deserializer)?;
let body = vec.iter().filter_map(|e| match e {
Val::Body(v) => Some(v.as_str()),
Val::Enum(v) => Some(&v.value),
_ => None
}).collect::<String>();
let mut r#type = None;
let mut name = None;
let mut optional = None;
let mut len = None;
let mut comment = None;
for e in vec {
match e {
Val::Type(v) => r#type = Some(convert_c_type(&v.value, &body)),
Val::Name(v) => name = Some(convert_name(&v.value)),
Val::Comment(v) => comment = Some(v.value),
Val::Len(v) => len = Some(v),
Val::Optional(v) => optional = Some(v),
_ => ()
}
}
Ok(Self {
r#type: r#type.ok_or_else(|| D::Error::missing_field("type"))?,
name: name.ok_or_else(|| D::Error::missing_field("name"))?,
optional,
len,
comment,
})
}
}
impl<'de> Deserialize<'de> for KhrCommand {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum Val {
Name(String),
Alias(String),
Proto(KhrCommandProto),
Param(KhrCommandParam),
Comment(String),
#[serde(other)]
Other
}
let mut name = None;
let mut alias = None;
let mut proto = None;
let mut param = Vec::new();
let mut comment = None;
for e in Vec::<Val>::deserialize(deserializer)? {
match e {
Val::Name(v) => name = Some(v),
Val::Alias(v) => alias = Some(v),
Val::Proto(v) => proto = Some(v),
Val::Param(v) => param.push(v),
Val::Comment(v) => comment = Some(v),
_ => ()
}
}
Ok(match (name, alias, proto) {
(Some(name), Some(alias), None) => KhrCommand::Alias {
name,
alias,
comment,
feature: None
},
(None, None, Some(proto)) => KhrCommand::Command {
proto,
param,
comment,
feature: None
},
_ => return Err(D::Error::custom("data did not match any variant of `KhrCommand`"))
})
}
}
impl<'de> Deserialize<'de> for KhrCommandProto {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
#[derive(Deserialize)]
struct Val {
r#type: Body<String>,
name: Body<String>
}
Val::deserialize(deserializer).map(|v| KhrCommandProto {
r#type: convert_c_type(&v.r#type.value, ""),
name: v.name.value
})
}
}
impl<'de> Deserialize<'de> for KhrCommandParam {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum Val {
Type(Body<String>),
Name(Body<String>),
Comment(Body<String>),
#[serde(rename = "$value")]
Body(String),
Optional(String),
Len(String),
Enum(Body<String>),
#[serde(other)]
Other
}
let vec = Vec::<Val>::deserialize(deserializer)?;
let body = vec.iter().filter_map(|e| match e {
Val::Body(v) => Some(v.as_str()),
Val::Enum(v) => Some(&v.value),
_ => None
}).collect::<String>();
let mut r#type = None;
let mut name = None;
let mut comment = None;
let mut optional = None;
let mut len = None;
for e in vec {
match e {
Val::Type(v) => r#type = Some(convert_c_type(&v.value, &body)),
Val::Name(v) => name = Some(convert_name(&v.value)),
Val::Comment(v) => comment = Some(v.value),
Val::Optional(v) => optional = Some(v),
Val::Len(v) => len = Some(v),
_ => ()
}
}
Ok(Self {
r#type: r#type.ok_or_else(|| D::Error::missing_field("type"))?,
name: name.ok_or_else(|| D::Error::missing_field("name"))?,
optional,
len,
comment,
})
}
}
impl<'de> Deserialize<'de> for KhrFeature {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum Val {
Api(String),
Name(String),
Number(String),
Comment(String),
Require(Vec<KhrRequireVariant>),
#[serde(other)]
Other
}
let mut api = None;
let mut name = None;
let mut number = None;
let mut comment = None;
let mut require = Vec::new();
for e in Vec::<Val>::deserialize(deserializer)? {
match e {
Val::Api(v) => api = Some(v),
Val::Name(v) => name = Some(v),
Val::Number(v) => number = Some(v),
Val::Comment(v) => comment = Some(v),
Val::Require(v) => require.push(v),
_ => ()
}
}
Ok(Self {
api: api.ok_or_else(|| D::Error::missing_field("api"))?,
name: name.ok_or_else(|| D::Error::missing_field("name"))?,
number: number.ok_or_else(|| D::Error::missing_field("number"))?,
comment,
require
})
}
}
impl<'de> Deserialize<'de> for KhrExtension {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum Val {
Name(String),
Number(usize),
Type(String),
Supported(String),
Requires(#[serde(deserialize_with = "deserialize_list", default)] Vec<String>),
#[serde(alias = "protect")]
Platform(String),
Require(Vec<KhrRequireVariant>),
#[serde(other)]
Other
}
let mut name = None;
let mut number = None;
let mut r#type = None;
let mut supported = None;
let mut requires = None;
let mut platform = None;
let mut require = Vec::new();
for e in Vec::<Val>::deserialize(deserializer)? {
match e {
Val::Name(v) => name = Some(v),
Val::Number(v) => number = Some(v),
Val::Type(v) => r#type = Some(v),
Val::Supported(v) => supported = Some(v),
Val::Requires(v) => requires = Some(v),
Val::Platform(v) => platform = Some(v),
Val::Require(v) => require.push(v),
_ => ()
}
}
Ok(Self {
name: name.ok_or_else(|| D::Error::missing_field("name"))?,
number: number.ok_or_else(|| D::Error::missing_field("number"))?,
r#type,
supported: supported.ok_or_else(|| D::Error::missing_field("supported"))?,
requires: requires.unwrap_or_else(Vec::new),
platform,
require
})
}
}
fn deserialize_enums<'de, D: Deserializer<'de>>(deserializer: D) -> Result<KhrEnums, D::Error> {
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum Val {
Name(String),
Type(KhrEnumsType),
Comment(CommentVariant),
Enum {
name: String,
#[serde(flatten)]
value: KhrEnumValue,
comment: Option<String>
},
#[serde(other)]
Other
}
let mut name = None;
let mut r#type = None;
let mut comment = None;
let mut enums = Vec::new();
for e in Vec::<Val>::deserialize(deserializer)? {
match e {
Val::Name(v) => name = Some(v),
Val::Type(v) => r#type = Some(v),
Val::Comment(CommentVariant::Attr(v)) => comment = Some(v),
Val::Comment(CommentVariant::Body(v)) => enums.push(KhrEnumsVariant::Comment(v.value)),
Val::Enum { name, value, comment } => enums.push(
KhrEnumsVariant::Enum { name, value, comment }),
_ => ()
}
}
Ok(KhrEnums {
name: name.ok_or_else(|| D::Error::missing_field("name"))?,
r#type: r#type.unwrap_or(KhrEnumsType::None),
comment,
enums
})
}
/// parses the type of the given value (e.g. 1u32 -> u32) or returns a default type (i32)
pub fn parse_type(s: &str) -> &str {
if s.contains("u128") { "u128" }
else if s.contains("u64") { "u64" }
else if s.contains("u32") { "u32" }
else if s.contains("u16") { "u16" }
else if s.contains("u8") { "u8" }
else if s.contains("i128") { "i128" }
else if s.contains("i64") { "i64" }
else if s.contains("i32") { "i32" }
else if s.contains("i16") { "i16" }
else if s.contains("i8") { "i8" }
else if s.contains("f64") { "f64" }
else if s.contains("f32") { "f32" }
else if s.contains("usize") { "usize" }
else if s.contains("isize") { "isize" }
else if s.contains("char") { "char" }
else if s.starts_with('\"') && s.ends_with('\"') { "&str" }
else if s.starts_with("b\"") && s.ends_with("\\0\".as_ptr()") { "*const u8" }
else { "i32" }
}
/// converts C-types to Rust-types (e.g. uint32_t -> u32)
pub fn convert_c_type(ty: &str, outer: &str) -> String {
#[allow(clippy::never_loop)]
let ty = 'outer: loop {
for (k, v) in C_TYPES.as_ref() {
if *k == ty { break 'outer *v; }
}
break ty;
};
let outer = match outer.trim() {
"*" | "struct*" => "*mut",
"**" | "struct**" => "*mut *mut",
"const*" | "const struct*" => "*const",
"const**" | "const struct**" => "*mut *const",
"const* const*" => "*const *const",
"" | "typedef;" | "()" => return ty.to_string(),
ty if ty.starts_with(':') => {
BITFIELDS.store(true, std::sync::atomic::Ordering::Relaxed);
""
},
r#type => return parse_array(ty, r#type.trim_start_matches("const")),
};
let mut s = String::new();
s.push_str(outer);
s.push(' ');
s.push_str(ty);
s
}
fn parse_array(ty: &str, outer: &str) -> String {
match (outer.strip_prefix('['), outer.find(']')) {
(Some(t), Some(end)) => format!("[{}; {}]", parse_array(ty, &outer[end + 1..]), &t[..end - 1]),
_ => ty.to_string()
}
}
/// converts C-style values to Rust-style values (e.g.: 1ULL -> 1u64)
fn convert_c_value(name: &str) -> String {
if name.starts_with('\"') && name.ends_with('\"') {
let mut name = String::from(name);
name.insert(0, 'b');
name.truncate(name.len() - 1);
name.push_str("\\0\".as_ptr()");
return name;
}
let mut s = String::new();
let mut i = 0;
let name = name.as_bytes();
while i < name.len() {
if name[i] >= b'0' && name[i] <= b'9' {
s.push(name[i] as char);
if name[i + 1..].starts_with(b"ULL") {
s.push_str("u64");
i += 3;
} else if i + 1 < name.len() && name[i + 1] == b'U' {
s.push_str("u32");
i += 1;
} else if i + 1 < name.len() && (name[i + 1] == b'f' || name[i + 1] == b'F') {
s.push_str("f32");
i += 1;
}
} else if i + 1 < name.len() && name[i] == b'~' && name[i + 1] >= b'0' && name[i + 1] <= b'9'{
s.push('!');
} else {
s.push(name[i] as char);
}
i += 1;
}
s
}
/// converts names that contain Rust keywords (e.g.: type -> r#type)
fn convert_name(name: &str) -> String {
match name {
name if KEYWORDS.contains(&name) => format!("r#{}", name),
name => name.to_string()
}
}
static C_TYPES: [(&str, &str); 18] = [
("int8_t", "i8"),
("int16_t", "i16"),
("int32_t", "i32"),
("int64_t", "i64"),
("uint8_t", "u8"),
("uint16_t", "u16"),
("uint32_t", "u32"),
("uint64_t", "u64"),
("float", "f32"),
("double", "f64"),
("size_t", "usize"),
("int", "i32"),
("char", "u8"),
("void", "()"),
("VK_DEFINE_HANDLE", "u64"),
("VK_DEFINE_NON_DISPATCHABLE_HANDLE", "u64"),
("XR_DEFINE_HANDLE", "u64"),
("XR_DEFINE_ATOM", "u64")
];
static KEYWORDS: [&str; 50] = [
"as",
"break",
"const",
"continue",
"crate",
"dyn",
"else",
"enum",
"extern",
"false",
"fn",
"for",
"if",
"impl",
"in",
"let",
"loop",
"match",
"mod",
"move",
"mut",
"pub",
"ref",
"return",
"Self",
"self",
"static",
"struct",
"super",
"trait",
"true",
"type",
"unsafe",
"use",
"where",
"while",
"abstract",
"async",
"become",
"box",
"do",
"final",
"macro",
"override",
"priv",
"try",
"typeof",
"unsized",
"virtual",
"yield"
];
fn get_vk_items() -> Vec<RegistryElement> {
vec![
Macro {
name: "VK_MAKE_VERSION".to_string(),
content: "(major: u32, minor: u32, patch: u32) -> u32 { (major << 22) | (minor << 12) | patch }".to_string()
},
Macro {
name: "VK_VERSION_MAJOR".to_string(),
content: "(version: u32) -> u32 { version >> 22 }".to_string()
},
Macro {
name: "VK_VERSION_MINOR".to_string(),
content: "(version: u32) -> u32 { version >> 12 & 0x3ff }".to_string()
},
Macro {
name: "VK_VERSION_PATCH".to_string(),
content: "(version: u32) -> u32 { version & 0xfff }".to_string()
},
Type(KhrType::FuncPtr(KhrTypeFuncPtr {
name: "PFN_vkInternalAllocationNotification".to_string(),
comment: None,
result: "()".to_string(),
params: vec![
KhrCommandParam { name: "pUserData".to_string(), r#type: "*const u8".to_string(), ..Default::default() },
KhrCommandParam { name: "size".to_string(), r#type: "usize".to_string(), ..Default::default() },
KhrCommandParam { name: "allocationType".to_string(), r#type: "VkInternalAllocationType".to_string(), ..Default::default() },
KhrCommandParam { name: "allocationScope".to_string(), r#type: "VkSystemAllocationScope".to_string(), ..Default::default() }
]
})),
Type(KhrType::FuncPtr(KhrTypeFuncPtr {
name: "PFN_vkInternalFreeNotification".to_string(),
comment: None,
result: "()".to_string(),
params: vec![
KhrCommandParam { name: "pUserData".to_string(), r#type: "*const u8".to_string(), ..Default::default() },
KhrCommandParam { name: "size".to_string(), r#type: "usize".to_string(), ..Default::default() },
KhrCommandParam { name: "allocationType".to_string(), r#type: "VkInternalAllocationType".to_string(), ..Default::default() },
KhrCommandParam { name: "allocationScope".to_string(), r#type: "VkSystemAllocationScope".to_string(), ..Default::default() }
]
})),
Type(KhrType::FuncPtr(KhrTypeFuncPtr {
name: "PFN_vkReallocationFunction".to_string(),
comment: None,
result: "()".to_string(),
params: vec![
KhrCommandParam { name: "pUserData".to_string(), r#type: "*const u8".to_string(), ..Default::default() },
KhrCommandParam { name: "pOriginal".to_string(), r#type: "*const u8".to_string(), ..Default::default() },
KhrCommandParam { name: "size".to_string(), r#type: "usize".to_string(), ..Default::default() },
KhrCommandParam { name: "alignment".to_string(), r#type: "usize".to_string(), ..Default::default() },
KhrCommandParam { name: "allocationScope".to_string(), r#type: "VkSystemAllocationScope".to_string(), ..Default::default() }
]
})),
Type(KhrType::FuncPtr(KhrTypeFuncPtr {
name: "PFN_vkAllocationFunction".to_string(),
comment: None,
result: "()".to_string(),
params: vec![
KhrCommandParam { name: "pUserData".to_string(), r#type: "*const u8".to_string(), ..Default::default() },
KhrCommandParam { name: "size".to_string(), r#type: "usize".to_string(), ..Default::default() },
KhrCommandParam { name: "alignment".to_string(), r#type: "usize".to_string(), ..Default::default() },
KhrCommandParam { name: "allocationScope".to_string(), r#type: "VkSystemAllocationScope".to_string(), ..Default::default() }
]
})),
Type(KhrType::FuncPtr(KhrTypeFuncPtr {
name: "PFN_vkFreeFunction".to_string(),
comment: None,
result: "()".to_string(),
params: vec![
KhrCommandParam { name: "pUserData".to_string(), r#type: "*const u8".to_string(), ..Default::default() },
KhrCommandParam { name: "pMemory".to_string(), r#type: "*const u8".to_string(), ..Default::default() }
]
})),
Type(KhrType::FuncPtr(KhrTypeFuncPtr {
name: "PFN_vkVoidFunction".to_string(),
comment: None,
result: "()".to_string(),
params: Vec::new()
})),
Type(KhrType::FuncPtr(KhrTypeFuncPtr {
name: "PFN_vkDebugReportCallbackEXT".to_string(),
comment: None,
result: "VkBool32".to_string(),
params: vec![
KhrCommandParam { name: "flags".to_string(), r#type: "VkDebugReportFlagsEXT".to_string(), ..Default::default() },
KhrCommandParam { name: "objectType".to_string(), r#type: "VkDebugReportObjectTypeEXT".to_string(), ..Default::default() },
KhrCommandParam { name: "object".to_string(), r#type: "u64".to_string(), ..Default::default() },
KhrCommandParam { name: "location".to_string(), r#type: "usize".to_string(), ..Default::default() },
KhrCommandParam { name: "messageCode".to_string(), r#type: "i32".to_string(), ..Default::default() },
KhrCommandParam { name: "pLayerPrefix".to_string(), r#type: "*const u8".to_string(), ..Default::default() },
KhrCommandParam { name: "pMessage".to_string(), r#type: "*const u8".to_string(), ..Default::default() },
KhrCommandParam { name: "pUserData".to_string(), r#type: "*const u8".to_string(), ..Default::default() }
]
})),
Type(KhrType::FuncPtr(KhrTypeFuncPtr {
name: "PFN_vkDebugUtilsMessengerCallbackEXT".to_string(),
comment: None,
result: "VkBool32".to_string(),
params: vec![KhrCommandParam { name: "messageSeverity".to_string(), r#type: "VkDebugUtilsMessageSeverityFlagBitsEXT".to_string(), ..Default::default() },
KhrCommandParam { name: "messageTypes".to_string(), r#type: "VkDebugUtilsMessageTypeFlagsEXT".to_string(), ..Default::default() },
KhrCommandParam { name: "pCallbackData".to_string(), r#type: "*const VkDebugUtilsMessengerCallbackDataEXT".to_string(), ..Default::default() },
KhrCommandParam { name: "pUserData".to_string(), r#type: "*const u8".to_string(), ..Default::default() }]
})),
Type(KhrType::FuncPtr(KhrTypeFuncPtr {
name: "PFN_vkDeviceMemoryReportCallbackEXT".to_string(),
comment: None,
result: "()".to_string(),
params: vec![
KhrCommandParam { name: "pCallbackData".to_string(), r#type: "*const VkDeviceMemoryReportCallbackDataEXT".to_string(), ..Default::default() },
KhrCommandParam { name: "pUserData".to_string(), r#type: "*mut u8".to_string(), ..Default::default() }
]
}))
]
}
fn get_xr_items() -> Vec<RegistryElement> {
vec![
Macro {
name: "XR_MAKE_VERSION".to_string(),
content: "(major: u64, minor: u64, patch: u64) -> XrVersion { (major & 0xffff << 48) | (minor & 0xffff << 32) | (patch & 0xffffffff) }".to_string()
},
Macro {
name: "XR_VERSION_MAJOR".to_string(),
content: "(version: XrVersion) -> u64 { version >> 48 & 0xffff }".to_string()
},
Macro {
name: "XR_VERSION_MINOR".to_string(),
content: "(version: XrVersion) -> u64 { version >> 32 & 0xffff }".to_string()
},
Macro {
name: "XR_VERSION_PATCH".to_string(),
content: "(version: XrVersion) -> u64 { version & 0xffffffff }".to_string()
},
Macro {
name: "XR_SUCCEEDED".to_string(),
content: "(result: XrResult) -> bool { result as i32 >= 0 }".to_string()
},
Macro {
name: "XR_UNQUALIFIED_SUCCESS".to_string(),
content: "(result: XrResult) -> bool { result as i32 == 0 }".to_string()
},
Macro {
name: "XR_FAILED".to_string(),
content: "(result: XrResult) -> bool { (result as i32) < 0 }".to_string()
},
Type(KhrType::FuncPtr(KhrTypeFuncPtr {
name: "PFN_xrVoidFunction".to_string(),
comment: None,
result: "()".to_string(),
params: Vec::new()
})),
Type(KhrType::FuncPtr(KhrTypeFuncPtr {
name: "PFN_xrDebugUtilsMessengerCallbackEXT".to_string(),
comment: None,
result: "XrBool32".to_string(),
params: vec![
KhrCommandParam { r#type: "XrDebugUtilsMessageSeverityFlagsEXT".to_string(), name: "messageSeverity".to_string(), ..Default::default() },
KhrCommandParam { r#type: "XrDebugUtilsMessageTypeFlagsEXT".to_string(), name: "messageTypes".to_string(), ..Default::default() },
KhrCommandParam { r#type: "*const XrDebugUtilsMessengerCallbackDataEXT".to_string(), name: "callbackData".to_string(), ..Default::default() },
KhrCommandParam { r#type: "*const u8".to_string(), name: "pUserData".to_string(), ..Default::default() },
]
})),
]
}
|
#[derive(Debug)]
pub enum TagNum {
BenchmarkCurveCurrency => 220,
AggregatedBook => 266,
DefOfferSize => 294,
ContractMultiplier => 231,
DeliverToCompID => 128,
DeleteReason => 285,
TaxAdvantageType => 495,
NoDates => 580,
OfferForwardPoints => 191,
TransactTime => 60,
SettlCurrFxRate => 155,
LegCFICode => 608,
UnderlyingMaturityDate => 542,
OnBehalfOfCompID => 115,
EffectiveTime => 168,
LegFutSettDate => 588,
CardIssNo => 491,
CashSettlAgentContactPhone => 187,
PriorityIndicator => 638,
Password => 554,
SecuritySettlAgentName => 176,
QuoteResponseLevel => 301,
UnderlyingMaturityMonthYear => 313,
EncodedUnderlyingSecurityDesc => 365,
TradeInputSource => 578,
TotNoOrders => 68,
OrderQty => 38,
AllocQty => 80,
LegSettlmntTyp => 587,
SymbolSfx => 65,
CashSettlAgentName => 182,
DeliverToSubID => 129,
Currency => 15,
CashDistribPayRef => 501,
LegSecurityAltID => 605,
UnderlyingSecurityAltIDSource => 459,
QuoteCondition => 276,
MDReqRejReason => 281,
Quantity => 53,
NoMiscFees => 136,
RefSeqNum => 45,
Subject => 147,
AllocRejCode => 88,
MoneyLaunderingStatus => 481,
RegistEmail => 511,
CorporateAction => 292,
LegPrice => 566,
UnderlyingSymbolSfx => 312,
OrderID => 37,
NumDaysInterest => 157,
LegSymbol => 600,
MarketDepth => 264,
SettlInstMode => 160,
OfferSpotRate => 190,
FutSettDate => 64,
UnderlyingPutOrCall => 315,
MDUpdateAction => 279,
ListOrderStatus => 431,
MDImplicitDelete => 547,
AffectedOrderID => 535,
OnBehalfOfSendingTime => 370,
LiquidityPctHigh => 403,
HopSendingTime => 629,
EncodedText => 355,
LegCoveredOrUncovered => 565,
RFQReqID => 644,
UnderlyingLastQty => 652,
CumQty => 14,
EncodedSubjectLen => 356,
LiquidityPctLow => 402,
DayBookingInst => 589,
FundRenewWaiv => 497,
StandInstDbID => 171,
Commission => 12,
UnderlyingIssuer => 306,
ListName => 392,
IOITransType => 28,
UnderlyingSecurityID => 309,
StipulationValue => 234,
NoPartyIDs => 453,
NoMDEntries => 268,
PaymentMethod => 492,
RegistID => 513,
CardHolderName => 488,
NestedPartyIDSource => 525,
MultiLegRptTypeReq => 563,
PartySubID => 523,
OwnerType => 522,
SettlCurrOfferFxRate => 657,
PossDupFlag => 43,
BusinessRejectRefID => 379,
OrderCapacity => 528,
NestedPartyID => 524,
OfferSize => 135,
RoundLot => 561,
NoLegSecurityAltID => 604,
OwnershipType => 517,
QuoteReqID => 131,
RptSeq => 83,
SecuritySettlAgentContactPhone => 181,
StrikePrice => 202,
EndSeqNo => 16,
EncodedListExecInstLen => 352,
MinTradeVol => 562,
MassCancelResponse => 531,
LegCurrency => 556,
BasisFeaturePrice => 260,
BidDescriptorType => 399,
MsgSeqNum => 34,
MailingInst => 482,
QuoteRequestRejectReason => 658,
NoDistribInsts => 510,
URLLink => 149,
GTBookingInst => 427,
UnderlyingSecurityAltID => 458,
ResetSeqNumFlag => 141,
PositionEffect => 77,
PegDifference => 211,
MaxFloor => 111,
AllocLinkType => 197,
Symbol => 55,
OfferForwardPoints2 => 643,
SecurityID => 48,
ExecType => 150,
UnderlyingRepoCollateralSecurityType => 243,
QuantityType => 465,
TradSesMode => 339,
DistribPaymentMethod => 477,
DeliverToLocationID => 145,
NoHops => 627,
SecurityListRequestType => 559,
LegSide => 624,
LegCountryOfIssue => 596,
TotalAffectedOrders => 533,
MDUpdateType => 265,
SecondaryExecID => 527,
CreditRating => 255,
CardNumber => 489,
MinBidSize => 647,
CashSettlAgentAcctName => 185,
RefMsgType => 372,
SellVolume => 331,
DayAvgPx => 426,
AllocAccount => 79,
BidForwardPoints => 189,
OfferPx => 133,
StandInstDbName => 170,
NoQuoteEntries => 295,
RoutingID => 217,
ClOrdLinkID => 583,
NoNestedPartyIDs => 539,
NestedPartyRole => 538,
NoAllocs => 78,
MaxShow => 210,
CountryOfIssue => 470,
SettlInstCode => 175,
Urgency => 61,
ListExecInstType => 433,
SecuritySettlAgentCode => 177,
CrossPercent => 413,
LegRepurchaseTerm => 251,
DiscretionInst => 388,
UnderlyingRepurchaseRate => 245,
OutMainCntryUIndex => 412,
AllocAvgPx => 153,
CashSettlAgentContactName => 186,
MktOfferPx => 646,
LegSecurityIDSource => 603,
CrossPrioritization => 550,
SettlDeliveryType => 172,
PossResend => 97,
DiscretionOffset => 389,
OptAttribute => 206,
SecuritySettlAgentContactName => 180,
EmailThreadID => 164,
TickDirection => 274,
TradSesOpenTime => 342,
SettlInstID => 162,
NoContraBrokers => 382,
FairValue => 406,
CommCurrency => 479,
HopCompID => 628,
NoOrders => 73,
InViewOfCommon => 328,
OrigTime => 42,
ContraLegRefID => 655,
QuoteSetID => 302,
Issuer => 106,
NumberOfOrders => 346,
Price => 44,
SellerDays => 287,
SubscriptionRequestType => 263,
DayCumQty => 425,
MiscFeeCurr => 138,
BasisFeatureDate => 259,
MDEntryBuyer => 288,
TradSesEndTime => 345,
EncodedSubject => 357,
ContraTrader => 337,
TradSesStatusRejReason => 567,
LegMaturityMonthYear => 610,
CashDistribCurr => 478,
ExecValuationPoint => 515,
TradeType => 418,
NoRegistDtls => 473,
OrdRejReason => 103,
TradeOriginationDate => 229,
AccountType => 581,
UnderlyingCountryOfIssue => 592,
NoSecurityTypes => 558,
Account => 1,
Adjustment => 334,
BidYield => 632,
ClearingFeeIndicator => 635,
BodyLength => 9,
SecurityResponseType => 323,
UnderlyingInstrRegistry => 595,
LastMkt => 30,
Signature => 89,
AdvTransType => 5,
EmailType => 94,
NoTradingSessions => 386,
UnderlyingRedemptionDate => 247,
ExecInst => 18,
ProgPeriodInterval => 415,
NoStrikes => 428,
MsgDirection => 385,
EncodedIssuerLen => 348,
UnderlyingLocaleOfIssue => 594,
UnderlyingCouponPaymentDate => 241,
LegPositionEffect => 564,
ContraBroker => 375,
FutSettDate2 => 193,
LegIssueDate => 249,
LegCreditRating => 257,
TradSesStatus => 340,
ClOrdID => 11,
BidForwardPoints2 => 642,
CxlRejReason => 102,
LegFactor => 253,
CrossID => 548,
TradeReportTransType => 487,
NoContAmts => 518,
SecurityRequestResult => 560,
HeartBtInt => 108,
CheckSum => 10,
ExecPriceAdjustment => 485,
ReportToExch => 113,
SecurityRequestType => 321,
LegalConfirm => 650,
GapFillFlag => 123,
EncodedLegIssuerLen => 618,
MDEntryType => 269,
MDEntryTime => 273,
NoStipulations => 232,
UnderlyingStrikePrice => 316,
FinancialStatus => 291,
ClientBidID => 391,
NoMsgTypes => 384,
Headline => 148,
RedemptionDate => 240,
LiquidityNumSecurities => 441,
AdvId => 2,
PriceType => 423,
Scope => 546,
TargetSubID => 57,
UnderlyingRepurchaseTerm => 244,
NumBidders => 417,
UnderlyingSecurityExchange => 308,
ListExecInst => 69,
SenderLocationID => 142,
TradeRequestType => 569,
TargetLocationID => 143,
RoutingType => 216,
MDEntrySeller => 289,
ExecRestatementReason => 378,
LocateReqd => 114,
Spread => 218,
Price2 => 640,
Concession => 238,
LiquidityIndType => 409,
AdvRefID => 3,
MassCancelRejectReason => 532,
ExecID => 17,
InvestorCountryOfResidence => 475,
ContAmtCurr => 521,
OrigCrossID => 551,
CustOrderCapacity => 582,
StandInstDbType => 169,
CardStartDate => 503,
ProcessCode => 81,
ExDate => 230,
MassCancelRequestType => 530,
TargetCompID => 56,
LegLastPx => 637,
AvgPrxPrecision => 74,
SettlBrkrCode => 174,
CashDistribAgentAcctNumber => 500,
LeavesQty => 151,
LegRefID => 654,
CardExpDate => 490,
UnderlyingSymbol => 311,
LegRepurchaseRate => 252,
StipulationType => 233,
TotalNumSecurityTypes => 557,
DistribPercentage => 512,
UnsolicitedIndicator => 325,
MDEntryPositionNo => 290,
PartyID => 448,
AllocID => 70,
NotifyBrokerOfCredit => 208,
LegContractMultiplier => 614,
MDEntryOriginator => 282,
UnderlyingSecurityIDSource => 305,
MaturityMonthYear => 200,
InstrRegistry => 543,
TotalVolumeTradedTime => 450,
MDEntryRefID => 280,
MiscFeeType => 139,
AvgPx => 6,
CashDistribAgentCode => 499,
AllocHandlInst => 209,
BenchmarkCurveName => 221,
Benchmark => 219,
NoSecurityAltID => 454,
AccruedInterestAmt => 159,
IssueDate => 225,
OrigClOrdID => 41,
NoRelatedSym => 146,
LinesOfText => 33,
HighPx => 332,
DateOfBirth => 486,
PreviouslyReported => 570,
ExchangeForPhysical => 411,
EncodedUnderlyingSecurityDescLen => 364,
Rule80A => 47,
CxlRejResponseTo => 434,
SecureData => 91,
LegRatioQty => 623,
CancellationRights => 480,
ExpireTime => 126,
CashDistribAgentName => 498,
TradSesMethod => 338,
LegStrikePrice => 612,
UnderlyingContractMultiplier => 436,
ValueOfFutures => 408,
QuoteType => 537,
IOIQltyInd => 25,
LegProduct => 607,
TradSesReqID => 335,
SettlDepositoryCode => 173,
UnderlyingSecurityDesc => 307,
OnBehalfOfSubID => 116,
OrdStatus => 39,
LastForwardPoints => 195,
NoAffectedOrders => 534,
ContraTradeTime => 438,
BuyVolume => 330,
AllocType => 626,
TotQuoteEntries => 304,
BusinessRejectReason => 380,
Factor => 228,
EncodedListStatusText => 446,
LegLocaleOfIssue => 598,
IOINaturalFlag => 130,
NoIOIQualifiers => 199,
QuoteSetValidUntilTime => 367,
SecurityTradingStatus => 326,
PaymentDate => 504,
ListStatusType => 429,
TradeRequestID => 568,
TotalVolumeTradedDate => 449,
BookingUnit => 590,
MDEntrySize => 271,
SecurityIDSource => 22,
ForexReq => 121,
BeginString => 8,
TradeDate => 75,
StopPx => 99,
WorkingIndicator => 636,
CashSettlAgentCode => 183,
CashOrderQty => 152,
BidDescriptor => 400,
MassStatusReqType => 585,
LastForwardPoints2 => 641,
TradeInputDevice => 579,
MktBidPx => 645,
EncodedUnderlyingIssuerLen => 362,
CommType => 13,
TradSesCloseTime => 344,
RawDataLength => 95,
QuoteStatusReqID => 649,
DueToRelated => 329,
TradeReportID => 571,
SettlCurrBidFxRate => 656,
OrderPercent => 516,
CoveredOrUncovered => 203,
SideValue1 => 396,
Product => 460,
QuoteID => 117,
RefAllocID => 72,
UnderlyingCreditRating => 256,
NoSides => 552,
SettlmntTyp => 63,
SettlCurrAmt => 119,
TradingSessionID => 336,
LegSecurityDesc => 620,
LegSecurityType => 609,
NewSeqNo => 36,
RawData => 96,
SenderCompID => 49,
SettlInstSource => 165,
ClearingInstruction => 577,
MidPx => 631,
IncTaxInd => 416,
LastSpotRate => 194,
OrigSendingTime => 122,
BasisPxType => 419,
MDEntryPx => 270,
LegSymbolSfx => 601,
OrigOrdModTime => 586,
TestMessageIndicator => 464,
TradSesStartTime => 341,
TradSesPreCloseTime => 343,
MassStatusReqID => 584,
Yield => 236,
ContraTradeQty => 437,
ValidUntilTime => 62,
ListSeqNo => 67,
CashMargin => 544,
IOIid => 23,
EncryptMethod => 98,
RoundingDirection => 468,
EncodedSecurityDescLen => 350,
RegistTransType => 514,
RoundingModulus => 469,
CashSettlAgentAcctNum => 184,
LegSecurityID => 602,
LastQty => 32,
BidID => 390,
MultiLegReportingType => 442,
LegRepoCollateralSecurityType => 250,
TransBkdTime => 483,
EFPTrackingError => 405,
EncodedLegSecurityDescLen => 621,
PrevClosePx => 140,
LastCapacity => 29,
ExpireDate => 432,
LegOptAttribute => 613,
TradedFlatSwitch => 258,
NoUnderlyingSecurityAltID => 457,
PreallocMethod => 591,
OutsideIndexPct => 407,
DeskID => 284,
TimeInForce => 59,
TradingSessionSubID => 625,
LegMaturityDate => 611,
EncodedUnderlyingIssuer => 363,
NoQuoteSets => 296,
LegRedemptionDate => 254,
UnderlyingOptAttribute => 317,
SessionRejectReason => 373,
EncodedListExecInst => 353,
LegIssuer => 617,
MsgType => 35,
Country => 421,
MatchType => 574,
AllocLinkID => 196,
HopRefID => 630,
TotNoStrikes => 422,
TotalNumSecurities => 393,
SecurityDesc => 107,
Username => 553,
SecurityAltID => 455,
LegInstrRegistry => 599,
IOIRefID => 26,
SideValueInd => 401,
MatchStatus => 573,
RepurchaseTerm => 226,
NumTickets => 395,
SettlInstRefID => 214,
ComplianceID => 376,
SecondaryClOrdID => 526,
BidType => 394,
NoBidComponents => 420,
LegCouponPaymentDate => 248,
NoRoutingIDs => 215,
DKReason => 127,
BookingRefID => 466,
AffectedSecondaryOrderID => 536,
OrderRestrictions => 529,
OfferYield => 634,
MiscFeeAmt => 137,
ProgRptReqs => 414,
TradeReportRefID => 572,
UnderlyingLastPx => 651,
SettlCurrency => 120,
EncodedHeadline => 359,
ContAmtValue => 520,
MDEntryID => 278,
RepoCollateralSecurityType => 239,
BeginSeqNo => 7,
XmlDataLen => 212,
EncodedLegSecurityDesc => 622,
SignatureLength => 93,
SenderSubID => 50,
RepurchaseRate => 227,
SecuritySettlAgentAcctName => 179,
IOIQualifier => 104,
CouponRate => 223,
QuoteCancelType => 298,
TradeCondition => 277,
NetMoney => 118,
CrossType => 549,
PaymentRemitterID => 505,
PartyRole => 452,
NetGrossInd => 430,
RegistRejReasonCode => 507,
MDEntryDate => 272,
LegSecurityAltIDSource => 606,
MailingDtls => 474,
SendingTime => 52,
EncodedIssuer => 349,
AllocTransType => 71,
SolicitedFlag => 377,
XmlData => 213,
EncodedSecurityDesc => 351,
BidSize => 134,
PriceImprovement => 639,
TotalTakedown => 237,
SecurityType => 167,
ListStatusText => 444,
OnBehalfOfLocationID => 144,
MessageEncoding => 347,
PaymentRef => 476,
SecurityAltIDSource => 456,
MidYield => 633,
RegistRejReasonText => 496,
MaturityDate => 541,
RegistStatus => 506,
AllocStatus => 87,
UnderlyingProduct => 462,
StateOrProvinceOfIssue => 471,
OpenCloseSettleFlag => 286,
DayOrderQty => 424,
AccruedInterestRate => 158,
EncodedTextLen => 354,
RegistAcctType => 493,
SecurityStatusReqID => 324,
OrdType => 40,
UnderlyingStateOrProvinceOfIssue => 593,
NoExecs => 124,
SecurityResponseID => 322,
EncodedHeadlineLen => 358,
LegCouponRate => 615,
NestedPartySubID => 545,
HaltReasonChar => 327,
YieldType => 235,
ListID => 66,
SecurityReqID => 320,
GrossTradeAmt => 381,
LegStateOrProvinceOfIssue => 597,
DefBidSize => 293,
EncodedAllocTextLen => 360,
MaxMessageSize => 383,
SettlCurrFxRateCalc => 156,
UnderlyingCouponRate => 435,
RegistDetls => 509,
AllocText => 161,
LocaleOfIssue => 472,
LegSecurityExchange => 616,
EncodedAllocText => 361,
PartyIDSource => 447,
ExDestination => 100,
SecurityExchange => 207,
QuoteRequestType => 303,
IOIQty => 27,
BenchmarkCurvePoint => 222,
BidSpotRate => 188,
TotalAccruedInterestAmt => 540,
NoLegs => 555,
MinOfferSize => 648,
NoMDEntryTypes => 267,
CxlQty => 84,
ExecPriceType => 484,
TestReqID => 112,
BidPx => 132,
SideComplianceID => 659,
NetChgPrevDay => 451,
QuoteEntryRejectReason => 368,
SecondaryOrderID => 198,
SideValue2 => 397,
UnderlyingSecurityType => 310,
NoRpts => 82,
UnderlyingCFICode => 463,
MDMkt => 275,
QuoteEntryID => 299,
LocationID => 283,
NoBidDescriptors => 398,
CouponPaymentDate => 224,
Text => 58,
WtAverageLiquidity => 410,
QuoteRejectReason => 300,
LastMsgSeqNumProcessed => 369,
StrikeTime => 443,
EncodedLegIssuer => 619,
EncodedListStatusTextLen => 445,
MDReqID => 262,
RegistRefID => 508,
Designation => 494,
UnderlyingIssueDate => 242,
IndividualAllocID => 467,
NoClearingInstructions => 576,
BidRequestTransType => 374,
SecuritySettlAgentAcctNum => 178,
SecureDataLen => 90,
LiquidityValue => 404,
AllocPrice => 366,
QuoteStatus => 297,
ExecRefID => 19,
CFICode => 461,
MinQty => 110,
SettlInstTransType => 163,
TotalVolumeTraded => 387,
RefTagID => 371,
UnderlyingFactor => 246,
LowPx => 333,
Side => 54,
ContAmtType => 519,
AdvSide => 4,
AllocNetMoney => 154,
OrderQty2 => 192,
HandlInst => 21,
OddLot => 575,
LastPx => 31,
} |
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::num::ParseIntError;
use std::str::FromStr;
#[derive(Debug)]
struct Point {
x: isize,
y: isize,
}
impl FromStr for Point {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let coords : Vec<&str> = s.trim_matches(|p| p == '(' || p == ')').split(',').collect();
let x = coords[0].parse::<isize>()?;
let y = coords[1].parse::<isize>()?;
Ok(Point { x: x, y: y})
}
}
fn main() {
// Process the file
let args: Vec<String> = env::args().collect();
if args.len() == 1 {
eprintln!("Please to set a file name");
std::process::exit(1);
}
let f_pointer = File::open(&args[1]).expect(
"Unable to open
the given file",
);
let f_lines: Vec<String> = BufReader::new(f_pointer)
.lines()
.map(|line| line.unwrap())
.collect();
let points: Vec<Point> = f_lines
.iter()
.map(|l| Point::from_str(l).ok().unwrap())
.collect();
}
|
use heck::*;
use proc_macro2::Span;
use quote::{quote, ToTokens};
use syn::Ident;
pub struct AsInto<'a> {
pub ident_camel: &'a Ident,
}
impl<'a> ToTokens for AsInto<'a> {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let ident = &self.ident_camel;
let as_ident = Ident::new(&format!("as_{}", ident).to_snake_case(), Span::call_site());
let as_ident_mut = Ident::new(&format!("as_{}_mut", ident).to_snake_case(), Span::call_site());
let into_ident = Ident::new(&format!("into_{}", ident).to_snake_case(), Span::call_site());
let expr = quote! {
fn #as_ident(&self) -> &dyn #ident;
fn #as_ident_mut(&mut self) -> &mut dyn #ident;
fn #into_ident(self: Box<Self>) -> Box<dyn #ident>;
};
expr.to_tokens(tokens)
}
}
|
use crate::Todo;
use seed::{*, prelude::*};
use crate::messages::{Msg, StateChangeMessage};
//The single todo item
pub struct TodoItemComponent;
impl TodoItemComponent {
pub fn view_with_props(todo: &Todo) -> Node<Msg> {
div![
class!("todo_item"),
div![
class!("todo_item_left"),
format!("{}", todo.title)
],
div![
class!("todo_item_right"),
i![
simple_ev(Ev::Click, Msg::StateChange(StateChangeMessage::RemoveTodo(todo.index))),
class!("fas fa-times")
],
]
]
}
}
|
use super::car::*;
use super::primitives::*;
use super::sim_id::*;
use cgmath::*;
use conrod::color::*;
use piston::input::{Button, Key};
use rand::*;
use std::boxed::Box;
use std::collections::HashSet;
#[macro_use]
use std::time;
use super::debouncer::*;
use std::collections::HashMap;
pub struct VehicleManagerKeyMapping {
key_action_map: HashMap<piston_window::Key, Box<Debouncer<VehicleManager>>>
}
pub struct VehicleManager {
// non playable vehicles
id_provider: Box<IdProvider>,
non_playable_vehicles: Vec<Car>,
protagonist_vehicle: Car,
last_spawn_time: time::Instant,
}
impl VehicleManagerKeyMapping {
pub fn new() -> VehicleManagerKeyMapping {
let mut key_action_map: HashMap<
piston_window::Key,
Box<Debouncer<VehicleManager>>,
> = HashMap::new();
let debouncer_k: Debouncer<VehicleManager> =
Debouncer::from_millis(200, |mgr: &mut VehicleManager| {
mgr.spawn_random_close_to_protagonist();
});
let debouncer_space: Debouncer<VehicleManager> =
Debouncer::from_millis(200, |mgr: &mut VehicleManager| {
mgr.toggle_cars_movement();
});
let debouncer_k_box = Box::new(debouncer_k);
let debouncer_space_box = Box::new(debouncer_space);
key_action_map.insert(piston_window::Key::K, debouncer_k_box);
key_action_map.insert(piston_window::Key::Space, debouncer_space_box);
VehicleManagerKeyMapping {
key_action_map: key_action_map
}
}
}
impl VehicleManager {
pub fn get_non_playable_vehicles(&self) -> &Vec<Car> {
&self.non_playable_vehicles
}
pub fn get_protagonist_vehicle(&self) -> &Car {
&self.protagonist_vehicle
}
pub fn new(mut id_provider: Box<IdProvider>) -> VehicleManager {
let protagonist_car = Car {
id: id_provider.next(),
pose: Pose2DF64 {
center: Point2f64 { x: 0.0, y: 0.0 },
yaw: 0.0,
},
//longitudinal_speed: 10.0,
longitudinal_speed: 0.0,
yaw_rate: 0.0,
bb_size: Size2f64::new(1.5, 3.0),
color: rgb(1.0, 0.0, 1.0),
};
let vehicle_manager = VehicleManager {
id_provider: id_provider,
non_playable_vehicles: Vec::new(),
protagonist_vehicle: protagonist_car,
last_spawn_time: time::Instant::now()
};
vehicle_manager
}
pub fn process_buttons(&mut self, vehicle_manager_key_mappings : &mut VehicleManagerKeyMapping,
buttons: &HashSet<piston_window::Button>) {
if buttons.contains( &piston_window::Button::Keyboard(piston_window::Key::K) ) {
let action = vehicle_manager_key_mappings.key_action_map.get_mut(&piston_window::Key::K);
action.unwrap().debounce(self);
}
if buttons.contains( &piston_window::Button::Keyboard(piston_window::Key::C) ) {
self.non_playable_vehicles.clear();
}
if buttons.contains( &piston_window::Button::Keyboard(piston_window::Key::W) ) {
//self.protagonist_vehicle.longitudinal_speed += 0.1;
self.protagonist_vehicle.pose.center.x += 0.1*self.protagonist_vehicle.pose.yaw.cos();
self.protagonist_vehicle.pose.center.y += 0.1*self.protagonist_vehicle.pose.yaw.sin();
}
if buttons.contains( &piston_window::Button::Keyboard(piston_window::Key::S) ) {
self.protagonist_vehicle.pose.center.x -= 0.1*self.protagonist_vehicle.pose.yaw.cos();
self.protagonist_vehicle.pose.center.y -= 0.1*self.protagonist_vehicle.pose.yaw.sin();
}
if buttons.contains( &piston_window::Button::Keyboard(piston_window::Key::A) ) {
self.protagonist_vehicle.pose.yaw += 0.05;
}
if buttons.contains( &piston_window::Button::Keyboard(piston_window::Key::D) ) {
self.protagonist_vehicle.pose.yaw -= 0.05;
}
if buttons.contains( &piston_window::Button::Keyboard(piston_window::Key::Space) ) {
let action = vehicle_manager_key_mappings.key_action_map.get_mut(&piston_window::Key::Space);
action.unwrap().debounce(self);
}
}
pub fn set_protagonist_speed(speed: f64, yawrate: f64) {
}
pub fn spawn_random_close_to_protagonist(&mut self) {
let mut new_car = random_car(&mut *self.id_provider);
let protagonist_trasl = self.protagonist_vehicle.pose.center;
let mut new_car_pose = Pose2DF64::default();
new_car_pose.center.x = protagonist_trasl.x + thread_rng().gen_range(10.0, 20.0);
new_car_pose.center.y = protagonist_trasl.y + thread_rng().gen_range(-20.0, 20.0);
let protagonist_ds = protagonist_trasl - new_car_pose.center;
let angle = Vec2f64::unit_x().angle(protagonist_ds);
new_car_pose.yaw = std::f64::consts::PI / 2.0 * angle.sin().signum() + thread_rng().gen_range(-1.0, 1.0);
new_car.pose = new_car_pose;
self.non_playable_vehicles.push(new_car);
self.last_spawn_time = time::Instant::now();
}
pub fn toggle_cars_movement(&mut self) {
for car in &mut self.non_playable_vehicles {
if car.longitudinal_speed > 0.0 {
car.longitudinal_speed = 0.0;
car.yaw_rate = 0.0
}
else {
car.longitudinal_speed = 10.0;
car.yaw_rate = 0.01;
}
}
}
pub fn update(&mut self, dt_s: f32) {
let protagonist_car_center = self.protagonist_vehicle.pose.center;
self.non_playable_vehicles.retain(|vehicle| vehicle.pose.center.distance(protagonist_car_center) < 1.0e3);
&mut self.protagonist_vehicle.update(dt_s);
for car in &mut self.non_playable_vehicles {
car.update(dt_s);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_constructor() {
let mut id_provider = Box::new(IdProvider::new());
let vehicle_manager = VehicleManager::new(id_provider);
assert_eq!(0, vehicle_manager.non_playable_vehicles.len());
}
#[test]
fn spawn_one_car() {
let mut id_provider = Box::new(IdProvider::new());
let mut vehicle_manager = VehicleManager::new(id_provider);
vehicle_manager.spawn_random_close_to_protagonist();
assert_eq!(1, vehicle_manager.non_playable_vehicles.len());
}
}
|
use svm_types::Address;
use crate::{impl_from_svm_byte_array, impl_into_svm_byte_array};
impl_from_svm_byte_array!(Address);
impl_into_svm_byte_array!(Address);
|
#[doc = "Reader of register HOST_DMA_ENBL"]
pub type R = crate::R<u32, super::HOST_DMA_ENBL>;
#[doc = "Writer for register HOST_DMA_ENBL"]
pub type W = crate::W<u32, super::HOST_DMA_ENBL>;
#[doc = "Register HOST_DMA_ENBL `reset()`'s with value 0"]
impl crate::ResetValue for super::HOST_DMA_ENBL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `DM_EP1DRQE`"]
pub type DM_EP1DRQE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DM_EP1DRQE`"]
pub struct DM_EP1DRQE_W<'a> {
w: &'a mut W,
}
impl<'a> DM_EP1DRQE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `DM_EP2DRQE`"]
pub type DM_EP2DRQE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DM_EP2DRQE`"]
pub struct DM_EP2DRQE_W<'a> {
w: &'a mut W,
}
impl<'a> DM_EP2DRQE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
impl R {
#[doc = "Bit 2 - This bit enables DMA Request by EP1DRQ. '0' : Disable '1' : Enable"]
#[inline(always)]
pub fn dm_ep1drqe(&self) -> DM_EP1DRQE_R {
DM_EP1DRQE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - This bit enables DMA Request by EP2DRQ. '0' : Disable '1' : Enable"]
#[inline(always)]
pub fn dm_ep2drqe(&self) -> DM_EP2DRQE_R {
DM_EP2DRQE_R::new(((self.bits >> 3) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 2 - This bit enables DMA Request by EP1DRQ. '0' : Disable '1' : Enable"]
#[inline(always)]
pub fn dm_ep1drqe(&mut self) -> DM_EP1DRQE_W {
DM_EP1DRQE_W { w: self }
}
#[doc = "Bit 3 - This bit enables DMA Request by EP2DRQ. '0' : Disable '1' : Enable"]
#[inline(always)]
pub fn dm_ep2drqe(&mut self) -> DM_EP2DRQE_W {
DM_EP2DRQE_W { w: self }
}
}
|
// 2019-01-01
// On veut à nouveau calculer la longueur d'une chaine de caractères.
// Seulement, on va chercher à ne pas prendre l'ownership de la variable.
// Pour agrémenter le game, j'ai rajouté une invite à l'utilisateur.
// importer la bibliothèque entrée/sortie
use std::io;
fn main() {
println!("Tapez une chaîne de caractères !");
// Définir la variable s1 comme une chaîne de caractères
let mut s1 = String::new();
// récupérer l'entrée tapée par l'utilisateur dans la variable s1
io::stdin()
.read_line(&mut s1)
.expect("Pas pu lire l'entrée");
// Ici il faut encore nettoyer la variable pour enlever le retour à la ligne.
// Appel de la fonction calcule_longueur()
let len = calcule_longueur(&s1);
println!("La longueur de la chaîne '{}' est de {} caractères.", s1, len);
}
// Contrairement au programme ownership_length, on ne renvoie pas la variable.
// La variable n'est qu'empruntée.
// L'input est défini entre parenthèse. Il s'appelle s, c'est une chaîne.
// L'ampersand fait de s une RÉFÉRENCE qui pointera vers s1
// L'output est un entier positif. usize signifie u64 pour une archi 64 bits
fn calcule_longueur(s: &String) -> usize {
// la fonction len() calcule et retourne la longueur de s
s.len()
} // On sort du scope, s est dropé, mais pas s1
|
// This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4)
// from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70)
// DO NOT EDIT
use SocketConnection;
use SocketListener;
use SocketService;
use ffi;
use glib;
use glib::StaticType;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::boxed::Box as Box_;
use std::mem;
use std::mem::transmute;
use std::ptr;
glib_wrapper! {
pub struct ThreadedSocketService(Object<ffi::GThreadedSocketService, ffi::GThreadedSocketServiceClass>): SocketService, SocketListener;
match fn {
get_type => || ffi::g_threaded_socket_service_get_type(),
}
}
impl ThreadedSocketService {
pub fn new(max_threads: i32) -> ThreadedSocketService {
unsafe {
SocketService::from_glib_full(ffi::g_threaded_socket_service_new(max_threads)).downcast_unchecked()
}
}
}
pub trait ThreadedSocketServiceExt {
fn get_property_max_threads(&self) -> i32;
fn connect_run<F: Fn(&Self, &SocketConnection, &glib::Object) -> bool + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_max_threads_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<ThreadedSocketService> + IsA<glib::object::Object>> ThreadedSocketServiceExt for O {
fn get_property_max_threads(&self) -> i32 {
unsafe {
let mut value = Value::from_type(<i32 as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "max-threads".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn connect_run<F: Fn(&Self, &SocketConnection, &glib::Object) -> bool + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self, &SocketConnection, &glib::Object) -> bool + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "run",
transmute(run_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_max_threads_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::max-threads",
transmute(notify_max_threads_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
}
unsafe extern "C" fn run_trampoline<P>(this: *mut ffi::GThreadedSocketService, connection: *mut ffi::GSocketConnection, source_object: *mut gobject_ffi::GObject, f: glib_ffi::gpointer) -> glib_ffi::gboolean
where P: IsA<ThreadedSocketService> {
callback_guard!();
let f: &&(Fn(&P, &SocketConnection, &glib::Object) -> bool + 'static) = transmute(f);
f(&ThreadedSocketService::from_glib_borrow(this).downcast_unchecked(), &from_glib_borrow(connection), &from_glib_borrow(source_object)).to_glib()
}
unsafe extern "C" fn notify_max_threads_trampoline<P>(this: *mut ffi::GThreadedSocketService, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<ThreadedSocketService> {
callback_guard!();
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&ThreadedSocketService::from_glib_borrow(this).downcast_unchecked())
}
|
use crate::get_result;
// https://adventofcode.com/2020/day/15
// https://www.reddit.com/r/rust/comments/kdh7rr/advent_of_code_2020_day_15/
const INPUT_FILENAME: &str = "inputs/input15";
pub fn solve() {
get_result(1, part01, INPUT_FILENAME);
get_result(2, part02, INPUT_FILENAME);
}
fn part01(input: String) -> usize {
let input: Vec<_> = input.trim_end().split(',').map(|n| n.parse().unwrap()).collect();
play(&input, 2020)
}
fn part02(input: String) -> usize {
let input: Vec<_> = input.trim_end().split(',').map(|n| n.parse().unwrap()).collect();
play(&input, 30000000)
}
fn play(input: &[usize], number_rounds: usize) -> usize {
let mut vec: Vec<usize> = vec![0; number_rounds + 1];
for i in 0..input.len() {
vec[input[i]] = i + 1;
}
vec[*input.last().unwrap()] = 0;
let mut last_word = *input.last().unwrap();
for turn in input.len() + 1..=number_rounds {
let mut last_spoken = vec[last_word];
if last_spoken != 0 {
last_spoken = turn - 1 - last_spoken;
}
vec[last_word] = turn - 1;
last_word = last_spoken;
}
last_word
}
|
use advent_libs::input_helpers;
/// Ship struct is used to represent both a ship and a waypoint
#[derive(Debug)]
struct Ship {
/// Heading of 0 represents EAST. Positive rotation is clockwise (E,S,W,N)
pub heading: i32,
pub lat: i32,
pub lon: i32,
}
impl Ship {
fn new(heading: i32, lat: i32, lon: i32) -> Ship {
Ship { heading, lat, lon }
}
}
fn process_command(ship: &mut Ship, cmd: &String) {
let val: i32 = cmd[1..].parse().unwrap();
let cmd = &cmd[0..1];
match cmd {
"N" => ship.lon += val,
"S" => ship.lon -= val,
"E" => ship.lat += val,
"W" => ship.lat -= val,
"R" => {
ship.heading += val;
ship.heading = ship.heading % 360;
}
"L" => {
ship.heading -= val;
if ship.heading < 0 {
ship.heading += 360;
}
}
"F" => match ship.heading {
0 => ship.lat += val,
90 => ship.lon -= val,
180 => ship.lat -= val,
270 => ship.lon += val,
_ => panic!("Invalid heading"),
},
_ => panic!("Invalid command"),
}
}
fn process_command_part2(ship: &mut Ship, waypoint: &mut Ship, cmd: &String) {
// Local rotation functions
fn rotate_left(waypoint: &mut Ship) {
let lon = waypoint.lon * -1;
waypoint.lon = waypoint.lat;
waypoint.lat = lon;
}
fn rotate_right(waypoint: &mut Ship) {
let lat = waypoint.lat * -1;
waypoint.lat = waypoint.lon;
waypoint.lon = lat;
}
let val: i32 = cmd[1..].parse().unwrap();
let cmd = &cmd[0..1];
match cmd {
"N" => waypoint.lon += val,
"S" => waypoint.lon -= val,
"E" => waypoint.lat += val,
"W" => waypoint.lat -= val,
"R" => {
for _x in 0..(val / 90) {
rotate_right(waypoint);
}
}
"L" => {
for _x in 0..(val / 90) {
rotate_left(waypoint);
}
}
"F" => {
ship.lat += waypoint.lat * val;
ship.lon += waypoint.lon * val;
}
_ => panic!("Invalid command"),
}
}
fn main() {
println!("Advent of Code 2020 - Day 12");
println!("---------------------------");
// Read in puzzle input
let mut input = input_helpers::read_puzzle_input_to_string(12);
// Strip out the carriage returns (on Windows)
input.retain(|c| c != '\r');
// Parse to vector of usize on newline
let input_vec: Vec<String> = input_helpers::split_string_to_vector(&input, "\n");
// Create ship object
let mut ship = Ship::new(0, 0, 0);
// Part 1
for cmd in input_vec.iter() {
process_command(&mut ship, cmd);
}
let manhattan_dist = ship.lat.abs() + ship.lon.abs();
println!("Part 1 -");
println!("{:?}", &ship);
println!("Manhattan Distance: {}", manhattan_dist);
// Part 2
ship = Ship::new(0, 0, 0); // Reset ship
let mut waypoint = Ship::new(0, 10, 1); // Waypoint starts E:10 and N:1 of the ship
for cmd in input_vec.iter() {
process_command_part2(&mut ship, &mut waypoint, cmd);
}
let manhattan_dist = ship.lat.abs() + ship.lon.abs();
println!("Part 2 -");
println!("{:?}", &ship);
println!("Manhattan Distance: {}", manhattan_dist);
}
|
use super::render;
use crate::{Operator, Polyhedron};
pub struct Generator {
polyhedron: Polyhedron,
}
impl Generator {
pub fn seed(polyhedron: Polyhedron) -> Generator {
Generator {
polyhedron
}
}
pub fn apply_operator(&mut self, operator: Operator) {
let temp_value = crate::seeds::Platonic::Tetrahedron.polyhedron(1.0);
let old = std::mem::replace(&mut self.polyhedron, temp_value);
let new = old.apply(operator);
std::mem::replace(&mut self.polyhedron, new);
}
pub fn apply_iter(&mut self, operators: impl IntoIterator<Item = Operator>) {
let temp_value = crate::seeds::Platonic::Tetrahedron.polyhedron(1.0);
let mut polyhedron = std::mem::replace(&mut self.polyhedron, temp_value);
for op in operators.into_iter() {
polyhedron = polyhedron.apply(op);
}
std::mem::replace(&mut self.polyhedron, polyhedron);
}
pub fn scale(&mut self, max_radius: f64) {
self.polyhedron.center_on_origin();
self.polyhedron.scale(max_radius);
}
pub fn to_mesh(&self) -> render::Mesh {
use std::iter::FromIterator;
use render::Mesh;
type MeshVertex = render::Vertex;
let polyhedron = &self.polyhedron;
let faces = polyhedron.faces();
let classes = polyhedron.classify_faces();
let mesh = Mesh::from_vertex_groups(faces.iter().enumerate().map(
|(i, face)| -> Vec<MeshVertex> {
let class = classes[i];
let coord_x = ((class % 8) as f32 + 0.5) / 8.0;
let coord_y = ((class / 8) as f32 + 0.5) as f32 / 8.0;
let vertices = polyhedron.face_vertices(face);
let normal = normal(vertices.clone()).cast::<f32>().unwrap();
Vec::from_iter(vertices.map(|vertex| -> MeshVertex {
MeshVertex::new(vertex.cast::<f32>().unwrap(), [coord_x, coord_y], normal)
}))
},
));
eprintln!(
"faces: {}, triangles: {}, verts: {}",
faces.len(),
mesh.triangles().len(),
mesh.vertices().len()
);
mesh
}
}
fn normal(mut vertices: impl Iterator<Item = polyhedrator::Vertex>) -> cgmath::Vector3<f64> {
use cgmath::{EuclideanSpace, InnerSpace, Point3, Vector3};
// Using a vertex near the polygon reduces error for polygons far from the origin
let origin = Point3::origin();
let first = vertices.next().unwrap_or(origin);
let normalizer = first;
let mut normal = Vector3 {
x: 0.0,
y: 0.0,
z: 0.0,
};
let mut previous = first - normalizer;
for vertex in vertices {
let current = vertex - normalizer;
normal += previous.cross(current);
previous = current;
}
normal += previous.cross(first - normalizer);
normal.normalize()
}
|
#![allow(dead_code)]
use std::net::{TcpListener};
use std::thread;
use argparse::{ArgumentParser,Store};
use std::env;
extern crate time;
extern crate mime_guess;
extern crate argparse;
pub mod request;
pub mod response;
pub mod stream;
fn main() {
let mut dir = env::current_dir().unwrap().to_str().unwrap().to_string();
{
let mut ap = ArgumentParser::new();
ap.set_description("Serve static files at the provided directory over HTTP");
ap.refer(&mut dir)
.add_option(&["-d", "--directory"], Store, "Directory to serve over HTTP");
ap.parse_args_or_exit();
}
let listener = TcpListener::bind("0.0.0.0:80").unwrap();
println!("Listening on port 80\n");
for stream in listener.incoming() {
let cdir = dir.clone();
//spawn thread to handle client
thread::spawn(move || {
let mut client = stream::Stream::new(stream.unwrap(), String::from(cdir));
client.handle_client();
});
}
}
|
#![cfg(target_os = "cuda")]
#![deny(clippy::pedantic)]
#![no_std]
#![feature(abi_ptx)]
#![feature(alloc_error_handler)]
#![feature(panic_info_message)]
#![feature(atomic_from_mut)]
#![feature(asm)]
extern crate alloc;
#[macro_use]
extern crate rustcoalescence_algorithms_cuda_kernel_specialiser;
use core::sync::atomic::{AtomicU64, Ordering};
use necsim_core::{
cogs::{
CoalescenceSampler, DispersalSampler, EmigrationExit, Habitat, ImmigrationEntry,
LineageReference, LineageStore, MinSpeciationTrackingEventSampler,
PeekableActiveLineageSampler, PrimeableRng, SingularActiveLineageSampler,
SpeciationProbability, SpeciationSample, TurnoverRate,
},
lineage::Lineage,
reporter::boolean::Boolean,
simulation::Simulation,
};
use necsim_core_bond::{NonNegativeF64, PositiveF64};
use necsim_impls_cuda::{event_buffer::EventBuffer, value_buffer::ValueBuffer};
use rust_cuda::rustacuda_core::DeviceCopy;
use rustcoalescence_algorithms_cuda_kernel_ptx_jit::PtxJITConstLoad;
use rust_cuda::{
common::{DeviceBoxMut, RustToCuda},
device::{nvptx, utils, AnyDeviceBoxMut, BorrowFromRust},
};
#[global_allocator]
static _GLOBAL_ALLOCATOR: utils::PTXAllocator = utils::PTXAllocator;
#[cfg(not(debug_assertions))]
#[panic_handler]
fn panic(_panic_info: &::core::panic::PanicInfo) -> ! {
unsafe { nvptx::trap() }
}
#[cfg(debug_assertions)]
#[panic_handler]
fn panic(panic_info: &::core::panic::PanicInfo) -> ! {
use rust_cuda::println;
println!(
"Panic occurred at {:?}: {:?}!",
panic_info.location(),
panic_info
.message()
.unwrap_or(&format_args!("unknown reason"))
);
unsafe { nvptx::trap() }
}
#[alloc_error_handler]
fn alloc_error_handler(_: core::alloc::Layout) -> ! {
unsafe { nvptx::trap() }
}
/// # Safety
/// This CUDA kernel is unsafe as it is called with untyped `AnyDeviceBox`.
#[no_mangle]
pub unsafe extern "ptx-kernel" fn simulate(
simulation_any: AnyDeviceBoxMut,
task_list_any: AnyDeviceBoxMut,
event_buffer_any: AnyDeviceBoxMut,
min_spec_sample_buffer_any: AnyDeviceBoxMut,
next_event_time_buffer_any: AnyDeviceBoxMut,
total_time_max: AnyDeviceBoxMut,
total_steps_sum: AnyDeviceBoxMut,
max_steps: u64,
max_next_event_time: NonNegativeF64,
) {
specialise!(simulate_generic)(
simulation_any.into(),
task_list_any.into(),
event_buffer_any.into(),
min_spec_sample_buffer_any.into(),
next_event_time_buffer_any.into(),
total_time_max.into(),
total_steps_sum.into(),
max_steps,
max_next_event_time,
)
}
#[inline]
unsafe fn simulate_generic<
H: Habitat + RustToCuda,
G: PrimeableRng + RustToCuda,
R: LineageReference<H> + DeviceCopy,
S: LineageStore<H, R> + RustToCuda,
X: EmigrationExit<H, G, R, S> + RustToCuda,
D: DispersalSampler<H, G> + RustToCuda,
C: CoalescenceSampler<H, R, S> + RustToCuda,
T: TurnoverRate<H> + RustToCuda,
N: SpeciationProbability<H> + RustToCuda,
E: MinSpeciationTrackingEventSampler<H, G, R, S, X, D, C, T, N> + RustToCuda,
I: ImmigrationEntry + RustToCuda,
A: SingularActiveLineageSampler<H, G, R, S, X, D, C, T, N, E, I>
+ PeekableActiveLineageSampler<H, G, R, S, X, D, C, T, N, E, I>
+ RustToCuda,
ReportSpeciation: Boolean,
ReportDispersal: Boolean,
>(
simulation_cuda_repr: DeviceBoxMut<
<Simulation<H, G, R, S, X, D, C, T, N, E, I, A> as RustToCuda>::CudaRepresentation,
>,
task_list_cuda_repr: DeviceBoxMut<<ValueBuffer<Lineage> as RustToCuda>::CudaRepresentation>,
event_buffer_cuda_repr: DeviceBoxMut<
<EventBuffer<ReportSpeciation, ReportDispersal> as RustToCuda>::CudaRepresentation,
>,
min_spec_sample_buffer_cuda_repr: DeviceBoxMut<
<ValueBuffer<SpeciationSample> as RustToCuda>::CudaRepresentation,
>,
next_event_time_buffer_cuda_repr: DeviceBoxMut<
<ValueBuffer<PositiveF64> as RustToCuda>::CudaRepresentation,
>,
mut total_time_max: DeviceBoxMut<u64>,
mut total_steps_sum: DeviceBoxMut<u64>,
max_steps: u64,
max_next_event_time: NonNegativeF64,
) {
PtxJITConstLoad!([0] => simulation_cuda_repr.as_ref());
PtxJITConstLoad!([1] => task_list_cuda_repr.as_ref());
PtxJITConstLoad!([2] => event_buffer_cuda_repr.as_ref());
PtxJITConstLoad!([3] => min_spec_sample_buffer_cuda_repr.as_ref());
PtxJITConstLoad!([4] => next_event_time_buffer_cuda_repr.as_ref());
let total_time_max = AtomicU64::from_mut(total_time_max.as_mut());
let total_steps_sum = AtomicU64::from_mut(total_steps_sum.as_mut());
Simulation::with_borrow_from_rust_mut(simulation_cuda_repr, |simulation| {
ValueBuffer::with_borrow_from_rust_mut(task_list_cuda_repr, |task_list| {
task_list.with_value_for_core(|task| {
// Discard the prior task (the simulation is just a temporary local copy)
core::mem::drop(
simulation
.active_lineage_sampler_mut()
.replace_active_lineage(task),
);
EventBuffer::with_borrow_from_rust_mut(
event_buffer_cuda_repr,
|event_buffer_reporter| {
ValueBuffer::with_borrow_from_rust_mut(
min_spec_sample_buffer_cuda_repr,
|min_spec_sample_buffer| {
min_spec_sample_buffer.with_value_for_core(|min_spec_sample| {
// Discard the prior sample (same reason as above)
simulation
.event_sampler_mut()
.replace_min_speciation(min_spec_sample);
let (time, steps) = simulation.simulate_incremental_early_stop(
|simulation, steps| {
steps >= max_steps
|| simulation
.peek_time_of_next_event()
.map_or(true, |next_time| {
next_time >= max_next_event_time
})
},
event_buffer_reporter,
);
ValueBuffer::with_borrow_from_rust_mut(
next_event_time_buffer_cuda_repr,
|next_event_time_buffer| {
next_event_time_buffer.with_value_for_core(|_| {
simulation.peek_time_of_next_event()
})
},
);
if steps > 0 {
total_time_max
.fetch_max(time.get().to_bits(), Ordering::Relaxed);
total_steps_sum.fetch_add(steps, Ordering::Relaxed);
}
simulation.event_sampler_mut().replace_min_speciation(None)
})
},
)
},
);
simulation
.active_lineage_sampler_mut()
.replace_active_lineage(None)
})
})
})
}
|
fn main() {
/* Code as notes (splited into functions) here. */
ref_basic_usage();
ref_type_mutable_immutable();
mutable_ref_bypass_limit();
immutable_ref_must_stay_imtble();
dangling_refs();
}
fn ref_basic_usage() {
/*
[ABBREVIATION]
abt about
*/
/*
In short, reference does NOT <take ownership>.
| But they DO HAVE restrictions of their own :P
What changed?
=> arg we passed -> &VARIABLE
=> func's param -> &TYPE
Note here
-> Apart from the ref, there's a opposite one
-> which was called 'deref' (using *), we'll take abt it later.
*/
let s1 = String::from("Hmm");
let s1_len = calc_len(&s1);
/*
References are immutable by default.
Just keywords added actually
| var let VAR -> let mut VAR
| arg &VAR -> &mut VAR
| param param: &String -> param: &mut String
*/
let mut r1 = String::from("Hallo");
add_greeting(&mut r1);
println!("--- [{}], [{}]", s1, s1_len);
println!("--- [{}]", r1);
}
/* Starting helper of: <ref_basic_usage> */
fn calc_len(s: &String) -> usize {
s.len()
}
fn add_greeting(s: &mut String) {
s.push_str(", wie geht es?");
}
/* Ending helper of: <ref_basic_usage> */
fn ref_type_mutable_immutable() {
let mut ms = String::from("Aha");
let ims = String::from("Woo");
/*
Mutable ref could only be borrowed once.
| to be clear,
| this is valid only they're inside the same scope).
*/
let m = &mut ms;
// Immutable could be borrowed multiple times (no limit I assume).
let i1 = &ims;
let i2 = &ims;
let i3 = &ims;
println!("--- [{}]" , m);
println!("--- [{}, {}, {}]" , i1, i2, i3);
}
fn mutable_ref_bypass_limit() {
/*
[ABBREVIATION]
undef undefined
[SYMBOL_IN_COMMENT]
& and
=> become (became)
*/
/*
Kinda like the problems we want to solve before.
So .. why the heck that there is a LIMIT ?!
It helps to prevent <data races> at compile time, e.g.
-> Two-or-more pointers access the same data (& same time)
=> At lease one of them is bein' used to write to the data
=> and there's no mechanism bein' used to sync access to the data
The <data races> might cause
| undef behaviour and can be difficult to diagnose & fix.
| So, Rust directly prevents u from drowning in such situations.
*/
let us = String::from("Calm down.");
/*
But we could use tricks to bypass it
| well, sort of, the rule still appies!
*/
let mut haha = String::from("HaHa");
{ // ALL HAIL THE CURLY-BRACKETS!
let mt1 = &mut haha;
} // 'mt1' goes out-of-scope here (& => invalid!)
let mt2 = &mut haha;
}
fn immutable_ref_must_stay_imtble() {
/*
[ABBREVIATION]
mtble mutable
imtble immutable
*/
/*
We cannot have a mutable ref
| which we have an immutable one.
Multiple imtble ref is fine,
-> but the mtble ref could
-> affect anyone else's readin' of the data.
*/
let mut _stimt = String::from("Wooo");
let f1 = &_stimt;
let f2 = &_stimt;
// let f3 = &mut _stimt;
println!("--- [{}, {}]" , f1, f2);
// println!("--- [{}]" , f3);
}
fn dangling_refs() {
/*
Let's deconstruct these two funcs.
fn main() {
/*
Two steps happens here (both the first and the last).
-> Step[0]: func was invoked (then [1], [2], [3])
-> Step[4]: exec finished, go back for assign
The last step was the problem
| after the step[3], the 's' have already been invalid
| so when you trying assign the val (which is the step[4])
-> what u assign is actually a <null pointer>,
-> which is a big deal (and bad!),
-> what u should do is directly return it.
*/
let ref_to_nothin = dangle_it();
}
fn dangle_it() -> &String {
let s = String::from("Yo"); // Step[1]: 's' was created
&s // Step[2]: return its ref
} // Step[3]: the 's' => invalid
*/
let ref_to_thing = no_dangle();
println!("--- [{}]", ref_to_thing);
}
/* Starting helper of: <dangling_refs> */
fn no_dangle() -> String {
let s = String::from("Hello");
s
}
/* Ending helper of: <dangling_refs> */ |
use actix_multipart::Multipart;
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
use std::borrow::BorrowMut;
use utils::payload_handler::{split_payload};
mod utils;
async fn handle_form_data(mut payload: Multipart) -> Result<HttpResponse, Error> {
let (form, files) = split_payload(payload.borrow_mut()).await;
println!("bytes={:#?}", form);
println!("files={:#?}", files);
Ok(HttpResponse::Ok().into())
}
fn index() -> HttpResponse {
let html = r#"<html>
<head><title>Upload Test</title>
<style>
*{
margin: 0;
}
body{
display: flex;
}
form{
margin: auto;
box-sizing: border-box;
width: 20rem;
max-width: 100%;
display: flex;
flex-direction: column;
background-color: lightgray;
padding: 2rem 1rem;
}
input{
margin: 0.8rem 0;
}
</style>
</head>
<body>
<form target="/" method="post" enctype="multipart/form-data" id="myForm" >
<input type="text" name="title" placeholder="give it a name"/>
<input type="text" name="description" placeholder="describe it"/>
<input type="number" placeholder="how many" name="count" value=""/>
<input type="file" multiple name="file"/>
<input type="submit" value="Submit"></button>
</form>
</body>
<script>
</script>
</html>"#;
HttpResponse::Ok().body(html)
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
std::fs::create_dir_all("./files").unwrap();
let ip = "0.0.0.0:3000";
HttpServer::new(|| {
App::new().wrap(middleware::Logger::default()).service(
web::resource("/")
.route(web::get().to(index))
.route(web::post().to(handle_form_data)),
)
})
.bind(ip)?
.run()
.await
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub mod operations {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<OperationListResult, list::Error> {
let client = &operation_config.client;
let uri_str = &format!("{}/providers/Microsoft.Consumption/operations", &operation_config.base_path,);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: OperationListResult = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod credit_summary_by_billing_profile {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
billing_profile_id: &str,
) -> std::result::Result<CreditSummary, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/providers/Microsoft.Consumption/credits/balanceSummary",
&operation_config.base_path, billing_account_id, billing_profile_id
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: CreditSummary = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod events_by_billing_profile {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
billing_profile_id: &str,
start_date: &str,
end_date: &str,
) -> std::result::Result<Events, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/providers/Microsoft.Consumption/events",
&operation_config.base_path, billing_account_id, billing_profile_id
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.query(&[("startDate", start_date)]);
req_builder = req_builder.query(&[("endDate", end_date)]);
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: Events = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod lots_by_billing_profile {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
billing_profile_id: &str,
) -> std::result::Result<Lots, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/providers/Microsoft.Consumption/lots",
&operation_config.base_path, billing_account_id, billing_profile_id
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: Lots = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod invoice_pricesheet {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn download(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
invoice_name: &str,
) -> std::result::Result<download::Response, download::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Consumption/billingAccounts/{}/invoices/{}/pricesheet/default/download",
&operation_config.base_path, billing_account_id, invoice_name
);
let mut req_builder = client.post(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(download::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0);
let req = req_builder.build().context(download::BuildRequestError)?;
let rsp = client.execute(req).await.context(download::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(download::ResponseBytesError)?;
let rsp_value: PricesheetDownloadResponse = serde_json::from_slice(&body).context(download::DeserializeError { body })?;
Ok(download::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(download::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(download::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(download::DeserializeError { body })?;
download::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod download {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(PricesheetDownloadResponse),
Accepted202,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod billing_profile_pricesheet {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn download(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
billing_profile_id: &str,
) -> std::result::Result<download::Response, download::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Consumption/billingAccounts/{}/billingProfiles/{}/pricesheet/default/download",
&operation_config.base_path, billing_account_id, billing_profile_id
);
let mut req_builder = client.post(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(download::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0);
let req = req_builder.build().context(download::BuildRequestError)?;
let rsp = client.execute(req).await.context(download::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(download::ResponseBytesError)?;
let rsp_value: PricesheetDownloadResponse = serde_json::from_slice(&body).context(download::DeserializeError { body })?;
Ok(download::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => Ok(download::Response::Accepted202),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(download::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(download::DeserializeError { body })?;
download::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod download {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(PricesheetDownloadResponse),
Accepted202,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod charges_by_billing_account {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
start_date: &str,
end_date: &str,
apply: Option<&str>,
) -> std::result::Result<ChargesListByBillingAccount, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.Consumption/charges",
&operation_config.base_path, billing_account_id
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.query(&[("startDate", start_date)]);
req_builder = req_builder.query(&[("endDate", end_date)]);
if let Some(apply) = apply {
req_builder = req_builder.query(&[("$apply", apply)]);
}
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: ChargesListByBillingAccount = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod charges_by_billing_profile {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
billing_profile_id: &str,
start_date: &str,
end_date: &str,
) -> std::result::Result<ChargesListByBillingProfile, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/providers/Microsoft.Consumption/charges",
&operation_config.base_path, billing_account_id, billing_profile_id
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.query(&[("startDate", start_date)]);
req_builder = req_builder.query(&[("endDate", end_date)]);
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: ChargesListByBillingProfile = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod charges_by_invoice_section {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
invoice_section_id: &str,
start_date: &str,
end_date: &str,
apply: Option<&str>,
) -> std::result::Result<ChargesListByInvoiceSection, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/invoiceSections/{}/providers/Microsoft.Consumption/charges",
&operation_config.base_path, billing_account_id, invoice_section_id
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.query(&[("startDate", start_date)]);
req_builder = req_builder.query(&[("endDate", end_date)]);
if let Some(apply) = apply {
req_builder = req_builder.query(&[("$apply", apply)]);
}
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: ChargesListByInvoiceSection = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub mod bots {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
subscription_id: &str,
) -> std::result::Result<Bot, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: Bot = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn create(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
parameters: &Bot,
subscription_id: &str,
) -> std::result::Result<create::Response, create::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create::BuildRequestError)?;
let rsp = client.execute(req).await.context(create::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: Bot = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
Ok(create::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: Bot = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
Ok(create::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
create::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(Bot),
Created201(Bot),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
parameters: &Bot,
subscription_id: &str,
) -> std::result::Result<update::Response, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name
);
let mut req_builder = client.patch(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(update::BuildRequestError)?;
let rsp = client.execute(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: Bot = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(update::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: Bot = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(update::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(Bot),
Created201(Bot),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
subscription_id: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(delete::DeserializeError { body })?;
delete::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn list_by_resource_group(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
subscription_id: &str,
) -> std::result::Result<BotResponseList, list_by_resource_group::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices",
&operation_config.base_path, subscription_id, resource_group_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_by_resource_group::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list_by_resource_group::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_resource_group::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?;
let rsp_value: BotResponseList =
serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?;
list_by_resource_group::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_resource_group {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
) -> std::result::Result<BotResponseList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.BotService/botServices",
&operation_config.base_path, subscription_id
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: BotResponseList = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn get_check_name_availability(
operation_config: &crate::OperationConfig,
parameters: &CheckNameAvailabilityRequestBody,
) -> std::result::Result<CheckNameAvailabilityResponseBody, get_check_name_availability::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.BotService/checkNameAvailability",
&operation_config.base_path,
);
let mut req_builder = client.post(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get_check_name_availability::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(get_check_name_availability::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(get_check_name_availability::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_check_name_availability::ResponseBytesError)?;
let rsp_value: CheckNameAvailabilityResponseBody =
serde_json::from_slice(&body).context(get_check_name_availability::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_check_name_availability::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(get_check_name_availability::DeserializeError { body })?;
get_check_name_availability::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_check_name_availability {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
}
pub mod channels {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
channel_name: &str,
subscription_id: &str,
) -> std::result::Result<BotChannel, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/channels/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name, channel_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: BotChannel = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn create(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
channel_name: &str,
parameters: &BotChannel,
subscription_id: &str,
) -> std::result::Result<create::Response, create::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/channels/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name, channel_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create::BuildRequestError)?;
let rsp = client.execute(req).await.context(create::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: BotChannel = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
Ok(create::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: BotChannel = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
Ok(create::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
create::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(BotChannel),
Created201(BotChannel),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
channel_name: &str,
parameters: &BotChannel,
subscription_id: &str,
) -> std::result::Result<update::Response, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/channels/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name, channel_name
);
let mut req_builder = client.patch(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(update::BuildRequestError)?;
let rsp = client.execute(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: BotChannel = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(update::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: BotChannel = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(update::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(BotChannel),
Created201(BotChannel),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
channel_name: &str,
subscription_id: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/channels/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name, channel_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(delete::DeserializeError { body })?;
delete::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn list_with_keys(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
channel_name: &str,
subscription_id: &str,
) -> std::result::Result<BotChannel, list_with_keys::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/channels/{}/listChannelWithKeys",
&operation_config.base_path, subscription_id, resource_group_name, resource_name, channel_name
);
let mut req_builder = client.post(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_with_keys::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0);
let req = req_builder.build().context(list_with_keys::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_with_keys::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_with_keys::ResponseBytesError)?;
let rsp_value: BotChannel = serde_json::from_slice(&body).context(list_with_keys::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_with_keys::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(list_with_keys::DeserializeError { body })?;
list_with_keys::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_with_keys {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn list_by_resource_group(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
subscription_id: &str,
) -> std::result::Result<ChannelResponseList, list_by_resource_group::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/channels",
&operation_config.base_path, subscription_id, resource_group_name, resource_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_by_resource_group::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list_by_resource_group::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_resource_group::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?;
let rsp_value: ChannelResponseList =
serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?;
list_by_resource_group::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_resource_group {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
}
pub mod operations {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<OperationEntityListResult, list::Error> {
let client = &operation_config.client;
let uri_str = &format!("{}/providers/Microsoft.BotService/operations", &operation_config.base_path,);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: OperationEntityListResult = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
list::UnexpectedResponse { status_code, body: body }.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
}
pub mod bot_connection {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_service_providers(
operation_config: &crate::OperationConfig,
subscription_id: &str,
) -> std::result::Result<ServiceProviderResponseList, list_service_providers::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.BotService/listAuthServiceProviders",
&operation_config.base_path, subscription_id
);
let mut req_builder = client.post(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_service_providers::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0);
let req = req_builder.build().context(list_service_providers::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_service_providers::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_service_providers::ResponseBytesError)?;
let rsp_value: ServiceProviderResponseList =
serde_json::from_slice(&body).context(list_service_providers::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_service_providers::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(list_service_providers::DeserializeError { body })?;
list_service_providers::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_service_providers {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn list_with_secrets(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
connection_name: &str,
subscription_id: &str,
) -> std::result::Result<ConnectionSetting, list_with_secrets::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/Connections/{}/listWithSecrets",
&operation_config.base_path, subscription_id, resource_group_name, resource_name, connection_name
);
let mut req_builder = client.post(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_with_secrets::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0);
let req = req_builder.build().context(list_with_secrets::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_with_secrets::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_with_secrets::ResponseBytesError)?;
let rsp_value: ConnectionSetting = serde_json::from_slice(&body).context(list_with_secrets::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_with_secrets::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(list_with_secrets::DeserializeError { body })?;
list_with_secrets::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_with_secrets {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
connection_name: &str,
subscription_id: &str,
) -> std::result::Result<ConnectionSetting, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/Connections/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name, connection_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: ConnectionSetting = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn create(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
connection_name: &str,
parameters: &ConnectionSetting,
subscription_id: &str,
) -> std::result::Result<create::Response, create::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/Connections/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name, connection_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create::BuildRequestError)?;
let rsp = client.execute(req).await.context(create::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: ConnectionSetting = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
Ok(create::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: ConnectionSetting = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
Ok(create::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
create::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(ConnectionSetting),
Created201(ConnectionSetting),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
connection_name: &str,
parameters: &ConnectionSetting,
subscription_id: &str,
) -> std::result::Result<update::Response, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/Connections/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name, connection_name
);
let mut req_builder = client.patch(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(update::BuildRequestError)?;
let rsp = client.execute(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: ConnectionSetting = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(update::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: ConnectionSetting = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(update::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(ConnectionSetting),
Created201(ConnectionSetting),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
connection_name: &str,
subscription_id: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/Connections/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name, connection_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(delete::DeserializeError { body })?;
delete::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn list_by_bot_service(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
subscription_id: &str,
) -> std::result::Result<ConnectionSettingResponseList, list_by_bot_service::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/connections",
&operation_config.base_path, subscription_id, resource_group_name, resource_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_by_bot_service::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list_by_bot_service::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_bot_service::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_bot_service::ResponseBytesError)?;
let rsp_value: ConnectionSettingResponseList =
serde_json::from_slice(&body).context(list_by_bot_service::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_bot_service::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(list_by_bot_service::DeserializeError { body })?;
list_by_bot_service::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_bot_service {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
}
pub mod enterprise_channels {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn check_name_availability(
operation_config: &crate::OperationConfig,
parameters: &EnterpriseChannelCheckNameAvailabilityRequest,
) -> std::result::Result<EnterpriseChannelCheckNameAvailabilityResponse, check_name_availability::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.BotService/checkEnterpriseChannelNameAvailability",
&operation_config.base_path,
);
let mut req_builder = client.post(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(check_name_availability::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(check_name_availability::BuildRequestError)?;
let rsp = client.execute(req).await.context(check_name_availability::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(check_name_availability::ResponseBytesError)?;
let rsp_value: EnterpriseChannelCheckNameAvailabilityResponse =
serde_json::from_slice(&body).context(check_name_availability::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(check_name_availability::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(check_name_availability::DeserializeError { body })?;
check_name_availability::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod check_name_availability {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn list_by_resource_group(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
subscription_id: &str,
) -> std::result::Result<EnterpriseChannelResponseList, list_by_resource_group::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/enterpriseChannels",
&operation_config.base_path, subscription_id, resource_group_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_by_resource_group::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list_by_resource_group::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_resource_group::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?;
let rsp_value: EnterpriseChannelResponseList =
serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?;
list_by_resource_group::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_resource_group {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
subscription_id: &str,
) -> std::result::Result<EnterpriseChannel, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/enterpriseChannels/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: EnterpriseChannel = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn create(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
parameters: &EnterpriseChannel,
subscription_id: &str,
) -> std::result::Result<create::Response, create::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/enterpriseChannels/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create::BuildRequestError)?;
let rsp = client.execute(req).await.context(create::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: EnterpriseChannel = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
Ok(create::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: EnterpriseChannel = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
Ok(create::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(create::DeserializeError { body })?;
create::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(EnterpriseChannel),
Created201(EnterpriseChannel),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
parameters: &EnterpriseChannel,
subscription_id: &str,
) -> std::result::Result<update::Response, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/enterpriseChannels/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name
);
let mut req_builder = client.patch(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(update::BuildRequestError)?;
let rsp = client.execute(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: EnterpriseChannel = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(update::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: EnterpriseChannel = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(update::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(EnterpriseChannel),
Created201(EnterpriseChannel),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
resource_name: &str,
subscription_id: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/enterpriseChannels/{}",
&operation_config.base_path, subscription_id, resource_group_name, resource_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: Error = serde_json::from_slice(&body).context(delete::DeserializeError { body })?;
delete::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse { status_code: StatusCode, value: models::Error },
BuildRequestError { source: reqwest::Error },
ExecuteRequestError { source: reqwest::Error },
ResponseBytesError { source: reqwest::Error },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
}
|
#[cfg(all(test, feature = "hmac", feature = "sha256"))]
mod test {
use cryptographer::hmac::{self, Hash};
use cryptographer::sha256;
use encoding::hex;
use std::io::Write;
#[test]
fn hmac_sha256() {
let key = "hello".as_bytes();
//let mut h = hmac::new::<SHA256>(&key);
let mut h = hmac::new(sha256::new, &key);
let world = "world".as_bytes();
h.write(&world).expect("failed to consume 'world'");
let how_do_you_do = "how do you do".as_bytes();
h.write(&how_do_you_do)
.expect("failed to consume 'how_do_you_do'");
let d = h.sum();
let got = hex::encode_to_string(&d[..]);
let expect = "a6a247ab2f6e7f4487996f18bb8290a7829a21cc8e79bb129e8451bf97e14f6d";
assert_eq!(&got, expect);
}
#[test]
fn sum_sha256() {
// in form of (key, data, expect)
let test_cases = vec![(
"my secret and secure key".as_bytes(),
"input message".as_bytes(),
"97d2a569059bbcd8ead4444ff99071f4c01d005bcefe0d3567e1be628e5fdcd9",
)];
for v in test_cases.iter() {
let (key, data, expect) = v;
let digest = hmac::sum(sha256::new, key, data);
let got = hex::encode_to_string(&digest[..]);
assert_eq!(*expect, &got);
}
}
}
|
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![warn(clippy::all)]
#![warn(clippy::else_if_without_else)]
fn bla1() -> bool {
unimplemented!()
}
fn bla2() -> bool {
unimplemented!()
}
fn bla3() -> bool {
unimplemented!()
}
fn main() {
if bla1() {
println!("if");
}
if bla1() {
println!("if");
} else {
println!("else");
}
if bla1() {
println!("if");
} else if bla2() {
println!("else if");
} else {
println!("else")
}
if bla1() {
println!("if");
} else if bla2() {
println!("else if 1");
} else if bla3() {
println!("else if 2");
} else {
println!("else")
}
if bla1() {
println!("if");
} else if bla2() {
//~ ERROR else if without else
println!("else if");
}
if bla1() {
println!("if");
} else if bla2() {
println!("else if 1");
} else if bla3() {
//~ ERROR else if without else
println!("else if 2");
}
}
|
use termion::TermWrite;
use std::io::{self, Write};
use std::iter::FromIterator;
#[derive(Debug,Clone)]
pub enum Action {
Insert {
start: usize,
text: Vec<char>,
},
Remove {
start: usize,
text: Vec<char>,
},
}
impl Action {
pub fn do_on(&self, buf: &mut Buffer) {
match *self {
Action::Insert { start, ref text } => buf.insert_raw(start, &text[..]),
Action::Remove { start, ref text } => {
buf.remove_raw(start, start + text.len());
}
}
}
pub fn undo(&self, buf: &mut Buffer) {
match *self {
Action::Insert { start, ref text } => {
buf.remove_raw(start, start + text.len());
}
Action::Remove { start, ref text } => buf.insert_raw(start, &text[..]),
}
}
}
#[derive(Debug, Clone)]
pub struct Buffer {
data: Vec<char>,
actions: Vec<Action>,
undone_actions: Vec<Action>,
}
impl From<Buffer> for String {
fn from(buf: Buffer) -> Self {
String::from_iter(buf.data)
}
}
impl From<String> for Buffer {
fn from(s: String) -> Self {
Buffer::from_iter(s.chars())
}
}
impl<'a> From<&'a str> for Buffer {
fn from(s: &'a str) -> Self {
Buffer::from_iter(s.chars())
}
}
impl FromIterator<char> for Buffer {
fn from_iter<T: IntoIterator<Item = char>>(t: T) -> Self {
Buffer {
data: t.into_iter().collect(),
actions: Vec::new(),
undone_actions: Vec::new(),
}
}
}
impl Buffer {
pub fn new() -> Self {
Buffer {
data: Vec::new(),
actions: Vec::new(),
undone_actions: Vec::new(),
}
}
pub fn clear_actions(&mut self) {
self.actions.clear();
self.undone_actions.clear();
}
pub fn undo(&mut self) -> bool {
match self.actions.pop() {
None => false,
Some(act) => {
act.undo(self);
self.undone_actions.push(act);
true
}
}
}
pub fn redo(&mut self) -> bool {
match self.undone_actions.pop() {
None => false,
Some(act) => {
act.do_on(self);
self.actions.push(act);
true
}
}
}
pub fn revert(&mut self) -> bool {
if self.actions.len() == 0 {
return false;
}
while self.undo() {}
true
}
fn push_action(&mut self, act: Action) {
self.actions.push(act);
self.undone_actions.clear();
}
pub fn num_chars(&self) -> usize {
self.data.len()
}
pub fn num_bytes(&self) -> usize {
let s: String = self.clone().into();
s.len()
}
pub fn char_before(&self, cursor: usize) -> Option<char> {
if cursor == 0 {
None
} else {
self.data.get(cursor - 1).cloned()
}
}
pub fn char_after(&self, cursor: usize) -> Option<char> {
self.data.get(cursor).cloned()
}
/// Returns the number of characters removed.
pub fn remove(&mut self, start: usize, end: usize) -> usize {
let s = self.remove_raw(start, end);
let num_removed = s.len();
let act = Action::Remove {
start: start,
text: s,
};
self.push_action(act);
num_removed
}
pub fn insert(&mut self, start: usize, text: &[char]) {
let act = Action::Insert {
start: start,
text: text.into(),
};
act.do_on(self);
self.push_action(act);
}
pub fn range(&self, start: usize, end: usize) -> String {
self.data[start..end].iter().cloned().collect()
}
pub fn range_chars(&self, start: usize, end: usize) -> Vec<char> {
self.data[start..end].iter().cloned().collect()
}
pub fn chars(&self) -> ::std::slice::Iter<char> {
self.data.iter()
}
pub fn truncate(&mut self, num: usize) {
self.data.truncate(num);
}
pub fn print<W>(&self, out: &mut W) -> io::Result<()>
where W: TermWrite + Write
{
let string: String = self.data.iter().cloned().collect();
try!(out.write(string.as_bytes()));
Ok(())
}
fn remove_raw(&mut self, start: usize, end: usize) -> Vec<char> {
self.data.drain(start..end).collect()
}
fn insert_raw(&mut self, start: usize, text: &[char]) {
for (i, &c) in text.iter().enumerate() {
self.data.insert(start + i, c)
}
}
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get_user_settings_with_location(
operation_config: &crate::OperationConfig,
user_settings_name: &str,
location: &str,
) -> std::result::Result<UserSettingsResponse, get_user_settings_with_location::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/locations/{}/userSettings/{}",
&operation_config.base_path, location, user_settings_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get_user_settings_with_location::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get_user_settings_with_location::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(get_user_settings_with_location::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_user_settings_with_location::ResponseBytesError)?;
let rsp_value: UserSettingsResponse =
serde_json::from_slice(&body).context(get_user_settings_with_location::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_user_settings_with_location::ResponseBytesError)?;
let rsp_value: ErrorResponse =
serde_json::from_slice(&body).context(get_user_settings_with_location::DeserializeError { body })?;
get_user_settings_with_location::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_user_settings_with_location {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn put_user_settings_with_location(
operation_config: &crate::OperationConfig,
user_settings_name: &str,
location: &str,
parameters: &CloudShellUserSettings,
) -> std::result::Result<UserSettingsResponse, put_user_settings_with_location::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/locations/{}/userSettings/{}",
&operation_config.base_path, location, user_settings_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(put_user_settings_with_location::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(put_user_settings_with_location::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(put_user_settings_with_location::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(put_user_settings_with_location::ResponseBytesError)?;
let rsp_value: UserSettingsResponse =
serde_json::from_slice(&body).context(put_user_settings_with_location::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(put_user_settings_with_location::ResponseBytesError)?;
let rsp_value: ErrorResponse =
serde_json::from_slice(&body).context(put_user_settings_with_location::DeserializeError { body })?;
put_user_settings_with_location::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod put_user_settings_with_location {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn patch_user_settings_with_location(
operation_config: &crate::OperationConfig,
user_settings_name: &str,
location: &str,
parameters: &CloudShellPatchUserSettings,
) -> std::result::Result<UserSettingsResponse, patch_user_settings_with_location::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/locations/{}/userSettings/{}",
&operation_config.base_path, location, user_settings_name
);
let mut req_builder = client.patch(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(patch_user_settings_with_location::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(patch_user_settings_with_location::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(patch_user_settings_with_location::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(patch_user_settings_with_location::ResponseBytesError)?;
let rsp_value: UserSettingsResponse =
serde_json::from_slice(&body).context(patch_user_settings_with_location::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(patch_user_settings_with_location::ResponseBytesError)?;
let rsp_value: ErrorResponse =
serde_json::from_slice(&body).context(patch_user_settings_with_location::DeserializeError { body })?;
patch_user_settings_with_location::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod patch_user_settings_with_location {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn delete_user_settings_with_location(
operation_config: &crate::OperationConfig,
user_settings_name: &str,
location: &str,
) -> std::result::Result<delete_user_settings_with_location::Response, delete_user_settings_with_location::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/locations/{}/userSettings/{}",
&operation_config.base_path, location, user_settings_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete_user_settings_with_location::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete_user_settings_with_location::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(delete_user_settings_with_location::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete_user_settings_with_location::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete_user_settings_with_location::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete_user_settings_with_location::ResponseBytesError)?;
let rsp_value: ErrorResponse =
serde_json::from_slice(&body).context(delete_user_settings_with_location::DeserializeError { body })?;
delete_user_settings_with_location::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete_user_settings_with_location {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn get_console_with_location(
operation_config: &crate::OperationConfig,
console_name: &str,
location: &str,
) -> std::result::Result<CloudShellConsole, get_console_with_location::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/locations/{}/consoles/{}",
&operation_config.base_path, location, console_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get_console_with_location::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get_console_with_location::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_console_with_location::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_console_with_location::ResponseBytesError)?;
let rsp_value: CloudShellConsole =
serde_json::from_slice(&body).context(get_console_with_location::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_console_with_location::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(get_console_with_location::DeserializeError { body })?;
get_console_with_location::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_console_with_location {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn put_console_with_location(
operation_config: &crate::OperationConfig,
console_name: &str,
location: &str,
) -> std::result::Result<put_console_with_location::Response, put_console_with_location::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/locations/{}/consoles/{}",
&operation_config.base_path, location, console_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(put_console_with_location::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(put_console_with_location::BuildRequestError)?;
let rsp = client.execute(req).await.context(put_console_with_location::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(put_console_with_location::ResponseBytesError)?;
let rsp_value: CloudShellConsole =
serde_json::from_slice(&body).context(put_console_with_location::DeserializeError { body })?;
Ok(put_console_with_location::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(put_console_with_location::ResponseBytesError)?;
let rsp_value: CloudShellConsole =
serde_json::from_slice(&body).context(put_console_with_location::DeserializeError { body })?;
Ok(put_console_with_location::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(put_console_with_location::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(put_console_with_location::DeserializeError { body })?;
put_console_with_location::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod put_console_with_location {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(CloudShellConsole),
Created201(CloudShellConsole),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn delete_console_with_location(
operation_config: &crate::OperationConfig,
console_name: &str,
location: &str,
) -> std::result::Result<delete_console_with_location::Response, delete_console_with_location::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/locations/{}/consoles/{}",
&operation_config.base_path, location, console_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete_console_with_location::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete_console_with_location::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(delete_console_with_location::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete_console_with_location::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete_console_with_location::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete_console_with_location::ResponseBytesError)?;
let rsp_value: ErrorResponse =
serde_json::from_slice(&body).context(delete_console_with_location::DeserializeError { body })?;
delete_console_with_location::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete_console_with_location {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn keep_alive_with_location(
operation_config: &crate::OperationConfig,
console_name: &str,
location: &str,
) -> std::result::Result<(), keep_alive_with_location::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/locations/{}/consoles/{}/keepAlive",
&operation_config.base_path, location, console_name
);
let mut req_builder = client.post(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(keep_alive_with_location::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0);
let req = req_builder.build().context(keep_alive_with_location::BuildRequestError)?;
let rsp = client.execute(req).await.context(keep_alive_with_location::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(()),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(keep_alive_with_location::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(keep_alive_with_location::DeserializeError { body })?;
keep_alive_with_location::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod keep_alive_with_location {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn get_user_settings(
operation_config: &crate::OperationConfig,
user_settings_name: &str,
) -> std::result::Result<UserSettingsResponse, get_user_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/userSettings/{}",
&operation_config.base_path, user_settings_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get_user_settings::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get_user_settings::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_user_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_user_settings::ResponseBytesError)?;
let rsp_value: UserSettingsResponse = serde_json::from_slice(&body).context(get_user_settings::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_user_settings::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(get_user_settings::DeserializeError { body })?;
get_user_settings::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_user_settings {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn put_user_settings(
operation_config: &crate::OperationConfig,
user_settings_name: &str,
parameters: &CloudShellUserSettings,
) -> std::result::Result<UserSettingsResponse, put_user_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/userSettings/{}",
&operation_config.base_path, user_settings_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(put_user_settings::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(put_user_settings::BuildRequestError)?;
let rsp = client.execute(req).await.context(put_user_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(put_user_settings::ResponseBytesError)?;
let rsp_value: UserSettingsResponse = serde_json::from_slice(&body).context(put_user_settings::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(put_user_settings::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(put_user_settings::DeserializeError { body })?;
put_user_settings::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod put_user_settings {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn patch_user_settings(
operation_config: &crate::OperationConfig,
user_settings_name: &str,
parameters: &CloudShellPatchUserSettings,
) -> std::result::Result<UserSettingsResponse, patch_user_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/userSettings/{}",
&operation_config.base_path, user_settings_name
);
let mut req_builder = client.patch(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(patch_user_settings::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(patch_user_settings::BuildRequestError)?;
let rsp = client.execute(req).await.context(patch_user_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(patch_user_settings::ResponseBytesError)?;
let rsp_value: UserSettingsResponse = serde_json::from_slice(&body).context(patch_user_settings::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(patch_user_settings::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(patch_user_settings::DeserializeError { body })?;
patch_user_settings::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod patch_user_settings {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn delete_user_settings(
operation_config: &crate::OperationConfig,
user_settings_name: &str,
) -> std::result::Result<delete_user_settings::Response, delete_user_settings::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/userSettings/{}",
&operation_config.base_path, user_settings_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete_user_settings::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete_user_settings::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete_user_settings::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete_user_settings::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete_user_settings::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete_user_settings::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(delete_user_settings::DeserializeError { body })?;
delete_user_settings::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete_user_settings {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn get_console(
operation_config: &crate::OperationConfig,
console_name: &str,
) -> std::result::Result<CloudShellConsole, get_console::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/consoles/{}",
&operation_config.base_path, console_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get_console::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get_console::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_console::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_console::ResponseBytesError)?;
let rsp_value: CloudShellConsole = serde_json::from_slice(&body).context(get_console::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_console::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(get_console::DeserializeError { body })?;
get_console::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_console {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn put_console(
operation_config: &crate::OperationConfig,
console_name: &str,
parameters: &ConsoleDefinition,
) -> std::result::Result<put_console::Response, put_console::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/consoles/{}",
&operation_config.base_path, console_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(put_console::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(put_console::BuildRequestError)?;
let rsp = client.execute(req).await.context(put_console::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(put_console::ResponseBytesError)?;
let rsp_value: CloudShellConsole = serde_json::from_slice(&body).context(put_console::DeserializeError { body })?;
Ok(put_console::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(put_console::ResponseBytesError)?;
let rsp_value: CloudShellConsole = serde_json::from_slice(&body).context(put_console::DeserializeError { body })?;
Ok(put_console::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(put_console::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(put_console::DeserializeError { body })?;
put_console::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod put_console {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(CloudShellConsole),
Created201(CloudShellConsole),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn delete_console(
operation_config: &crate::OperationConfig,
console_name: &str,
) -> std::result::Result<delete_console::Response, delete_console::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/consoles/{}",
&operation_config.base_path, console_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete_console::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete_console::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete_console::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete_console::Response::Ok200),
StatusCode::NO_CONTENT => Ok(delete_console::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete_console::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(delete_console::DeserializeError { body })?;
delete_console::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete_console {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn keep_alive(operation_config: &crate::OperationConfig, console_name: &str) -> std::result::Result<(), keep_alive::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/providers/Microsoft.Portal/consoles/{}/keepAlive",
&operation_config.base_path, console_name
);
let mut req_builder = client.post(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(keep_alive::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0);
let req = req_builder.build().context(keep_alive::BuildRequestError)?;
let rsp = client.execute(req).await.context(keep_alive::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(()),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(keep_alive::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(keep_alive::DeserializeError { body })?;
keep_alive::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod keep_alive {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
|
use std::net::IpAddr;
use std::path::PathBuf;
use std::process::exit;
use std::str::FromStr;
fn help_msg() -> String {
format!(
"Simple command-line tool to get your external IP address.
Usage:
myip [options]
Options:
-a --address <ip> Look for specified IP
-d --database <path> Custom MaxMind database directory [default: {}]
-c --color <when> When to colorize text output [possible values: {}]
-s --short Show only IP (skip query to local MaxMind database)
-j --json Output in JSON
-h --help Prints help information
-v --version Prints version information",
crate::DEFAULT_DATABASE_PATH,
crate::COLORS.join(", ")
)
}
#[derive(Debug)]
pub struct Args {
pub address: Option<IpAddr>,
pub database: PathBuf,
pub color: Color,
pub short: bool,
pub json: bool,
version: bool,
}
pub fn from_env() -> Result<Args, lexopt::Error> {
use lexopt::prelude::*;
let mut args = Args {
address: None,
database: PathBuf::from(crate::DEFAULT_DATABASE_PATH),
color: Color::Auto,
short: false,
json: false,
version: false,
};
let mut parser = lexopt::Parser::from_env();
while let Some(arg) = parser.next()? {
match arg {
Short('a') | Long("address") if args.address.is_none() => {
args.address = Some(parser.value()?.parse()?)
}
Short('d') | Long("database") => args.database = parser.value()?.into_string()?.into(),
Short('c') | Long("color") => args.color = parser.value()?.parse()?,
Short('s') | Long("short") => args.short = true,
Short('j') | Long("json") => args.json = true,
Short('v') | Long("version") => {
println!("{} {}", crate::NAME, crate::VERSION);
exit(0);
}
Short('h') | Long("help") => {
println!("{}", help_msg());
exit(0);
}
_ => return Err(arg.unexpected()),
}
}
Ok(args)
}
#[derive(Debug, PartialEq)]
pub enum Color {
Auto,
Always,
Never,
}
impl FromStr for Color {
type Err = String;
fn from_str(input: &str) -> Result<Color, Self::Err> {
match input {
"auto" => Ok(Color::Auto),
"always" => Ok(Color::Always),
"never" => Ok(Color::Never),
_ => Err(format!(
"Invalid color '{}' [possible values: {}]",
input,
crate::COLORS.join(", ")
)),
}
}
}
|
use string_repr::StringRepr;
#[macro_export]
macro_rules! host {
($host:expr) => {
Host::new($host)
};
}
pub struct Host<'a>(&'a str);
impl<'a> Host<'a> {
/// Create new Host.
/// # Example:
/// ```
/// use wdg_uri::authority::Host;
/// let host = Host::new("localhost");
/// ```
pub fn new(data: &str) -> Host {
Host(data)
}
/// Validate Host.
/// # Support:
/// * IPv4Address
/// * IPv6Address
/// # Example:
/// ```
/// use wdg_uri::authority::Host;
/// let host = Host::new("127.0.0.1");
/// if !host.validate() {
/// panic!("fail");
/// }
/// ```
pub fn validate(&self) -> bool {
self.is_ipv4addr() | self.is_ipv6addr()
}
/// Check if Host is IPv4Address.
/// # Example:
/// ```
/// use wdg_uri::authority::Host;
/// let host = Host::new("127.0.0.1");
/// if host.is_ipv4addr() {
/// println!("Host is IPv4Address.");
/// }
/// ```
pub fn is_ipv4addr(&self) -> bool {
regexp::IP_V4_ADDR(&self.0)
}
/// Check if Host is IPv6Address.
/// # Example:
/// ```
/// use wdg_uri::authority::Host;
/// let host = Host::new("::");
/// if host.is_ipv6addr() {
/// println!("Host is IPv6Address.");
/// }
/// ```
pub fn is_ipv6addr(&self) -> bool {
regexp::IP_V6_ADDR(&self.0)
}
}
impl<'a> StringRepr for Host<'a> {
fn string_repr(&self) -> String {
String::from(self.0)
}
}
|
// MIT License
//
// Copyright (c) 2018-2021 Hans-Martin Will
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use users;
use super::schema;
use super::symbols;
/// Session state maintained for interactions with the database.
pub struct Session {
/// The database object describing all known schemata
pub database: schema::Database,
/// The user name associated with this session
pub user: String,
/// The default schema associated with this session; for now, this is the same as the user name
pub default_schema: symbols::Name,
}
impl Session {
pub fn new() -> Session {
let username = users::get_current_username().unwrap();
let mut database = schema::Database::new();
let schema_name = symbols::Name::from(&username[..]);
database
.create_schema(&schema_name)
.expect("Database expected to be empty");
Session {
database,
user: username,
// we are using the OS user name as schema
default_schema: schema_name,
}
}
}
|
use super::{Command, Stack};
use crate::{
ast::Block, AliasId, BlockId, DeclId, Example, Overlay, OverlayId, ShellError, Signature, Span,
Type, VarId, Variable,
};
use core::panic;
use std::{
collections::HashMap,
sync::{atomic::AtomicBool, Arc},
};
use crate::Value;
use std::borrow::Borrow;
use std::path::Path;
#[cfg(feature = "plugin")]
use std::path::PathBuf;
static PWD_ENV: &str = "PWD";
// Tells whether a decl etc. is visible or not
#[derive(Debug, Clone)]
pub struct Visibility {
decl_ids: HashMap<DeclId, bool>,
alias_ids: HashMap<AliasId, bool>,
}
impl Visibility {
pub fn new() -> Self {
Visibility {
decl_ids: HashMap::new(),
alias_ids: HashMap::new(),
}
}
pub fn is_decl_id_visible(&self, decl_id: &DeclId) -> bool {
*self.decl_ids.get(decl_id).unwrap_or(&true) // by default it's visible
}
pub fn is_alias_id_visible(&self, alias_id: &AliasId) -> bool {
*self.alias_ids.get(alias_id).unwrap_or(&true) // by default it's visible
}
fn hide_decl_id(&mut self, decl_id: &DeclId) {
self.decl_ids.insert(*decl_id, false);
}
fn hide_alias_id(&mut self, alias_id: &AliasId) {
self.alias_ids.insert(*alias_id, false);
}
fn use_decl_id(&mut self, decl_id: &DeclId) {
self.decl_ids.insert(*decl_id, true);
}
fn use_alias_id(&mut self, alias_id: &AliasId) {
self.alias_ids.insert(*alias_id, true);
}
pub fn merge_with(&mut self, other: Visibility) {
// overwrite own values with the other
self.decl_ids.extend(other.decl_ids);
self.alias_ids.extend(other.alias_ids);
// self.env_var_ids.extend(other.env_var_ids);
}
fn append(&mut self, other: &Visibility) {
// take new values from the other but keep own values
for (decl_id, visible) in other.decl_ids.iter() {
if !self.decl_ids.contains_key(decl_id) {
self.decl_ids.insert(*decl_id, *visible);
}
}
for (alias_id, visible) in other.alias_ids.iter() {
if !self.alias_ids.contains_key(alias_id) {
self.alias_ids.insert(*alias_id, *visible);
}
}
}
}
impl Default for Visibility {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone)]
pub struct ScopeFrame {
pub vars: HashMap<Vec<u8>, VarId>,
predecls: HashMap<Vec<u8>, DeclId>, // temporary storage for predeclarations
pub decls: HashMap<Vec<u8>, DeclId>,
pub aliases: HashMap<Vec<u8>, AliasId>,
pub env_vars: HashMap<Vec<u8>, BlockId>,
pub overlays: HashMap<Vec<u8>, OverlayId>,
pub visibility: Visibility,
}
impl ScopeFrame {
pub fn new() -> Self {
Self {
vars: HashMap::new(),
predecls: HashMap::new(),
decls: HashMap::new(),
aliases: HashMap::new(),
env_vars: HashMap::new(),
overlays: HashMap::new(),
visibility: Visibility::new(),
}
}
pub fn get_var(&self, var_name: &[u8]) -> Option<&VarId> {
self.vars.get(var_name)
}
}
impl Default for ScopeFrame {
fn default() -> Self {
Self::new()
}
}
/// The core global engine state. This includes all global definitions as well as any global state that
/// will persist for the whole session.
///
/// Declarations, variables, blocks, and other forms of data are held in the global state and referenced
/// elsewhere using their IDs. These IDs are simply their index into the global state. This allows us to
/// more easily handle creating blocks, binding variables and callsites, and more, because each of these
/// will refer to the corresponding IDs rather than their definitions directly. At runtime, this means
/// less copying and smaller structures.
///
/// Note that the runtime stack is not part of this global state. Runtime stacks are handled differently,
/// but they also rely on using IDs rather than full definitions.
///
/// A note on implementation:
///
/// Much of the global definitions are built on the Bodil's 'im' crate. This gives us a way of working with
/// lists of definitions in a way that is very cheap to access, while also allowing us to update them at
/// key points in time (often, the transition between parsing and evaluation).
///
/// Over the last two years we tried a few different approaches to global state like this. I'll list them
/// here for posterity, so we can more easily know how we got here:
///
/// * `Rc` - Rc is cheap, but not thread-safe. The moment we wanted to work with external processes, we
/// needed a way send to stdin/stdout. In Rust, the current practice is to spawn a thread to handle both.
/// These threads would need access to the global state, as they'll need to process data as it streams out
/// of the data pipeline. Because Rc isn't thread-safe, this breaks.
///
/// * `Arc` - Arc is the thread-safe version of the above. Often Arc is used in combination with a Mutex or
/// RwLock, but you can use Arc by itself. We did this a few places in the original Nushell. This *can* work
/// but because of Arc's nature of not allowing mutation if there's a second copy of the Arc around, this
/// ultimately becomes limiting.
///
/// * `Arc` + `Mutex/RwLock` - the standard practice for thread-safe containers. Unfortunately, this would
/// have meant we would incur a lock penalty every time we needed to access any declaration or block. As we
/// would be reading far more often than writing, it made sense to explore solutions that favor large amounts
/// of reads.
///
/// * `im` - the `im` crate was ultimately chosen because it has some very nice properties: it gives the
/// ability to cheaply clone these structures, which is nice as EngineState may need to be cloned a fair bit
/// to follow ownership rules for closures and iterators. It also is cheap to access. Favoring reads here fits
/// more closely to what we need with Nushell. And, of course, it's still thread-safe, so we get the same
/// benefits as above.
///
#[derive(Clone)]
pub struct EngineState {
files: im::Vector<(String, usize, usize)>,
file_contents: im::Vector<(Vec<u8>, usize, usize)>,
vars: im::Vector<Variable>,
decls: im::Vector<Box<dyn Command + 'static>>,
aliases: im::Vector<Vec<Span>>,
blocks: im::Vector<Block>,
overlays: im::Vector<Overlay>,
pub scope: im::Vector<ScopeFrame>,
pub ctrlc: Option<Arc<AtomicBool>>,
pub env_vars: im::HashMap<String, Value>,
#[cfg(feature = "plugin")]
pub plugin_signatures: Option<PathBuf>,
}
pub const NU_VARIABLE_ID: usize = 0;
pub const IN_VARIABLE_ID: usize = 1;
pub const CONFIG_VARIABLE_ID: usize = 2;
pub const ENV_VARIABLE_ID: usize = 3;
// NOTE: If you add more to this list, make sure to update the > checks based on the last in the list
impl EngineState {
pub fn new() -> Self {
Self {
files: im::vector![],
file_contents: im::vector![],
vars: im::vector![
Variable::new(Span::new(0, 0), Type::Any),
Variable::new(Span::new(0, 0), Type::Any),
Variable::new(Span::new(0, 0), Type::Any),
Variable::new(Span::new(0, 0), Type::Any),
Variable::new(Span::new(0, 0), Type::Any)
],
decls: im::vector![],
aliases: im::vector![],
blocks: im::vector![],
overlays: im::vector![],
scope: im::vector![ScopeFrame::new()],
ctrlc: None,
env_vars: im::HashMap::new(),
#[cfg(feature = "plugin")]
plugin_signatures: None,
}
}
/// Merges a `StateDelta` onto the current state. These deltas come from a system, like the parser, that
/// creates a new set of definitions and visible symbols in the current scope. We make this transactional
/// as there are times when we want to run the parser and immediately throw away the results (namely:
/// syntax highlighting and completions).
///
/// When we want to preserve what the parser has created, we can take its output (the `StateDelta`) and
/// use this function to merge it into the global state.
pub fn merge_delta(
&mut self,
mut delta: StateDelta,
stack: Option<&mut Stack>,
cwd: impl AsRef<Path>,
) -> Result<(), ShellError> {
// Take the mutable reference and extend the permanent state from the working set
self.files.extend(delta.files);
self.file_contents.extend(delta.file_contents);
self.decls.extend(delta.decls);
self.aliases.extend(delta.aliases);
self.vars.extend(delta.vars);
self.blocks.extend(delta.blocks);
self.overlays.extend(delta.overlays);
if let Some(last) = self.scope.back_mut() {
let first = delta.scope.remove(0);
for item in first.decls.into_iter() {
last.decls.insert(item.0, item.1);
}
for item in first.vars.into_iter() {
last.vars.insert(item.0, item.1);
}
for item in first.aliases.into_iter() {
last.aliases.insert(item.0, item.1);
}
for item in first.overlays.into_iter() {
last.overlays.insert(item.0, item.1);
}
last.visibility.merge_with(first.visibility);
#[cfg(feature = "plugin")]
if delta.plugins_changed {
let result = self.update_plugin_file();
if result.is_ok() {
delta.plugins_changed = false;
}
return result;
}
}
if let Some(stack) = stack {
for mut env_scope in stack.env_vars.drain(..) {
for (k, v) in env_scope.drain() {
self.env_vars.insert(k, v);
}
}
}
// FIXME: permanent state changes like this hopefully in time can be removed
// and be replaced by just passing the cwd in where needed
std::env::set_current_dir(cwd)?;
Ok(())
}
#[cfg(feature = "plugin")]
pub fn update_plugin_file(&self) -> Result<(), ShellError> {
use std::io::Write;
// Updating the signatures plugin file with the added signatures
self.plugin_signatures
.as_ref()
.ok_or_else(|| ShellError::PluginFailedToLoad("Plugin file not found".into()))
.and_then(|plugin_path| {
// Always create the file, which will erase previous signatures
std::fs::File::create(plugin_path.as_path())
.map_err(|err| ShellError::PluginFailedToLoad(err.to_string()))
})
.and_then(|mut plugin_file| {
// Plugin definitions with parsed signature
self.plugin_decls().try_for_each(|decl| {
// A successful plugin registration already includes the plugin filename
// No need to check the None option
let (path, encoding, shell) =
decl.is_plugin().expect("plugin should have file name");
let file_name = path
.to_str()
.expect("path was checked during registration as a str");
serde_json::to_string_pretty(&decl.signature())
.map(|signature| {
// Extracting the possible path to the shell used to load the plugin
let shell_str = match shell {
Some(path) => format!(
"-s {}",
path.to_str().expect(
"shell path was checked during registration as a str"
)
),
None => "".into(),
};
// Each signature is stored in the plugin file with the required
// encoding, shell and signature
// This information will be used when loading the plugin
// information when nushell starts
format!(
"register {} -e {} {} {}\n\n",
file_name, encoding, shell_str, signature
)
})
.map_err(|err| ShellError::PluginFailedToLoad(err.to_string()))
.and_then(|line| {
plugin_file
.write_all(line.as_bytes())
.map_err(|err| ShellError::PluginFailedToLoad(err.to_string()))
})
})
})
}
pub fn num_files(&self) -> usize {
self.files.len()
}
pub fn num_vars(&self) -> usize {
self.vars.len()
}
pub fn num_decls(&self) -> usize {
self.decls.len()
}
pub fn num_aliases(&self) -> usize {
self.aliases.len()
}
pub fn num_blocks(&self) -> usize {
self.blocks.len()
}
pub fn num_overlays(&self) -> usize {
self.overlays.len()
}
pub fn print_vars(&self) {
for var in self.vars.iter().enumerate() {
println!("var{}: {:?}", var.0, var.1);
}
}
pub fn print_decls(&self) {
for decl in self.decls.iter().enumerate() {
println!("decl{}: {:?}", decl.0, decl.1.signature());
}
}
pub fn print_blocks(&self) {
for block in self.blocks.iter().enumerate() {
println!("block{}: {:?}", block.0, block.1);
}
}
pub fn print_contents(&self) {
for (contents, _, _) in self.file_contents.iter() {
let string = String::from_utf8_lossy(contents);
println!("{}", string);
}
}
pub fn find_decl(&self, name: &[u8]) -> Option<DeclId> {
let mut visibility: Visibility = Visibility::new();
for scope in self.scope.iter().rev() {
visibility.append(&scope.visibility);
if let Some(decl_id) = scope.decls.get(name) {
if visibility.is_decl_id_visible(decl_id) {
return Some(*decl_id);
}
}
}
None
}
pub fn find_alias(&self, name: &[u8]) -> Option<AliasId> {
let mut visibility: Visibility = Visibility::new();
for scope in self.scope.iter().rev() {
visibility.append(&scope.visibility);
if let Some(alias_id) = scope.aliases.get(name) {
if visibility.is_alias_id_visible(alias_id) {
return Some(*alias_id);
}
}
}
None
}
#[cfg(feature = "plugin")]
pub fn plugin_decls(&self) -> impl Iterator<Item = &Box<dyn Command + 'static>> {
let mut unique_plugin_decls = HashMap::new();
// Make sure there are no duplicate decls: Newer one overwrites the older one
for decl in self.decls.iter().filter(|d| d.is_plugin().is_some()) {
unique_plugin_decls.insert(decl.name(), decl);
}
let mut plugin_decls: Vec<(&str, &Box<dyn Command>)> =
unique_plugin_decls.into_iter().collect();
// Sort the plugins by name so we don't end up with a random plugin file each time
plugin_decls.sort_by(|a, b| a.0.cmp(b.0));
plugin_decls.into_iter().map(|(_, decl)| decl)
}
pub fn find_overlay(&self, name: &[u8]) -> Option<OverlayId> {
for scope in self.scope.iter().rev() {
if let Some(overlay_id) = scope.overlays.get(name) {
return Some(*overlay_id);
}
}
None
}
pub fn find_commands_by_prefix(&self, name: &[u8]) -> Vec<(Vec<u8>, Option<String>)> {
let mut output = vec![];
for scope in self.scope.iter().rev() {
for decl in &scope.decls {
if decl.0.starts_with(name) {
let command = self.get_decl(*decl.1);
output.push((decl.0.clone(), Some(command.usage().to_string())));
}
}
}
output
}
pub fn find_aliases_by_prefix(&self, name: &[u8]) -> Vec<Vec<u8>> {
self.scope
.iter()
.rev()
.flat_map(|scope| &scope.aliases)
.filter(|decl| decl.0.starts_with(name))
.map(|decl| decl.0.clone())
.collect()
}
pub fn get_span_contents(&self, span: &Span) -> &[u8] {
for (contents, start, finish) in &self.file_contents {
if span.start >= *start && span.end <= *finish {
return &contents[(span.start - start)..(span.end - start)];
}
}
panic!("internal error: span missing in file contents cache")
}
pub fn get_var(&self, var_id: VarId) -> &Variable {
self.vars
.get(var_id)
.expect("internal error: missing variable")
}
#[allow(clippy::borrowed_box)]
pub fn get_decl(&self, decl_id: DeclId) -> &Box<dyn Command> {
self.decls
.get(decl_id)
.expect("internal error: missing declaration")
}
pub fn get_alias(&self, alias_id: AliasId) -> &[Span] {
self.aliases
.get(alias_id)
.expect("internal error: missing alias")
.as_ref()
}
/// Get all IDs of all commands within scope, sorted by the commads' names
pub fn get_decl_ids_sorted(&self, include_hidden: bool) -> impl Iterator<Item = DeclId> {
let mut decls_map = HashMap::new();
for frame in &self.scope {
let frame_decls = if include_hidden {
frame.decls.clone()
} else {
frame
.decls
.clone()
.into_iter()
.filter(|(_, id)| frame.visibility.is_decl_id_visible(id))
.collect()
};
decls_map.extend(frame_decls);
}
let mut decls: Vec<(Vec<u8>, DeclId)> = decls_map.into_iter().collect();
decls.sort_by(|a, b| a.0.cmp(&b.0));
decls.into_iter().map(|(_, id)| id)
}
/// Get signatures of all commands within scope.
pub fn get_signatures(&self, include_hidden: bool) -> Vec<Signature> {
self.get_decl_ids_sorted(include_hidden)
.map(|id| {
let decl = self.get_decl(id);
(*decl).signature().update_from_command(decl.borrow())
})
.collect()
}
/// Get signatures of all commands within scope.
///
/// In addition to signatures, it returns whether each command is:
/// a) a plugin
/// b) custom
pub fn get_signatures_with_examples(
&self,
include_hidden: bool,
) -> Vec<(Signature, Vec<Example>, bool, bool)> {
self.get_decl_ids_sorted(include_hidden)
.map(|id| {
let decl = self.get_decl(id);
let signature = (*decl).signature().update_from_command(decl.borrow());
(
signature,
decl.examples(),
decl.is_plugin().is_some(),
decl.get_block_id().is_some(),
)
})
.collect()
}
pub fn get_block(&self, block_id: BlockId) -> &Block {
self.blocks
.get(block_id)
.expect("internal error: missing block")
}
pub fn get_overlay(&self, overlay_id: OverlayId) -> &Overlay {
self.overlays
.get(overlay_id)
.expect("internal error: missing overlay")
}
pub fn next_span_start(&self) -> usize {
if let Some((_, _, last)) = self.file_contents.last() {
*last
} else {
0
}
}
pub fn files(&self) -> impl Iterator<Item = &(String, usize, usize)> {
self.files.iter()
}
pub fn get_filename(&self, file_id: usize) -> String {
for file in self.files.iter().enumerate() {
if file.0 == file_id {
return file.1 .0.clone();
}
}
"<unknown>".into()
}
pub fn get_file_source(&self, file_id: usize) -> String {
for file in self.files.iter().enumerate() {
if file.0 == file_id {
let contents = self.get_span_contents(&Span {
start: file.1 .1,
end: file.1 .2,
});
let output = String::from_utf8_lossy(contents).to_string();
return output;
}
}
"<unknown>".into()
}
pub fn add_file(&mut self, filename: String, contents: Vec<u8>) -> usize {
let next_span_start = self.next_span_start();
let next_span_end = next_span_start + contents.len();
self.file_contents
.push_back((contents, next_span_start, next_span_end));
self.files
.push_back((filename, next_span_start, next_span_end));
self.num_files() - 1
}
}
impl Default for EngineState {
fn default() -> Self {
Self::new()
}
}
/// A temporary extension to the global state. This handles bridging between the global state and the
/// additional declarations and scope changes that are not yet part of the global scope.
///
/// This working set is created by the parser as a way of handling declarations and scope changes that
/// may later be merged or dropped (and not merged) depending on the needs of the code calling the parser.
pub struct StateWorkingSet<'a> {
pub permanent_state: &'a EngineState,
pub delta: StateDelta,
pub external_commands: Vec<Vec<u8>>,
}
/// A delta (or change set) between the current global state and a possible future global state. Deltas
/// can be applied to the global state to update it to contain both previous state and the state held
/// within the delta.
pub struct StateDelta {
files: Vec<(String, usize, usize)>,
pub(crate) file_contents: Vec<(Vec<u8>, usize, usize)>,
vars: Vec<Variable>, // indexed by VarId
decls: Vec<Box<dyn Command>>, // indexed by DeclId
aliases: Vec<Vec<Span>>, // indexed by AliasId
pub blocks: Vec<Block>, // indexed by BlockId
overlays: Vec<Overlay>, // indexed by OverlayId
pub scope: Vec<ScopeFrame>,
#[cfg(feature = "plugin")]
plugins_changed: bool, // marks whether plugin file should be updated
}
impl Default for StateDelta {
fn default() -> Self {
Self::new()
}
}
impl StateDelta {
pub fn new() -> Self {
StateDelta {
files: vec![],
file_contents: vec![],
vars: vec![],
decls: vec![],
aliases: vec![],
blocks: vec![],
overlays: vec![],
scope: vec![ScopeFrame::new()],
#[cfg(feature = "plugin")]
plugins_changed: false,
}
}
pub fn num_files(&self) -> usize {
self.files.len()
}
pub fn num_decls(&self) -> usize {
self.decls.len()
}
pub fn num_aliases(&self) -> usize {
self.aliases.len()
}
pub fn num_blocks(&self) -> usize {
self.blocks.len()
}
pub fn num_overlays(&self) -> usize {
self.overlays.len()
}
pub fn enter_scope(&mut self) {
self.scope.push(ScopeFrame::new());
}
pub fn exit_scope(&mut self) {
self.scope.pop();
}
}
impl<'a> StateWorkingSet<'a> {
pub fn new(permanent_state: &'a EngineState) -> Self {
Self {
delta: StateDelta::new(),
permanent_state,
external_commands: vec![],
}
}
pub fn num_files(&self) -> usize {
self.delta.num_files() + self.permanent_state.num_files()
}
pub fn num_decls(&self) -> usize {
self.delta.num_decls() + self.permanent_state.num_decls()
}
pub fn num_aliases(&self) -> usize {
self.delta.num_aliases() + self.permanent_state.num_aliases()
}
pub fn num_blocks(&self) -> usize {
self.delta.num_blocks() + self.permanent_state.num_blocks()
}
pub fn num_overlays(&self) -> usize {
self.delta.num_overlays() + self.permanent_state.num_overlays()
}
pub fn add_decl(&mut self, decl: Box<dyn Command>) -> DeclId {
let name = decl.name().as_bytes().to_vec();
self.delta.decls.push(decl);
let decl_id = self.num_decls() - 1;
let scope_frame = self
.delta
.scope
.last_mut()
.expect("internal error: missing required scope frame");
scope_frame.decls.insert(name, decl_id);
decl_id
}
pub fn use_decls(&mut self, decls: Vec<(Vec<u8>, DeclId)>) {
let scope_frame = self
.delta
.scope
.last_mut()
.expect("internal error: missing required scope frame");
for (name, decl_id) in decls {
scope_frame.decls.insert(name, decl_id);
scope_frame.visibility.use_decl_id(&decl_id);
}
}
pub fn use_aliases(&mut self, aliases: Vec<(Vec<u8>, AliasId)>) {
let scope_frame = self
.delta
.scope
.last_mut()
.expect("internal error: missing required scope frame");
for (name, alias_id) in aliases {
scope_frame.aliases.insert(name, alias_id);
scope_frame.visibility.use_alias_id(&alias_id);
}
}
pub fn add_predecl(&mut self, decl: Box<dyn Command>) -> Option<DeclId> {
let name = decl.name().as_bytes().to_vec();
self.delta.decls.push(decl);
let decl_id = self.num_decls() - 1;
let scope_frame = self
.delta
.scope
.last_mut()
.expect("internal error: missing required scope frame");
scope_frame.predecls.insert(name, decl_id)
}
#[cfg(feature = "plugin")]
pub fn mark_plugins_file_dirty(&mut self) {
self.delta.plugins_changed = true;
}
pub fn merge_predecl(&mut self, name: &[u8]) -> Option<DeclId> {
let scope_frame = self
.delta
.scope
.last_mut()
.expect("internal error: missing required scope frame");
if let Some(decl_id) = scope_frame.predecls.remove(name) {
scope_frame.decls.insert(name.into(), decl_id);
return Some(decl_id);
}
None
}
pub fn hide_decl(&mut self, name: &[u8]) -> Option<DeclId> {
let mut visibility: Visibility = Visibility::new();
// Since we can mutate scope frames in delta, remove the id directly
for scope in self.delta.scope.iter_mut().rev() {
visibility.append(&scope.visibility);
if let Some(decl_id) = scope.decls.get(name) {
if visibility.is_decl_id_visible(decl_id) {
// Hide decl only if it's not already hidden
scope.visibility.hide_decl_id(decl_id);
return Some(*decl_id);
}
}
}
// We cannot mutate the permanent state => store the information in the current scope frame
let last_scope_frame = self
.delta
.scope
.last_mut()
.expect("internal error: missing required scope frame");
for scope in self.permanent_state.scope.iter().rev() {
visibility.append(&scope.visibility);
if let Some(decl_id) = scope.decls.get(name) {
if visibility.is_decl_id_visible(decl_id) {
// Hide decl only if it's not already hidden
last_scope_frame.visibility.hide_decl_id(decl_id);
return Some(*decl_id);
}
}
}
None
}
pub fn use_alias(&mut self, alias_id: &AliasId) {
let mut visibility: Visibility = Visibility::new();
// Since we can mutate scope frames in delta, remove the id directly
for scope in self.delta.scope.iter_mut().rev() {
visibility.append(&scope.visibility);
if !visibility.is_alias_id_visible(alias_id) {
// Hide alias only if it's not already hidden
scope.visibility.use_alias_id(alias_id);
return;
}
}
// We cannot mutate the permanent state => store the information in the current scope frame
let last_scope_frame = self
.delta
.scope
.last_mut()
.expect("internal error: missing required scope frame");
for scope in self.permanent_state.scope.iter().rev() {
visibility.append(&scope.visibility);
if !visibility.is_alias_id_visible(alias_id) {
// Hide alias only if it's not already hidden
last_scope_frame.visibility.use_alias_id(alias_id);
return;
}
}
}
pub fn hide_alias(&mut self, name: &[u8]) -> Option<AliasId> {
let mut visibility: Visibility = Visibility::new();
// Since we can mutate scope frames in delta, remove the id directly
for scope in self.delta.scope.iter_mut().rev() {
visibility.append(&scope.visibility);
if let Some(alias_id) = scope.aliases.get(name) {
if visibility.is_alias_id_visible(alias_id) {
// Hide alias only if it's not already hidden
scope.visibility.hide_alias_id(alias_id);
return Some(*alias_id);
}
}
}
// We cannot mutate the permanent state => store the information in the current scope frame
let last_scope_frame = self
.delta
.scope
.last_mut()
.expect("internal error: missing required scope frame");
for scope in self.permanent_state.scope.iter().rev() {
visibility.append(&scope.visibility);
if let Some(alias_id) = scope.aliases.get(name) {
if visibility.is_alias_id_visible(alias_id) {
// Hide alias only if it's not already hidden
last_scope_frame.visibility.hide_alias_id(alias_id);
return Some(*alias_id);
}
}
}
None
}
pub fn hide_decls(&mut self, decls: &[Vec<u8>]) {
for decl in decls.iter() {
self.hide_decl(decl); // let's assume no errors
}
}
pub fn hide_aliases(&mut self, aliases: &[Vec<u8>]) {
for alias in aliases.iter() {
self.hide_alias(alias); // let's assume no errors
}
}
pub fn add_block(&mut self, block: Block) -> BlockId {
self.delta.blocks.push(block);
self.num_blocks() - 1
}
pub fn add_env_var(&mut self, name_span: Span, block: Block) -> BlockId {
self.delta.blocks.push(block);
let block_id = self.num_blocks() - 1;
let name = self.get_span_contents(name_span).to_vec();
let scope_frame = self
.delta
.scope
.last_mut()
.expect("internal error: missing required scope frame");
scope_frame.env_vars.insert(name, block_id);
block_id
}
pub fn add_overlay(&mut self, name: &str, overlay: Overlay) -> OverlayId {
let name = name.as_bytes().to_vec();
self.delta.overlays.push(overlay);
let overlay_id = self.num_overlays() - 1;
let scope_frame = self
.delta
.scope
.last_mut()
.expect("internal error: missing required scope frame");
scope_frame.overlays.insert(name, overlay_id);
overlay_id
}
pub fn next_span_start(&self) -> usize {
let permanent_span_start = self.permanent_state.next_span_start();
if let Some((_, _, last)) = self.delta.file_contents.last() {
*last
} else {
permanent_span_start
}
}
pub fn global_span_offset(&self) -> usize {
self.permanent_state.next_span_start()
}
pub fn files(&'a self) -> impl Iterator<Item = &(String, usize, usize)> {
self.permanent_state.files().chain(self.delta.files.iter())
}
pub fn get_filename(&self, file_id: usize) -> String {
for file in self.files().enumerate() {
if file.0 == file_id {
return file.1 .0.clone();
}
}
"<unknown>".into()
}
pub fn get_file_source(&self, file_id: usize) -> String {
for file in self.files().enumerate() {
if file.0 == file_id {
let output = String::from_utf8_lossy(self.get_span_contents(Span {
start: file.1 .1,
end: file.1 .2,
}))
.to_string();
return output;
}
}
"<unknown>".into()
}
pub fn add_file(&mut self, filename: String, contents: &[u8]) -> usize {
let next_span_start = self.next_span_start();
let next_span_end = next_span_start + contents.len();
self.delta
.file_contents
.push((contents.to_vec(), next_span_start, next_span_end));
self.delta
.files
.push((filename, next_span_start, next_span_end));
self.num_files() - 1
}
pub fn get_span_contents(&self, span: Span) -> &[u8] {
let permanent_end = self.permanent_state.next_span_start();
if permanent_end <= span.start {
for (contents, start, finish) in &self.delta.file_contents {
if (span.start >= *start) && (span.end <= *finish) {
return &contents[(span.start - start)..(span.end - start)];
}
}
} else {
return self.permanent_state.get_span_contents(&span);
}
panic!("internal error: missing span contents in file cache")
}
pub fn enter_scope(&mut self) {
self.delta.enter_scope();
}
pub fn exit_scope(&mut self) {
self.delta.exit_scope();
}
pub fn find_predecl(&self, name: &[u8]) -> Option<DeclId> {
for scope in self.delta.scope.iter().rev() {
if let Some(decl_id) = scope.predecls.get(name) {
return Some(*decl_id);
}
}
None
}
pub fn find_decl(&self, name: &[u8]) -> Option<DeclId> {
let mut visibility: Visibility = Visibility::new();
for scope in self.delta.scope.iter().rev() {
visibility.append(&scope.visibility);
if let Some(decl_id) = scope.predecls.get(name) {
if visibility.is_decl_id_visible(decl_id) {
return Some(*decl_id);
}
}
if let Some(decl_id) = scope.decls.get(name) {
if visibility.is_decl_id_visible(decl_id) {
return Some(*decl_id);
}
}
}
for scope in self.permanent_state.scope.iter().rev() {
visibility.append(&scope.visibility);
if let Some(decl_id) = scope.decls.get(name) {
if visibility.is_decl_id_visible(decl_id) {
return Some(*decl_id);
}
}
}
None
}
pub fn find_alias(&self, name: &[u8]) -> Option<AliasId> {
let mut visibility: Visibility = Visibility::new();
for scope in self.delta.scope.iter().rev() {
visibility.append(&scope.visibility);
if let Some(alias_id) = scope.aliases.get(name) {
if visibility.is_alias_id_visible(alias_id) {
return Some(*alias_id);
}
}
}
for scope in self.permanent_state.scope.iter().rev() {
visibility.append(&scope.visibility);
if let Some(alias_id) = scope.aliases.get(name) {
if visibility.is_alias_id_visible(alias_id) {
return Some(*alias_id);
}
}
}
None
}
pub fn find_overlay(&self, name: &[u8]) -> Option<OverlayId> {
for scope in self.delta.scope.iter().rev() {
if let Some(overlay_id) = scope.overlays.get(name) {
return Some(*overlay_id);
}
}
for scope in self.permanent_state.scope.iter().rev() {
if let Some(overlay_id) = scope.overlays.get(name) {
return Some(*overlay_id);
}
}
None
}
// pub fn update_decl(&mut self, decl_id: usize, block: Option<BlockId>) {
// let decl = self.get_decl_mut(decl_id);
// decl.body = block;
// }
pub fn contains_decl_partial_match(&self, name: &[u8]) -> bool {
for scope in self.delta.scope.iter().rev() {
for decl in &scope.decls {
if decl.0.starts_with(name) {
return true;
}
}
}
for scope in self.permanent_state.scope.iter().rev() {
for decl in &scope.decls {
if decl.0.starts_with(name) {
return true;
}
}
}
false
}
pub fn next_var_id(&self) -> VarId {
let num_permanent_vars = self.permanent_state.num_vars();
num_permanent_vars + self.delta.vars.len()
}
pub fn find_variable(&self, name: &[u8]) -> Option<VarId> {
for scope in self.delta.scope.iter().rev() {
if let Some(var_id) = scope.vars.get(name) {
return Some(*var_id);
}
}
for scope in self.permanent_state.scope.iter().rev() {
if let Some(var_id) = scope.vars.get(name) {
return Some(*var_id);
}
}
None
}
pub fn add_variable(&mut self, mut name: Vec<u8>, span: Span, ty: Type) -> VarId {
let next_id = self.next_var_id();
// correct name if necessary
if !name.starts_with(b"$") {
name.insert(0, b'$');
}
let last = self
.delta
.scope
.last_mut()
.expect("internal error: missing stack frame");
last.vars.insert(name, next_id);
self.delta.vars.push(Variable::new(span, ty));
next_id
}
pub fn add_alias(&mut self, name: Vec<u8>, replacement: Vec<Span>) {
self.delta.aliases.push(replacement);
let alias_id = self.num_aliases() - 1;
let last = self
.delta
.scope
.last_mut()
.expect("internal error: missing stack frame");
last.aliases.insert(name, alias_id);
last.visibility.use_alias_id(&alias_id);
}
pub fn get_cwd(&self) -> String {
let pwd = self
.permanent_state
.env_vars
.get(PWD_ENV)
.expect("internal error: can't find PWD");
pwd.as_string().expect("internal error: PWD not a string")
}
pub fn get_env(&self, name: &str) -> Option<&Value> {
self.permanent_state.env_vars.get(name)
}
pub fn set_variable_type(&mut self, var_id: VarId, ty: Type) {
let num_permanent_vars = self.permanent_state.num_vars();
if var_id < num_permanent_vars {
panic!("Internal error: attempted to set into permanent state from working set")
} else {
self.delta.vars[var_id - num_permanent_vars].ty = ty;
}
}
pub fn get_variable(&self, var_id: VarId) -> &Variable {
let num_permanent_vars = self.permanent_state.num_vars();
if var_id < num_permanent_vars {
self.permanent_state.get_var(var_id)
} else {
self.delta
.vars
.get(var_id - num_permanent_vars)
.expect("internal error: missing variable")
}
}
#[allow(clippy::borrowed_box)]
pub fn get_decl(&self, decl_id: DeclId) -> &Box<dyn Command> {
let num_permanent_decls = self.permanent_state.num_decls();
if decl_id < num_permanent_decls {
self.permanent_state.get_decl(decl_id)
} else {
self.delta
.decls
.get(decl_id - num_permanent_decls)
.expect("internal error: missing declaration")
}
}
pub fn get_decl_mut(&mut self, decl_id: DeclId) -> &mut Box<dyn Command> {
let num_permanent_decls = self.permanent_state.num_decls();
if decl_id < num_permanent_decls {
panic!("internal error: can only mutate declarations in working set")
} else {
self.delta
.decls
.get_mut(decl_id - num_permanent_decls)
.expect("internal error: missing declaration")
}
}
pub fn get_alias(&self, alias_id: AliasId) -> &[Span] {
let num_permanent_aliases = self.permanent_state.num_aliases();
if alias_id < num_permanent_aliases {
self.permanent_state.get_alias(alias_id)
} else {
self.delta
.aliases
.get(alias_id - num_permanent_aliases)
.expect("internal error: missing alias")
.as_ref()
}
}
pub fn find_commands_by_prefix(&self, name: &[u8]) -> Vec<(Vec<u8>, Option<String>)> {
let mut output = vec![];
for scope in self.delta.scope.iter().rev() {
for decl in &scope.decls {
if decl.0.starts_with(name) {
let command = self.get_decl(*decl.1);
output.push((decl.0.clone(), Some(command.usage().to_string())));
}
}
}
let mut permanent = self.permanent_state.find_commands_by_prefix(name);
output.append(&mut permanent);
output
}
pub fn find_aliases_by_prefix(&self, name: &[u8]) -> Vec<Vec<u8>> {
self.delta
.scope
.iter()
.rev()
.flat_map(|scope| &scope.aliases)
.filter(|decl| decl.0.starts_with(name))
.map(|decl| decl.0.clone())
.chain(self.permanent_state.find_aliases_by_prefix(name))
.collect()
}
pub fn get_block(&self, block_id: BlockId) -> &Block {
let num_permanent_blocks = self.permanent_state.num_blocks();
if block_id < num_permanent_blocks {
self.permanent_state.get_block(block_id)
} else {
self.delta
.blocks
.get(block_id - num_permanent_blocks)
.expect("internal error: missing block")
}
}
pub fn get_overlay(&self, overlay_id: OverlayId) -> &Overlay {
let num_permanent_overlays = self.permanent_state.num_overlays();
if overlay_id < num_permanent_overlays {
self.permanent_state.get_overlay(overlay_id)
} else {
self.delta
.overlays
.get(overlay_id - num_permanent_overlays)
.expect("internal error: missing overlay")
}
}
pub fn get_block_mut(&mut self, block_id: BlockId) -> &mut Block {
let num_permanent_blocks = self.permanent_state.num_blocks();
if block_id < num_permanent_blocks {
panic!("Attempt to mutate a block that is in the permanent (immutable) state")
} else {
self.delta
.blocks
.get_mut(block_id - num_permanent_blocks)
.expect("internal error: missing block")
}
}
pub fn render(self) -> StateDelta {
self.delta
}
}
impl<'a> miette::SourceCode for &StateWorkingSet<'a> {
fn read_span<'b>(
&'b self,
span: &miette::SourceSpan,
context_lines_before: usize,
context_lines_after: usize,
) -> Result<Box<dyn miette::SpanContents + 'b>, miette::MietteError> {
let debugging = std::env::var("MIETTE_DEBUG").is_ok();
if debugging {
let finding_span = "Finding span in StateWorkingSet";
dbg!(finding_span, span);
}
for (filename, start, end) in self.files() {
if debugging {
dbg!(&filename, start, end);
}
if span.offset() >= *start && span.offset() + span.len() <= *end {
if debugging {
let found_file = "Found matching file";
dbg!(found_file);
}
let our_span = Span {
start: *start,
end: *end,
};
// We need to move to a local span because we're only reading
// the specific file contents via self.get_span_contents.
let local_span = (span.offset() - *start, span.len()).into();
if debugging {
dbg!(&local_span);
}
let span_contents = self.get_span_contents(our_span);
if debugging {
dbg!(String::from_utf8_lossy(span_contents));
}
let span_contents = span_contents.read_span(
&local_span,
context_lines_before,
context_lines_after,
)?;
let content_span = span_contents.span();
// Back to "global" indexing
let retranslated = (content_span.offset() + start, content_span.len()).into();
if debugging {
dbg!(&retranslated);
}
let data = span_contents.data();
if filename == "<cli>" {
if debugging {
let success_cli = "Successfully read CLI span";
dbg!(success_cli, String::from_utf8_lossy(data));
}
return Ok(Box::new(miette::MietteSpanContents::new(
data,
retranslated,
span_contents.line(),
span_contents.column(),
span_contents.line_count(),
)));
} else {
if debugging {
let success_file = "Successfully read file span";
dbg!(success_file);
}
return Ok(Box::new(miette::MietteSpanContents::new_named(
filename.clone(),
data,
retranslated,
span_contents.line(),
span_contents.column(),
span_contents.line_count(),
)));
}
}
}
Err(miette::MietteError::OutOfBounds)
}
}
#[cfg(test)]
mod engine_state_tests {
use super::*;
#[test]
fn add_file_gives_id() {
let engine_state = EngineState::new();
let mut engine_state = StateWorkingSet::new(&engine_state);
let id = engine_state.add_file("test.nu".into(), &[]);
assert_eq!(id, 0);
}
#[test]
fn add_file_gives_id_including_parent() {
let mut engine_state = EngineState::new();
let parent_id = engine_state.add_file("test.nu".into(), vec![]);
let mut working_set = StateWorkingSet::new(&engine_state);
let working_set_id = working_set.add_file("child.nu".into(), &[]);
assert_eq!(parent_id, 0);
assert_eq!(working_set_id, 1);
}
#[test]
fn merge_states() -> Result<(), ShellError> {
let mut engine_state = EngineState::new();
engine_state.add_file("test.nu".into(), vec![]);
let delta = {
let mut working_set = StateWorkingSet::new(&engine_state);
working_set.add_file("child.nu".into(), &[]);
working_set.render()
};
let cwd = std::env::current_dir().expect("Could not get current working directory.");
engine_state.merge_delta(delta, None, &cwd)?;
assert_eq!(engine_state.num_files(), 2);
assert_eq!(&engine_state.files[0].0, "test.nu");
assert_eq!(&engine_state.files[1].0, "child.nu");
Ok(())
}
}
|
use core::{raw, slice};
use def::*;
use std::{io, mem, os, iter, ptr};
use std::collections::{LinkedList};
use std::vec::Vec;
use std::cell::RefCell;
use std::rc::Rc;
use libc;
use uio;
#[derive(PartialEq, PartialOrd, Eq, Ord, Clone, Debug)]
pub struct DbValue {
pub _data: Vec<u8>
}
impl DbValue {
pub fn from_vec(data: Vec<u8>) -> DbValue {
DbValue {
_data: data
}
}
}
pub type DbKey = DbValue;
bitflags!(
flags RecordFlags: u16 {
const FlagRecordBigData = 0x01
}
);
pub struct DbRecord {
pub page_number: PageNum,
pub record_flags: RecordFlags,
pub key: DbKey,
pub value: DbValue
}
bitflags!(
flags PageFlags: u16 {
const P_BRANCH = 0x01,
const P_LEAF = 0x02,
const P_OVERFLOW = 0x04,
const P_META = 0x08,
const P_DIRTY = 0x10,
const P_LOOSE = 0x4000
}
);
pub struct PageHeader {
pub page_num: PageNum,
pub space_indicator: SpaceIndicator,
pub flags: PageFlags
}
impl PageHeader {
pub fn new() -> PageHeader {
PageHeader {
page_num: 0,
space_indicator: SpaceIndicator::Bounds(0, 0),
flags: PageFlags::empty()
}
}
pub fn encode(&self, w: &mut io::MemWriter) -> Result<(), EncodeError> {
// 8 + 2 + 2 + 2
w.write_be_u64(self.page_num);
match self.space_indicator {
SpaceIndicator::Bounds(l, u) => {
w.write_be_u16(l);
w.write_be_u16(u);
},
SpaceIndicator::OverflowPageNum(pn) => {
w.write_be_u32(pn);
}
}
w.write_be_u16(self.flags.bits());
Ok(())
}
pub fn decode(r: &mut io::BufReader) -> Result<Self, DecodeError> {
let ph = PageHeader {
page_num: 0,
space_indicator: SpaceIndicator::Bounds(0, 0),
flags: PageFlags::empty()
};
Ok(ph)
}
}
pub struct Page {
pub _data: RefCell<Vec<u8>>,
}
impl Page {
pub fn is_overflow_page(&self) -> bool {
let f = self.get_dbpage_flag();
f.contains(P_OVERFLOW)
}
pub fn is_leaf_page(&self) -> bool {
let f = self.get_dbpage_flag();
f.contains(P_LEAF)
}
pub fn is_branch_page(&self) -> bool {
let f = self.get_dbpage_flag();
f.contains(P_BRANCH)
}
pub fn is_meta_page(&self) -> bool {
let f = self.get_dbpage_flag();
f.contains(P_META)
}
pub fn is_dirty(&self) -> bool {
let f = self.get_dbpage_flag();
f.contains(P_DIRTY)
}
pub fn set_dirty(&mut self) -> () {
let mut f = self.get_dbpage_flag();
f.insert(P_DIRTY);
self.set_dbpage_flag(f);
}
pub fn clear_dirty(&mut self) -> () {
let mut f = self.get_dbpage_flag();
f.remove(P_DIRTY);
self.set_dbpage_flag(f);
}
pub fn set_loose(&mut self) -> () {
let mut f = self.get_dbpage_flag();
f.insert(P_LOOSE);
self.set_dbpage_flag(f);
}
pub fn get_dbpage_number(&self) -> PageNum {
let data = self._data.borrow();
let mut r = io::BufReader::new(data.slice(0, 8));
let page_num = r.read_be_u64().unwrap();
page_num
}
pub fn get_page_span(&self) -> PageNum {
//FIXME
1
}
pub fn get_upper_bound(&self) -> Offset {
123
}
pub fn set_dbpage_number(&mut self, pgno: PageNum) -> () {
let mut data = self._data.borrow_mut();
let mut r = data.slice_mut(0, 8);
let a: [u8; 8] = unsafe { mem::transmute(pgno) };
for i in range(0, 8) {
r[i] = a[i];
}
}
pub fn get_dbpage_flag(&self) -> PageFlags {
let data = self._data.borrow();
let r = data.slice(12, 14);
let raw_flag: u16 = (r[0].to_u16().unwrap() << 8) + (r[1].to_u16().unwrap());
let f: PageFlags = unsafe { mem::transmute(raw_flag) };
f
}
pub fn set_dbpage_flag(&self, f: PageFlags) -> () {
let mut data = self._data.borrow_mut();
let mut w = io::MemWriter::new();
w.write_be_u16(f.bits());
let mut slot = data.slice_mut(12, 14);
slot[0] = w.get_ref()[0];
slot[1] = w.get_ref()[1];
}
pub fn set_space_indicator(&mut self, sp: SpaceIndicator) -> () {
let mut data = self._data.borrow_mut();
let mut r = data.slice_mut(8, 12);
//FIXME
}
pub fn get_page_header(&self) -> Option<PageHeader> {
let data = self._data.borrow();
let mut r = io::BufReader::new(data.as_slice());
let page_num = r.read_be_u64().unwrap();
let space_indicator = r.read_be_u32().unwrap();
let flags = r.read_be_u16().unwrap();
let p = PageHeader {
page_num: page_num,
space_indicator: SpaceIndicator::OverflowPageNum(space_indicator),
flags: unsafe { mem::transmute(flags) }
};
Some(p)
}
pub fn get_mut_idx_slice<'a>(&'a mut self) -> &'a mut [RecordIndex] {
unsafe {
let size_offset = PAGE_HEADER_SIZE.to_int().unwrap();
let data_offset = PAGE_HEADER_SIZE.to_int().unwrap() + mem::size_of::<RecordIndex>().to_int().unwrap();
let p: *const RecordIndex = self._data.borrow().as_ptr().offset(size_offset) as *const RecordIndex;
let l: RecordIndex = unsafe { ptr::read(p) };
mem::transmute(raw::Slice {
data: self._data.borrow_mut().as_mut_ptr().offset(data_offset) as *const RecordIndex,
len: l.to_uint().unwrap()
})
}
}
pub fn get_mut_idx<'a>(&'a mut self, index: usize) -> &'a mut RecordIndex {
&mut self.get_mut_idx_slice()[index]
}
pub fn size_left(&self) -> usize {
let header = self.get_page_header().unwrap();
match header.space_indicator {
SpaceIndicator::Bounds(l, u) => {
(u - l).to_uint().unwrap()
},
_ => { panic!("size_left shouldn't be called with overflow page") }
}
}
pub fn number_of_keys(&self) -> usize {
assert_eq!(self.is_branch_page(), true);
let header_size: u16 = 8 + 4 + 2;
let key_size: u16 = 4;
let mut data = self._data.borrow_mut();
let r = data.slice_mut(8, 10);
let lower_bound: u16 = (r[0].to_u16().unwrap() << 8) + (r[1].to_u16().unwrap());
let key_num: usize = ((lower_bound - header_size) / key_size).to_uint().unwrap();
return key_num;
}
pub fn get_dbrecord(&self, i: usize) -> Option<DbRecord> {
let header_size: usize = 14;
let key_size: usize = 4;
let offset: usize = header_size + (i * key_size);
let data = self._data.borrow();
let mut r = io::BufReader::new(data.slice(offset, offset+key_size));
let page_number = r.read_be_u64().unwrap();
let db_record = DbRecord {
page_number: page_number,
record_flags: RecordFlags::empty(),
key: DbKey { _data: Vec::new() },
value: DbValue { _data: Vec::new() }
};
Some(db_record)
}
}
pub struct PageManager {
pub mapped_region: MemoryMap,
pub db_fd: Rc<RefCell<file::FileDesc>>,
pub db_pagesize: usize,
pub db_mapsize: usize,
pub free_pages: Vec<Rc<RefCell<Box<Page>>>>,
pub dirty_pages: LinkedList<Rc<RefCell<Box<Page>>>>,
pub loose_pages: Vec<Rc<RefCell<Box<Page>>>>
}
impl PageManager {
pub fn new(db_pagesize: usize, db_mapsize: usize, filedesc: Rc<RefCell<file::FileDesc>>) -> Option<PageManager> {
let options = [MapOption::MapReadable, MapOption::MapFd(filedesc.borrow().fd())];
let region = match MemoryMap::new(db_mapsize, &options) {
Ok(map) => map,
Err(e) => {
debug!("mmap for dbpage of size {} paniced", DEFAULT_MAPSIZE);
return None;
}
};
let pm = PageManager {
mapped_region: region,
db_fd: filedesc.clone(),
db_pagesize: db_pagesize,
db_mapsize: db_mapsize,
free_pages: Vec::new(),
dirty_pages: LinkedList::new(),
loose_pages: Vec::new()
};
Some(pm)
}
pub fn alloc(&self, pgno: PageNum) -> Option<Rc<RefCell<Box<Page>>>> {
let vec = unsafe {
let region_base: *mut u8 = self.mapped_region.data();
let page_offset = pgno.to_int().unwrap() * self.db_pagesize.to_int().unwrap();
let ptr: *mut u8 = region_base.offset(page_offset);
Vec::from_raw_parts(ptr, self.db_pagesize, self.db_pagesize)
};
let dbpage = Box::new(Page { _data: RefCell::new(vec) });
let rc_dbpage = Rc::new(RefCell::new(dbpage));
Some(rc_dbpage)
}
pub fn dealloc(&mut self, dbpage: Box<Page>) -> () {
//self.free_pages.push(dbpage);
}
pub fn is_dirty_page_full(&self) -> bool {
self.dirty_pages.len() >= MAX_DIRTY_PAGES_IN_TXN
}
pub fn flush_dirty_pages(&self) -> SaveResult<()> {
let mut it = self.dirty_pages.iter();
let mut iovecs: [uio::iovec; MAX_COMMIT_PAGES] = unsafe { mem::uninitialized() };
let mut n: usize = 0;
let mut write_pos: usize = 0;
let mut next_write_pos: usize = 1;
let mut write_size: usize = 0;
let mut total_write_size = 0;
loop {
match it.next() {
Some(p) => {
let pgno: usize = p.borrow().get_dbpage_number().to_uint().unwrap();
p.borrow_mut().clear_dirty();
write_pos = pgno * self.db_pagesize;
write_size = self.db_pagesize;
if p.borrow().is_overflow_page() {
let ps = p.borrow().get_page_span().to_uint().unwrap();
write_size *= ps;
}
//accumulate to enough of amount, write to disk
if (write_pos != next_write_pos || n == MAX_COMMIT_PAGES || total_write_size + write_size > MAX_COMMIT_WRITE_SIZE) {
if n > 0 {
match self.__flush(&iovecs, write_pos.to_i64().unwrap(), write_size.to_u64().unwrap()) {
Ok(_) => {},
Err(_) => {
panic!(format!("writing db pages paniced: {}", os::last_os_error()));
}
}
n = 0;
}
total_write_size = 0;
}
debug!("committing page {}", pgno);
next_write_pos = write_pos + write_size;
iovecs[n].iov_base = {
let t1 = p.borrow_mut();
let t2 = t1._data.borrow_mut();
t2.as_ptr() as *mut libc::c_void
};
iovecs[n].iov_len = write_size as libc::size_t;
total_write_size += write_size;
n += 1;
},
None => {
if (write_pos != next_write_pos || n == MAX_COMMIT_PAGES || total_write_size + write_size > MAX_COMMIT_WRITE_SIZE) {
if n > 0 {
match self.__flush(&iovecs, write_pos.to_i64().unwrap(), write_size.to_u64().unwrap()) {
Ok(_) => {},
Err(_) => {
panic!(format!("writing db pages paniced: {}", os::last_os_error()));
}
}
}
}
}
}
}
}
#[cfg(target_os = "macos")]
fn __flush(&self, iovecs: &[uio::iovec], write_pos: i64, wirte_size: u64) -> SaveResult<()> {
let iovcnt = iovecs.len();
if (iovcnt == 1) {
let ptr: *const u8 = unsafe { mem::transmute(iovecs[0].iov_base) };
let len: usize = iovecs[0].iov_len.to_uint().unwrap();
let pbuf: &[u8] = unsafe { mem::transmute(raw::Slice { data: ptr, len: len }) };
match self.db_fd.borrow_mut().pwrite(pbuf, write_pos) {
Ok(_) => Ok(()),
Err(e) => {
Err(SaveError::WriteError)
}
}
} else {
let iovcnt = iovecs.len();
let seek_pos = write_pos.to_i64().unwrap();
self.db_fd.borrow_mut().seek(seek_pos, io::SeekStyle::SeekSet).ok().unwrap();
match self.db_fd.borrow_mut().writev(iovecs, iovcnt) {
Ok(_) => Ok(()),
Err(e) => {
Err(SaveError::WriteError)
}
}
}
}
#[cfg(target_os = "linux")]
fn __flush(&self, iovecs: &[uio::iovec], write_pos: i64, wirte_size: u64) -> SaveResult<()> {
let iovcnt = iovecs.len();
match self.db_fd.borrow_mut().pwritev(iovecs, iovcnt, write_pos) {
Ok(_) => Ok(()),
Err(e) => {
Err(SaveError::WriteError)
}
}
}
}
|
use rand:Rng;
pub fn gen_unfair_rand_nums() -> Vec<u32>{
let v = vec![];
for i in 0..100 {
if i < 10 {
v.push(900);
}
if i >= 10 && i < 20 {
v.push(12)
}
v.push(11)
}
v
}
|
fn main() {
let input = std::fs::read_to_string("../input.txt").unwrap();
let lines: Vec<usize> = input
.split("\n")
.filter(|l| !l.is_empty())
.map(|l| l.parse().unwrap())
.collect();
let mut window: std::collections::VecDeque<usize> =
std::collections::VecDeque::with_capacity(25);
for (i, &num) in lines.iter().enumerate() {
if i < 25 {
window.push_back(num);
continue;
}
let mut found: bool = false;
'a: for a in 0..24 {
for b in a..25 {
if window[a] + window[b] == num {
found = true;
break 'a;
}
}
}
if !found {
println!("{}", num);
return;
}
window.pop_front();
window.push_back(num);
}
}
|
#![allow(dead_code, unused_variables)]
mod new;
mod arm;
mod parser2;
mod new_main;
pub use self::new_main::run_new;
pub use self::arm::main_arm;
pub use self::parser2::read_new;
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// UsageSummaryResponse : Response with hourly report of all data billed by Datadog all organizations.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageSummaryResponse {
/// Shows the 99th percentile of all agent hosts over all hours in the current months for all organizations.
#[serde(rename = "agent_host_top99p_sum", skip_serializing_if = "Option::is_none")]
pub agent_host_top99p_sum: Option<i64>,
/// Shows the 99th percentile of all Azure app services using APM over all hours in the current months all organizations.
#[serde(rename = "apm_azure_app_service_host_top99p_sum", skip_serializing_if = "Option::is_none")]
pub apm_azure_app_service_host_top99p_sum: Option<i64>,
/// Shows the 99th percentile of all distinct APM hosts over all hours in the current months for all organizations.
#[serde(rename = "apm_host_top99p_sum", skip_serializing_if = "Option::is_none")]
pub apm_host_top99p_sum: Option<i64>,
/// Shows the 99th percentile of all AWS hosts over all hours in the current months for all organizations.
#[serde(rename = "aws_host_top99p_sum", skip_serializing_if = "Option::is_none")]
pub aws_host_top99p_sum: Option<i64>,
/// Shows the average of the number of functions that executed 1 or more times each hour in the current months for all organizations.
#[serde(rename = "aws_lambda_func_count", skip_serializing_if = "Option::is_none")]
pub aws_lambda_func_count: Option<i64>,
/// Shows the sum of all AWS Lambda invocations over all hours in the current months for all organizations.
#[serde(rename = "aws_lambda_invocations_sum", skip_serializing_if = "Option::is_none")]
pub aws_lambda_invocations_sum: Option<i64>,
/// Shows the 99th percentile of all Azure app services over all hours in the current months for all organizations.
#[serde(rename = "azure_app_service_top99p_sum", skip_serializing_if = "Option::is_none")]
pub azure_app_service_top99p_sum: Option<i64>,
/// Shows the 99th percentile of all Azure hosts over all hours in the current months for all organizations.
#[serde(rename = "azure_host_top99p_sum", skip_serializing_if = "Option::is_none")]
pub azure_host_top99p_sum: Option<i64>,
/// Shows the sum of all log bytes ingested over all hours in the current months for all organizations.
#[serde(rename = "billable_ingested_bytes_agg_sum", skip_serializing_if = "Option::is_none")]
pub billable_ingested_bytes_agg_sum: Option<i64>,
/// Shows the sum of all compliance containers over all hours in the current months for all organizations.
#[serde(rename = "compliance_container_agg_sum", skip_serializing_if = "Option::is_none")]
pub compliance_container_agg_sum: Option<serde_json::Value>,
/// Shows the sum of all compliance hosts over all hours in the current months for all organizations.
#[serde(rename = "compliance_host_agg_sum", skip_serializing_if = "Option::is_none")]
pub compliance_host_agg_sum: Option<i64>,
/// Shows the average of all distinct containers over all hours in the current months for all organizations.
#[serde(rename = "container_avg_sum", skip_serializing_if = "Option::is_none")]
pub container_avg_sum: Option<i64>,
/// Shows the sum of the high-water marks of all distinct containers over all hours in the current months for all organizations.
#[serde(rename = "container_hwm_sum", skip_serializing_if = "Option::is_none")]
pub container_hwm_sum: Option<i64>,
/// Shows the average number of distinct custom metrics over all hours in the current months for all organizations.
#[serde(rename = "custom_ts_sum", skip_serializing_if = "Option::is_none")]
pub custom_ts_sum: Option<i64>,
/// Shows the last date of usage in the current months for all organizations.
#[serde(rename = "end_date", skip_serializing_if = "Option::is_none")]
pub end_date: Option<String>,
/// Shows the average of all Fargate tasks over all hours in the current months for all organizations.
#[serde(rename = "fargate_tasks_count_avg_sum", skip_serializing_if = "Option::is_none")]
pub fargate_tasks_count_avg_sum: Option<i64>,
/// Shows the sum of the high-water marks of all Fargate tasks over all hours in the current months for all organizations.
#[serde(rename = "fargate_tasks_count_hwm_sum", skip_serializing_if = "Option::is_none")]
pub fargate_tasks_count_hwm_sum: Option<i64>,
/// Shows the 99th percentile of all GCP hosts over all hours in the current months for all organizations.
#[serde(rename = "gcp_host_top99p_sum", skip_serializing_if = "Option::is_none")]
pub gcp_host_top99p_sum: Option<i64>,
/// Shows the 99th percentile of all Heroku dynos over all hours in the current months for all organizations.
#[serde(rename = "heroku_host_top99p_sum", skip_serializing_if = "Option::is_none")]
pub heroku_host_top99p_sum: Option<i64>,
/// Shows sum of the the high-water marks of incident management monthly active users in the current months for all organizations.
#[serde(rename = "incident_management_monthly_active_users_hwm_sum", skip_serializing_if = "Option::is_none")]
pub incident_management_monthly_active_users_hwm_sum: Option<i64>,
/// Shows the sum of all log events indexed over all hours in the current months for all organizations.
#[serde(rename = "indexed_events_count_agg_sum", skip_serializing_if = "Option::is_none")]
pub indexed_events_count_agg_sum: Option<i64>,
/// Shows the 99th percentile of all distinct infrastructure hosts over all hours in the current months for all organizations.
#[serde(rename = "infra_host_top99p_sum", skip_serializing_if = "Option::is_none")]
pub infra_host_top99p_sum: Option<i64>,
/// Shows the sum of all log bytes ingested over all hours in the current months for all organizations.
#[serde(rename = "ingested_events_bytes_agg_sum", skip_serializing_if = "Option::is_none")]
pub ingested_events_bytes_agg_sum: Option<i64>,
/// Shows the sum of all IoT devices over all hours in the current months for all organizations.
#[serde(rename = "iot_device_agg_sum", skip_serializing_if = "Option::is_none")]
pub iot_device_agg_sum: Option<i64>,
/// Shows the 99th percentile of all IoT devices over all hours in the current months of all organizations.
#[serde(rename = "iot_device_top99p_sum", skip_serializing_if = "Option::is_none")]
pub iot_device_top99p_sum: Option<i64>,
/// Shows the the most recent hour in the current months for all organizations for which all usages were calculated.
#[serde(rename = "last_updated", skip_serializing_if = "Option::is_none")]
pub last_updated: Option<String>,
/// Shows the sum of all live logs indexed over all hours in the current months for all organizations (data available as of December 1, 2020).
#[serde(rename = "live_indexed_events_agg_sum", skip_serializing_if = "Option::is_none")]
pub live_indexed_events_agg_sum: Option<i64>,
/// Shows the sum of all live logs bytes ingested over all hours in the current months for all organizations (data available as of December 1, 2020).
#[serde(rename = "live_ingested_bytes_agg_sum", skip_serializing_if = "Option::is_none")]
pub live_ingested_bytes_agg_sum: Option<i64>,
/// Shows the sum of all mobile RUM Sessions over all hours in the current months for all organizations.
#[serde(rename = "mobile_rum_session_count_agg_sum", skip_serializing_if = "Option::is_none")]
pub mobile_rum_session_count_agg_sum: Option<i64>,
/// Shows the sum of all mobile RUM Sessions on Android over all hours in the current months for all organizations.
#[serde(rename = "mobile_rum_session_count_android_agg_sum", skip_serializing_if = "Option::is_none")]
pub mobile_rum_session_count_android_agg_sum: Option<i64>,
/// Shows the sum of all mobile RUM Sessions on iOS over all hours in the current months for all organizations.
#[serde(rename = "mobile_rum_session_count_ios_agg_sum", skip_serializing_if = "Option::is_none")]
pub mobile_rum_session_count_ios_agg_sum: Option<i64>,
/// Shows the sum of all Network flows indexed over all hours in the current months for all organizations.
#[serde(rename = "netflow_indexed_events_count_agg_sum", skip_serializing_if = "Option::is_none")]
pub netflow_indexed_events_count_agg_sum: Option<i64>,
/// Shows the 99th percentile of all distinct Networks hosts over all hours in the current months for all organizations.
#[serde(rename = "npm_host_top99p_sum", skip_serializing_if = "Option::is_none")]
pub npm_host_top99p_sum: Option<i64>,
/// Shows the 99th percentile of all hosts reported by the Datadog exporter for the OpenTelemetry Collector over all hours in the current months for all organizations.
#[serde(rename = "opentelemetry_host_top99p_sum", skip_serializing_if = "Option::is_none")]
pub opentelemetry_host_top99p_sum: Option<i64>,
/// Shows the average number of profiled containers over all hours in the current months for all organizations.
#[serde(rename = "profiling_container_agent_count_avg", skip_serializing_if = "Option::is_none")]
pub profiling_container_agent_count_avg: Option<i64>,
/// Shows the 99th percentile of all profiled hosts over all hours in the current months for all organizations.
#[serde(rename = "profiling_host_count_top99p_sum", skip_serializing_if = "Option::is_none")]
pub profiling_host_count_top99p_sum: Option<i64>,
/// Shows the sum of all rehydrated logs indexed over all hours in the current months for all organizations (data available as of December 1, 2020).
#[serde(rename = "rehydrated_indexed_events_agg_sum", skip_serializing_if = "Option::is_none")]
pub rehydrated_indexed_events_agg_sum: Option<i64>,
/// Shows the sum of all rehydrated logs bytes ingested over all hours in the current months for all organizations (data available as of December 1, 2020).
#[serde(rename = "rehydrated_ingested_bytes_agg_sum", skip_serializing_if = "Option::is_none")]
pub rehydrated_ingested_bytes_agg_sum: Option<i64>,
/// Shows the sum of all browser RUM Sessions over all hours in the current months for all organizations.
#[serde(rename = "rum_session_count_agg_sum", skip_serializing_if = "Option::is_none")]
pub rum_session_count_agg_sum: Option<i64>,
/// Shows the sum of RUM Sessions (browser and mobile) over all hours in the current months for all organizations.
#[serde(rename = "rum_total_session_count_agg_sum", skip_serializing_if = "Option::is_none")]
pub rum_total_session_count_agg_sum: Option<i64>,
/// Shows the first date of usage in the current months for all organizations.
#[serde(rename = "start_date", skip_serializing_if = "Option::is_none")]
pub start_date: Option<String>,
/// Shows the sum of all Synthetic browser tests over all hours in the current months for all organizations.
#[serde(rename = "synthetics_browser_check_calls_count_agg_sum", skip_serializing_if = "Option::is_none")]
pub synthetics_browser_check_calls_count_agg_sum: Option<i64>,
/// Shows the sum of all Synthetic API tests over all hours in the current months for all organizations.
#[serde(rename = "synthetics_check_calls_count_agg_sum", skip_serializing_if = "Option::is_none")]
pub synthetics_check_calls_count_agg_sum: Option<i64>,
/// Shows the sum of all Indexed Spans indexed over all hours in the current months for all organizations.
#[serde(rename = "trace_search_indexed_events_count_agg_sum", skip_serializing_if = "Option::is_none")]
pub trace_search_indexed_events_count_agg_sum: Option<i64>,
/// Shows the sum of all tracing without limits bytes ingested over all hours in the current months for all organizations.
#[serde(rename = "twol_ingested_events_bytes_agg_sum", skip_serializing_if = "Option::is_none")]
pub twol_ingested_events_bytes_agg_sum: Option<i64>,
/// An array of objects regarding hourly usage.
#[serde(rename = "usage", skip_serializing_if = "Option::is_none")]
pub usage: Option<Vec<crate::models::UsageSummaryDate>>,
/// Shows the 99th percentile of all vSphere hosts over all hours in the current months for all organizations.
#[serde(rename = "vsphere_host_top99p_sum", skip_serializing_if = "Option::is_none")]
pub vsphere_host_top99p_sum: Option<i64>,
}
impl UsageSummaryResponse {
/// Response with hourly report of all data billed by Datadog all organizations.
pub fn new() -> UsageSummaryResponse {
UsageSummaryResponse {
agent_host_top99p_sum: None,
apm_azure_app_service_host_top99p_sum: None,
apm_host_top99p_sum: None,
aws_host_top99p_sum: None,
aws_lambda_func_count: None,
aws_lambda_invocations_sum: None,
azure_app_service_top99p_sum: None,
azure_host_top99p_sum: None,
billable_ingested_bytes_agg_sum: None,
compliance_container_agg_sum: None,
compliance_host_agg_sum: None,
container_avg_sum: None,
container_hwm_sum: None,
custom_ts_sum: None,
end_date: None,
fargate_tasks_count_avg_sum: None,
fargate_tasks_count_hwm_sum: None,
gcp_host_top99p_sum: None,
heroku_host_top99p_sum: None,
incident_management_monthly_active_users_hwm_sum: None,
indexed_events_count_agg_sum: None,
infra_host_top99p_sum: None,
ingested_events_bytes_agg_sum: None,
iot_device_agg_sum: None,
iot_device_top99p_sum: None,
last_updated: None,
live_indexed_events_agg_sum: None,
live_ingested_bytes_agg_sum: None,
mobile_rum_session_count_agg_sum: None,
mobile_rum_session_count_android_agg_sum: None,
mobile_rum_session_count_ios_agg_sum: None,
netflow_indexed_events_count_agg_sum: None,
npm_host_top99p_sum: None,
opentelemetry_host_top99p_sum: None,
profiling_container_agent_count_avg: None,
profiling_host_count_top99p_sum: None,
rehydrated_indexed_events_agg_sum: None,
rehydrated_ingested_bytes_agg_sum: None,
rum_session_count_agg_sum: None,
rum_total_session_count_agg_sum: None,
start_date: None,
synthetics_browser_check_calls_count_agg_sum: None,
synthetics_check_calls_count_agg_sum: None,
trace_search_indexed_events_count_agg_sum: None,
twol_ingested_events_bytes_agg_sum: None,
usage: None,
vsphere_host_top99p_sum: None,
}
}
}
|
//! Miscellaneous utility functions.
pub mod ecdsa;
pub mod base58;
pub mod wif;
|
use std::cmp;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::ops::{Deref, DerefMut};
use std::path::Path;
use std::time::UNIX_EPOCH;
use byteorder::{BigEndian, LittleEndian, NativeEndian};
use nom::Endianness;
use errors::Result;
use linktype::LinkType;
use pcap::header::{Header as FileHeader, WriteHeaderExt};
use pcap::packet::{Header as PacketHeader, WritePacket};
use pcap::Packet;
use traits::AsEndianness;
/// Opens a file as a stream in write-only mode.
pub fn create<P: AsRef<Path>, W>(path: P) -> Result<Builder<BufWriter<File>>> {
let f = File::create(path)?;
let w = BufWriter::new(f);
Ok(Builder::new(w))
}
/// The `Builder` struct contains the options for creating a new packet capture.
pub struct Builder<W> {
w: Writer<W>,
}
impl<W> Builder<W> {
/// Create a new `Builder` which can be used configure the options of a new `Writer`.
pub fn new(w: W) -> Self {
Self::with_byteorder::<NativeEndian>(w)
}
/// Create a new `Builder` with special `Endianness` which can be used configure the options of a new `Writer`.
pub fn with_endianness(w: W, endianness: Endianness) -> Self {
match endianness {
Endianness::Little => Self::with_byteorder::<LittleEndian>(w),
Endianness::Big => Self::with_byteorder::<BigEndian>(w),
}
}
/// Create a new `Builder` with special `ByteOrder` which can be used configure the options of a new `Writer`.
pub fn with_byteorder<T: AsEndianness>(w: W) -> Self {
Builder {
w: Writer {
w,
file_header: FileHeader::new::<T>(),
},
}
}
/// The correction time in seconds between GMT (UTC) and the local timezone of the following packet header timestamps.
#[must_use]
pub fn utc_offset_seconds(mut self, utc_offset_secs: i32) -> Self {
self.w.file_header.thiszone = utc_offset_secs;
self
}
/// The maximum size of a packet that can be written to the file.
#[must_use]
pub fn snapshot_length(mut self, snaplen: u32) -> Self {
self.w.file_header.snaplen = snaplen;
self
}
/// The type of packets that will be written to the file.
///
/// See `Linktype` for known values.
#[must_use]
pub fn link_type(mut self, link_type: LinkType) -> Self {
self.w.file_header.network = link_type as u32;
self
}
}
impl<W> Builder<W>
where
W: Write,
{
/// Build a new `Writer` that writes the packet capture data to the specified `Write`.
#[must_use]
pub fn build(mut self) -> Result<Writer<W>> {
match self.w.file_header.magic().endianness() {
Endianness::Little => {
self.w.w.write_header::<LittleEndian>(&self.w.file_header)?;
}
Endianness::Big => {
self.w.w.write_header::<BigEndian>(&self.w.file_header)?;
}
}
Ok(self.w)
}
}
/// The `Writer` struct allows writing packets as a packet capture.
pub struct Writer<W> {
w: W,
file_header: FileHeader,
}
impl<W> Writer<W>
where
W: Default + Write,
{
/// Create a new `Writer` that writes the packet capture data from an iterator to the specified `Write`.
pub fn from_packets<'a, I: IntoIterator<Item = Packet<'a>>>(iter: I) -> Result<Self> {
Builder::new(W::default())
.build()
.and_then(|mut writer| writer.write_packets(iter).map(|_| writer))
}
}
impl<W> Writer<W> {
/// Consumes this `Writer`, returning the underlying value.
pub fn into_inner(self) -> W {
self.w
}
}
impl<W> Deref for Writer<W> {
type Target = W;
fn deref(&self) -> &Self::Target {
&self.w
}
}
impl<W> DerefMut for Writer<W> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.w
}
}
impl<W> Writer<W>
where
W: Write,
{
/// Create a new `Writer` that writes the packet capture data to the specified `Write`.
pub fn new(w: W) -> Result<Self> {
Builder::new(w).build()
}
/// Write a packet to the packet capture stream.
pub fn write_packet<'a>(&mut self, packet: &Packet<'a>) -> Result<usize> {
let d = packet.timestamp.duration_since(UNIX_EPOCH)?;
let incl_len = cmp::min(packet.payload.len() as u32, self.file_header.snaplen);
let payload = &packet.payload[..incl_len as usize];
let packet_header = PacketHeader {
ts_sec: d.as_secs() as u32,
ts_usec: d.subsec_nanos() as u32, // always use nanosecond resolution
incl_len,
orig_len: packet.actual_length as u32,
};
match self.file_header.magic().endianness() {
Endianness::Little => self
.w
.write_packet_data::<LittleEndian, _>(&packet_header, &payload),
Endianness::Big => self
.w
.write_packet_data::<BigEndian, _>(&packet_header, &payload),
}
}
/// Write a packet to the packets from an iterator capture stream.
pub fn write_packets<'a, I: IntoIterator<Item = Packet<'a>>>(
&mut self,
iter: I,
) -> Result<usize> {
let mut wrote = 0;
for packet in iter {
wrote += self.write_packet(&packet)?;
}
Ok(wrote)
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use std::iter::{once, repeat};
use std::time::Duration;
use super::*;
use pcap::tests::NANO_PACKETS;
#[test]
pub fn test_write() {
for (buf, magic) in NANO_PACKETS.iter() {
let packet = Packet {
timestamp: UNIX_EPOCH + Duration::new(0x56506e1a, 0x182b0ad0),
actual_length: 60,
payload: Cow::from(&[0x44u8, 0x41, 0x54, 0x41][..]),
};
let mut data = vec![];
let mut writer = Builder::with_endianness(data, magic.endianness())
.link_type(LinkType::RAW)
.build()
.unwrap();
let wrote = writer.write_packets(once(packet)).unwrap();
assert_eq!(FileHeader::size() + wrote, buf.len());
assert_eq!(writer.as_slice(), *buf);
}
}
#[test]
pub fn test_from_packets() {
let packet = Packet {
timestamp: UNIX_EPOCH + Duration::new(0x56506e1a, 0x182b0ad0),
actual_length: 60,
payload: Cow::from(&[0x44u8, 0x41, 0x54, 0x41][..]),
};
let payload_len = packet.payload.len();
let data = Writer::<Vec<u8>>::from_packets(repeat(packet).take(5))
.unwrap()
.into_inner();
assert_eq!(
data.len(),
FileHeader::size() + (PacketHeader::size() + payload_len) * 5
);
}
}
|
use crate::generated::*;
struct RequestMetaInfo {
raft_group: Option<u16>,
inode: Option<u64>, // Some if the request accesses a single inode (i.e. None for Rename)
lock_id: Option<u64>,
access_type: AccessType, // Used to determine locks to acquire
distribution_requirement: DistributionRequirement,
}
pub enum AccessType {
ReadData,
ReadMetadata,
LockMetadata,
WriteMetadata,
WriteDataAndMetadata,
NoAccess,
}
// Where this message can be processed
pub enum DistributionRequirement {
Any, // Any node can process this message
TransactionCoordinator, // Any node can process this message by acting as a transcation coordinator
RaftGroup, // Must be processed by a specific rgroup
Node, // Must be processed by a specific node
}
fn request_meta_info(request: &GenericRequest<'_>) -> RequestMetaInfo {
match request.request_type() {
RequestType::FilesystemReadyRequest => RequestMetaInfo {
raft_group: None,
inode: None,
lock_id: None,
access_type: AccessType::NoAccess,
distribution_requirement: DistributionRequirement::Any,
},
RequestType::FilesystemCheckRequest => RequestMetaInfo {
raft_group: None,
inode: None,
lock_id: None,
access_type: AccessType::NoAccess,
distribution_requirement: DistributionRequirement::Any,
},
RequestType::FilesystemInformationRequest => RequestMetaInfo {
raft_group: None,
inode: None,
lock_id: None,
access_type: AccessType::NoAccess,
distribution_requirement: DistributionRequirement::Any,
},
RequestType::FilesystemChecksumRequest => RequestMetaInfo {
raft_group: None,
inode: None,
lock_id: None,
access_type: AccessType::NoAccess,
distribution_requirement: DistributionRequirement::Node,
},
RequestType::ReadRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_read_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::ReadData,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::ReadRawRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_read_raw_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::ReadData,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::SetXattrRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_set_xattr_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::RemoveXattrRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_remove_xattr_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::UnlinkRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_unlink_request().unwrap().parent()),
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::RmdirRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_rmdir_request().unwrap().parent()),
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::WriteRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_write_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::WriteDataAndMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::UtimensRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_utimens_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::ChmodRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_chmod_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::ChownRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_chown_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::TruncateRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_truncate_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::WriteDataAndMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::FsyncRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_fsync_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::NoAccess,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::MkdirRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_mkdir_request().unwrap().parent()),
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::TransactionCoordinator,
},
RequestType::CreateRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_create_request().unwrap().parent()),
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::TransactionCoordinator,
},
RequestType::LockRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_lock_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::LockMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::UnlockRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_unlock_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::NoAccess,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::HardlinkIncrementRequest => RequestMetaInfo {
raft_group: None,
inode: Some(
request
.request_as_hardlink_increment_request()
.unwrap()
.inode(),
),
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::HardlinkRollbackRequest => RequestMetaInfo {
raft_group: None,
inode: Some(
request
.request_as_hardlink_rollback_request()
.unwrap()
.inode(),
),
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::CreateInodeRequest => RequestMetaInfo {
raft_group: Some(
request
.request_as_create_inode_request()
.unwrap()
.raft_group(),
),
inode: None,
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::DecrementInodeRequest => RequestMetaInfo {
raft_group: None,
inode: Some(
request
.request_as_decrement_inode_request()
.unwrap()
.inode(),
),
lock_id: request
.request_as_decrement_inode_request()
.unwrap()
.lock_id()
.map(|x| x.value()),
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::RemoveLinkRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_remove_link_request().unwrap().parent()),
lock_id: request
.request_as_remove_link_request()
.unwrap()
.lock_id()
.map(|x| x.value()),
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::CreateLinkRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_create_link_request().unwrap().parent()),
lock_id: request
.request_as_create_link_request()
.unwrap()
.lock_id()
.map(|x| x.value()),
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::ReplaceLinkRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_replace_link_request().unwrap().parent()),
lock_id: request
.request_as_replace_link_request()
.unwrap()
.lock_id()
.map(|x| x.value()),
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::UpdateParentRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_update_parent_request().unwrap().inode()),
lock_id: request
.request_as_update_parent_request()
.unwrap()
.lock_id()
.map(|x| x.value()),
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::UpdateMetadataChangedTimeRequest => RequestMetaInfo {
raft_group: None,
inode: Some(
request
.request_as_update_metadata_changed_time_request()
.unwrap()
.inode(),
),
lock_id: request
.request_as_update_metadata_changed_time_request()
.unwrap()
.lock_id()
.map(|x| x.value()),
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::HardlinkRequest => RequestMetaInfo {
raft_group: None,
inode: None,
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::TransactionCoordinator,
},
RequestType::RenameRequest => RequestMetaInfo {
raft_group: None,
inode: None,
lock_id: None,
access_type: AccessType::WriteMetadata,
distribution_requirement: DistributionRequirement::TransactionCoordinator,
},
RequestType::LookupRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_lookup_request().unwrap().parent()),
lock_id: None,
access_type: AccessType::ReadMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::GetXattrRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_get_xattr_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::ReadMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::ListXattrsRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_list_xattrs_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::ReadMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::ReaddirRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_readdir_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::ReadMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::GetattrRequest => RequestMetaInfo {
raft_group: None,
inode: Some(request.request_as_getattr_request().unwrap().inode()),
lock_id: None,
access_type: AccessType::ReadMetadata,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::RaftRequest => RequestMetaInfo {
raft_group: Some(request.request_as_raft_request().unwrap().raft_group()),
inode: None,
lock_id: None,
access_type: AccessType::NoAccess,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::LatestCommitRequest => RequestMetaInfo {
raft_group: Some(
request
.request_as_latest_commit_request()
.unwrap()
.raft_group(),
),
inode: None,
lock_id: None,
access_type: AccessType::NoAccess,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::RaftGroupLeaderRequest => RequestMetaInfo {
raft_group: Some(
request
.request_as_raft_group_leader_request()
.unwrap()
.raft_group(),
),
inode: None,
lock_id: None,
access_type: AccessType::NoAccess,
distribution_requirement: DistributionRequirement::RaftGroup,
},
RequestType::NONE => unreachable!(),
}
}
// Locks held by the request
pub fn request_locks(request: &GenericRequest<'_>) -> Option<u64> {
request_meta_info(request).lock_id
}
pub fn accessed_inode(request: &GenericRequest<'_>) -> Option<u64> {
request_meta_info(request).inode
}
pub fn raft_group(request: &GenericRequest) -> Option<u16> {
request_meta_info(request).raft_group
}
pub fn access_type(request: &GenericRequest) -> AccessType {
request_meta_info(request).access_type
}
pub fn distribution_requirement(request: &GenericRequest) -> DistributionRequirement {
request_meta_info(request).distribution_requirement
}
|
use protocol::client::*;
use protocol::server::*;
use protocol::client::Login as ClientLogin;
use protocol::server::Login as ServerLogin;
/// All possible server packets.
///
/// This is an enum of all possible packet
/// message types. It can be serialized
/// and deserialized from byte buffers
/// using [`from_bytes`](fn.from_bytes.html)
/// and [`to_bytes`](fn.to_bytes.html).
///
/// Some packets do not contain any data
/// and thus do not have any data within
/// their enum variants.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ServerPacket {
Login(ServerLogin),
Backup,
Ping(Ping),
PingResult(PingResult),
Ack,
Error(Error),
CommandReply(CommandReply),
PlayerNew(PlayerNew),
PlayerLeave(PlayerLeave),
PlayerUpdate(PlayerUpdate),
PlayerFire(PlayerFire),
PlayerRespawn(PlayerRespawn),
PlayerFlag(PlayerFlag),
PlayerHit(PlayerHit),
PlayerKill(PlayerKill),
PlayerUpgrade(PlayerUpgrade),
PlayerType(PlayerType),
PlayerPowerup(PlayerPowerup),
PlayerLevel(PlayerLevel),
PlayerReteam(PlayerReteam),
GameFlag(GameFlag),
GameSpectate(GameSpectate),
GamePlayersAlive(GamePlayersAlive),
GameFireWall(GameFirewall),
EventRepel(EventRepel),
EventBoost(EventBoost),
EventBounce(EventBounce),
EventStealth(EventStealth),
EventLeaveHorizon(EventLeaveHorizon),
MobUpdate(MobUpdate),
MobUpdateStationary(MobUpdateStationary),
MobDespawn(MobDespawn),
MobDespawnCoords(MobDespawnCoords),
ScoreUpdate(ScoreUpdate),
ScoreBoard(ScoreBoard),
ScoreDetailedFFA(ScoreDetailedFFA),
ScoreDetailedCTF(ScoreDetailedCTF),
ScoreDetailedBTR(ScoreDetailedBTR),
ChatTeam(ChatTeam),
ChatPublic(ChatPublic),
ChatSay(ChatSay),
ChatWhisper(ChatWhisper),
ChatVoteMutePassed(ChatVoteMutePassed),
ChatVoteMuted,
ServerMessage(ServerMessage),
ServerCustom(ServerCustom),
}
impl ServerPacket {
/// Gets the id of the packet associated
/// with the current packet type.
pub fn variant_id(&self) -> u8 {
use protocol::codes::server::*;
match self {
&ServerPacket::Login(_) => LOGIN,
&ServerPacket::Backup => BACKUP,
&ServerPacket::Ping(_) => PING,
&ServerPacket::PingResult(_) => PING_RESULT,
&ServerPacket::Ack => ACK,
&ServerPacket::Error(_) => ERROR,
&ServerPacket::CommandReply(_) => COMMAND_REPLY,
&ServerPacket::PlayerNew(_) => PLAYER_NEW,
&ServerPacket::PlayerLeave(_) => PLAYER_LEAVE,
&ServerPacket::PlayerUpdate(_) => PLAYER_UPDATE,
&ServerPacket::PlayerFire(_) => PLAYER_FIRE,
&ServerPacket::PlayerHit(_) => PLAYER_HIT,
&ServerPacket::PlayerRespawn(_) => PLAYER_RESPAWN,
&ServerPacket::PlayerFlag(_) => PLAYER_FLAG,
&ServerPacket::PlayerKill(_) => PLAYER_KILL,
&ServerPacket::PlayerUpgrade(_) => PLAYER_UPGRADE,
&ServerPacket::PlayerType(_) => PLAYER_TYPE,
&ServerPacket::PlayerPowerup(_) => PLAYER_POWERUP,
&ServerPacket::PlayerLevel(_) => PLAYER_LEVEL,
&ServerPacket::PlayerReteam(_) => PLAYER_RETEAM,
&ServerPacket::GameFlag(_) => GAME_FLAG,
&ServerPacket::GameSpectate(_) => GAME_SPECTATE,
&ServerPacket::GamePlayersAlive(_) => GAME_PLAYERSALIVE,
&ServerPacket::GameFireWall(_) => GAME_FIREWALL,
&ServerPacket::EventRepel(_) => EVENT_REPEL,
&ServerPacket::EventBoost(_) => EVENT_BOOST,
&ServerPacket::EventBounce(_) => EVENT_BOUNCE,
&ServerPacket::EventStealth(_) => EVENT_STEALTH,
&ServerPacket::EventLeaveHorizon(_) => EVENT_LEAVEHORIZON,
&ServerPacket::MobUpdate(_) => MOB_UPDATE,
&ServerPacket::MobUpdateStationary(_) => MOB_UPDATE_STATIONARY,
&ServerPacket::MobDespawn(_) => MOB_DESPAWN,
&ServerPacket::MobDespawnCoords(_) => MOB_DESPAWN_COORDS,
&ServerPacket::ChatPublic(_) => CHAT_PUBLIC,
&ServerPacket::ChatTeam(_) => CHAT_TEAM,
&ServerPacket::ChatSay(_) => CHAT_SAY,
&ServerPacket::ChatWhisper(_) => CHAT_WHISPER,
&ServerPacket::ChatVoteMutePassed(_) => CHAT_VOTEMUTEPASSED,
&ServerPacket::ChatVoteMuted => CHAT_VOTEMUTED,
&ServerPacket::ScoreUpdate(_) => SCORE_UPDATE,
&ServerPacket::ScoreBoard(_) => SCORE_BOARD,
&ServerPacket::ScoreDetailedFFA(_) => SCORE_DETAILED_FFA,
&ServerPacket::ScoreDetailedCTF(_) => SCORE_DETAILED_CTF,
&ServerPacket::ScoreDetailedBTR(_) => SCORE_DETAILED_BTR,
&ServerPacket::ServerMessage(_) => SERVER_MESSAGE,
&ServerPacket::ServerCustom(_) => SERVER_CUSTOM,
}
}
}
/// All possible client packets.
///
/// This contains all valid packets that
/// the client can send to the server
/// (in the current version of the airmash
/// protocol). It can be serialized and
/// deserialized to/from byte buffers
/// using [`to_bytes`](fn.to_bytes.html)
/// and [`from_bytes`](fn.from_bytes.html).
///
/// Some packets don't contain any data, these
/// packets do not have an associated struct
/// and as such are just empty variants within
/// this enum.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ClientPacket {
Login(ClientLogin),
Backup(Backup),
Horizon(Horizon),
Ack,
Pong(Pong),
Key(Key),
Command(Command),
ScoreDetailed,
Chat(Chat),
TeamChat(TeamChat),
Whisper(Whisper),
Say(Say),
VoteMute(VoteMute),
LocalPing(LocalPing),
}
|
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
println!("day 2 part 2");
let f = File::open("src/bin/day02.txt")?;
let mut reader = BufReader::new(f);
let mut input_buf = vec![];
reader.read_to_end(&mut input_buf)?;
let input = input_buf.split(|i| *i == '\n' as u8).collect::<Vec<&[u8]>>();
for (li, ref line1) in (&input).iter().enumerate() {
for line2 in (&input).iter().skip(li+1) {
let mut hd = 0;
let mut differing_index = -1;
assert!(line1.len() == line2.len());
for i in 0..line1.len() {
if line1[i] != line2[i] {
differing_index = i as i32;
hd += 1;
}
}
if hd == 1 {
for i in 0..line1.len() {
if i as i32 != differing_index {
print!("{}", line1[i] as char);
}
}
print!("\n");
return Ok(());
}
}
}
Ok(())
} |
#[doc = "Register `AHB2LPENR` reader"]
pub type R = crate::R<AHB2LPENR_SPEC>;
#[doc = "Register `AHB2LPENR` writer"]
pub type W = crate::W<AHB2LPENR_SPEC>;
#[doc = "Field `RNGLPEN` reader - RNGLPEN"]
pub type RNGLPEN_R = crate::BitReader<RNGLPEN_A>;
#[doc = "RNGLPEN\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RNGLPEN_A {
#[doc = "0: Selected module is disabled during Sleep mode"]
DisabledInSleep = 0,
#[doc = "1: Selected module is enabled during Sleep mode"]
EnabledInSleep = 1,
}
impl From<RNGLPEN_A> for bool {
#[inline(always)]
fn from(variant: RNGLPEN_A) -> Self {
variant as u8 != 0
}
}
impl RNGLPEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RNGLPEN_A {
match self.bits {
false => RNGLPEN_A::DisabledInSleep,
true => RNGLPEN_A::EnabledInSleep,
}
}
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn is_disabled_in_sleep(&self) -> bool {
*self == RNGLPEN_A::DisabledInSleep
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn is_enabled_in_sleep(&self) -> bool {
*self == RNGLPEN_A::EnabledInSleep
}
}
#[doc = "Field `RNGLPEN` writer - RNGLPEN"]
pub type RNGLPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, RNGLPEN_A>;
impl<'a, REG, const O: u8> RNGLPEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Selected module is disabled during Sleep mode"]
#[inline(always)]
pub fn disabled_in_sleep(self) -> &'a mut crate::W<REG> {
self.variant(RNGLPEN_A::DisabledInSleep)
}
#[doc = "Selected module is enabled during Sleep mode"]
#[inline(always)]
pub fn enabled_in_sleep(self) -> &'a mut crate::W<REG> {
self.variant(RNGLPEN_A::EnabledInSleep)
}
}
#[doc = "Field `OTGFSLPEN` reader - USB OTG FS clock enable during Sleep mode"]
pub use RNGLPEN_R as OTGFSLPEN_R;
#[doc = "Field `OTGFSLPEN` writer - USB OTG FS clock enable during Sleep mode"]
pub use RNGLPEN_W as OTGFSLPEN_W;
impl R {
#[doc = "Bit 6 - RNGLPEN"]
#[inline(always)]
pub fn rnglpen(&self) -> RNGLPEN_R {
RNGLPEN_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - USB OTG FS clock enable during Sleep mode"]
#[inline(always)]
pub fn otgfslpen(&self) -> OTGFSLPEN_R {
OTGFSLPEN_R::new(((self.bits >> 7) & 1) != 0)
}
}
impl W {
#[doc = "Bit 6 - RNGLPEN"]
#[inline(always)]
#[must_use]
pub fn rnglpen(&mut self) -> RNGLPEN_W<AHB2LPENR_SPEC, 6> {
RNGLPEN_W::new(self)
}
#[doc = "Bit 7 - USB OTG FS clock enable during Sleep mode"]
#[inline(always)]
#[must_use]
pub fn otgfslpen(&mut self) -> OTGFSLPEN_W<AHB2LPENR_SPEC, 7> {
OTGFSLPEN_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "AHB2 peripheral clock enable in low power mode register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb2lpenr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ahb2lpenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct AHB2LPENR_SPEC;
impl crate::RegisterSpec for AHB2LPENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ahb2lpenr::R`](R) reader structure"]
impl crate::Readable for AHB2LPENR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ahb2lpenr::W`](W) writer structure"]
impl crate::Writable for AHB2LPENR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets AHB2LPENR to value 0xf1"]
impl crate::Resettable for AHB2LPENR_SPEC {
const RESET_VALUE: Self::Ux = 0xf1;
}
|
fn main(){
let mut s1 = String::from("hello");
{ let s2 = &mut s1;
s2.push_str("world!\n"); //disallowed
} //drops s2
s1.push_str("world!"); //ok
println!("String is {}",s1);//prints updated s1
let x = 32;
x = 22;
}
|
// Copyright 2019 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate log;
extern crate env_logger;
extern crate protobuf;
extern crate raft;
extern crate regex;
use std::collections::{HashMap, VecDeque};
use std::sync::mpsc::{self, Receiver, Sender, SyncSender, TryRecvError};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use std::{str, thread};
use protobuf::Message as PbMessage;
use raft::storage::MemStorage;
use raft::{prelude::*, StateRole};
use regex::Regex;
pub fn raft_cluster_main() {
env_logger::init();
// Create 5 mailboxes to send/receive messages. Every node holds a `Receiver` to receive
// messages from others, and uses the respective `Sender` to send messages to others.
let (mut tx_vec, mut rx_vec) = (Vec::new(), Vec::new());
for _ in 0..5 {
let (tx, rx) = mpsc::channel();
tx_vec.push(tx);
rx_vec.push(rx);
}
// A global pending proposals queue. New proposals will be pushed back into the queue, and
// after it's committed by the raft cluster, it will be poped from the queue.
let proposals = Arc::new(Mutex::new(VecDeque::<Proposal>::new()));
let mut handles = Vec::new();
for (i, rx) in rx_vec.into_iter().enumerate() {
// A map[peer_id -> sender]. In the example we create 5 nodes, with ids in [1, 5].
let mailboxes = (1..6u64).zip(tx_vec.iter().cloned()).collect();
let mut node = match i {
// Peer 1 is the leader.
0 => Node::create_raft_leader(1, rx, mailboxes),
// Other peers are followers.
_ => Node::create_raft_follower(rx, mailboxes),
};
let proposals = Arc::clone(&proposals);
// Tick the raft node per 100ms. So use an `Instant` to trace it.
let mut t = Instant::now();
// Here we spawn the node on a new thread and keep a handle so we can join on them later.
let handle = thread::spawn(move || loop {
thread::sleep(Duration::from_millis(10));
loop {
// Step raft messages.
match node.my_mailbox.try_recv() {
Ok(msg) => node.step(msg),
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => return,
}
}
let raft_group = match node.raft_group {
Some(ref mut r) => r,
// When Node::raft_group is `None` it means the node is not initialized.
_ => continue,
};
if t.elapsed() >= Duration::from_millis(100) {
// Tick the raft.
raft_group.tick();
t = Instant::now();
}
// Let the leader pick pending proposals from the global queue.
if raft_group.raft.state == StateRole::Leader {
// Handle new proposals.
let mut proposals = proposals.lock().unwrap();
for p in proposals.iter_mut().skip_while(|p| p.proposed > 0) {
propose(raft_group, p);
}
}
// Handle readies from the raft.
on_ready(raft_group, &mut node.kv_pairs, &node.mailboxes, &proposals);
});
handles.push(handle);
}
// Propose some conf changes so that followers can be initialized.
add_all_followers(proposals.as_ref());
// Put 100 key-value pairs.
(0..100u16)
.filter(|i| {
let (proposal, rx) = Proposal::normal(*i, "hello, world".to_owned());
proposals.lock().unwrap().push_back(proposal);
// After we got a response from `rx`, we can assume the put succeeded and following
// `get` operations can find the key-value pair.
rx.recv().unwrap()
})
.count();
for th in handles {
th.join().unwrap();
}
}
struct Node {
// None if the raft is not initialized.
raft_group: Option<RawNode<MemStorage>>,
my_mailbox: Receiver<Message>,
mailboxes: HashMap<u64, Sender<Message>>,
// Key-value pairs after applied. `MemStorage` only contains raft logs,
// so we need an additional storage engine.
kv_pairs: HashMap<u16, String>,
}
impl Node {
// Create a raft leader only with itself in its configuration.
fn create_raft_leader(
id: u64,
my_mailbox: Receiver<Message>,
mailboxes: HashMap<u64, Sender<Message>>,
) -> Self {
let mut cfg = example_config();
cfg.id = id;
cfg.peers = vec![id];
cfg.tag = format!("peer_{}", id);
let storage = MemStorage::new();
let raft_group = Some(RawNode::new(&cfg, storage, vec![]).unwrap());
Node {
raft_group,
my_mailbox,
mailboxes,
kv_pairs: Default::default(),
}
}
// Create a raft follower.
fn create_raft_follower(
my_mailbox: Receiver<Message>,
mailboxes: HashMap<u64, Sender<Message>>,
) -> Self {
Node {
raft_group: None,
my_mailbox,
mailboxes,
kv_pairs: Default::default(),
}
}
// Initialize raft for followers.
fn initialize_raft_from_message(&mut self, msg: &Message) {
if !is_initial_msg(msg) {
return;
}
let mut cfg = example_config();
cfg.id = msg.get_to();
let storage = MemStorage::new();
self.raft_group = Some(RawNode::new(&cfg, storage, vec![]).unwrap());
}
// Step a raft message, initialize the raft if need.
fn step(&mut self, msg: Message) {
if self.raft_group.is_none() {
if is_initial_msg(&msg) {
self.initialize_raft_from_message(&msg);
} else {
return;
}
}
let raft_group = self.raft_group.as_mut().unwrap();
let _ = raft_group.step(msg);
}
}
fn on_ready(
raft_group: &mut RawNode<MemStorage>,
kv_pairs: &mut HashMap<u16, String>,
mailboxes: &HashMap<u64, Sender<Message>>,
proposals: &Mutex<VecDeque<Proposal>>,
) {
if !raft_group.has_ready() {
return;
}
// Get the `Ready` with `RawNode::ready` interface.
let mut ready = raft_group.ready();
// Persistent raft logs. It's necessary because in `RawNode::advance` we stabilize
// raft logs to the latest position.
if let Err(e) = raft_group.raft.raft_log.store.wl().append(ready.entries()) {
error!("persist raft log fail: {:?}, need to retry or panic", e);
return;
}
// Send out the messages come from the node.
for msg in ready.messages.drain(..) {
let to = msg.get_to();
if mailboxes[&to].send(msg).is_err() {
warn!("send raft message to {} fail, let Raft retry it", to);
}
}
// Apply all committed proposals.
if let Some(committed_entries) = ready.committed_entries.take() {
for entry in committed_entries {
if entry.get_data().is_empty() {
// From new elected leaders.
continue;
}
if let EntryType::EntryConfChange = entry.get_entry_type() {
// For conf change messages, make them effective.
let mut cc = ConfChange::new();
cc.merge_from_bytes(entry.get_data()).unwrap();
let node_id = cc.get_node_id();
match cc.get_change_type() {
ConfChangeType::AddNode => raft_group.raft.add_node(node_id).unwrap(),
ConfChangeType::RemoveNode => raft_group.raft.remove_node(node_id).unwrap(),
ConfChangeType::AddLearnerNode => raft_group.raft.add_learner(node_id).unwrap(),
ConfChangeType::BeginMembershipChange
| ConfChangeType::FinalizeMembershipChange => unimplemented!(),
}
} else {
// For normal proposals, extract the key-value pair and then
// insert them into the kv engine.
let data = str::from_utf8(entry.get_data()).unwrap();
let reg = Regex::new("put ([0-9]+) (.+)").unwrap();
if let Some(caps) = reg.captures(&data) {
kv_pairs.insert(caps[1].parse().unwrap(), caps[2].to_string());
}
}
if raft_group.raft.state == StateRole::Leader {
// The leader should response to the clients, tell them if their proposals
// succeeded or not.
let proposal = proposals.lock().unwrap().pop_front().unwrap();
proposal.propose_success.send(true).unwrap();
}
}
}
// Call `RawNode::advance` interface to update position flags in the raft.
raft_group.advance(ready);
}
fn example_config() -> Config {
Config {
election_tick: 10,
heartbeat_tick: 3,
..Default::default()
}
}
// The message can be used to initialize a raft node or not.
fn is_initial_msg(msg: &Message) -> bool {
let msg_type = msg.get_msg_type();
msg_type == MessageType::MsgRequestVote
|| msg_type == MessageType::MsgRequestPreVote
|| (msg_type == MessageType::MsgHeartbeat && msg.get_commit() == 0)
}
struct Proposal {
normal: Option<(u16, String)>, // key is an u16 integer, and value is a string.
conf_change: Option<ConfChange>, // conf change.
transfer_leader: Option<u64>,
// If it's proposed, it will be set to the index of the entry.
proposed: u64,
propose_success: SyncSender<bool>,
}
impl Proposal {
fn conf_change(cc: &ConfChange) -> (Self, Receiver<bool>) {
let (tx, rx) = mpsc::sync_channel(1);
let proposal = Proposal {
normal: None,
conf_change: Some(cc.clone()),
transfer_leader: None,
proposed: 0,
propose_success: tx,
};
(proposal, rx)
}
fn normal(key: u16, value: String) -> (Self, Receiver<bool>) {
let (tx, rx) = mpsc::sync_channel(1);
let proposal = Proposal {
normal: Some((key, value)),
conf_change: None,
transfer_leader: None,
proposed: 0,
propose_success: tx,
};
(proposal, rx)
}
}
fn propose(raft_group: &mut RawNode<MemStorage>, proposal: &mut Proposal) {
let last_index1 = raft_group.raft.raft_log.last_index() + 1;
if let Some((ref key, ref value)) = proposal.normal {
let data = format!("put {} {}", key, value).into_bytes();
let _ = raft_group.propose(vec![], data);
} else if let Some(ref cc) = proposal.conf_change {
let _ = raft_group.propose_conf_change(vec![], cc.clone());
} else if let Some(_tranferee) = proposal.transfer_leader {
// TODO: implement tranfer leader.
unimplemented!();
}
let last_index2 = raft_group.raft.raft_log.last_index() + 1;
if last_index2 == last_index1 {
// Propose failed, don't forget to respond to the client.
proposal.propose_success.send(false).unwrap();
} else {
proposal.proposed = last_index1;
}
}
// Proposes some conf change for peers [2, 5].
fn add_all_followers(proposals: &Mutex<VecDeque<Proposal>>) {
for i in 2..6u64 {
let mut conf_change = ConfChange::default();
conf_change.set_node_id(i);
conf_change.set_change_type(ConfChangeType::AddNode);
loop {
let (proposal, rx) = Proposal::conf_change(&conf_change);
proposals.lock().unwrap().push_back(proposal);
if rx.recv().unwrap() {
break;
}
thread::sleep(Duration::from_millis(100));
}
}
} |
//! Determine offset of stack pointer from function entry.
//!
//! Determine the value of the stack pointer at every location in the function
//! as an offset from the stack pointer's value at function entry.
//!
//! This analysis works off a very simple lattice, Top/Value/Bottom, where Value
//! is a single il::Constant.
use architecture::Architecture;
use analysis::fixed_point;
use error::*;
use executor::eval;
use il;
use std::collections::HashMap;
use std::cmp::{Ordering, PartialOrd};
/// Determine offset of stack pointer from program entry at each place in the
/// program.
pub fn stack_pointer_offsets<'f>(
function: &'f il::Function,
architecture: &Architecture
) -> Result<HashMap<il::RefProgramLocation<'f>, StackPointerOffset>> {
let spoa = StackPointerOffsetAnalysis {
stack_pointer: architecture.stack_pointer()
};
fixed_point::fixed_point_forward(spoa, function)
}
/// Returns true if there is a valid StackPointerOffset value for every location
/// in the function.
pub fn perfect<'f>(
stack_pointer_offsets: &HashMap<il::RefProgramLocation<'f>, StackPointerOffset>
) -> bool {
stack_pointer_offsets.iter().all(|(_, spo)| spo.is_value())
}
/// A constant value representing the value of the stack pointer at some point
/// in the function.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub enum StackPointerOffset {
Top,
Value(il::Constant),
Bottom
}
impl StackPointerOffset {
pub fn is_top(&self) -> bool {
match *self {
StackPointerOffset::Top => true,
_ => false
}
}
pub fn is_value(&self) -> bool {
match *self {
StackPointerOffset::Value(_) => true,
_ => false
}
}
pub fn value(&self) -> Option<&il::Constant> {
if let StackPointerOffset::Value(ref constant) = *self {
Some(constant)
}
else {
None
}
}
pub fn is_bottom(&self) -> bool {
match *self {
StackPointerOffset::Bottom => true,
_ => false
}
}
}
impl PartialOrd for StackPointerOffset {
fn partial_cmp(&self, other: &StackPointerOffset) -> Option<Ordering> {
match *self {
StackPointerOffset::Top => match *other {
StackPointerOffset::Top => Some(Ordering::Equal),
StackPointerOffset::Value(_) |
StackPointerOffset::Bottom => Some(Ordering::Greater)
},
StackPointerOffset::Value(ref lhs) => match *other {
StackPointerOffset::Top => Some(Ordering::Less),
StackPointerOffset::Value(ref rhs) =>
if lhs == rhs { Some(Ordering::Equal) }
else { None},
StackPointerOffset::Bottom => Some(Ordering::Greater)
},
StackPointerOffset::Bottom => match *other {
StackPointerOffset::Top |
StackPointerOffset::Value(_) => Some(Ordering::Less),
StackPointerOffset::Bottom => Some(Ordering::Equal)
}
}
}
}
struct StackPointerOffsetAnalysis {
stack_pointer: il::Scalar
}
impl StackPointerOffsetAnalysis {
/// Handle an operation for stack pointer offset analysis
fn handle_operation(
&self,
operation: &il::Operation,
stack_pointer_offset: StackPointerOffset
) -> Result<StackPointerOffset> {
Ok(match *operation {
// If we're assigning, operate off current stack pointer value
il::Operation::Assign { ref dst, ref src } => {
if *dst == self.stack_pointer {
match stack_pointer_offset {
StackPointerOffset::Top => StackPointerOffset::Top,
StackPointerOffset::Value(ref constant) => {
let expr = src.replace_scalar(&self.stack_pointer,
&constant.clone().into())?;
if expr.all_constants() {
StackPointerOffset::Value(eval(&expr)?.into())
}
else {
StackPointerOffset::Top
}
},
StackPointerOffset::Bottom => StackPointerOffset::Bottom
}
}
else {
stack_pointer_offset
}
},
// If we are loading stack pointer, set it to top
il::Operation::Load { ref dst, .. } => {
if *dst == self.stack_pointer {
StackPointerOffset::Top
}
else {
stack_pointer_offset
}
},
_ => stack_pointer_offset
})
}
}
/// Track the offset for the stack pointer at any point in the program
impl<'f> fixed_point::FixedPointAnalysis<'f, StackPointerOffset> for StackPointerOffsetAnalysis {
fn trans(
&self,
location: il::RefProgramLocation<'f>,
state: Option<StackPointerOffset>
) -> Result<StackPointerOffset> {
// If we are the function entry, we set the value of the stack pointer
// to 0.
let stack_pointer_offset = match state {
Some(state) => state,
None => {
// Get function entry
let function_entry =
il::RefProgramLocation::from_function(location.function())
.ok_or("Unable to get function entry")?;
if location == function_entry {
StackPointerOffset::Value(il::const_(0, 32))
}
else {
StackPointerOffset::Top
}
}
};
Ok(match *location.function_location() {
il::RefFunctionLocation::Instruction(_, ref instruction) =>
self.handle_operation(instruction.operation(),
stack_pointer_offset)?,
_ => stack_pointer_offset
})
}
fn join(&self, state0: StackPointerOffset, state1: &StackPointerOffset)
-> Result<StackPointerOffset> {
Ok(match state0 {
StackPointerOffset::Top => StackPointerOffset::Top,
StackPointerOffset::Value(v0) => {
match *state1 {
StackPointerOffset::Top => StackPointerOffset::Top,
StackPointerOffset::Value(ref v1) => {
if v0 == *v1 {
StackPointerOffset::Value(v0)
}
else {
StackPointerOffset::Top
}
},
StackPointerOffset::Bottom => StackPointerOffset::Value(v0)
}
},
StackPointerOffset::Bottom => {
match *state1 {
StackPointerOffset::Top => StackPointerOffset::Top,
StackPointerOffset::Value(ref v1) =>
StackPointerOffset::Value(v1.clone()),
StackPointerOffset::Bottom => StackPointerOffset::Bottom
}
}
})
}
} |
pub mod mysql;
pub mod responsetime;
|
#[macro_use] extern crate lazy_static;
extern crate regex;
use std::collections::HashMap;
use std::str::FromStr;
use regex::Regex;
include!("operation.rs");
include!("instruction.rs");
lazy_static! {
static ref COMMAND: Regex =
Regex::new(r"^(nop|acc|jmp) ([+-]\d+)$").unwrap();
}
#[derive(Debug)]
pub struct CommandParseError;
type HandlerFn = fn(&mut StemBrain, i32) -> Result<(),()>;
pub struct StemBrain {
memory: HashMap<usize, u8>,
accumulator: i32,
program: HashMap<usize, Instruction>,
instruction_pointer: usize,
handlers: HashMap<Operation, HandlerFn>
}
impl Default for StemBrain {
fn default() -> StemBrain {
let mut h = HashMap::new();
h.insert(Operation::JMP,
StemBrain::handle_jmp as HandlerFn);
h.insert(Operation::ACC,
StemBrain::handle_acc);
h.insert(Operation::NOP,
|_, _| Ok(()));
StemBrain {
memory: HashMap::new(),
accumulator: 0,
program: HashMap::new(),
instruction_pointer: 0,
handlers: h
}
}
}
impl StemBrain {
#[must_use]
pub fn new() -> StemBrain {
StemBrain::default()
}
#[must_use]
pub fn get_ip(&self) -> usize {
self.instruction_pointer
}
#[must_use]
pub fn get_acc(&self) -> i32 {
self.accumulator
}
pub fn set_acc(&mut self, acc: i32) {
self.accumulator = acc;
}
pub fn reset(&mut self) {
self.accumulator = 0;
self.instruction_pointer = 0;
}
/// # Errors
///
/// Returns () for lack of a better type
pub fn handle_jmp(&mut self, param: i32) -> Result<(),()> {
//let ip = self.instruction_pointer as i32 + param;
//if ip < 0 {
//return Err(());
//}
//self.instruction_pointer = ip as usize;
if param < 0 {
return match self.instruction_pointer.checked_sub(param.abs() as usize) {
None => Err(()),
Some(k) => { self.instruction_pointer = k; Ok(()) }
}
} else {
self.instruction_pointer += param as usize;
}
Ok(())
}
/// # Errors
///
/// Returns () for lack of a better type
pub fn handle_acc(&mut self, param: i32) -> Result<(),()> {
self.accumulator += param;
Ok(())
}
/// # Errors
///
/// Returns () for lack of a better type
pub fn zap(&mut self, at: usize) -> Result<(),()> {
let instruction = self.read_instruction_at(at).cloned();
if instruction.is_none() {
return Err(());
}
let instruction = instruction.unwrap();
match (instruction.get_op(), instruction.get_param()) {
(Operation::JMP, p) => { self.program.insert(at, Instruction {
op: Operation::NOP,
param: *p
}); Ok(()) },
(Operation::NOP, p) => { self.program.insert(at, Instruction {
op: Operation::JMP,
param: *p
}); Ok(()) },
_ => { Err(()) }
}
}
/// # Errors
///
/// Returns `CommandParseError` as type
pub fn inject(&mut self, commands: &str) -> Result<usize,CommandParseError> {
for command in commands.split('\n') {
self.program.insert(self.program.len(),
command.parse::<Instruction>()?);
}
//println!("Injected {} commands", self.program.len());
Ok(self.program.len())
}
#[must_use]
pub fn read_mem_at(&self, at: usize) -> u8 {
*self.memory.get(&at).unwrap_or(&0)
}
#[must_use]
pub fn read_instruction_at(&self, at: usize) -> Option<&Instruction> {
self.program.get(&at)
}
/// # Errors
///
/// Returns () for lack of a better type
pub fn dispatch(&mut self, command: &Instruction) -> Result<(),()> {
let handler: HandlerFn = *self.handlers.get(command.get_op())
.unwrap();
handler(self, *command.get_param())
}
/// # Errors
///
/// Will return a unit as an error for lack of better type.
pub fn step(&mut self) -> Result<(),()> {
let instruction = self.read_instruction_at(self.instruction_pointer)
.cloned();
let ptsave = self.instruction_pointer;
if instruction.is_none() {
return Err(());
}
let instruction = instruction.unwrap();
self.dispatch(&instruction)?;
if ptsave == self.instruction_pointer {
self.instruction_pointer+=1;
}
Ok(())
}
}
impl std::fmt::Debug for StemBrain {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "<StemBrain;ip={:?};acc={};program=<{} instructions>;handlers=<{} handlers>>",
self.instruction_pointer,
self.accumulator,
self.program.len(),
self.handlers.len())
}
}
impl std::fmt::Display for StemBrain {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Brain instance. Accumulator={}. IP={}.\nHandlers={:?}",
self.accumulator, self.instruction_pointer,
self.handlers.len())?;
let size = (self.handlers.len() as f64).log2().ceil() as usize;
for idx in 0..self.program.len() {
let mut u = format!("{}", idx);
while u.len() < size+1 {
u = format!("0{}", u);
}
let ist = self.program.get(&idx).unwrap();
let k = write!(f, "\n[{}] {}", u, ist);
if k.is_err() {
return k;
}
}
Ok(())
}
}
|
use std::cell::RefCell;
use piston_window::{clear, Button, Event, Key, PistonWindow};
use rand::Rng;
use crate::colors;
use crate::metrics::{Metrics, WINDOW_HEIGHT, WINDOW_WIDTH};
use crate::player::Player;
use crate::scenery::{Scenery, SceneryType};
use crate::shapes::Shape;
pub enum GameState {
Start,
}
pub struct Game<'a> {
pub user_player: Player<'a>,
pub other_players: Vec<Player<'a>>,
pub scenery: RefCell<Vec<Scenery>>,
pub metrics: &'a Metrics,
}
impl<'a> Game<'a> {
pub fn display_items(state: GameState, metrics: &'a Metrics) -> Self {
match state {
GameState::Start => {
// Currently just have one player for setup purposes, eventually there should be more and this can be moved
let player = Player {
shape: Shape::Circle { radius: 50.0 },
size: (50.0, 50.0),
location: (50.0, 50.0),
color: colors::RED,
metrics,
};
let tree = Scenery {
type_: SceneryType::Tree {
base_width: 45.0,
base_height: 120.0,
top_radius: 60.0,
},
location: (500.0, 600.0),
};
return Game {
user_player: player,
other_players: Vec::new(),
scenery: RefCell::new(vec![tree]),
metrics,
};
}
}
}
// Render function checks arguments and events and changes display based on this
pub fn render(&self, window: &mut PistonWindow, event: &Event) {
window.draw_2d(event, |context, graphics, _| {
clear(colors::GREEN, graphics);
self.user_player.render(context, graphics);
for player in &self.other_players {
player.render(context, graphics);
}
for scene in &*self.scenery.borrow() {
scene.render(context, graphics);
}
});
}
pub fn move_player(&self, player: &Player<'_>, movement: (f64, f64)) -> Option<(f64, f64)> {
let (min_x, max_x) = match player.shape {
Shape::Circle { radius } => (radius, self.metrics.width - radius),
Shape::Rectangle { .. } => unimplemented!("Add later"),
};
let (min_y, max_y) = match player.shape {
Shape::Circle { radius } => (radius, self.metrics.height - radius),
Shape::Rectangle { .. } => unimplemented!("Add later"),
};
let x = clamp(
player.location.0 + (movement.0 * player.size.0),
min_x,
max_x,
);
let y = clamp(
player.location.1 + (movement.1 * player.size.1),
min_y,
max_y,
);
let future_player = Player {
location: (x, y),
..player.clone()
};
for scenery in &*self.scenery.borrow() {
if scenery.collides(&future_player) {
return None;
}
}
Some((x, y))
}
// Handles all press interactions and returns Tuple of (x, y) coordinate changes if character requires movement
// In the future could return an enum of character reaction, if something different than key arrows was pressed
pub fn on_press(&self, args: &Button) -> Option<(f64, f64)> {
println!("Entered on_press function");
match args {
Button::Keyboard(args) => self.on_key(args),
_ => None,
}
}
// Specifically handles keyboard presses and returns tuple of (x, y) coordinate changes for character movement
// Currently only handling arrow keys
fn on_key(&self, key: &Key) -> Option<(f64, f64)> {
println!("Entered on_key function");
match key {
Key::Right => Some((1.0, 0.0)),
Key::Left => Some((-1.0, 0.0)),
Key::Up => Some((0.0, -1.0)),
Key::Down => Some((0.0, 1.0)),
_ => {
if (Key::A..=Key::Z).contains(key) {
self.handle_letter(key)
}
None
}
}
}
fn handle_letter(&self, key: &Key) {
match key {
Key::T => {
//plant tree in random location on board
let scene_type = SceneryType::Tree {
base_width: 45.0,
base_height: 120.0,
top_radius: 60.0,
};
&self.make_scenery(scene_type);
}
_ => {}
}
}
fn make_scenery(&self, scenery_type: SceneryType) {
let mut rng = rand::thread_rng();
let ran_x = rng.gen_range(100.0, WINDOW_WIDTH - 100.0);
let ran_y = rng.gen_range(100.0, WINDOW_HEIGHT - 100.0);
&self.add_scenery((ran_x, ran_y), scenery_type);
}
fn add_scenery(&self, location: (f64, f64), scenery_type: SceneryType) {
let scenery = Scenery {
type_: scenery_type,
location: location,
};
self.scenery.borrow_mut().push(scenery);
}
}
fn clamp(value: f64, min: f64, max: f64) -> f64 {
if value < min {
min
} else if value > max {
max
} else {
value
}
}
|
#[doc = "Register `ISR` reader"]
pub type R = crate::R<ISR_SPEC>;
#[doc = "Field `JEOCF` reader - End of injected conversion flag This bit is set by hardware. It is cleared when the software or DMA reads DFSDM_FLTxJDATAR."]
pub type JEOCF_R = crate::BitReader;
#[doc = "Field `REOCF` reader - End of regular conversion flag This bit is set by hardware. It is cleared when the software or DMA reads DFSDM_FLTxRDATAR."]
pub type REOCF_R = crate::BitReader;
#[doc = "Field `JOVRF` reader - Injected conversion overrun flag This bit is set by hardware. It can be cleared by software using the CLRJOVRF bit in the DFSDM_FLTxICR register."]
pub type JOVRF_R = crate::BitReader;
#[doc = "Field `ROVRF` reader - Regular conversion overrun flag This bit is set by hardware. It can be cleared by software using the CLRROVRF bit in the DFSDM_FLTxICR register."]
pub type ROVRF_R = crate::BitReader;
#[doc = "Field `AWDF` reader - Analog watchdog This bit is set by hardware. It is cleared by software by clearing all source flag bits AWHTF\\[7:0\\]
and AWLTF\\[7:0\\]
in DFSDM_FLTxAWSR register (by writing '1â\u{80}\u{99} into the clear bits in DFSDM_FLTxAWCFR register)."]
pub type AWDF_R = crate::BitReader;
#[doc = "Field `JCIP` reader - Injected conversion in progress status A request to start an injected conversion is ignored when JCIP=1."]
pub type JCIP_R = crate::BitReader;
#[doc = "Field `RCIP` reader - Regular conversion in progress status A request to start a regular conversion is ignored when RCIP=1."]
pub type RCIP_R = crate::BitReader;
#[doc = "Field `CKABF` reader - Clock absence flag CKABF\\[y\\]=0: Clock signal on channel y is present. CKABF\\[y\\]=1: Clock signal on channel y is not present. Given y bit is set by hardware when clock absence is detected on channel y. It is held at CKABF\\[y\\]=1 state by hardware when CHEN=0 (see DFSDM_CHyCFGR1 register). It is held at CKABF\\[y\\]=1 state by hardware when the transceiver is not yet synchronized.It can be cleared by software using the corresponding CLRCKABF\\[y\\]
bit in the DFSDM_FLTxICR register. Note: CKABF\\[7:0\\]
is present only in DFSDM_FLT0ISR register (filter x=0)"]
pub type CKABF_R = crate::FieldReader;
#[doc = "Field `SCDF` reader - short-circuit detector flag SDCF\\[y\\]=0: No short-circuit detector event occurred on channel y SDCF\\[y\\]=1: The short-circuit detector counter reaches, on channel y, the value programmed in the DFSDM_CHyAWSCDR registers This bit is set by hardware. It can be cleared by software using the corresponding CLRSCDF\\[y\\]
bit in the DFSDM_FLTxICR register. SCDF\\[y\\]
is cleared also by hardware when CHEN\\[y\\]
= 0 (given channel is disabled). Note: SCDF\\[7:0\\]
is present only in DFSDM_FLT0ISR register (filter x=0)"]
pub type SCDF_R = crate::FieldReader;
impl R {
#[doc = "Bit 0 - End of injected conversion flag This bit is set by hardware. It is cleared when the software or DMA reads DFSDM_FLTxJDATAR."]
#[inline(always)]
pub fn jeocf(&self) -> JEOCF_R {
JEOCF_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - End of regular conversion flag This bit is set by hardware. It is cleared when the software or DMA reads DFSDM_FLTxRDATAR."]
#[inline(always)]
pub fn reocf(&self) -> REOCF_R {
REOCF_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Injected conversion overrun flag This bit is set by hardware. It can be cleared by software using the CLRJOVRF bit in the DFSDM_FLTxICR register."]
#[inline(always)]
pub fn jovrf(&self) -> JOVRF_R {
JOVRF_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Regular conversion overrun flag This bit is set by hardware. It can be cleared by software using the CLRROVRF bit in the DFSDM_FLTxICR register."]
#[inline(always)]
pub fn rovrf(&self) -> ROVRF_R {
ROVRF_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Analog watchdog This bit is set by hardware. It is cleared by software by clearing all source flag bits AWHTF\\[7:0\\]
and AWLTF\\[7:0\\]
in DFSDM_FLTxAWSR register (by writing '1â\u{80}\u{99} into the clear bits in DFSDM_FLTxAWCFR register)."]
#[inline(always)]
pub fn awdf(&self) -> AWDF_R {
AWDF_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 13 - Injected conversion in progress status A request to start an injected conversion is ignored when JCIP=1."]
#[inline(always)]
pub fn jcip(&self) -> JCIP_R {
JCIP_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - Regular conversion in progress status A request to start a regular conversion is ignored when RCIP=1."]
#[inline(always)]
pub fn rcip(&self) -> RCIP_R {
RCIP_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bits 16:23 - Clock absence flag CKABF\\[y\\]=0: Clock signal on channel y is present. CKABF\\[y\\]=1: Clock signal on channel y is not present. Given y bit is set by hardware when clock absence is detected on channel y. It is held at CKABF\\[y\\]=1 state by hardware when CHEN=0 (see DFSDM_CHyCFGR1 register). It is held at CKABF\\[y\\]=1 state by hardware when the transceiver is not yet synchronized.It can be cleared by software using the corresponding CLRCKABF\\[y\\]
bit in the DFSDM_FLTxICR register. Note: CKABF\\[7:0\\]
is present only in DFSDM_FLT0ISR register (filter x=0)"]
#[inline(always)]
pub fn ckabf(&self) -> CKABF_R {
CKABF_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 24:31 - short-circuit detector flag SDCF\\[y\\]=0: No short-circuit detector event occurred on channel y SDCF\\[y\\]=1: The short-circuit detector counter reaches, on channel y, the value programmed in the DFSDM_CHyAWSCDR registers This bit is set by hardware. It can be cleared by software using the corresponding CLRSCDF\\[y\\]
bit in the DFSDM_FLTxICR register. SCDF\\[y\\]
is cleared also by hardware when CHEN\\[y\\]
= 0 (given channel is disabled). Note: SCDF\\[7:0\\]
is present only in DFSDM_FLT0ISR register (filter x=0)"]
#[inline(always)]
pub fn scdf(&self) -> SCDF_R {
SCDF_R::new(((self.bits >> 24) & 0xff) as u8)
}
}
#[doc = "\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`isr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ISR_SPEC;
impl crate::RegisterSpec for ISR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`isr::R`](R) reader structure"]
impl crate::Readable for ISR_SPEC {}
#[doc = "`reset()` method sets ISR to value 0x00ff_0000"]
impl crate::Resettable for ISR_SPEC {
const RESET_VALUE: Self::Ux = 0x00ff_0000;
}
|
use crate::storage::SeriesTable;
use std::convert::Infallible;
use std::sync::Arc;
use warp::Filter;
pub mod create;
pub mod append;
pub mod query;
pub mod export;
pub mod restore;
mod error;
pub fn with_series_table(
series_table: Arc<SeriesTable>,
) -> impl Filter<Extract = (Arc<SeriesTable>,), Error = Infallible> + Clone {
warp::any().map(move || series_table.clone())
} |
use futures::{stream, Stream, StreamExt};
use lazy_static::lazy_static;
use rand::distributions::{Distribution, Uniform};
use std::time::Duration;
use tokio::time::{sleep, Instant};
lazy_static! {
static ref START_TIME: Instant = Instant::now();
}
#[tokio::main]
async fn main() {
println!("First 10 pages:\n{:?}", get_n_pages(10).await);
}
async fn get_n_pages(n: usize) -> Vec<Vec<usize>> {
get_pages().take(n).collect().await
}
fn get_pages() -> impl Stream<Item = Vec<usize>> {
stream::iter(0..).then(|i| async move { get_page(i).await })
}
async fn get_page(i: usize) -> Vec<usize> {
let millis = Uniform::from(0..10).sample(&mut rand::thread_rng());
println!(
"[{}] # get_page({}) will complete in {} ms",
START_TIME.elapsed().as_millis(),
i,
millis
);
sleep(Duration::from_millis(millis)).await;
println!(
"[{}] # get_page({}) completed",
START_TIME.elapsed().as_millis(),
i
);
(10 * i..10 * (i + 1)).collect()
}
|
use std::fs;
use std::error::*;
use std::collections::{VecDeque, HashMap};
#[derive(Debug)]
pub enum IntcodeComputerState {
WaitingForInput,
Halted,
OutputProduced(i64),
}
#[derive(PartialEq, Debug)]
pub enum ParamMode {
PositionMode,
ImmediateMode,
RelativeMode,
}
#[derive(Clone)]
pub struct IntcodeComputer {
memory: HashMap<i32, i64>,
instruction_pointer: i32,
relative_base: i32,
input_queue: VecDeque<i64>,
output: Vec<i64>,
output_queue: VecDeque<i64>,
}
impl IntcodeComputer {
pub fn new(program: Vec<i64>) -> IntcodeComputer {
let memory: HashMap<i32, i64> = program
.iter()
.enumerate()
.map(|(i, v)| (i as i32, *v))
.collect();
IntcodeComputer {
memory,
instruction_pointer: 0,
relative_base: 0,
input_queue: VecDeque::new(),
output: vec![],
output_queue: VecDeque::new(),
}
}
pub fn new_from_file(path: &str) -> IntcodeComputer {
IntcodeComputer::new(load_input(path))
}
pub fn provide_input(&mut self, input: i64) {
self.input_queue.push_back(input);
}
pub fn provide_input_iter<T: IntoIterator<Item=i64>>(&mut self, input: T) {
for value in input {
self.input_queue.push_back(value);
}
}
fn read_memory(&self, location: &i32) -> Result<i64, Box<dyn Error>> {
if location < &0 {
Err("Accessing memory in negative index")?;
}
Ok(*self.memory.get(&location).unwrap_or(&0))
}
pub fn write_memory(&mut self, location: i32, value: i64, mode: ParamMode) -> Result<(), Box<dyn Error>> {
let location = match mode {
ParamMode::ImmediateMode => panic!("wrong param mode for write"),
ParamMode::PositionMode => location,
ParamMode::RelativeMode => location + self.relative_base,
};
if location < 0 {
Err("Writing memory in negative index")?;
}
self.memory.insert(location, value);
Ok(())
}
fn load_param(&self, location: &i32, mode: ParamMode) -> Result<i64, Box<dyn Error>> {
match mode {
ParamMode::ImmediateMode => Ok(self.read_memory(location)?),
ParamMode::PositionMode => {
let absolute_position = self.read_memory(location)?;
Ok(self.read_memory(&(absolute_position as i32))?)
},
ParamMode::RelativeMode => {
let relative_position = self.read_memory(location)? as i32;
Ok(self.read_memory(&(relative_position + self.relative_base))?)
}
}
}
pub fn dump_memory(&self) -> Vec<i64> {
let max = self.memory.keys().max().unwrap_or(&0) + 1;
let mut memory_vec = Vec::with_capacity(max as usize);
for key in 0..max {
memory_vec.push(self.read_memory(&key).unwrap());
}
memory_vec
}
pub fn get_output(&self) -> Vec<i64> {
self.output.clone()
}
pub fn pop_output(&mut self) -> Vec<i64> {
let mut output = vec![];
while let Some(val) = self.output_queue.pop_front() {
output.push(val);
}
output
}
pub fn run_ignore_output(&mut self) -> Result<IntcodeComputerState, Box<dyn Error>> {
loop {
match self.run()? {
IntcodeComputerState::Halted => return Ok(IntcodeComputerState::Halted),
IntcodeComputerState::WaitingForInput => return Ok(IntcodeComputerState::WaitingForInput),
IntcodeComputerState::OutputProduced(_) => (),
}
}
}
pub fn run(&mut self) -> Result<IntcodeComputerState, Box<dyn Error>> {
loop {
// let op = self.memory.get(&self.instruction_pointer)
let op = &self.read_memory(&self.instruction_pointer)?;
match get_op_code(op) {
1 => {
// addition
let a = self.load_param(&(self.instruction_pointer + 1), get_param_mode(op, 0))?;
let b = self.load_param(&(self.instruction_pointer + 2), get_param_mode(op, 1))?;
let output_location = self.load_param(&(self.instruction_pointer + 3), ParamMode::ImmediateMode)?;
self.write_memory(output_location as i32, a + b, get_param_mode(op, 2))?;
self.instruction_pointer += 4;
},
2 => {
// multiplication
let a = self.load_param(&(self.instruction_pointer + 1), get_param_mode(op, 0))?;
let b = self.load_param(&(self.instruction_pointer + 2), get_param_mode(op, 1))?;
let output_location = self.load_param(&(self.instruction_pointer + 3), ParamMode::ImmediateMode)?;
self.write_memory(output_location as i32, a * b, get_param_mode(op, 2))?;
self.instruction_pointer += 4;
},
3 => {
// input
let output_location = self.load_param(&(self.instruction_pointer + 1), ParamMode::ImmediateMode)? as i32;
if let Some(value) = self.input_queue.pop_front() {
self.write_memory(output_location, value, get_param_mode(op, 0))?;
self.instruction_pointer += 2;
} else {
return Ok(IntcodeComputerState::WaitingForInput);
}
},
4 => {
// output
let output = self.load_param(&(self.instruction_pointer + 1), get_param_mode(op, 0))?;
self.instruction_pointer += 2;
self.output.push(output);
self.output_queue.push_back(output);
return Ok(IntcodeComputerState::OutputProduced(output));
},
5 => {
// jump if true
let input = self.load_param(&(self.instruction_pointer + 1), get_param_mode(op, 0))?;
let target = self.load_param(&(self.instruction_pointer + 2), get_param_mode(op, 1))?;
if input != 0 {
self.instruction_pointer = target as i32;
} else {
self.instruction_pointer += 3;
}
},
6 => {
// jump if false
let input = self.load_param(&(self.instruction_pointer + 1), get_param_mode(op, 0))?;
let target = self.load_param(&(self.instruction_pointer + 2), get_param_mode(op, 1))?;
if input == 0 {
self.instruction_pointer = target as i32;
} else {
self.instruction_pointer += 3;
}
},
7 => {
// less than
let a = self.load_param(&(self.instruction_pointer + 1), get_param_mode(op, 0))?;
let b = self.load_param(&(self.instruction_pointer + 2), get_param_mode(op, 1))?;
let output_location = self.load_param(&(self.instruction_pointer + 3), ParamMode::ImmediateMode)?;
self.write_memory(output_location as i32, if a < b { 1 } else { 0 }, get_param_mode(op, 2))?;
self.instruction_pointer += 4;
},
8 => {
// equals
let a = self.load_param(&(self.instruction_pointer + 1), get_param_mode(op, 0))?;
let b = self.load_param(&(self.instruction_pointer + 2), get_param_mode(op, 1))?;
let output_location = self.load_param(&(self.instruction_pointer + 3), ParamMode::ImmediateMode)?;
self.write_memory(output_location as i32, if a == b { 1 } else { 0 }, get_param_mode(op, 2))?;
self.instruction_pointer += 4;
},
9 => {
// shift relative base
let a = self.load_param(&(self.instruction_pointer + 1), get_param_mode(op, 0))? as i32;
self.relative_base += a;
self.instruction_pointer += 2;
}
99 => {
return Ok(IntcodeComputerState::Halted);
},
_ => Err(format!("Unsupported operation {} at {}", get_op_code(op), self.instruction_pointer))?,
}
}
}
}
fn load_input(path: &str) -> Vec<i64> {
fs::read_to_string(path)
.expect("Something went wrong reading the file")
.split(",")
.filter_map(|s| s.parse::<i64>().ok())
.collect()
}
fn get_op_code(op: &i64) -> i64 {
op % 100
}
fn get_param_mode(op: &i64, param_index: u32) -> ParamMode {
let mode = op / (10_i64.pow(param_index + 2)) % 10;
match mode {
0 => ParamMode::PositionMode,
1 => ParamMode::ImmediateMode,
2 => ParamMode::RelativeMode,
_ => panic!("Unknown param mode"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_op_code_extracts() {
assert_eq!(get_op_code(&1002), 02);
assert_eq!(get_op_code(&2), 02);
}
#[test]
fn get_param_mode_one() {
assert_eq!(get_param_mode(&1002, 0), ParamMode::PositionMode);
assert_eq!(get_param_mode(&1002, 1), ParamMode::ImmediateMode);
assert_eq!(get_param_mode(&1002, 2), ParamMode::PositionMode);
}
#[test]
fn test_computer_one() {
let input = vec![1002, 4, 3, 4, 33];
let mut computer = IntcodeComputer::new(input);
computer.run().unwrap();
assert_eq!(computer.dump_memory(), vec![1002, 4, 3, 4, 99]);
}
#[test]
fn test_computer_two() {
let input = vec![1101, 100, -1, 4, 0];
let mut computer = IntcodeComputer::new(input);
computer.run().unwrap();
assert_eq!(computer.dump_memory(), vec![1101, 100, -1, 4, 99]);
}
#[test]
fn test_computer_input() {
let program = load_input("input/day_five.txt");
let mut computer = IntcodeComputer::new(program);
computer.provide_input(1);
computer.run_ignore_output().unwrap();
assert_eq!(computer.get_output(), vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 9006673]);
}
#[test]
fn jump_if_true_yes_pos_mode() {
let program = vec![3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9];
let mut computer = IntcodeComputer::new(program);
let mut output = -1;
loop {
match computer.run().unwrap() {
IntcodeComputerState::Halted => break,
IntcodeComputerState::OutputProduced(res) => output = res,
IntcodeComputerState::WaitingForInput => computer.provide_input(6),
}
}
assert_eq!(output, 1);
}
#[test]
fn jump_if_true_no_pos_mode() {
let program = vec![3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9];
let mut computer = IntcodeComputer::new(program);
let mut output = -1;
loop {
match computer.run().unwrap() {
IntcodeComputerState::Halted => break,
IntcodeComputerState::OutputProduced(res) => output = res,
IntcodeComputerState::WaitingForInput => computer.provide_input(0),
}
}
assert_eq!(output, 0);
}
#[test]
fn jump_if_true_yes_ime_mode() {
let program = vec![3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1];
let mut computer = IntcodeComputer::new(program);
let mut output = -1;
loop {
match computer.run().unwrap() {
IntcodeComputerState::Halted => break,
IntcodeComputerState::OutputProduced(res) => output = res,
IntcodeComputerState::WaitingForInput => computer.provide_input(6),
}
}
assert_eq!(output, 1);
}
#[test]
fn jump_if_true_no_ime_mode() {
let program = vec![3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1];
let mut computer = IntcodeComputer::new(program);
let mut output = -1;
loop {
match computer.run().unwrap() {
IntcodeComputerState::Halted => break,
IntcodeComputerState::OutputProduced(res) => output = res,
IntcodeComputerState::WaitingForInput => computer.provide_input(0),
}
}
assert_eq!(output, 0);
}
fn test_wrapper(program: &Vec<i64>, input: Option<Vec<i64>>) -> Vec<i64> {
let mut input = input.unwrap();
input.reverse();
let mut computer = IntcodeComputer::new(program.clone());
let mut output = -1;
loop {
match computer.run().unwrap() {
IntcodeComputerState::Halted => break,
IntcodeComputerState::OutputProduced(res) => output = res,
IntcodeComputerState::WaitingForInput => computer.provide_input(input.pop().unwrap())
}
}
vec![output]
}
#[test]
fn is_8_pos_mode_yes() {
let mut program = vec![3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8];
let input = vec![8];
let output = test_wrapper(&mut program, Some(input));
assert_eq!(output, vec![1]);
}
#[test]
fn is_8_pos_mode_no() {
let mut program = vec![3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8];
let input = vec![2];
let output = test_wrapper(&mut program, Some(input));
assert_eq!(output, vec![0]);
}
#[test]
fn less_than_8_pos_mode_yes() {
let mut program = vec![3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8];
let input = vec![2];
let output = test_wrapper(&mut program, Some(input));
assert_eq!(output, vec![1]);
}
#[test]
fn less_than_8_pos_mode_no() {
let mut program = vec![3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8];
let input = vec![8];
let output = test_wrapper(&mut program, Some(input));
assert_eq!(output, vec![0]);
}
#[test]
fn is_8_ime_mode_yes() {
let mut program = vec![3, 3, 1108, -1, 8, 3, 4, 3, 99];
let input = vec![8];
let output = test_wrapper(&mut program, Some(input));
assert_eq!(output, vec![1]);
}
#[test]
fn is_8_ime_mode_no() {
let mut program = vec![3, 3, 1108, -1, 8, 3, 4, 3, 99];
let input = vec![2];
let output = test_wrapper(&mut program, Some(input));
assert_eq!(output, vec![0]);
}
#[test]
fn less_than_8_ime_mode_yes() {
let mut program = vec![3, 3, 1107, -1, 8, 3, 4, 3, 99];
let input = vec![2];
let output = test_wrapper(&mut program, Some(input));
assert_eq!(output, vec![1]);
}
#[test]
fn less_than_8_ime_mode_no() {
let mut program = vec![3, 3, 1107, -1, 8, 3, 4, 3, 99];
let input = vec![8];
let output = test_wrapper(&mut program, Some(input));
assert_eq!(output, vec![0]);
}
#[test]
fn long_test_day5_task_2() {
let mut program = vec![
3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0,
0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4,
20, 1105, 1, 46, 98, 99,
];
let input = vec![7];
let output = test_wrapper(&mut program, Some(input));
assert_eq!(output, vec![999]);
let mut program = vec![
3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0,
0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4,
20, 1105, 1, 46, 98, 99,
];
let input = vec![8];
let output = test_wrapper(&mut program, Some(input));
assert_eq!(output, vec![1000]);
let mut program = vec![
3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0,
0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4,
20, 1105, 1, 46, 98, 99,
];
let input = vec![9];
let output = test_wrapper(&mut program, Some(input));
assert_eq!(output, vec![1001]);
}
#[test]
fn day_5_task_2() {
let mut program = load_input("input/day_five.txt");
let input = vec![5];
let output = test_wrapper(&mut program, Some(input));
assert_eq!(output, vec![3629692]);
}
}
|
use auto_impl::auto_impl;
#[auto_impl(Box)]
trait Trait {
fn foo(self);
}
fn assert_impl<T: Trait>() {}
fn main() {
assert_impl::<Box<dyn Trait>>();
}
|
extern crate serde;
extern crate serde_json;
extern crate fluent;
extern crate fluent_json;
extern crate getopts;
use std::fs::File;
use std::io::Read;
use std::io;
use std::env;
use getopts::Options;
use fluent::syntax::parser::parse;
use fluent_json::*;
use fluent_json::serialize_json;
#[derive(Debug)]
enum CliError {
Deserialize(serde_json::Error),
Parse(Vec<fluent::syntax::parser::ParserError>),
}
fn read_file(path: &str) -> Result<String, io::Error> {
let mut f = try!(File::open(path));
let mut s = String::new();
try!(f.read_to_string(&mut s));
Ok(s)
}
fn print_resource(res: &Resource) {
println!("{:?}", res);
}
fn print_json_resource(res: &Resource) {
println!("{}", serialize_json(&res));
}
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} FILE [options]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optflag("s", "silence", "disable output");
opts.optflag("r", "raw", "print raw result");
opts.optflag("h", "help", "print this help menu");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!(f.to_string()),
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
let input = if !matches.free.is_empty() {
matches.free[0].clone()
} else {
print_usage(&program, opts);
return;
};
let source = read_file(&input).expect("Read file failed");
let res: Result<Resource, CliError> = if input.contains(".json") {
serde_json::from_str(&source).map_err(|err| CliError::Deserialize(err))
} else {
parse(&source)
.map(|res| Resource::from(res))
.map_err(|(_, err)| CliError::Parse(err))
};
if matches.opt_present("s") {
return;
};
match res {
Ok(res) => {
if matches.opt_present("r") {
print_resource(&res);
} else {
print_json_resource(&res);
}
}
Err(err) => println!("Error: {:?}", err),
};
}
|
// 1.1 Is Unique
pub fn is_unique(string: &str) -> bool {
// Expects ascii characters. O(n) time, O(1) extra space
// This solution keeps a table that keeps track of the number of times
// a character has been seen. If it finds a character that has been seen
// before, it returns false.
let mut bitset: [u8; 256] = [0; 256];
for character in string.bytes() {
let index: usize = character as usize;
if bitset[index] == 0 {
bitset[index] = 1;
} else {
return false;
}
}
true
}
pub fn is_unique_no_extra_space(string: &str) -> bool {
// Expects ascii characters. O(n^2), 0 extra space
// For each character, scan the string until here to check for duplicates.
for index in 1..string.len() {
let slice = &string.as_bytes()[0..index - 1];
if slice.contains(&string.as_bytes()[index]) {
return false;
}
}
true
}
#[test]
fn test() {
for f in &[is_unique, is_unique_no_extra_space] {
assert!(f(&String::from("abcd")));
assert!(f(&String::from("")));
assert!(f(&String::from("a")));
assert!(!f(&String::from("abba")));
}
println!("Ex 1.1 ok!");
}
|
use core::ptr::NonNull;
use std::collections::HashMap;
use std::path::PathBuf;
#[derive(Debug, Clone, PartialEq)]
pub struct Annot<T> {
pub kind: T,
pub loc: Loc,
}
impl<T> Annot<T> {
pub fn new(kind: T, loc: Loc) -> Self {
Annot { kind, loc }
}
pub fn loc(&self) -> Loc {
self.loc
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Loc(pub u32, pub u32);
impl Loc {
pub fn new(loc: Loc) -> Self {
loc
}
pub fn dec(&self) -> Self {
use std::cmp::*;
Loc(min(self.0, self.1 - 1), self.1 - 1)
}
pub fn merge(&self, loc: Loc) -> Self {
use std::cmp::*;
Loc(min(self.0, loc.0), max(self.1, loc.1))
}
}
//------------------------------------------------------------
#[derive(Debug)]
pub struct Ref<T>(NonNull<T>);
impl<T> Ref<T> {
pub fn new(info: T) -> Self {
let boxed = Box::into_raw(Box::new(info));
Ref(unsafe { NonNull::new_unchecked(boxed) })
}
pub fn from_ref(info: &T) -> Self {
Ref(unsafe { NonNull::new_unchecked(info as *const T as *mut T) })
}
pub fn inner(&self) -> &T {
unsafe { &*self.0.as_ptr() }
}
pub fn inner_mut(&self) -> &mut T {
unsafe { &mut *self.0.as_ptr() }
}
pub fn id(&self) -> u64 {
self.0.as_ptr() as u64
}
}
impl<T: Clone> Ref<T> {
/// Allocates a copy of `self<T>` on the heap, returning `Ref`.
pub fn dup(&self) -> Self {
Self::new(self.inner().clone())
}
}
unsafe impl<T> Send for Ref<T> {}
impl<T> Copy for Ref<T> {}
impl<T> Clone for Ref<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> PartialEq for Ref<T> {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<T> Eq for Ref<T> {}
impl<T> std::hash::Hash for Ref<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl<T> std::ops::Deref for Ref<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &*self.0.as_ptr() }
}
}
impl<T> std::ops::DerefMut for Ref<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *self.0.as_ptr() }
}
}
//------------------------------------------------------------
pub type SourceInfoRef = Ref<SourceInfo>;
#[derive(Debug, Clone, PartialEq)]
pub struct SourceInfo {
pub path: PathBuf,
pub code: Vec<char>,
}
impl SourceInfoRef {
pub fn empty() -> Self {
SourceInfoRef::new(SourceInfo::new(PathBuf::default()))
}
}
impl SourceInfo {
pub fn new(path: PathBuf) -> Self {
SourceInfo {
path: path,
code: vec![],
}
}
pub fn show_file_name(&self) {
eprintln!("{}", self.path.to_string_lossy());
}
/// Show the location of the Loc in the source code using '^^^'.
pub fn show_loc(&self, loc: &Loc) {
let mut line: u32 = 1;
let mut line_top_pos: u32 = 0;
let mut line_pos = vec![];
for (pos, ch) in self.code.iter().enumerate() {
if *ch == '\n' {
line_pos.push((line, line_top_pos, pos as u32));
line += 1;
line_top_pos = pos as u32 + 1;
}
}
if line_top_pos as usize <= self.code.len() - 1 {
line_pos.push((line, line_top_pos, self.code.len() as u32 - 1));
}
let mut found = false;
for line in &line_pos {
if line.2 < loc.0 || line.1 > loc.1 {
continue;
}
if !found {
eprintln!("{}:{}", self.path.to_string_lossy(), line.0);
};
found = true;
let start = line.1 as usize;
let mut end = line.2 as usize;
if self.code[end] == '\n' {
end -= 1
}
eprintln!("{}", self.code[start..=end].iter().collect::<String>());
use std::cmp::*;
let read = if loc.0 <= line.1 {
0
} else {
self.code[(line.1 as usize)..(loc.0 as usize)]
.iter()
.map(|x| calc_width(x))
.sum()
};
let length: usize = self.code[max(loc.0, line.1) as usize..min(loc.1, line.2) as usize]
.iter()
.map(|x| calc_width(x))
.sum();
eprintln!("{}{}", " ".repeat(read), "^".repeat(length + 1));
}
if !found {
let line = match line_pos.last() {
Some(line) => (line.0 + 1, line.2 + 1, loc.1),
None => (1, 0, loc.1),
};
let read = self.code[(line.1 as usize)..(loc.0 as usize)]
.iter()
.map(|x| calc_width(x))
.sum();
let length: usize = self.code[loc.0 as usize..loc.1 as usize]
.iter()
.map(|x| calc_width(x))
.sum();
let is_cr = loc.1 as usize >= self.code.len() || self.code[loc.1 as usize] == '\n';
eprintln!("{}:{}", self.path.to_string_lossy(), line.0);
eprintln!(
"{}",
if !is_cr {
self.code[(line.1 as usize)..=(loc.1 as usize)]
.iter()
.collect::<String>()
} else {
self.code[(line.1 as usize)..(loc.1 as usize)]
.iter()
.collect::<String>()
}
);
eprintln!("{}{}", " ".repeat(read), "^".repeat(length + 1));
}
fn calc_width(ch: &char) -> usize {
if ch.is_ascii() {
1
} else {
2
}
}
}
}
//------------------------------------------------------------
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IdentId(std::num::NonZeroU32);
impl std::hash::Hash for IdentId {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl Into<usize> for IdentId {
fn into(self) -> usize {
self.0.get() as usize
}
}
impl Into<u32> for IdentId {
fn into(self) -> u32 {
self.0.get()
}
}
impl From<u32> for IdentId {
fn from(id: u32) -> Self {
let id = unsafe { std::num::NonZeroU32::new_unchecked(id) };
IdentId(id)
}
}
pub struct OptionalId(Option<IdentId>);
impl OptionalId {
pub fn new(id: impl Into<Option<IdentId>>) -> Self {
OptionalId(id.into())
}
}
impl std::ops::Deref for OptionalId {
type Target = Option<IdentId>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
macro_rules! id {
($constant:expr) => {
IdentId(unsafe { std::num::NonZeroU32::new_unchecked($constant) })
};
}
impl IdentId {
pub const INITIALIZE: IdentId = id!(1);
pub const OBJECT: IdentId = id!(2);
pub const NEW: IdentId = id!(3);
pub const NAME: IdentId = id!(4);
pub const _ADD: IdentId = id!(5);
pub const _SUB: IdentId = id!(6);
pub const _MUL: IdentId = id!(7);
pub const _POW: IdentId = id!(8);
pub const _SHL: IdentId = id!(9);
pub const _REM: IdentId = id!(10);
pub const _EQ: IdentId = id!(11);
pub const _NEQ: IdentId = id!(12);
pub const _GT: IdentId = id!(13);
pub const _GE: IdentId = id!(14);
}
#[derive(Debug, Clone, PartialEq)]
pub struct IdentifierTable {
table: HashMap<String, u32>,
table_rev: HashMap<u32, String>,
ident_id: u32,
}
impl IdentifierTable {
pub fn new() -> Self {
let mut table = IdentifierTable {
table: HashMap::new(),
table_rev: HashMap::new(),
ident_id: 20,
};
table.set_ident_id("<null>", IdentId::from(0));
table.set_ident_id("initialize", IdentId::INITIALIZE);
table.set_ident_id("Object", IdentId::OBJECT);
table.set_ident_id("new", IdentId::NEW);
table.set_ident_id("name", IdentId::NAME);
table.set_ident_id("+", IdentId::_ADD);
table.set_ident_id("-", IdentId::_SUB);
table.set_ident_id("*", IdentId::_MUL);
table.set_ident_id("**", IdentId::_POW);
table.set_ident_id("<<", IdentId::_SHL);
table.set_ident_id("%", IdentId::_REM);
table.set_ident_id("==", IdentId::_EQ);
table.set_ident_id("!=", IdentId::_NEQ);
table.set_ident_id(">", IdentId::_GT);
table.set_ident_id(">=", IdentId::_GE);
table
}
fn set_ident_id(&mut self, name: impl Into<String>, id: IdentId) {
let name = name.into();
self.table.insert(name.clone(), id.into());
self.table_rev.insert(id.into(), name);
}
pub fn get_ident_id(&mut self, name: impl Into<String>) -> IdentId {
let name = name.into();
match self.table.get(&name) {
Some(id) => IdentId::from(*id),
None => {
let id = self.ident_id;
self.table.insert(name.clone(), id);
self.table_rev.insert(id, name.clone());
self.ident_id += 1;
IdentId::from(id)
}
}
}
pub fn get_name(&self, id: IdentId) -> &str {
self.table_rev.get(&id.0.get()).unwrap()
}
pub fn add_postfix(&mut self, id: IdentId, postfix: &str) -> IdentId {
let new_name = self.get_name(id).to_string() + postfix;
self.get_ident_id(new_name)
}
}
|
#![allow(clippy::must_use_candidate)]
use silkenweb::{
elements::{button, div, Button, DivBuilder},
signal::{ReadSignal, Signal, WriteSignal},
Builder,
};
// ANCHOR: define_counter
pub fn define_counter(count: &Signal<i64>) -> DivBuilder {
let count_text: ReadSignal<String> = count.read().map(|i| format!("{}", i));
div()
.child(define_button("-", -1, count.write()))
.text(count_text)
.child(define_button("+", 1, count.write()))
}
// ANCHOR_END: define_counter
// ANCHOR: define_button
pub fn define_button(label: &str, delta: i64, set_count: WriteSignal<i64>) -> Button {
button()
.on_click(move |_, _| set_count.replace(move |&i| i + delta))
.text(label)
.build()
}
// ANCHOR_END: define_button
|
struct Solution;
/// https://leetcode.com/problems/number-of-islands/
impl Solution {
/// 4 ms 5.4 MB
pub fn num_islands(grid: Vec<Vec<char>>) -> i32 {
if grid.len() == 0 || grid[0].len() == 0 {
return 0;
}
let mut visited = vec![vec![false; grid[0].len()]; grid.len()];
let mut count = 0;
for (i, row) in grid.iter().enumerate() {
for (j, &char) in row.iter().enumerate() {
if visited[i][j] {
continue;
}
if char == '0' {
visited[i][j] = true;
continue;
}
count += 1;
Solution::walk(i, j, &grid, &mut visited);
}
}
count
}
fn walk(i: usize, j: usize, grid: &Vec<Vec<char>>, visited: &mut Vec<Vec<bool>>) {
if grid.len() <= i || grid[0].len() <= j || visited[i][j] {
return;
}
visited[i][j] = true;
if grid[i][j] == '0' {
return;
}
if i != 0 {
Solution::walk(i - 1, j, grid, visited);
}
Solution::walk(i + 1, j, grid, visited);
if j != 0 {
Solution::walk(i, j - 1, grid, visited);
}
Solution::walk(i, j + 1, grid, visited);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
fn assert(g: Vec<Vec<char>>, expected: i32) {
assert_eq!(Solution::num_islands(g), expected);
}
assert(
vec![
vec!['1', '1', '1', '1', '0'],
vec!['1', '1', '0', '1', '0'],
vec!['1', '1', '0', '0', '0'],
vec!['0', '0', '0', '0', '0'],
],
1,
);
assert(
vec![
vec!['1', '1', '0', '0', '0'],
vec!['1', '1', '0', '0', '0'],
vec!['0', '0', '1', '0', '0'],
vec!['0', '0', '0', '1', '1'],
],
3,
);
}
}
|
use super::token::{FilePos, Op, Position, Span};
use std::string::ToString;
pub type Ptr<T> = Box<T>;
pub trait TreeRender {
fn render(&self, idx: u32);
}
pub trait AstNode {
fn pos(&self) -> &Position;
}
fn indent(idt: u32) -> String {
let mut value = String::new();
for _ in 0..idt {
value.push('\t');
}
value
}
#[derive(Debug, Clone)]
pub enum Mutability {
Mutable,
Immutable,
}
impl ToString for Mutability {
fn to_string(&self) -> String {
match self {
Mutability::Mutable => "mutable",
Mutability::Immutable => "immutable",
}
.to_string()
}
}
#[derive(Debug, Clone, Copy)]
pub enum Visibility {
Public,
Private,
Module,
}
impl ToString for Visibility {
fn to_string(&self) -> String {
match self {
Visibility::Public => "public",
Visibility::Private => "private",
Visibility::Module => "module",
}
.to_string()
}
}
#[derive(Debug, Clone)]
pub struct Ident {
val: String,
pos: Position,
}
impl Ident {
pub fn new(val: &str, pos: Position) -> Self {
Self {
val: val.to_string(),
pos,
}
}
#[inline]
pub fn value(&self) -> &str {
self.val.as_str()
}
#[inline]
pub fn value_string(&self) -> &String {
&self.val
}
#[inline]
pub fn pos(&self) -> &Position {
&self.pos
}
}
impl TreeRender for Ident {
fn render(&self, idx: u32) {
println!(
"{}Ident: {} {}",
indent(idx),
self.val.as_str(),
self.pos.span
);
}
}
impl PartialEq for Ident {
fn eq(&self, other: &Self) -> bool {
self.val == other.val
}
}
#[derive(Debug, Clone)]
pub enum ExprKind {
Name(Ident),
NameTyped(Ident, Vec<Ptr<Expr>>),
IntegerLiteral(u64),
FloatLiteral(f64),
StringLiteral(String),
CharLiteral(char),
Unary(Op, Ptr<Expr>),
Binary(Op, Ptr<Expr>, Ptr<Expr>),
FunctionCall(Ptr<Expr>, Vec<Ptr<Expr>>),
/// the first element of .1 is the receiver
MethodCall(Ptr<Expr>, Vec<Ptr<Expr>>),
Field(Ptr<Expr>, Ident),
Block(Vec<Ptr<Stmt>>),
If(Ptr<Expr>, Ptr<Expr>),
While(Ptr<Expr>, Ptr<Expr>),
For(Ptr<Pattern>, Ptr<Expr>, Ptr<Expr>),
Loop(Ptr<Expr>),
// ListGenerator(),
}
#[derive(Debug, Clone)]
pub struct Expr {
pub kind: ExprKind,
position: Position,
}
impl Expr {
pub fn new(kind: ExprKind, position: Position) -> Self {
Self { kind, position }
}
pub fn kind(&self) -> &ExprKind {
&self.kind
}
}
impl AstNode for Expr {
fn pos(&self) -> &Position {
&self.position
}
}
impl TreeRender for Expr {
fn render(&self, idx: u32) {
match &self.kind {
ExprKind::Name(name) => {
println!("{}Name: {} {}", indent(idx), name.value(), self.pos().span);
}
ExprKind::NameTyped(name, types) => {
println!(
"{}Typed Name: {} {}",
indent(idx),
name.value(),
self.pos().span
);
for ty in types {
ty.render(idx + 1);
}
}
ExprKind::IntegerLiteral(value) => {
println!("{}Integer: {} {}", indent(idx), value, self.pos().span);
}
ExprKind::FloatLiteral(value) => {
println!("{}Float: {} {}", indent(idx), value, self.pos().span);
}
ExprKind::StringLiteral(ref value) => {
println!("{}String: {} {}", indent(idx), value, self.pos().span);
}
ExprKind::CharLiteral(ch) => {
println!("{}Char: {} {}", indent(idx), ch, self.pos().span);
}
ExprKind::Unary(ref op, ref expr) => {
println!(
"{}Unary: {} {}",
indent(idx),
op.to_string(),
self.pos().span
);
expr.render(idx + 1);
}
ExprKind::Binary(ref op, ref lhs, ref rhs) => {
println!(
"{}Binary: {} {}",
indent(idx),
op.to_string(),
self.pos().span
);
lhs.render(idx + 1);
rhs.render(idx + 1);
}
ExprKind::FunctionCall(ref operand, ref actuals) => {
println!("{}Fn Call {}:", indent(idx), self.pos().span);
operand.render(idx + 1);
println!("{}Actuals:", indent(idx + 1));
for actual in actuals {
actual.render(idx + 1);
}
}
ExprKind::MethodCall(ref operand, ref actuals) => {
println!("{}Method Call {}:", indent(idx), self.pos().span);
operand.render(idx + 1);
println!("{}Actuals:", indent(idx + 1));
for actual in actuals {
actual.render(idx + 1);
}
}
ExprKind::Field(operand, field) => {
println!("{}Field {}:", indent(idx), self.pos().span);
operand.render(idx + 1);
field.render(idx + 1);
}
ExprKind::Block(stmts) => {
println!("{}Block {}:", indent(idx), self.pos().span);
for stmt in stmts {
stmt.render(idx + 1);
}
}
ExprKind::If(cond, body) => {
println!("{}If {}:", indent(idx), self.pos().span);
cond.render(idx + 1);
body.render(idx + 1);
}
ExprKind::While(cond, body) => {
println!("{}While {}:", indent(idx), self.pos().span);
cond.render(idx + 1);
body.render(idx + 1);
}
ExprKind::For(pattern, expr, body) => {
println!("{}For {}:", indent(idx), self.pos().span);
pattern.render(idx + 1);
expr.render(idx + 1);
body.render(idx + 1);
}
ExprKind::Loop(body) => {
println!("{}Loop {}:", indent(idx), self.pos().span);
body.render(idx + 1);
}
}
}
}
#[derive(Debug, Clone)]
pub enum StmtKind {
ItemStmt(Ptr<Item>),
ExprStmt(Ptr<Expr>),
SemiStmt(Ptr<Expr>),
}
#[derive(Debug, Clone)]
pub struct Stmt {
pub kind: StmtKind,
position: Position,
}
impl Stmt {
pub fn new(kind: StmtKind, position: Position) -> Self {
Self { kind, position }
}
pub fn kind(&self) -> &StmtKind {
&self.kind
}
}
impl AstNode for Stmt {
fn pos(&self) -> &Position {
&self.position
}
}
impl TreeRender for Stmt {
fn render(&self, idx: u32) {
match &self.kind {
StmtKind::ItemStmt(item) => {
println!("{}Item Stmt:", indent(idx));
item.render(idx + 1);
}
StmtKind::ExprStmt(expr) => {
println!("{}Expr Stmt:", indent(idx));
expr.render(idx + 1);
}
StmtKind::SemiStmt(expr) => {
println!("{}Semi Stmt:", indent(idx));
expr.render(idx + 1);
}
}
}
}
#[derive(Debug, Clone)]
pub enum PatternKind {
Identifier(Ident),
Tuple(Vec<Ptr<Pattern>>),
// Ident here should be changed to a Path of some sort
Variant(Ident, Vec<Ptr<Pattern>>),
// Struct(Ident, Vec<>)
Ignore,
}
#[derive(Debug, Clone)]
pub struct Pattern {
kind: PatternKind,
position: Position,
}
impl Pattern {
pub fn new(kind: PatternKind, position: Position) -> Self {
Self { kind, position }
}
pub fn kind(&self) -> &PatternKind {
&self.kind
}
pub fn collect_names<'a>(&'a self) -> Vec<&'a String> {
let mut res = Vec::<&'a _>::new();
match self.kind() {
PatternKind::Identifier(ident) => {
res.push(&ident.val);
}
PatternKind::Tuple(patterns) => {
for pattern in patterns {
res.extend(pattern.collect_names());
}
}
PatternKind::Variant(_, patterns) => {
for pattern in patterns {
res.extend(pattern.collect_names());
}
}
PatternKind::Ignore => {},
}
res
}
}
impl AstNode for Pattern {
fn pos(&self) -> &Position {
&self.position
}
}
impl TreeRender for Pattern {
fn render(&self, idx: u32) {
match &self.kind {
PatternKind::Identifier(ident) => {
println!("{}Ident Pattern: {}", indent(idx), ident.value());
}
PatternKind::Tuple(patterns) => {
println!("{}Tuple Pattern:", indent(idx));
for pattern in patterns {
pattern.render(idx + 1);
}
}
PatternKind::Variant(name, patterns) => {
println!("{}Variant Pattern: {}", indent(idx), name.value());
for pattern in patterns {
pattern.render(idx + 1);
}
}
PatternKind::Ignore => {
println!("{}Ignore Pattern:", indent(idx));
}
}
}
}
#[derive(Debug, Clone)]
pub enum TypeParamKind {
// When the type parameter doesn't have any
Named(Ident),
BoundedNamed(Ident, Vec<Ptr<TypeSpec>>),
}
#[derive(Debug, Clone)]
pub struct TypeParam {
kind: TypeParamKind,
position: Position,
}
impl TypeParam {
pub fn new(kind: TypeParamKind, position: Position) -> Self {
Self { kind, position }
}
pub fn kind(&self) -> &TypeParamKind {
&self.kind
}
pub fn name(&self) -> &str {
self.name_string().as_str()
}
pub fn name_string(&self) -> &String {
use TypeParamKind::*;
match self.kind() {
Named(n) |
BoundedNamed(n, ..) => &n.val
}
}
}
impl AstNode for TypeParam {
fn pos(&self) -> &Position {
&self.position
}
}
impl TreeRender for TypeParam {
fn render(&self, idx: u32) {
match self.kind() {
TypeParamKind::Named(name) => {
println!("{}Named: {}", indent(idx), name.value());
}
TypeParamKind::BoundedNamed(name, bounds) => {
println!("{}Bounded Named: {}", indent(idx), name.value());
for bound in bounds {
bound.render(idx + 1);
}
}
}
}
}
#[derive(Debug, Clone)]
pub struct TypeParams {
types: Vec<Ptr<Item>>,
position: Position,
}
impl TypeParams {
pub fn new(types: Vec<Ptr<Item>>, position: Position) -> Self {
Self { types, position }
}
}
impl AstNode for TypeParams {
fn pos(&self) -> &Position {
&self.position
}
}
impl TreeRender for TypeParams {
fn render(&self, idx: u32) {
println!("{}Type Parameters: {}", indent(idx), self.pos().span);
for ty in &self.types {
ty.render(idx + 1);
}
}
}
#[derive(Debug, Clone)]
pub enum VariableKind {
Init(Ptr<Expr>),
Typed(Ptr<TypeSpec>),
Full(Ptr<TypeSpec>, Ptr<Expr>),
}
impl TreeRender for VariableKind {
fn render(&self, idx: u32) {
use VariableKind::*;
match &self {
Init(init) => {
println!("{}Init:", indent(idx));
init.render(idx + 1);
}
Typed(types) => {
println!("{}Typed:", indent(idx));
types.render(idx + 1);
}
Full(types, init) => {
println!("{}Full:", indent(idx));
types.render(idx + 1);
init.render(idx + 1);
}
}
}
}
#[derive(Debug, Clone)]
pub struct Local {
pub mutability: Mutability,
pub local: Ptr<Pattern>,
pub kind: VariableKind,
pub position: Position
}
impl AstNode for Local {
fn pos(&self) -> &Position {
&self.position
}
}
impl TreeRender for Local {
fn render(&self, idx: u32) {
println!("{}Field:", indent(idx));
println!("{}Mut: {}", indent(idx + 1), self.mutability.to_string());
self.local.render(idx + 1);
self.kind.render(idx + 1);
}
}
#[derive(Debug, Clone)]
pub struct Field {
vis: Visibility,
name: Ident,
pub kind: VariableKind,
position: Position,
}
impl Field {
pub fn new(vis: Visibility, name: Ident, kind: VariableKind, position: Position) -> Self {
Self {
vis,
name,
kind,
position,
}
}
pub fn vis(&self) -> Visibility {
self.vis
}
pub fn kind(&self) -> &VariableKind {
&self.kind
}
pub fn name(&self) -> &Ident {
&self.name
}
pub fn name_string(&self) -> &String {
&self.name.val
}
}
impl AstNode for Field {
fn pos(&self) -> &Position {
&self.position
}
}
impl TreeRender for Field {
fn render(&self, idx: u32) {
println!("{}Field:", indent(idx));
println!("{}Vis: {}", indent(idx + 1), self.vis.to_string());
self.name.render(idx + 1);
self.kind.render(idx + 1);
}
}
#[derive(Debug, Clone)]
pub struct Param {
mutability: Mutability,
name: Ident,
pub kind: VariableKind,
position: Position,
}
impl Param {
pub fn new(mutability: Mutability, name: Ident, kind: VariableKind, position: Position) -> Self {
Self {
mutability,
name,
kind,
position,
}
}
pub fn kind(&self) -> &VariableKind {
&self.kind
}
pub fn name(&self) -> &str {
self.name_string().as_str()
}
pub fn name_string(&self) -> &String {
&self.name.val
}
}
impl AstNode for Param {
fn pos(&self) -> &Position {
&self.position
}
}
impl TreeRender for Param {
fn render(&self, idx: u32) {
println!("{}Param:", indent(idx));
println!("{}Mut: {}", indent(idx + 1), self.mutability.to_string());
self.name.render(idx + 1);
self.kind.render(idx + 1);
}
}
#[derive(Debug, Clone)]
pub struct Function {
pub name: Ident,
pub type_params: Option<TypeParams>,
pub params: Vec<Ptr<Item>>,
pub ret: Ptr<TypeSpec>,
pub body: Ptr<Expr>,
}
impl TreeRender for Function {
fn render(&self, idx: u32) {
let mut pos = self.name.pos().clone();
pos.span.extend_node(self.body.as_ref());
println!("{}Function: {} {}",
indent(idx),
self.name.value(),
pos.span
);
// println!("{}Vis: {}", indent(idx + 1));
self.name.render(idx + 1);
self.type_params.as_ref().map(|param| param.render(idx + 1));
println!("{}Params:", indent(idx + 1));
for param in &self.params {
param.render(idx + 1);
}
println!("{}Return:", indent(idx + 1));
self.ret.render(idx + 1);
println!("{}Body:", indent(idx + 1));
self.body.render(idx + 1);
}
}
#[derive(Debug, Clone)]
pub struct Structure {
pub name: Ident,
pub type_params: Option<TypeParams>,
pub fields: Vec<Ptr<Item>>
}
impl TreeRender for Structure {
fn render(&self, idx: u32) {
let pos = self.name.pos().clone();
println!(
"{}Structure: {} {}",
indent(idx),
self.name.value(),
pos.span
);
self.name.render(idx + 1);
self.type_params.as_ref().map(|param| param.render(idx + 1));
println!("{}Fields:", indent(idx + 1));
for field in &self.fields {
field.render(idx + 1);
}
}
}
#[derive(Debug, Clone)]
pub enum ItemKind {
Funct(Function),
Struct(Structure),
Trait(),
LocalVar(Local),
StructField(Field),
FunctionParam(Param),
TypeParam(TypeParam),
// for items defined by the compiler and are not located in a file.
Internal,
// for primative types defined by the compiler
Primative,
// for items that should not be copied yet. This is really a hack because I do not know how to handle this.
Invalid,
}
#[derive(Debug, Clone)]
pub struct Item {
vis: Visibility,
pub kind: ItemKind,
position: Position,
}
impl Item {
pub fn internal_ptr() -> Ptr<Item> {
Ptr::new(Item::new(
Visibility::Public,
ItemKind::Internal,
Position::zero(),
))
}
pub fn invalid_ptr() -> Ptr<Item> {
Ptr::new(Item::new(
Visibility::Private,
ItemKind::Invalid,
Position::zero()
))
}
pub fn primative_ptr() -> Ptr<Item> {
Ptr::new(Item::new(
Visibility::Public,
ItemKind::Primative,
Position::zero(),
))
}
pub fn new(vis: Visibility, kind: ItemKind, position: Position) -> Self {
Self {
vis,
kind,
position,
}
}
pub fn kind(&self) -> &ItemKind {
&self.kind
}
pub fn is_import(&self) -> bool {
use ItemKind::*;
match self.kind() {
_ => false,
}
}
pub fn is_variable(&self) -> bool {
use ItemKind::*;
match self.kind() {
LocalVar(_) => true,
_ => false,
}
}
pub fn is_struct(&self) -> bool {
use ItemKind::*;
match self.kind() {
Struct(..) => true,
_ => false,
}
}
pub fn is_function(&self) -> bool {
use ItemKind::*;
match self.kind() {
Funct(..) => true,
_ => false,
}
}
pub fn is_primative(&self) -> bool {
use ItemKind::*;
match self.kind() {
Primative => true,
_ => false,
}
}
pub fn name(&self) -> &String {
use ItemKind::*;
static INVALID_STRING: String = String::new();
match self.kind() {
Funct(f) => &f.name.val,
Struct(s) => &s.name.val,
StructField(field) => field.name_string(),
FunctionParam(param) => param.name_string(),
TypeParam(type_param) => type_param.name_string(),
_ => &INVALID_STRING,
}
}
}
impl AstNode for Item {
fn pos(&self) -> &Position {
&self.position
}
}
impl TreeRender for Item {
fn render(&self, idx: u32) {
match &self.kind {
ItemKind::Funct(f) => {
f.render(idx);
}
ItemKind::Struct(s) => {
s.render(idx);
}
ItemKind::LocalVar(local) => {
local.render(idx);
},
ItemKind::StructField(field) => {
field.render(idx);
},
ItemKind::FunctionParam(param) => {
param.render(idx);
},
ItemKind::TypeParam(type_param) => {
type_param.render(idx);
},
_ => {}
}
}
}
#[derive(Debug, Clone)]
pub enum TypeSpecKind {
ExprType(Ptr<Expr>),
MutType(Ptr<TypeSpec>),
TupleType(Vec<Ptr<TypeSpec>>),
PtrType(Ptr<TypeSpec>),
UnitType,
}
#[derive(Debug, Clone)]
pub struct TypeSpec {
pub kind: TypeSpecKind,
position: Position,
}
impl TypeSpec {
pub fn new(kind: TypeSpecKind, position: Position) -> Self {
Self { kind, position }
}
pub fn kind(&self) -> &TypeSpecKind {
&self.kind
}
pub fn new_unit_type(pos: &Position) -> Self {
Self {
kind: TypeSpecKind::UnitType,
position: pos.clone(),
}
}
}
impl AstNode for TypeSpec {
fn pos(&self) -> &Position {
&self.position
}
}
impl TreeRender for TypeSpec {
fn render(&self, idx: u32) {
match self.kind() {
TypeSpecKind::ExprType(ty) => {
println!("{}Expression Type:", indent(idx));
ty.render(idx + 1);
}
// TypeSpecKind::MutType(ty) => {
// println!("{}Mutable Type:", indent(idx));
// ty.render(idx + 1);
// }
TypeSpecKind::TupleType(types) => {
println!("{}Tuple Type:", indent(idx));
for ty in types {
ty.render(idx + 1);
}
}
TypeSpecKind::PtrType(ty) => {
println!("{}Ptr Type:", indent(idx));
ty.render(idx + 1);
}
_ => {}
}
}
}
pub struct ParsedFile {
path: std::path::PathBuf,
imports: Vec<Ptr<Item>>,
items: Vec<Ptr<Item>>,
}
impl ParsedFile {
pub fn new(path: &std::path::PathBuf) -> Self {
Self {
path: path.clone(),
imports: Vec::new(),
items: Vec::new(),
}
}
pub fn add_import(&mut self, item: Ptr<Item>) {
self.imports.push(item)
}
pub fn add_item(&mut self, item: Ptr<Item>) {
self.items.push(item)
}
pub fn items(&self) -> &[Ptr<Item>] {
self.items.as_slice()
}
pub fn items_mut(&mut self) -> &mut [Ptr<Item>] {
self.items.as_mut_slice()
}
}
impl TreeRender for ParsedFile {
fn render(&self, idx: u32) {
println!("{}Imports:", indent(idx));
for imp in &self.imports {
imp.render(idx + 1);
}
println!("{}Items:", indent(idx));
for item in &self.items {
item.render(idx + 1);
}
}
}
|
// grouped values of different types
// max 12 elements
pub fn run() {
let person: (&str, &str, i8) = ("First", "Second", 25);
println!("{} {} {}", person.1, person.2, person.0);
} |
fn main() {
let t = (12, "eggs");
println!("{:?} stored in the stack", t);
let b = Box::new(t); // allocate a tuple in the heap
println!("{:?} stored in the heap", b);
}
|
//! Destination implementation for Arrow and Polars.
mod arrow_assoc;
mod errors;
mod funcs;
pub mod typesystem;
pub use self::errors::{ArrowDestinationError, Result};
pub use self::typesystem::ArrowTypeSystem;
use super::{Consume, Destination, DestinationPartition};
use crate::constants::RECORD_BATCH_SIZE;
use crate::data_order::DataOrder;
use crate::typesystem::{Realize, TypeAssoc, TypeSystem};
use anyhow::anyhow;
use arrow::{datatypes::Schema, record_batch::RecordBatch};
use arrow_assoc::ArrowAssoc;
use fehler::{throw, throws};
use funcs::{FFinishBuilder, FNewBuilder, FNewField};
use itertools::Itertools;
use std::{
any::Any,
sync::{Arc, Mutex},
};
type Builder = Box<dyn Any + Send>;
type Builders = Vec<Builder>;
pub struct ArrowDestination {
schema: Vec<ArrowTypeSystem>,
names: Vec<String>,
data: Arc<Mutex<Vec<RecordBatch>>>,
arrow_schema: Arc<Schema>,
batch_size: usize,
}
impl Default for ArrowDestination {
fn default() -> Self {
ArrowDestination {
schema: vec![],
names: vec![],
data: Arc::new(Mutex::new(vec![])),
arrow_schema: Arc::new(Schema::empty()),
batch_size: RECORD_BATCH_SIZE,
}
}
}
impl ArrowDestination {
pub fn new() -> Self {
Self::default()
}
pub fn new_with_batch_size(batch_size: usize) -> Self {
ArrowDestination {
schema: vec![],
names: vec![],
data: Arc::new(Mutex::new(vec![])),
arrow_schema: Arc::new(Schema::empty()),
batch_size,
}
}
}
impl Destination for ArrowDestination {
const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::ColumnMajor, DataOrder::RowMajor];
type TypeSystem = ArrowTypeSystem;
type Partition<'a> = ArrowPartitionWriter;
type Error = ArrowDestinationError;
fn needs_count(&self) -> bool {
false
}
#[throws(ArrowDestinationError)]
fn allocate<S: AsRef<str>>(
&mut self,
_nrow: usize,
names: &[S],
schema: &[ArrowTypeSystem],
data_order: DataOrder,
) {
// todo: support colmajor
if !matches!(data_order, DataOrder::RowMajor) {
throw!(crate::errors::ConnectorXError::UnsupportedDataOrder(
data_order
))
}
// parse the metadata
self.schema = schema.to_vec();
self.names = names.iter().map(|n| n.as_ref().to_string()).collect();
let fields = self
.schema
.iter()
.zip_eq(&self.names)
.map(|(&dt, h)| Ok(Realize::<FNewField>::realize(dt)?(h.as_str())))
.collect::<Result<Vec<_>>>()?;
self.arrow_schema = Arc::new(Schema::new(fields));
}
#[throws(ArrowDestinationError)]
fn partition(&mut self, counts: usize) -> Vec<Self::Partition<'_>> {
let mut partitions = vec![];
for _ in 0..counts {
partitions.push(ArrowPartitionWriter::new(
self.schema.clone(),
Arc::clone(&self.data),
Arc::clone(&self.arrow_schema),
self.batch_size,
)?);
}
partitions
}
fn schema(&self) -> &[ArrowTypeSystem] {
self.schema.as_slice()
}
}
impl ArrowDestination {
#[throws(ArrowDestinationError)]
pub fn arrow(self) -> Vec<RecordBatch> {
let lock = Arc::try_unwrap(self.data).map_err(|_| anyhow!("Partitions are not freed"))?;
lock.into_inner()
.map_err(|e| anyhow!("mutex poisoned {}", e))?
}
#[throws(ArrowDestinationError)]
pub fn record_batch(&mut self) -> Option<RecordBatch> {
let mut guard = self
.data
.lock()
.map_err(|e| anyhow!("mutex poisoned {}", e))?;
(*guard).pop()
}
pub fn empty_batch(&self) -> RecordBatch {
RecordBatch::new_empty(self.arrow_schema.clone())
}
pub fn arrow_schema(&self) -> Arc<Schema> {
self.arrow_schema.clone()
}
pub fn names(&self) -> &[String] {
self.names.as_slice()
}
}
pub struct ArrowPartitionWriter {
schema: Vec<ArrowTypeSystem>,
builders: Option<Builders>,
current_row: usize,
current_col: usize,
data: Arc<Mutex<Vec<RecordBatch>>>,
arrow_schema: Arc<Schema>,
batch_size: usize,
}
// unsafe impl Sync for ArrowPartitionWriter {}
impl ArrowPartitionWriter {
#[throws(ArrowDestinationError)]
fn new(
schema: Vec<ArrowTypeSystem>,
data: Arc<Mutex<Vec<RecordBatch>>>,
arrow_schema: Arc<Schema>,
batch_size: usize,
) -> Self {
let mut pw = ArrowPartitionWriter {
schema,
builders: None,
current_row: 0,
current_col: 0,
data,
arrow_schema,
batch_size,
};
pw.allocate()?;
pw
}
#[throws(ArrowDestinationError)]
fn allocate(&mut self) {
let builders = self
.schema
.iter()
.map(|dt| Ok(Realize::<FNewBuilder>::realize(*dt)?(self.batch_size)))
.collect::<Result<Vec<_>>>()?;
self.builders.replace(builders);
}
#[throws(ArrowDestinationError)]
fn flush(&mut self) {
let builders = self
.builders
.take()
.unwrap_or_else(|| panic!("arrow builder is none when flush!"));
let columns = builders
.into_iter()
.zip(self.schema.iter())
.map(|(builder, &dt)| Realize::<FFinishBuilder>::realize(dt)?(builder))
.collect::<std::result::Result<Vec<_>, crate::errors::ConnectorXError>>()?;
let rb = RecordBatch::try_new(Arc::clone(&self.arrow_schema), columns)?;
{
let mut guard = self
.data
.lock()
.map_err(|e| anyhow!("mutex poisoned {}", e))?;
let inner_data = &mut *guard;
inner_data.push(rb);
}
self.current_row = 0;
self.current_col = 0;
}
}
impl<'a> DestinationPartition<'a> for ArrowPartitionWriter {
type TypeSystem = ArrowTypeSystem;
type Error = ArrowDestinationError;
#[throws(ArrowDestinationError)]
fn finalize(&mut self) {
if self.builders.is_some() {
self.flush()?;
}
}
#[throws(ArrowDestinationError)]
fn aquire_row(&mut self, _n: usize) -> usize {
self.current_row
}
fn ncols(&self) -> usize {
self.schema.len()
}
}
impl<'a, T> Consume<T> for ArrowPartitionWriter
where
T: TypeAssoc<<Self as DestinationPartition<'a>>::TypeSystem> + ArrowAssoc + 'static,
{
type Error = ArrowDestinationError;
#[throws(ArrowDestinationError)]
fn consume(&mut self, value: T) {
let col = self.current_col;
self.current_col = (self.current_col + 1) % self.ncols();
self.schema[col].check::<T>()?;
loop {
match &mut self.builders {
Some(builders) => {
<T as ArrowAssoc>::append(
builders[col]
.downcast_mut::<T::Builder>()
.ok_or_else(|| anyhow!("cannot cast arrow builder for append"))?,
value,
)?;
break;
}
None => self.allocate()?, // allocate if builders are not initialized
}
}
// flush if exceed batch_size
if self.current_col == 0 {
self.current_row += 1;
if self.current_row >= self.batch_size {
self.flush()?;
self.allocate()?;
}
}
}
}
|
use std::sync::mpsc;
use std::sync::mpsc::{Sender, Receiver};
pub struct Unziperator<I, T> {
inner: I,
children: Vec<Sender<Option<T>>>,
}
impl<I, T> Unziperator<I, T>
where I: Iterator<Item=[T; 4]> {
pub fn new(inner: I) -> Self {
Unziperator {
inner,
children: vec![],
}
}
pub fn subscribe(&mut self) -> NCIterChild<T> {
let (tx, rx) = mpsc::channel();
self.children.push(tx);
NCIterChild {
inner: rx
}
}
}
impl<'a, I, T> Iterator for Unziperator<I, T>
where I: Iterator<Item=[T; 4]>,
T: Clone {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if let Some(inner) = self.inner.next() {
self.children.iter()
.enumerate()
.for_each(|(i, child)| {
let _ = child.send(Some(inner[i + 1].clone()));
});
Some(inner[0].clone())
} else {
self.children.iter()
.for_each(|child| {
let _ = child.send(None);
});
None
}
}
}
pub struct NCIterChild<T> {
inner: Receiver<Option<T>>,
}
impl<T> Iterator for NCIterChild<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if let Ok(item) = self.inner.try_recv() {
item
} else {
None
}
}
}
pub struct Teeterator<I, T> {
inner: I,
children: Vec<Sender<Option<T>>>,
}
impl<I, T> Teeterator<I, T> {
pub fn new(inner: I) -> Self {
Teeterator {
inner,
children: vec![],
}
}
pub fn subscribe(&mut self) -> NCIterChild<T> {
let (tx, rx) = mpsc::channel();
self.children.push(tx);
NCIterChild {
inner: rx
}
}
}
impl<'a, I, T> Iterator for Teeterator<I, T>
where I: Iterator<Item=T>,
T: Copy {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if let Some(item) = self.inner.next() {
self.children.iter()
.for_each(|child| {
let _ = child.send(Some(item));
});
Some(item)
} else {
self.children.iter()
.for_each(|child| {
let _ = child.send(None);
});
None
}
}
}
|
pub mod transvoxel;
pub mod dual;
use gdnative::prelude::*;
use gdnative::api::{Mesh, ArrayMesh};
use noise::Perlin;
#[derive(NativeClass)]
#[inherit(Node)]
struct ProcGen;
#[gdnative::methods]
impl ProcGen {
fn new(_owner: &Node) -> Self {
ProcGen
}
#[export]
fn hello(&self, _owner: &Node) {
godot_print!("hello, world.")
}
#[export]
fn proc_gen(&self, _owner: &Node
, seed: usize
, zoom: Vector3
, origin: Vector3
, thresh: f64
, res: Vector3
, size: Vector3
, trans: Vector3)
-> Ref<ArrayMesh, Unique> {
let (vertices, normals) =
transvoxel::marching_cubes(
Perlin::new()
, seed as u32
, [zoom.x as f64, zoom.y as f64, zoom.z as f64]
, [origin.x as f64, origin.y as f64, origin.z as f64]
, thresh
, [res.x as f64, res.y as f64, res.z as f64]
, [size.x as f64, size.y as f64, size.z as f64]
, [trans.x as f64, trans.y as f64, trans.z as f64]
);
//https://godotengine.org/qa/22503/using-mesh-addsurfacefromarrays-from-c%23
// var arrays = []
// arrays.resize(Mesh.ARRAY_MAX)
// arrays[Mesh.ARRAY_VERTEX] = vertex_array
// arrays[Mesh.ARRAY_NORMAL] = normal_array
let array_mesh = ArrayMesh::new();
let arrays = VariantArray::new();
arrays.resize(Mesh::ARRAY_MAX as i32);
let mut vertex_array = Vector3Array::new();
for vertex in vertices.iter() {
let [x,y,z] = vertex;
vertex_array.push(Vector3::new(*x as f32, *y as f32, *z as f32));
}
let mut normal_array = Vector3Array::new();
for normal in normals.iter() {
let [x,y,z] = normal;
normal_array.push(Vector3::new(*x as f32, *y as f32, *z as f32));
}
arrays.set(Mesh::ARRAY_VERTEX as i32, vertex_array);
arrays.set(Mesh::ARRAY_NORMAL as i32, normal_array);
array_mesh.add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays.into_shared(), VariantArray::new().into_shared(), 97280);
array_mesh
}
//#[export]
//fn terrain() ...
}
fn init(handle: InitHandle) {
handle.add_tool_class::<ProcGen>();
}
godot_init!(init); |
// SPDX-License-Identifier: GPL-2.0
//! More About Cargo and crates.io
pub mod art {
//! A library for modeling artistic concepts
pub use self::kinds::PrimaryColor;
pub use self::kinds::SecondaryColor;
pub mod kinds {
/// The primary colors according to the RYB color model.
#[derive(PartialEq, Debug)]
pub enum PrimaryColor {
Red,
Yellow,
Blue,
}
/// The secondary colors according to the RYB color model.
pub enum SecondaryColor {
Orange,
Green,
Purple,
}
}
pub mod utils {
use super::kinds::*;
/// Combines two primary colors in equal amounts to create
/// a secondary color.
pub fn mix(_c1: PrimaryColor, _c2: PrimaryColor) -> SecondaryColor {
SecondaryColor::Orange
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn check_primary_color_re_exports() {
struct Test {
color: PrimaryColor,
want: PrimaryColor,
}
let tests = [
Test {
color: kinds::PrimaryColor::Red,
want: PrimaryColor::Red,
},
Test {
color: kinds::PrimaryColor::Yellow,
want: PrimaryColor::Yellow,
},
Test {
color: kinds::PrimaryColor::Blue,
want: PrimaryColor::Blue,
},
];
for t in &tests {
assert_eq!(t.want, t.color);
}
}
}
}
|
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use std::{fs, fmt, path};
use std::io::{self, Seek, SeekFrom, Write, Read};
use std::path::PathBuf;
use torrent::Info;
use slog::Logger;
use util::hash_to_id;
use ring::digest;
use amy;
use {handle, CONFIG};
const POLL_INT_MS: usize = 1000;
pub struct Disk {
poll: amy::Poller,
ch: handle::Handle<Request, Response>,
l: Logger,
files: FileCache,
}
#[derive(Clone)]
struct FileCache {
files: Arc<Mutex<HashMap<path::PathBuf, fs::File>>>,
}
pub enum Request {
Write {
tid: usize,
data: Box<[u8; 16384]>,
locations: Vec<Location>,
path: Option<String>,
},
Read {
data: Box<[u8; 16384]>,
locations: Vec<Location>,
context: Ctx,
path: Option<String>,
},
Serialize {
tid: usize,
data: Vec<u8>,
hash: [u8; 20],
},
Delete { tid: usize, hash: [u8; 20] },
Validate { tid: usize, info: Arc<Info> },
Shutdown,
}
pub struct Ctx {
pub pid: usize,
pub tid: usize,
pub idx: u32,
pub begin: u32,
pub length: u32,
}
impl Ctx {
pub fn new(pid: usize, tid: usize, idx: u32, begin: u32, length: u32) -> Ctx {
Ctx {
pid,
tid,
idx,
begin,
length,
}
}
}
impl FileCache {
pub fn new() -> FileCache {
FileCache { files: Arc::new(Mutex::new(HashMap::new())) }
}
pub fn get_file<F: FnOnce(&mut fs::File) -> io::Result<()>>(
&self,
path: &path::Path,
f: F,
) -> io::Result<()> {
let mut d = self.files.lock().unwrap();
if d.contains_key(path) {
f(d.get_mut(path).unwrap())?;
} else {
// TODO: LRU maybe?
if d.len() >= CONFIG.net.max_open_files {
let removal = d.iter().map(|(id, _)| id.clone()).next().unwrap();
d.remove(&removal);
}
let mut file = fs::OpenOptions::new()
.write(true)
.create(true)
.read(true)
.open(path)?;
f(&mut file)?;
d.insert(path.to_path_buf(), file);
}
Ok(())
}
}
impl Request {
pub fn write(
tid: usize,
data: Box<[u8; 16384]>,
locations: Vec<Location>,
path: Option<String>,
) -> Request {
Request::Write {
tid,
data,
locations,
path,
}
}
pub fn read(
context: Ctx,
data: Box<[u8; 16384]>,
locations: Vec<Location>,
path: Option<String>,
) -> Request {
Request::Read {
context,
data,
locations,
path,
}
}
pub fn serialize(tid: usize, data: Vec<u8>, hash: [u8; 20]) -> Request {
Request::Serialize { tid, data, hash }
}
pub fn validate(tid: usize, info: Arc<Info>) -> Request {
Request::Validate { tid, info }
}
pub fn delete(tid: usize, hash: [u8; 20]) -> Request {
Request::Delete { tid, hash }
}
pub fn shutdown() -> Request {
Request::Shutdown
}
fn execute(self, fc: FileCache) -> io::Result<Option<Response>> {
let sd = &CONFIG.disk.session;
let dd = &CONFIG.disk.directory;
match self {
Request::Write { data, locations, path, .. } => {
let mut pb = path::PathBuf::from(path.as_ref().unwrap_or(dd));
for loc in locations {
pb.push(&loc.file);
fc.get_file(&pb, |f| {
f.seek(SeekFrom::Start(loc.offset))?;
f.write(&data[loc.start..loc.end])?;
Ok(())
})?;
pb.pop();
}
}
Request::Read {
context,
mut data,
locations,
path,
..
} => {
let mut pb = path::PathBuf::from(path.as_ref().unwrap_or(dd));
for loc in locations {
pb.push(&loc.file);
fc.get_file(&pb, |f| {
f.seek(SeekFrom::Start(loc.offset))?;
f.read(&mut data[loc.start..loc.end])?;
Ok(())
})?;
pb.pop();
}
let data = Arc::new(data);
return Ok(Some(Response::read(context, data)));
}
Request::Serialize { data, hash, .. } => {
let mut pb = path::PathBuf::from(sd);
pb.push(hash_to_id(&hash));
let mut f = fs::OpenOptions::new().write(true).create(true).open(&pb)?;
f.write(&data)?;
}
Request::Delete { hash, .. } => {
let mut pb = path::PathBuf::from(sd);
pb.push(hash_to_id(&hash));
fs::remove_file(pb)?;
}
Request::Validate { tid, info } => {
let mut invalid = Vec::new();
let mut buf = vec![0u8; info.piece_len as usize];
let mut pb = path::PathBuf::from(dd);
let mut init_locs = info.piece_disk_locs(0);
let mut cf = init_locs.remove(0).file;
pb.push(&cf);
let mut f = fs::OpenOptions::new().read(true).open(&pb);
for i in 0..info.pieces() {
let mut valid = true;
let mut ctx = digest::Context::new(&digest::SHA1);
let locs = info.piece_disk_locs(i);
for loc in locs {
if &loc.file != &cf {
pb.pop();
pb.push(&loc.file);
f = fs::OpenOptions::new().read(true).open(&pb);
cf = loc.file;
}
if let Ok(Ok(amnt)) = f.as_mut().map(|file| file.read(&mut buf)) {
ctx.update(&buf[0..amnt]);
} else {
valid = false;
}
}
let digest = ctx.finish();
if !valid || digest.as_ref() != &info.hashes[i as usize][..] {
invalid.push(i);
}
}
return Ok(Some(Response::validation_complete(tid, invalid)));
}
Request::Shutdown => unreachable!(),
}
Ok(None)
}
pub fn tid(&self) -> usize {
match *self {
Request::Serialize { tid, .. } |
Request::Validate { tid, .. } |
Request::Delete { tid, .. } |
Request::Write { tid, .. } => tid,
Request::Read { ref context, .. } => context.tid,
Request::Shutdown => unreachable!(),
}
}
}
impl fmt::Debug for Request {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "disk::Request")
}
}
pub struct Location {
pub file: PathBuf,
pub offset: u64,
pub start: usize,
pub end: usize,
}
impl Location {
pub fn new(file: PathBuf, offset: u64, start: usize, end: usize) -> Location {
Location {
file,
offset,
start,
end,
}
}
}
pub enum Response {
Read {
context: Ctx,
data: Arc<Box<[u8; 16384]>>,
},
ValidationComplete { tid: usize, invalid: Vec<u32> },
Error { tid: usize, err: io::Error },
}
impl Response {
pub fn read(context: Ctx, data: Arc<Box<[u8; 16384]>>) -> Response {
Response::Read { context, data }
}
pub fn error(tid: usize, err: io::Error) -> Response {
Response::Error { tid, err }
}
pub fn validation_complete(tid: usize, invalid: Vec<u32>) -> Response {
Response::ValidationComplete { tid, invalid }
}
pub fn tid(&self) -> usize {
match *self {
Response::Read { ref context, .. } => context.tid,
Response::ValidationComplete { tid, .. } |
Response::Error { tid, .. } => tid,
}
}
}
impl fmt::Debug for Response {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "disk::Response")
}
}
impl Disk {
pub fn new(poll: amy::Poller, ch: handle::Handle<Request, Response>, l: Logger) -> Disk {
Disk {
poll,
ch,
l,
files: FileCache::new(),
}
}
pub fn run(&mut self) {
let sd = &CONFIG.disk.session;
fs::create_dir_all(sd).unwrap();
loop {
match self.poll.wait(POLL_INT_MS) {
Ok(_) => {
if self.handle_events() {
break;
}
}
Err(e) => {
warn!(self.l, "Failed to poll for events: {:?}", e);
}
}
}
}
pub fn handle_events(&mut self) -> bool {
loop {
match self.ch.recv() {
Ok(Request::Shutdown) => {
return true;
}
Ok(r) => {
trace!(self.l, "Handling disk job!");
let tid = r.tid();
match r.execute(self.files.clone()) {
Ok(Some(r)) => {
self.ch.send(r).ok();
}
Ok(None) => {}
Err(e) => {
self.ch.send(Response::error(tid, e)).ok();
}
}
}
_ => break,
}
}
false
}
}
pub fn start(creg: &mut amy::Registrar) -> io::Result<handle::Handle<Response, Request>> {
let poll = amy::Poller::new()?;
let mut reg = poll.get_registrar()?;
let (ch, dh) = handle::Handle::new(creg, &mut reg)?;
dh.run("disk", move |h, l| Disk::new(poll, h, l).run());
Ok(ch)
}
|
fn main() {
let w: i32 = parse_line();
let word = "DiscoPresentsDiscoveryChannelProgrammingContest2016";
let mut res = vec![];
for i in 0..((word.len() as i32) / w + 1) {
let mut line = String::from("");
for (j, c) in word.chars().enumerate() {
if i * w <= (j as i32) && (j as i32) < i * w + w {
line.push(c);
}
}
res.push(line);
}
for l in res.iter() {
if l.len() > 0 {
println!("{}", l);
}
}
}
fn parse_line<T: std::str::FromStr>() -> T {
let mut buf = String::new();
std::io::stdin().read_line(&mut buf).unwrap();
buf.trim_end().parse().ok().unwrap()
}
|
// struct def
#[derive(Debug)]
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
#[derive(Debug)]
struct RefUser {
// username: &str, // missing lifetime specifier
// email: &str,
sign_in_count: u64,
active: bool,
}
#[derive(Debug)]
struct Rectangle {
width: i32,
height: i32,
}
impl Rectangle {
// method function
fn area(&self) -> i32 {
self.width * self.height
}
// method function
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
// associated function(static in cpp) NO SELF
fn square(size: i32) -> Rectangle {
Rectangle {
width: size,
height: size,
}
}
}
//multiple impl struct (the same inside)
impl Rectangle {
fn perimeter(&self) -> i32 {
2 * (self.width + self.height)
}
}
fn main() {
// construct from def
let mut user1 = User {
email: String::from("tly@163.com"),
username: String::from("tly"),
sign_in_count: 1,
active: true,
};
println!("user1 is {:#?}", user1);
// modify
user1.email = String::from("tly@gmail.com");
println!("user1 is {:#?}", user1);
// buid from function
let user2 = build_user(String::from("frank"), String::from("frank@163.com"));
println!("user2 is {:#?}", user2);
// buid from function (simple)
let user3 = build_user_simple(String::from("franksim"), String::from("franksim@163.com"));
println!("user3 is {:#?}", user3);
// create instance from other instance with struct update syntax
let user4 = User {
email: String::from("tly@163.com"),
username: String::from("tly"),
sign_in_count: user1.sign_in_count,
active: user1.active,
};
println!("user4 is {:#?}", user4);
// create instance from other instance with struct update syntax (simple) base struct
// inheriated from user1
let user5 = User {
email: String::from("tly@163.com"),
username: String::from("tly"),
..user1
};
println!("user5 is {:#?}", user5);
// tuple structs
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
println!("black = {},{},{}", black.0, black.1, black.2);
println!("origin = {},{},{}", origin.0, origin.1, origin.2);
let user_ref: RefUser = RefUser {
sign_in_count: user1.sign_in_count,
active: user1.active,
};
println!("user_ref is {:#?}", user_ref);
// normal
let w1 = 20;
let h1 = 40;
println!("The area of rectangle is {} square pixels", area(w1, h1));
// tuple
let rect1 = (w1, h1);
println!(
"The area of rectangle is {} square pixels",
area_tuple(rect1)
);
//struct
let rect2 = Rectangle {
width: w1,
height: h1,
};
println!("rect2 is ({}, {})", rect2.width, rect2.height);
println!("rect2 is {:?}", rect2);
println!("rect2 is {:#?}", rect2);
let rect3 = Rectangle {
width: 10,
height: 10,
};
let rect4 = Rectangle {
width: 60,
height: 100,
};
// struct impl method
println!("rect2 area is {}", rect2.area());
println!("can rect2 hold rect3 : {}", rect2.can_hold(&rect3));
println!("can rect2 hold rect4 : {}", rect2.can_hold(&rect4));
let rect5 = Rectangle::square(30);
println!("rect5 perimeter is {}", rect5.perimeter());
}
fn area(width: i32, height: i32) -> i32 {
width * height
}
fn area_tuple(dimensions: (i32, i32)) -> i32 {
dimensions.0 * dimensions.1
}
fn build_user(email: String, username: String) -> User {
User {
email: email,
username: username,
active: true,
sign_in_count: 1,
}
}
fn build_user_simple(email: String, username: String) -> User {
User {
email,
username,
active: true,
sign_in_count: 1,
}
}
|
use strategy::*;
use docker::image::Image;
fn image(id: &str) -> Image {
Image{
Created: 0,
Id: id.to_string(),
ParentId: "mock".to_string(),
RepoTags: Vec::new(),
Size: 0,
VirtualSize: 0,
}
}
fn image_tag(id: &str, tags: Vec<&str>) -> Image {
let mut out = image(id);
out.RepoTags = tags.into_iter().map(|x| x.to_string()).collect();
out
}
#[test]
fn numbered() {
let numbered = NumberedCleanup::new("test", 3);
let result = numbered.filter(vec![
image_tag("m1", vec!["test:1"]),
image_tag("m2", vec!["test:2"]),
image_tag("m3", vec!["test:3"]),
image_tag("m4", vec!["test:4"]),
image_tag("m5", vec!["test:5"]),
]).unwrap();
assert_eq!(result.len(), 2);
assert_eq!(result[0].Id, "m1");
assert_eq!(result[1].Id, "m2");
}
#[test]
fn numbered_multiple() {
let numbered = NumberedCleanup::new("test", 1);
let result = numbered.filter(vec![
image_tag("m1", vec!["test:1"]),
image_tag("m2", vec!["test:2", "test:5"]),
image_tag("m3", vec!["test:3"]),
]).unwrap();
assert_eq!(result.len(), 2);
assert_eq!(result[0].Id, "m1");
assert_eq!(result[1].Id, "m3");
}
#[test]
fn numbered_keep_string() {
let numbered = NumberedCleanup::new("test", 0);
let result = numbered.filter(vec![
image_tag("m1", vec!["test:1", "test:keep"]),
]).unwrap();
assert_eq!(result.len(), 0);
}
#[test]
fn numbered_other_tag() {
let numbered = NumberedCleanup::new("test", 0);
let result = numbered.filter(vec![
image_tag("m1", vec!["nottest:1"]),
]).unwrap();
assert_eq!(result.len(), 0);
}
|
use anyhow::Result;
use std::io::Read;
use std::io::Write;
use std::{
cell::RefCell,
fmt,
process::{Child, Command, Stdio},
thread,
time::Duration,
};
pub struct Engine {
child: RefCell<Child>,
}
// Copied and modified from the uci crate https://crates.io/crates/uci
impl Engine {
pub fn new(path: &str) -> Result<Engine> {
let cmd = Command::new(path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("Unable to run engine");
let res = Engine {
child: RefCell::new(cmd),
};
res.read_line()?;
res.command("uci")?;
Ok(res)
}
pub fn set_position(&self, fen: &str) -> Result<()> {
self.write_fmt(format_args!("position fen {}\n", fen))
}
pub fn command(&self, cmd: &str) -> Result<String> {
self.write_fmt(format_args!("{}\n", cmd.trim()))?;
thread::sleep(Duration::from_millis(20));
self.read_output()
}
pub fn run(&self, depth: usize) -> Result<String> {
let cmd = format!("go depth {}", depth);
self.write_fmt(format_args!("{}\n", cmd.trim()))?;
self.wait_output_after_go()
}
fn read_output(&self) -> Result<String> {
let mut s: Vec<String> = vec![];
self.write_fmt(format_args!("isready\n"))?;
loop {
let next_line = self.read_line()?;
match next_line.trim() {
"readyok" => return Ok(s.join("\n")),
other => s.push(other.to_string()),
}
}
}
fn wait_output_after_go(&self) -> Result<String> {
let mut s: Vec<String> = vec![];
loop {
let next_line = self.read_line()?;
s.push(next_line.to_string());
if next_line.contains("bestmove") {
return Ok(s.join("\n"));
}
}
}
fn read_line(&self) -> Result<String> {
let mut s = String::new();
let mut buf: Vec<u8> = vec![0];
loop {
let _ = self
.child
.borrow_mut()
.stdout
.as_mut()
.unwrap()
.read(&mut buf)?;
s.push(buf[0] as char);
if buf[0] == b'\n' {
break;
}
}
Ok(s)
}
fn write_fmt(&self, args: fmt::Arguments) -> Result<()> {
self.child
.borrow_mut()
.stdin
.as_mut()
.unwrap()
.write_fmt(args)?;
Ok(())
}
}
|
use rand::Rng;
use rand_distr::{Distribution, StandardNormal};
use std::borrow::Borrow;
use super::estimator::MentalStateRep;
use crate::agent::estimator::Estimator;
use crate::agent::{Behavior, Hunger, MentalState};
use crate::entity::WorldEntity;
use crate::entity_type::EntityType;
use crate::position::Coord;
use crate::util::f32_cmp;
use crate::world::{Action, Event, Health, Observation, Occupancy, PhysicalState, Speed, World};
use crate::{Aggression, EmotionalState, Fear, Outcome, Position, Prob, Tiredness};
use lazysort::{SortedBy, SortedPartial};
use rand_xorshift::XorShiftRng;
use smallvec::SmallVec;
use std::iter::repeat;
#[derive(Clone, Debug)]
pub struct PointEstimateRep {
pub id: WorldEntity,
pub physical_state: PhysicalState,
pub emotional_state: EmotionalState,
pub current_action: Action,
pub current_behavior: Option<Behavior>,
pub sight_radius: Coord,
pub use_mdp: bool,
}
impl PointEstimateRep {
pub fn update(&mut self, ms: &MentalState) {
self.emotional_state += &ms.emotional_state;
self.current_behavior = ms.current_behavior.clone();
self.current_action = ms.current_action;
}
}
impl MentalStateRep for PointEstimateRep {
type Iter<'a> =
impl ExactSizeIterator<Item = (&'a EmotionalState, &'a Action, &'a Option<Behavior>)> + 'a;
fn iter<'a>(&'a self) -> Self::Iter<'a> {
Some((
&self.emotional_state,
&self.current_action,
&self.current_behavior,
))
.into_iter()
}
fn sample<R: Rng + ?Sized>(&self, scale: f32, rng: &mut R) -> MentalState {
let mut sample: MentalState = self.into();
sample_ms(&mut sample, scale, rng);
sample
}
fn update_seen<'a>(
&'a mut self,
action: Action,
others: &impl Estimator,
observation: &impl Observation,
) {
if let Some(phys) = observation.observed_physical_state(&self.id) {
self.physical_state = phys.clone();
}
if let Some(pos) = observation.observed_position(&self.id) {
let mut ms: MentalState = (&(*self)).into();
let threat_map = ms.threat_map(observation, others);
ms.update(
&self.physical_state,
pos,
observation,
threat_map[pos.idx()],
);
ms.decide_simple(
&(self.physical_state),
pos,
observation,
others,
&threat_map,
);
if action == ms.current_action {
self.update(&ms);
} else {
let mut rng: rand_xorshift::XorShiftRng =
rand::SeedableRng::seed_from_u64(self.id.id() as u64);
let max_tries = 255;
// let mut valid = Vec::new();
for i in (0..max_tries).rev() {
let scale = (1.0 + i as f32).log2() / (max_tries as f32).log2();
let mut sample = self.sample(scale, &mut rng);
sample.update(
&self.physical_state,
pos,
observation,
threat_map[pos.idx()],
);
sample.decide_simple(
&(self.physical_state),
pos,
observation,
others,
&threat_map,
);
if action == sample.current_action {
// valid.push(sample);
self.update(&sample);
break;
}
}
/*
if valid.len() > 0 {
self.update(&valid[0]);
self.emotional_state = EmotionalState::average(valid.drain(..).map(|ms| ms.emotional_state))
}
*/
}
}
}
fn update_unseen<'a>(&'a mut self, others: &impl Estimator, observation: &impl Observation) {
//TODO
}
fn into_ms(&self) -> MentalState {
MentalState {
id: self.id,
emotional_state: self.emotional_state.clone(),
current_action: self.current_action,
current_behavior: self.current_behavior.clone(),
sight_radius: self.sight_radius,
rng: rand::SeedableRng::seed_from_u64(self.id.id() as u64),
use_mdp: false,
world_model: None,
score: 0.0,
}
}
fn from_aggregate<B>(we: &WorldEntity, iter: impl Iterator<Item = B>) -> Self
where
B: Borrow<Self>,
{
let mut def = Self::default(we);
{
def.emotional_state =
EmotionalState::average(iter.map(|b| b.borrow().emotional_state.clone()));
}
def
}
fn default(entity: &WorldEntity) -> Self {
PointEstimateRep {
id: entity.clone(),
physical_state: entity
.e_type()
.typical_physical_state()
.unwrap_or(PhysicalState::new(Health(50.0), Speed(0.2), None)),
emotional_state: EmotionalState::new(
EntityType::iter()
.filter_map(|other| {
if entity.e_type().can_eat(&other) {
Some((other, 0.5))
} else {
None
}
})
.collect(),
),
current_action: Action::default(),
current_behavior: None,
sight_radius: 5,
use_mdp: false,
}
}
fn get_type(&self) -> EntityType {
self.id.e_type()
}
fn update_on_events<'a>(
&'a mut self,
events: impl IntoIterator<Item = &'a Event> + Copy,
_world_model: Option<&'a World<Occupancy>>,
) {
{
let mut new: MentalState = (&(*self)).into();
new.update_on_events(events);
self.update(&new);
}
}
}
impl std::fmt::Display for PointEstimateRep {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
let ms: MentalState = self.into();
writeln!(f, "{:?} ({})", self.id.e_type(), self.id.id())?;
writeln!(f, "Hunger: ({})", self.emotional_state.hunger().0)?;
writeln!(f, "Preferences:")?;
for (t, p) in ms.food_preferences() {
writeln!(f, "{:?}: {}", t, p)?;
}
writeln!(f, "Behavior:")?;
writeln!(f, "{}", Behavior::fmt(&self.current_behavior))?;
writeln!(f, "Action:")?;
self.current_action.fmt(f)
}
}
impl Borrow<EmotionalState> for PointEstimateRep {
fn borrow(&self) -> &EmotionalState {
&self.emotional_state
}
}
const PARTICLE_COUNT: usize = 20;
#[derive(Clone, Debug)]
pub struct ParticleFilterRep {
id: WorldEntity,
physical_state: PhysicalState,
last_position: Position,
particles: SmallVec<[(MentalState, Prob); PARTICLE_COUNT]>,
/// Probability of action missprediction given approximately correct mental state.
p_wrong_action: Prob,
}
impl ParticleFilterRep {
pub fn iter_particles(&self) -> impl Iterator<Item=&(MentalState, Prob)> {
self.particles.iter()
}
}
impl MentalStateRep for ParticleFilterRep {
type Iter<'a> =
impl ExactSizeIterator<Item = (&'a EmotionalState, &'a Action, &'a Option<Behavior>)> + 'a;
fn iter(&self) -> Self::Iter<'_> {
self.particles.iter().map(|(ms, _)| {
(
&ms.emotional_state,
&ms.current_action,
&ms.current_behavior,
)
})
}
fn sample<R: Rng + ?Sized>(&self, scale: f32, rng: &mut R) -> MentalState {
let distr = rand_distr::Uniform::new(0.0f32, 1.0);
let mut pick = rng.sample(distr);
let mut ms = self
.particles
.iter()
.find(|(ms, p)| {
pick -= *p;
pick <= 0.0
})
.unwrap_or(&self.particles[0])
.0
.clone();
sample_ms(&mut ms, scale, rng);
ms
}
fn update_seen<'a>(
&'a mut self,
action: Action,
others: &impl Estimator,
observation: &impl Observation,
) {
if let Some(phys) = observation.observed_physical_state(&self.id) {
self.physical_state = phys.clone();
}
if let Some(pos) = observation.observed_position(&self.id) {
self.last_position = pos;
}
let pos = self.last_position;
let threat_map = self.particles[0].0.threat_map(observation, others);
let mut rng = self.particles[0].0.rng.clone();
// Low variance resampling
let inc = 1.0 / PARTICLE_COUNT as f32;
let mut target = rng.sample(rand_distr::Uniform::new(0.0, inc));
let mut acc = 0.0;
let mut next = SmallVec::new();
let mut p_right_action = 0.0;
for (ms, p) in self.particles.iter() {
acc += *p;
if acc >= target {
let n = (((acc - target) / inc).ceil() as usize).max(PARTICLE_COUNT - next.len());
target += n as f32 * inc;
for i in 0..n {
let mut new_ms = ms.clone();
let scale = if n == 1 { 0.2 } else { 0.1 * i as f32 };
sample_ms(&mut new_ms, scale, &mut rng);
new_ms.update(
&self.physical_state,
pos,
observation,
threat_map[pos.idx()],
);
new_ms.decide_simple(
&self.physical_state,
pos,
observation,
others,
&threat_map,
);
let mut new_p = *p / n as f32;
if new_ms.current_action == action {
p_right_action += new_p;
new_p *= 1.0 - self.p_wrong_action;
} else {
new_p *= self.p_wrong_action;
}
next.push((new_ms, new_p));
}
}
}
let p_right: f32 = next.iter().map(|(_, p)| *p).sum();
let inv = 1.0 / p_right;
for (_, p) in next.iter_mut() {
*p *= inv;
}
next.sort_by(|(_, p0), (_, p1)| f32_cmp(p1, p0));
let p_right_action_given_right: f32 = p_right_action / p_right;
self.p_wrong_action = 0.9f32 * self.p_wrong_action
+ 0.1f32 * (1.0f32 - p_right_action_given_right).min(0.01).max(0.4);
self.particles = next;
}
fn update_on_events<'a>(
&'a mut self,
events: impl IntoIterator<Item = &'a Event> + Copy,
world_model: Option<&'a World<Occupancy>>,
) {
use itertools::Itertools;
if let Some(dir) = events.into_iter().find_map(|e| match e {
Event {
actor,
outcome: Outcome::Moved(dir),
} if *actor == self.id => Some(dir),
_ => None,
}) {
self.last_position = self.last_position.step(*dir).unwrap_or(self.last_position);
}
for (ms, _) in self.particles.iter_mut() {
ms.update_on_events(events);
}
}
fn update_unseen<'a>(&'a mut self, others: &impl Estimator, observation: &impl Observation) {
// "Observation" can be a world model with suspected physical state and position, if so use those.
if let Some(phys) = observation.observed_physical_state(&self.id) {
self.physical_state = phys.clone();
}
if let Some(pos) = observation.observed_position(&self.id) {
self.last_position = pos;
}
let threat_map = self.particles[0].0.threat_map(observation, others);
for (ms, _) in self.particles.iter_mut() {
ms.update(
&self.physical_state,
self.last_position,
observation,
threat_map[self.last_position.idx()],
);
ms.decide_simple(
&self.physical_state,
self.last_position,
observation,
others,
&threat_map,
);
}
}
fn default(we: &WorldEntity) -> Self {
let mut rng: XorShiftRng = rand::SeedableRng::seed_from_u64(we.id() as u64);
let particles = std::iter::repeat_with(|| {
let v: Vec<_> = EntityType::iter()
.filter_map(|et| {
if we.e_type().can_eat(&et) {
let pref = rng.gen_range(0.0, 1.0);
Some((et, pref))
} else {
None
}
})
.collect();
(
MentalState::new(*we, v, false, false),
1.0 / PARTICLE_COUNT as f32,
)
})
.take(PARTICLE_COUNT)
.collect();
ParticleFilterRep {
id: we.clone(),
physical_state: we
.e_type()
.typical_physical_state()
.unwrap_or(PhysicalState::new(Health(50.0), Speed(0.2), None)),
particles,
last_position: Position { x: 5, y: 5 },
p_wrong_action: 0.2,
}
}
fn from_aggregate<B>(we: &WorldEntity, iter: impl Iterator<Item = B>) -> Self
where
B: std::borrow::Borrow<Self>,
{
let mut rng: XorShiftRng = rand::SeedableRng::seed_from_u64(we.id() as u64);
use lazysort::{SortedBy, SortedPartial};
let mut particles: SmallVec<_> = iter
.flat_map(|b| {
let v: Vec<_> = b.borrow().particles.iter().cloned().collect();
v.into_iter()
})
.sorted_by(|(_, p0), (_, p1)| f32_cmp(p1, p0))
.map(|mut t| {
t.0.id = *we;
t
})
.chain(std::iter::repeat_with(|| {
let v: Vec<_> = EntityType::iter()
.filter_map(|et| {
if we.e_type().can_eat(&et) {
let pref = rng.gen_range(0.0, 1.0);
Some((et, pref))
} else {
None
}
})
.collect();
(MentalState::new(*we, v, false, false), 0.01)
}))
.take(PARTICLE_COUNT)
.collect(); // for_each(|(ms, p)| { particles.push(ms); probs.push(p); });
normalize(&mut particles, |(_, p)| p);
// let particles = unsafe { std::mem::transmute(arr) };
ParticleFilterRep {
id: *we,
physical_state: we.e_type().typical_physical_state().unwrap(),
particles,
last_position: Position { x: 5, y: 5 },
p_wrong_action: 0.2,
}
}
fn get_type(&self) -> EntityType {
self.id.e_type()
}
}
fn normalize<T, F: Fn(&mut T) -> &mut f32>(probs: &mut [T], accessor: F) {
let s: f32 = probs.iter_mut().map(|f| *((&accessor)(f))).sum();
let inv: f32 = 1.0f32 / s;
for p in probs.iter_mut() {
*(accessor(p)) *= inv;
}
}
fn sample_ms<R: Rng + ?Sized>(sample: &mut MentalState, scale: f32, rng: &mut R) {
let hunger_sample: f32 = StandardNormal.sample(rng);
sample.emotional_state += Hunger(hunger_sample * scale);
let fear_sample: f32 = StandardNormal.sample(rng);
sample.emotional_state += Fear(fear_sample * scale);
let aggression_sample: f32 = StandardNormal.sample(rng);
sample.emotional_state += Aggression(aggression_sample * scale);
let tiredness_sample: f32 = StandardNormal.sample(rng);
sample.emotional_state += Tiredness(tiredness_sample * scale);
for et in EntityType::iter() {
if sample.id.e_type().can_eat(&et) {
let pref_sample: f32 = StandardNormal.sample(rng);
sample
.emotional_state
.set_preference(et, sample.emotional_state.pref(et).0 + pref_sample * scale)
}
}
let bhv_sample: f32 = StandardNormal.sample(rng);
if bhv_sample * scale > 0.25f32 {
sample.current_behavior = None;
}
sample.rng = rand::SeedableRng::seed_from_u64(rng.gen());
}
impl std::fmt::Display for ParticleFilterRep {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
writeln!(f, "{:?} ({})", self.id.e_type(), self.id.id())?;
for (ms, prob) in self.particles.iter() {
writeln!(f, "Probability {:.2}%:", prob * 100.0)?;
writeln!(f, "Hunger: ({})", ms.emotional_state.hunger().0)?;
writeln!(f, "Preferences:")?;
for (t, p) in ms.food_preferences() {
writeln!(f, "{:?}: {}", t, p)?;
}
writeln!(f, "Behavior:")?;
writeln!(f, "{}", Behavior::fmt(&ms.current_behavior))?;
writeln!(f, "Action:")?;
ms.current_action.fmt(f)?;
}
Ok(())
}
}
|
use std::fs;
use std::collections::VecDeque;
const OP_HALT: i32 = 99;
const OP_ADD: i32 = 1;
const OP_MULTIPLY: i32 = 2;
const OP_INPUT: i32 = 3;
const OP_OUTPUT: i32 = 4;
const OP_JUMP_IF_TRUE: i32 = 5;
const OP_JUMP_IF_FALSE: i32 = 6;
const OP_LESS_THAN: i32 = 7;
const OP_EQUALS: i32 = 8;
const EXIT_END: i32 = -1;
const EXIT_HALT: i32 = 0;
const EXIT_NEED_INPUT: i32 = 1;
const EXIT_OUTPUT: i32 = 2;
struct Program {
code: Vec<i32>,
ip: usize
}
impl Clone for Program {
fn clone(&self) -> Program {
Program {code: self.code.clone(), ip: self.ip.clone()}
}
}
fn run_program(program: &mut Program, data: &mut VecDeque<i32>) -> i32 {
let mut ip = program.ip as usize;
let code = &mut program.code;
while ip < code.len() {
let instr = code[ip];
let opcode = read_opcode(instr);
ip += 1;
match opcode {
OP_HALT => {
return EXIT_HALT;
},
OP_ADD | OP_MULTIPLY | OP_LESS_THAN | OP_EQUALS => {
let param1 = read_param_value(ip, &code, 0);
let param2 = read_param_value(ip, &code, 1);
let result_address = code[ip + 2] as usize;
ip += 3;
match opcode {
OP_ADD => code[result_address] = param1 + param2,
OP_MULTIPLY => code[result_address] = param1 * param2,
OP_LESS_THAN => code[result_address] = if param1 < param2 { 1 } else { 0 },
OP_EQUALS => code[result_address] = if param1 == param2 { 1 } else { 0 },
_ => panic!()
}
},
OP_INPUT => {
let param = code[ip];
ip += 1;
match data.pop_front() {
Some(value) => code[param as usize] = value,
None => return EXIT_NEED_INPUT
}
},
OP_OUTPUT => {
let param = read_param_value(ip, &code, 0);
ip += 1;
data.push_back(param);
program.ip = ip;
return EXIT_OUTPUT;
},
OP_JUMP_IF_TRUE | OP_JUMP_IF_FALSE => {
let param1 = read_param_value(ip, &code, 0);
let param2 = read_param_value(ip, &code, 1);
ip += 2;
if (opcode == OP_JUMP_IF_TRUE && param1 != 0) || (opcode == OP_JUMP_IF_FALSE && param1 == 0) {
ip = param2 as usize;
}
}
_ => panic!()
}
program.ip = ip;
}
fn read_opcode(instr: i32) -> i32 {
return instr % 100;
}
fn read_param_mode(instr: i32, index: u32) -> i32 {
return instr % 10_i32.pow(index + 3) / 10_i32.pow(index + 2);
}
fn read_param_value(start: usize, code: &Vec<i32>, index: u32) -> i32 {
let mode = read_param_mode(code[start - 1], index);
let param = code[start + index as usize];
if mode == 0 {
return code[param as usize];
} else {
return param;
}
}
return EXIT_END;
}
fn permutations(values: Vec<i32>) -> Vec<Vec<i32>> {
let mut v = values.clone();
let mut ps = Vec::new();
permutations_internal(&mut v, &mut ps, values.len());
fn permutations_internal(v: &mut Vec<i32>, mut ps: &mut Vec<Vec<i32>>, i: usize) {
if i == 1 {
ps.push(v.clone());
return;
}
permutations_internal(v, &mut ps, i - 1);
for j in 0..(i - 1) {
if i % 2 == 0 {
v.swap(j, i - 1);
} else {
v.swap(0, i - 1);
}
permutations_internal(v, &mut ps, i - 1);
}
}
return ps;
}
fn main() {
let code = fs::read_to_string("input.txt")
.unwrap()
.trim()
.split(",")
.map(|x| x.parse::<i32>().unwrap())
.collect::<Vec<i32>>();
let program = Program {code: code, ip: 0};
let mut max_signal = 0;
let mut max_signal_phases = vec!();
for phases in permutations((5..=9).collect()) {
let mut amplifiers: Vec<Program> = vec![program.clone(); phases.len()];
let mut signal = 0;
let mut data = VecDeque::new();
println!("Phases: {:?}", phases);
for (index, amp) in amplifiers.iter_mut().enumerate() {
println!("Initializing amplifier {}", index);
data.push_back(phases[index]);
if run_program(amp, &mut data) != EXIT_NEED_INPUT {
panic!();
}
}
data.push_back(signal);
loop {
let mut exit_code = EXIT_HALT;
for (index, amp) in amplifiers.iter_mut().enumerate() {
println!("Running amplifier {} with input signal {}", index, data[0]);
exit_code = run_program(amp, &mut data);
println!("Output signal: {}", data[0]);
}
if exit_code == EXIT_HALT {
signal = data[0];
break;
}
}
if signal > max_signal {
max_signal = signal;
max_signal_phases = phases;
}
}
println!("{}", max_signal);
println!("{:?}", max_signal_phases);
}
|
#[doc = "Register `MMCCR` reader"]
pub type R = crate::R<MMCCR_SPEC>;
#[doc = "Register `MMCCR` writer"]
pub type W = crate::W<MMCCR_SPEC>;
#[doc = "Field `CR` reader - Counter reset"]
pub type CR_R = crate::BitReader<CR_A>;
#[doc = "Counter reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CR_A {
#[doc = "1: Reset all counters. Cleared automatically"]
Reset = 1,
}
impl From<CR_A> for bool {
#[inline(always)]
fn from(variant: CR_A) -> Self {
variant as u8 != 0
}
}
impl CR_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<CR_A> {
match self.bits {
true => Some(CR_A::Reset),
_ => None,
}
}
#[doc = "Reset all counters. Cleared automatically"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == CR_A::Reset
}
}
#[doc = "Field `CR` writer - Counter reset"]
pub type CR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CR_A>;
impl<'a, REG, const O: u8> CR_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Reset all counters. Cleared automatically"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(CR_A::Reset)
}
}
#[doc = "Field `CSR` reader - Counter stop rollover"]
pub type CSR_R = crate::BitReader<CSR_A>;
#[doc = "Counter stop rollover\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CSR_A {
#[doc = "0: Counters roll over to zero after reaching the maximum value"]
Disabled = 0,
#[doc = "1: Counters do not roll over to zero after reaching the maximum value"]
Enabled = 1,
}
impl From<CSR_A> for bool {
#[inline(always)]
fn from(variant: CSR_A) -> Self {
variant as u8 != 0
}
}
impl CSR_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CSR_A {
match self.bits {
false => CSR_A::Disabled,
true => CSR_A::Enabled,
}
}
#[doc = "Counters roll over to zero after reaching the maximum value"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == CSR_A::Disabled
}
#[doc = "Counters do not roll over to zero after reaching the maximum value"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == CSR_A::Enabled
}
}
#[doc = "Field `CSR` writer - Counter stop rollover"]
pub type CSR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CSR_A>;
impl<'a, REG, const O: u8> CSR_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Counters roll over to zero after reaching the maximum value"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(CSR_A::Disabled)
}
#[doc = "Counters do not roll over to zero after reaching the maximum value"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(CSR_A::Enabled)
}
}
#[doc = "Field `ROR` reader - Reset on read"]
pub type ROR_R = crate::BitReader<ROR_A>;
#[doc = "Reset on read\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ROR_A {
#[doc = "0: MMC counters do not reset on read"]
Disabled = 0,
#[doc = "1: MMC counters reset to zero after read"]
Enabled = 1,
}
impl From<ROR_A> for bool {
#[inline(always)]
fn from(variant: ROR_A) -> Self {
variant as u8 != 0
}
}
impl ROR_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ROR_A {
match self.bits {
false => ROR_A::Disabled,
true => ROR_A::Enabled,
}
}
#[doc = "MMC counters do not reset on read"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == ROR_A::Disabled
}
#[doc = "MMC counters reset to zero after read"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == ROR_A::Enabled
}
}
#[doc = "Field `ROR` writer - Reset on read"]
pub type ROR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ROR_A>;
impl<'a, REG, const O: u8> ROR_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "MMC counters do not reset on read"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(ROR_A::Disabled)
}
#[doc = "MMC counters reset to zero after read"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(ROR_A::Enabled)
}
}
#[doc = "Field `MCF` reader - MMC counter freeze"]
pub type MCF_R = crate::BitReader<MCF_A>;
#[doc = "MMC counter freeze\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MCF_A {
#[doc = "0: All MMC counters update normally"]
Unfrozen = 0,
#[doc = "1: All MMC counters frozen to their current value"]
Frozen = 1,
}
impl From<MCF_A> for bool {
#[inline(always)]
fn from(variant: MCF_A) -> Self {
variant as u8 != 0
}
}
impl MCF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MCF_A {
match self.bits {
false => MCF_A::Unfrozen,
true => MCF_A::Frozen,
}
}
#[doc = "All MMC counters update normally"]
#[inline(always)]
pub fn is_unfrozen(&self) -> bool {
*self == MCF_A::Unfrozen
}
#[doc = "All MMC counters frozen to their current value"]
#[inline(always)]
pub fn is_frozen(&self) -> bool {
*self == MCF_A::Frozen
}
}
#[doc = "Field `MCF` writer - MMC counter freeze"]
pub type MCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MCF_A>;
impl<'a, REG, const O: u8> MCF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "All MMC counters update normally"]
#[inline(always)]
pub fn unfrozen(self) -> &'a mut crate::W<REG> {
self.variant(MCF_A::Unfrozen)
}
#[doc = "All MMC counters frozen to their current value"]
#[inline(always)]
pub fn frozen(self) -> &'a mut crate::W<REG> {
self.variant(MCF_A::Frozen)
}
}
#[doc = "Field `MCP` reader - MMC counter preset"]
pub type MCP_R = crate::BitReader<MCP_A>;
#[doc = "MMC counter preset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MCP_A {
#[doc = "1: MMC counters will be preset to almost full or almost half. Cleared automatically"]
Preset = 1,
}
impl From<MCP_A> for bool {
#[inline(always)]
fn from(variant: MCP_A) -> Self {
variant as u8 != 0
}
}
impl MCP_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<MCP_A> {
match self.bits {
true => Some(MCP_A::Preset),
_ => None,
}
}
#[doc = "MMC counters will be preset to almost full or almost half. Cleared automatically"]
#[inline(always)]
pub fn is_preset(&self) -> bool {
*self == MCP_A::Preset
}
}
#[doc = "Field `MCP` writer - MMC counter preset"]
pub type MCP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MCP_A>;
impl<'a, REG, const O: u8> MCP_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "MMC counters will be preset to almost full or almost half. Cleared automatically"]
#[inline(always)]
pub fn preset(self) -> &'a mut crate::W<REG> {
self.variant(MCP_A::Preset)
}
}
#[doc = "Field `MCFHP` reader - MMC counter Full-Half preset"]
pub type MCFHP_R = crate::BitReader<MCFHP_A>;
#[doc = "MMC counter Full-Half preset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MCFHP_A {
#[doc = "0: When MCP is set, MMC counters are preset to almost-half value 0x7FFF_FFF0"]
AlmostHalf = 0,
#[doc = "1: When MCP is set, MMC counters are preset to almost-full value 0xFFFF_FFF0"]
AlmostFull = 1,
}
impl From<MCFHP_A> for bool {
#[inline(always)]
fn from(variant: MCFHP_A) -> Self {
variant as u8 != 0
}
}
impl MCFHP_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MCFHP_A {
match self.bits {
false => MCFHP_A::AlmostHalf,
true => MCFHP_A::AlmostFull,
}
}
#[doc = "When MCP is set, MMC counters are preset to almost-half value 0x7FFF_FFF0"]
#[inline(always)]
pub fn is_almost_half(&self) -> bool {
*self == MCFHP_A::AlmostHalf
}
#[doc = "When MCP is set, MMC counters are preset to almost-full value 0xFFFF_FFF0"]
#[inline(always)]
pub fn is_almost_full(&self) -> bool {
*self == MCFHP_A::AlmostFull
}
}
#[doc = "Field `MCFHP` writer - MMC counter Full-Half preset"]
pub type MCFHP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MCFHP_A>;
impl<'a, REG, const O: u8> MCFHP_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "When MCP is set, MMC counters are preset to almost-half value 0x7FFF_FFF0"]
#[inline(always)]
pub fn almost_half(self) -> &'a mut crate::W<REG> {
self.variant(MCFHP_A::AlmostHalf)
}
#[doc = "When MCP is set, MMC counters are preset to almost-full value 0xFFFF_FFF0"]
#[inline(always)]
pub fn almost_full(self) -> &'a mut crate::W<REG> {
self.variant(MCFHP_A::AlmostFull)
}
}
impl R {
#[doc = "Bit 0 - Counter reset"]
#[inline(always)]
pub fn cr(&self) -> CR_R {
CR_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Counter stop rollover"]
#[inline(always)]
pub fn csr(&self) -> CSR_R {
CSR_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Reset on read"]
#[inline(always)]
pub fn ror(&self) -> ROR_R {
ROR_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - MMC counter freeze"]
#[inline(always)]
pub fn mcf(&self) -> MCF_R {
MCF_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - MMC counter preset"]
#[inline(always)]
pub fn mcp(&self) -> MCP_R {
MCP_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - MMC counter Full-Half preset"]
#[inline(always)]
pub fn mcfhp(&self) -> MCFHP_R {
MCFHP_R::new(((self.bits >> 5) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Counter reset"]
#[inline(always)]
#[must_use]
pub fn cr(&mut self) -> CR_W<MMCCR_SPEC, 0> {
CR_W::new(self)
}
#[doc = "Bit 1 - Counter stop rollover"]
#[inline(always)]
#[must_use]
pub fn csr(&mut self) -> CSR_W<MMCCR_SPEC, 1> {
CSR_W::new(self)
}
#[doc = "Bit 2 - Reset on read"]
#[inline(always)]
#[must_use]
pub fn ror(&mut self) -> ROR_W<MMCCR_SPEC, 2> {
ROR_W::new(self)
}
#[doc = "Bit 3 - MMC counter freeze"]
#[inline(always)]
#[must_use]
pub fn mcf(&mut self) -> MCF_W<MMCCR_SPEC, 3> {
MCF_W::new(self)
}
#[doc = "Bit 4 - MMC counter preset"]
#[inline(always)]
#[must_use]
pub fn mcp(&mut self) -> MCP_W<MMCCR_SPEC, 4> {
MCP_W::new(self)
}
#[doc = "Bit 5 - MMC counter Full-Half preset"]
#[inline(always)]
#[must_use]
pub fn mcfhp(&mut self) -> MCFHP_W<MMCCR_SPEC, 5> {
MCFHP_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Ethernet MMC control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmccr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`mmccr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MMCCR_SPEC;
impl crate::RegisterSpec for MMCCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`mmccr::R`](R) reader structure"]
impl crate::Readable for MMCCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`mmccr::W`](W) writer structure"]
impl crate::Writable for MMCCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets MMCCR to value 0"]
impl crate::Resettable for MMCCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
/// Project Context
use crate::config::{Config, Deployment};
use anyhow::{anyhow, Result};
use std::env;
use std::fs;
use std::io::ErrorKind as IOErrorKind;
use std::path::{Path, PathBuf};
use std::str::FromStr;
const CONTRACTS_DIR: &str = "contracts";
const CONTRACTS_BUILD_DIR: &str = "build";
const MIGRATIONS_DIR: &str = "migrations";
const CONFIG_NAME: &str = "capsule.toml";
#[derive(Debug, Copy, Clone)]
pub enum BuildEnv {
Debug,
Release,
}
impl FromStr for BuildEnv {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"debug" => Ok(BuildEnv::Debug),
"release" => Ok(BuildEnv::Release),
_ => Err("no match"),
}
}
}
#[derive(Debug, Copy, Clone)]
pub enum DeployEnv {
Dev,
Production,
}
impl FromStr for DeployEnv {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"dev" => Ok(DeployEnv::Dev),
"production" => Ok(DeployEnv::Production),
_ => Err("no match"),
}
}
}
pub struct Context {
pub project_path: PathBuf,
pub config: Config,
}
impl Context {
pub fn contracts_path(&self) -> PathBuf {
let mut path = self.project_path.clone();
path.push(CONTRACTS_DIR);
path
}
pub fn contract_path<P: AsRef<Path>>(&self, contract_name: P) -> PathBuf {
let mut path = self.contracts_path();
path.push(contract_name);
path
}
pub fn contract_relative_path<P: AsRef<Path>>(&self, contract_name: P) -> PathBuf {
let mut path = PathBuf::new();
path.push(CONTRACTS_DIR);
path.push(contract_name);
path
}
pub fn contracts_build_path(&self, env: BuildEnv) -> PathBuf {
let mut path = self.project_path.clone();
path.push(CONTRACTS_BUILD_DIR);
let prefix = match env {
BuildEnv::Debug => "debug",
BuildEnv::Release => "release",
};
path.push(prefix);
path
}
pub fn migrations_path(&self, env: DeployEnv) -> PathBuf {
let mut path = self.project_path.clone();
path.push(MIGRATIONS_DIR);
let prefix = match env {
DeployEnv::Production => "production",
DeployEnv::Dev => "dev",
};
path.push(prefix);
path
}
pub fn load_deployment(&self) -> Result<Deployment> {
let mut path = self.project_path.clone();
path.push(&self.config.deployment);
let deployment: Deployment = toml::from_slice(&fs::read(path)?)?;
Ok(deployment)
}
}
pub fn read_config_file() -> Result<String> {
let mut project_path = PathBuf::new();
project_path.push(env::current_dir()?);
let mut path = project_path.clone();
path.push(CONFIG_NAME);
match fs::read_to_string(path) {
Ok(content) => Ok(content),
Err(err) if err.kind() == IOErrorKind::NotFound => Err(anyhow!(
"Can't found {}, current directory is not a project",
CONFIG_NAME
)),
Err(err) => Err(err.into()),
}
}
pub fn write_config_file(content: String) -> Result<()> {
let mut project_path = PathBuf::new();
project_path.push(env::current_dir()?);
let mut path = project_path.clone();
path.push(CONFIG_NAME);
fs::write(path, content)?;
Ok(())
}
pub fn load_project_context() -> Result<Context> {
let content = read_config_file()?;
let config: Config = toml::from_slice(content.as_bytes())?;
let mut project_path = PathBuf::new();
project_path.push(env::current_dir()?);
Ok(Context {
config,
project_path,
})
}
|
//! Transport-specific functionality.
//!
//! The current iteration requires 2 different implementations:
//! - SessionMetadata trait
//! - Transport trait
//!
//! Take a look at the CAN implementation for an example.
// Declaring all of the sub transport modules here.
pub mod can;
use streaming_iterator::StreamingIterator;
use crate::internal::InternalRxFrame;
use crate::NodeId;
use crate::{RxError, TxError};
/// Describes any transport-specific metadata required to construct a session.
///
/// In the example of CAN, you need to keep track of the toggle bit,
/// as well as the CRC for multi-frame transfers. This trait lets us pull that
/// code out of the generic processing and into more modular implementations.
pub trait SessionMetadata<C: embedded_time::Clock> {
/// Create a fresh instance of session metadata;
fn new() -> Self;
/// Update metadata with incoming frame's information.
///
/// If the frame is valid, returns Some(length of payload to ingest)
fn update(&mut self, frame: &InternalRxFrame<C>) -> Option<usize>;
/// Final check to see if transfer was successful.
fn is_valid(&self, frame: &InternalRxFrame<C>) -> bool;
}
/// This trait is to be implemented on a unit struct, in order to be specified
/// for different transport types.
pub trait Transport<C: embedded_time::Clock> {
type Frame;
// TODO does this properly describe the lifetime semantics of this type?
// I implemented this as a quick fix to get the PR tests going - David
type FrameIter<'a>: StreamingIterator where C: 'a;
/// Process a frame, returning the internal transport-independant representation,
/// or errors if invalid.
fn rx_process_frame<'a>(
node_id: &Option<NodeId>,
frame: &'a Self::Frame,
) -> Result<Option<InternalRxFrame<'a, C>>, RxError>;
/// Prepare an iterator of frames to send out on the wire.
fn transmit<'a>(
transfer: &'a crate::transfer::Transfer<C>,
) -> Result<Self::FrameIter<'a>, TxError>;
}
|
use std::{
sync::{
Arc,
Mutex,
},
thread,
time::Duration,
};
use crossbeam_channel::{
self,
Receiver,
};
use serde_json::Value;
use sqelf::{
process,
receive,
server,
};
use super::SERVER_BIND;
pub struct Builder {
tcp_max_size_bytes: u64,
tcp_keep_alive_secs: u64,
udp_max_chunks_per_message: u8,
}
impl Builder {
fn new() -> Self {
Builder {
tcp_max_size_bytes: 512,
tcp_keep_alive_secs: 10,
udp_max_chunks_per_message: u8::MAX,
}
}
pub fn tcp_max_size_bytes(mut self, v: u64) -> Self {
self.tcp_max_size_bytes = v;
self
}
pub fn tcp_keep_alive_secs(mut self, v: u64) -> Self {
self.tcp_keep_alive_secs = v;
self
}
pub fn udp_max_chunks(mut self, v: u8) -> Self {
self.udp_max_chunks_per_message = v;
self
}
fn build(self, protocol: server::Protocol) -> Server {
Server::new(
server::Config {
bind: server::Bind {
addr: SERVER_BIND.into(),
protocol,
},
tcp_max_size_bytes: self.tcp_max_size_bytes,
tcp_keep_alive_secs: self.tcp_keep_alive_secs,
..Default::default()
},
receive::Config {
max_chunks_per_message: self.udp_max_chunks_per_message,
..Default::default()
}
)
}
pub fn udp(self) -> Server {
self.build(server::Protocol::Udp)
}
pub fn tcp(self) -> Server {
self.build(server::Protocol::Tcp)
}
}
pub struct Server {
server: thread::JoinHandle<()>,
handle: server::Handle,
received: Arc<Mutex<usize>>,
rx: Receiver<Value>,
}
pub fn builder() -> Builder {
Builder::new()
}
pub fn udp() -> Server {
Builder::new().udp()
}
pub fn tcp() -> Server {
Builder::new().tcp()
}
impl Server {
fn new(server_config: server::Config, receive_config: receive::Config) -> Self {
let (tx, rx) = crossbeam_channel::unbounded();
let received = Arc::new(Mutex::new(0));
let mut server = server::build(
server_config,
{
let mut receive = receive::build(receive_config);
move |src| receive.decode(src)
},
{
let process = process::build(process::Config {
..Default::default()
});
let received = received.clone();
move |msg| {
*(received.lock().expect("poisoned lock")) += 1;
process.with_clef(msg, |clef| {
let json = serde_json::to_value(clef)?;
tx.send(json)?;
Ok(())
})
}
},
)
.expect("failed to build server");
let handle = server.take_handle().expect("no server handle");
let server = thread::spawn(move || server.run().expect("failed to run server"));
// Wait for the server to become available
thread::sleep(Duration::from_secs(1));
Server {
handle,
server,
rx,
received,
}
}
pub fn received(&mut self) -> usize {
*(self.received.lock().expect("poisoned lock"))
}
pub fn receive(&mut self, f: impl FnOnce(Value)) {
let msg = self
.rx
.recv_timeout(Duration::from_secs(3))
.expect("failed to receive a message");
f(msg)
}
pub fn close(self) {
self.handle.close();
self.server.join().expect("failed to run server");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.