text
stringlengths
8
4.13M
fn fib(z:&i32){ let mut a:i32 = 0; let mut b:i32 = 1; let mut c:i32 = 0; println!("{} \n{}",&a,&b); for _g in 0..*z-2{ c = a+b; print!("{} \n",c); a=b; b=c; } } fn main(){ let x:i32 = 10; fib(&x); }
use flatc_rust; use std::path::Path; fn main() { //let out_dir = env::var("OUT_DIR").unwrap(); let out_dir = "target"; let out_path = format!("{}/a19_data_persist/message/", out_dir); println!( "{}", format!( "cargo:rerun-if-changed={}/a19_data_persist/message/persisted_file.fbs", out_dir ) ); flatc_rust::run(flatc_rust::Args { inputs: &[Path::new("flat_buffers/persisted_file.fbs")], out_dir: Path::new(&out_path), ..Default::default() }) .expect("flatc"); }
// Hack of a crate until rust-lang/rust#51647 is fixed #![feature(no_core, panic_implementation)] #![no_core] extern crate core; #[panic_implementation] fn panic(_: &core::panic::PanicInfo) -> ! { loop {} }
use async_trait::async_trait; use serde::{Deserialize, Serialize}; use uuid::Uuid; pub type ObjectId = Uuid; #[async_trait] pub trait PersistenceManager { type Error: Send + Sync; async fn get_by_id<T>(&'async_trait self, id: ObjectId) -> Result<T, Self::Error> where T: Persistent + Deserialize<'async_trait>; async fn save<T>(&mut self, object: &T) -> Result<(), Self::Error> where T: Persistent + Serialize; } pub trait Persistent: Send + Sync { fn id(&self) -> ObjectId; } #[cfg(test)] mod tests { use std::collections::HashMap; use serde_derive::{Deserialize, Serialize}; use serde_json; use crate::*; #[derive(Deserialize, Serialize)] struct Widget { id: ObjectId, pub value: u32, } impl Widget { fn new(value: u32) -> Self { Self { id: ObjectId::new_v4(), value, } } } impl Persistent for Widget { fn id(&self) -> ObjectId { self.id } } #[derive(Deserialize, Serialize)] struct Thingy { id: ObjectId, pub value: String, } impl Thingy { fn new<S>(value: S) -> Self where S: ToString, { Self { id: ObjectId::new_v4(), value: value.to_string(), } } } impl Persistent for Thingy { fn id(&self) -> ObjectId { self.id } } struct TransientPersistence { objects: HashMap<ObjectId, String>, } impl TransientPersistence { fn new() -> Self { Self { objects: HashMap::new(), } } } #[derive(Debug)] enum TransientError { NoObject, BadObject, } impl std::fmt::Display for TransientError { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { write!(f, "({:?})", self) } } impl std::error::Error for TransientError {} #[async_trait] impl PersistenceManager for TransientPersistence { type Error = TransientError; async fn get_by_id<T>(&'async_trait self, id: ObjectId) -> Result<T, Self::Error> where T: Persistent + Deserialize<'async_trait>, { let json = match self.objects.get(&id) { Some(s) => s, None => return Err(TransientError::NoObject), }; serde_json::from_str(json).map_err(|_| TransientError::BadObject) } async fn save<T>(&mut self, object: &T) -> Result<(), Self::Error> where T: Persistent + Serialize, { let json = serde_json::to_string(object).map_err(|_| TransientError::BadObject)?; self.objects.insert(object.id(), json); Ok(()) } } #[async_std::test] async fn test_widget() -> Result<(), TransientError> { let mut persistence = TransientPersistence::new(); let widget = Widget::new(23); persistence.save(&widget).await?; let w2: Widget = persistence.get_by_id(widget.id()).await?; assert_eq!(widget.id(), w2.id()); assert_eq!(widget.value, w2.value); Ok(()) } #[async_std::test] async fn test_thingy() -> Result<(), TransientError> { let mut persistence = TransientPersistence::new(); let thingy = Thingy::new("twenty-three"); persistence.save(&thingy).await?; let t2: Thingy = persistence.get_by_id(thingy.id()).await?; assert_eq!(thingy.id(), t2.id()); assert_eq!(thingy.value, t2.value); Ok(()) } #[async_std::test] async fn test_widget_and_thingy() -> Result<(), TransientError> { let mut persistence = TransientPersistence::new(); let widget = Widget::new(23); let thingy = Thingy::new("twenty-three"); persistence.save(&widget).await?; persistence.save(&thingy).await?; let w2: Widget = persistence.get_by_id(widget.id()).await?; let t2: Thingy = persistence.get_by_id(thingy.id()).await?; assert_eq!(widget.id(), w2.id()); assert_eq!(widget.value, w2.value); assert_eq!(thingy.id(), t2.id()); assert_eq!(thingy.value, t2.value); Ok(()) } }
use async_std::net::{SocketAddr, ToSocketAddrs}; use async_std::task; use regex::Regex; pub trait ToPqConfig { fn to_pq_config(&self) -> Result<PqConfig, ConfParseError>; } #[derive(Debug)] pub struct PqConfig { pub address: SocketAddr, pub cred: Option<Credential>, pub dbname: Option<String>, } #[derive(Debug)] pub enum Credential { UserPass(String, Option<String>), } #[derive(Debug)] pub enum ConfParseError { // when parsing hostname / ip address port pair into socket address ResolveError(std::io::Error), // parsing successful but no host from iterator NoHost, } use std::fmt; impl fmt::Display for ConfParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Error when parsing configuration") } } impl std::error::Error for ConfParseError {} impl ToPqConfig for &str { // valid str // postgresql:// // postgresql:///mydb // postgresql://localhost // postgresql://localhost:5433 // postgresql://localhost/mydb // postgresql://user@localhost // postgresql://user:secret@localhost // postgresql://other@localhost/otherdb fn to_pq_config(&self) -> Result<PqConfig, ConfParseError> { lazy_static! { static ref RE: Regex = Regex::new(r#"^postgresql://([^@]+@)?([^/]+)?(/[\w]+)?$"#).unwrap(); } let captures = RE.captures(self).unwrap(); // resolve host and port into socket address let mut host_port = captures .get(2) .map(|c| c.as_str()) .unwrap_or("127.0.0.1:5432") .split(":"); let host = host_port.next().unwrap(); let port = host_port.next().unwrap_or("5432"); let socket: SocketAddr = task::block_on(async { let mut h = format!("{}:{}", host, port) .to_socket_addrs() .await .map_err(|e| ConfParseError::ResolveError(e))?; h.next().ok_or(ConfParseError::NoHost) })?; let cred = captures.get(1).map(|c| { let c = c.as_str(); let mut split = c[..c.len() - 1].split(":"); Credential::UserPass( split.next().unwrap().to_string(), split.next().map(String::from), ) }); let dbname = captures.get(3).map(|c| String::from(&c.as_str()[1..])); Ok(PqConfig { address: socket, cred, dbname, }) } } #[cfg(test)] mod tests { use super::*; use async_std::net::{Ipv4Addr, Ipv6Addr}; #[test] fn test_parse_default() { let conf = "postgresql://".to_pq_config().unwrap(); assert_eq!("127.0.0.1".parse::<Ipv4Addr>().unwrap(), conf.address.ip()); assert_eq!(5432, conf.address.port()); assert!(conf.cred.is_none()); assert!(conf.dbname.is_none()); } #[test] fn test_parse_no_host() { let conf = "postgresql:///mydb".to_pq_config().unwrap(); assert_eq!("127.0.0.1".parse::<Ipv4Addr>().unwrap(), conf.address.ip()); assert_eq!(5432, conf.address.port()); assert!(conf.cred.is_none()); assert_eq!("mydb", conf.dbname.unwrap()); } #[test] fn test_parse_single_host() { let conf = "postgresql://localhost".to_pq_config().unwrap(); assert_eq!("::1".parse::<Ipv6Addr>().unwrap(), conf.address.ip()); assert_eq!(5432, conf.address.port()); assert!(conf.cred.is_none()); assert!(conf.dbname.is_none()) } #[test] fn test_parse_host_with_port() { let conf = "postgresql://localhost:1123".to_pq_config().unwrap(); assert_eq!("::1".parse::<Ipv6Addr>().unwrap(), conf.address.ip()); assert_eq!(1123, conf.address.port()); assert!(conf.cred.is_none()); assert!(conf.dbname.is_none()) } #[test] fn test_parse_host_db() { let conf = "postgresql://localhost/mydb".to_pq_config().unwrap(); assert_eq!("::1".parse::<Ipv6Addr>().unwrap(), conf.address.ip()); assert_eq!(5432, conf.address.port()); assert!(conf.cred.is_none()); assert_eq!("mydb", conf.dbname.unwrap()); } #[test] fn test_parse_host_user() { let conf = "postgresql://user@localhost".to_pq_config().unwrap(); assert_eq!("::1".parse::<Ipv6Addr>().unwrap(), conf.address.ip()); assert_eq!(5432, conf.address.port()); match conf.cred { None => panic!("Should not be none"), Some(Credential::UserPass(user, pass)) => { assert_eq!("user", user); assert!(pass.is_none()); } } assert!(conf.dbname.is_none()) } #[test] fn test_parse_host_user_pass() { let conf = "postgresql://user:secret@localhost".to_pq_config().unwrap(); assert_eq!("::1".parse::<Ipv6Addr>().unwrap(), conf.address.ip()); assert_eq!(5432, conf.address.port()); match conf.cred { None => panic!("Should not be none"), Some(Credential::UserPass(user, pass)) => { assert_eq!("user", user); assert_eq!("secret", pass.unwrap()); } } assert!(conf.dbname.is_none()) } #[test] fn test_parse_complete() { let conf = "postgresql://user2:s3cret@33.3.1.1:3223/mydb" .to_pq_config() .unwrap(); assert_eq!("33.3.1.1".parse::<Ipv4Addr>().unwrap(), conf.address.ip()); assert_eq!(3223, conf.address.port()); match conf.cred { None => panic!("Should not be none"), Some(Credential::UserPass(user, pass)) => { assert_eq!("user2", user); assert_eq!("s3cret", pass.unwrap()); } } assert_eq!("mydb", conf.dbname.unwrap()); } }
use rustlearn::ownership_demo::{complex_ownership_demo, simple_ownership_demo}; #[macro_use] extern crate rustlearn; fn main() { let value = fmt!(100); println!("{}", value); simple_ownership_demo::simple_borrow_test(); simple_ownership_demo::clone_copy_test(); complex_ownership_demo::borrow_func_test(); complex_ownership_demo::slice_test(); complex_ownership_demo::andstr_test(); }
use std::fmt::Debug; use serde::{Serialize,Deserialize}; pub fn parse_array<T:Copy+Serialize>(data:&[Vec<Option<T>>]) -> Result<Vec<Metadata<T>>, Error>{ if data.len() == 0 { return Err(Error(String::from("数组高度不得为0"))) } let mut size = 0; for y in data { for _ in y { size += 1; } } let mut res = Vec::with_capacity(size+1); res.push(Metadata::Head {y:data.len(),x:data.get(0).unwrap().len(),size}); let width = data[0].len(); for y in 0..data.len() { if data[y].len() != width { return Err(Error(String::from("数组宽度必须一致"))) } for x in 0..data[y].len() { if let Some(value) = data[y][x] { res.push(Metadata::Info(ArrInfo::new(x,y,value))); } } } Ok(res) } pub fn reset<T:Copy+Serialize>(res:&Vec<Metadata<T>>) -> Result<Vec<Vec<Option<T>>>,Error>{ if let Metadata::Head{x,y,size:_} = res.get(0).unwrap(){ let mut data:Vec<Vec<Option<T>>> = vec![vec![Option::None;*x];*y]; for i in 1..res.len() { match res.get(i).unwrap() { Metadata::Info(info) => { data[info.y][info.x] = Some(info.value); }, _ => () } } return Ok(data); } Err(Error(String::from("数据不正确"))) } #[derive(Debug,Serialize,Deserialize)] pub enum Metadata<T:Copy+Serialize>{ Head{ x:usize, y:usize, size:usize }, Info(ArrInfo<T>) } #[derive(Debug,Serialize,Deserialize)] pub struct ArrInfo<T:Copy+Serialize>{ x:usize, y:usize, value:T } impl <T:Copy+Serialize> ArrInfo<T>{ fn new(x:usize,y:usize,value:T) -> ArrInfo<T>{ ArrInfo{x,y,value} } } #[derive(Debug)] pub struct Error(String); use std::fs::File; use serde::de::DeserializeOwned; pub fn serialize<T:Copy+Serialize>(file:File,res:&Vec<Metadata<T>>) { serde_json::to_writer(file,res).unwrap(); } pub fn deserialize<T: DeserializeOwned>(file:File) -> T{ return serde_json::from_reader(file).unwrap(); } #[cfg(test)] mod test{ use super::*; #[test] fn test() { let row1 = vec![None,None,None,None,Some(12),None,None]; let row2 = vec![None,None,Some(14),None,Some(18),None,None]; let row3 = vec![None,Some(17),None,Some(56),None,Some(4),None]; let data = [row1,row2,row3]; //压缩 let res = parse_array(&data).unwrap(); //序列化到文件 serialize(File::create("test.txt").unwrap(),&res); //反序列化 let aaa:Vec<Metadata<i32>> = deserialize(File::open("test.txt").unwrap()); //解压 println!("{:?}",reset(&aaa).unwrap()); } }
use std::mem; use std::ptr; use messages::Message; use storage::StorageValue; use libc::{c_char, size_t}; use assets::AssetBundle; use capi::common::*; use transactions::exchange::{ExchangeOfferWrapper, ExchangeWrapper}; use error::{Error, ErrorKind}; ffi_fn! { fn dmbc_exchange_offer_create( sender_public_key: *const c_char, sender_value: u64, recipient_public_key: *const c_char, fee_strategy: u8, seed: u64, memo: *const c_char, error: *mut Error, ) -> *mut ExchangeOfferWrapper { let sender_key = match parse_public_key(sender_public_key) { Ok(public_key) => public_key, Err(err) => { unsafe { if !error.is_null() { *error = err; } return ptr::null_mut(); } } }; let recipient_key = match parse_public_key(recipient_public_key) { Ok(public_key) => public_key, Err(err) => { unsafe { if !error.is_null() { *error = err; } return ptr::null_mut(); } } }; let memo = match parse_str(memo) { Ok(memo) => memo, Err(err) => { unsafe { if !error.is_null() { *error = err; } return ptr::null_mut(); } } }; let wrapper = ExchangeOfferWrapper::new(&sender_key, sender_value, &recipient_key, fee_strategy, seed, memo); Box::into_raw(Box::new(wrapper)) } } ffi_fn! { fn dmbc_exchange_offer_free(wrapper: *const ExchangeOfferWrapper) { if !wrapper.is_null() { unsafe { Box::from_raw(wrapper as *mut ExchangeOfferWrapper); } } } } ffi_fn! { fn dmbc_exchange_offer_recipient_add_asset( wrapper: *mut ExchangeOfferWrapper, asset: *mut AssetBundle, error: *mut Error, ) -> bool { let wrapper = match ExchangeOfferWrapper::from_ptr(wrapper) { Ok(wrapper) => wrapper, Err(err) => { unsafe { if !error.is_null() { *error = err; } return false; } } }; if asset.is_null() { unsafe { if !error.is_null() { *error = Error::new(ErrorKind::Text("Invalid asset pointer.".to_string())); } return false; } } let asset = AssetBundle::from_ptr(asset); wrapper.add_recipient_asset(asset.clone()); true } } ffi_fn! { fn dmbc_exchange_offer_sender_add_asset( wrapper: *mut ExchangeOfferWrapper, asset: *mut AssetBundle, error: *mut Error, ) -> bool { let wrapper = match ExchangeOfferWrapper::from_ptr(wrapper) { Ok(wrapper) => wrapper, Err(err) => { unsafe { if !error.is_null() { *error = err; } return false; } } }; if asset.is_null() { unsafe { if !error.is_null() { *error = Error::new(ErrorKind::Text("Invalid asset pointer.".to_string())); } return false; } } let asset = AssetBundle::from_ptr(asset); wrapper.add_sender_asset(asset.clone()); true } } ffi_fn! { fn dmbc_exchange_offer_into_bytes( wrapper: *mut ExchangeOfferWrapper, length: *mut size_t, error: *mut Error ) -> *const u8 { let wrapper = match ExchangeOfferWrapper::from_ptr(wrapper) { Ok(wrapper) => wrapper, Err(err) => { unsafe { if !error.is_null() { *error = err; } return ptr::null(); } } }; let bytes = wrapper.unwrap().clone().into_bytes(); assert!(bytes.len() == bytes.capacity()); let length = unsafe { &mut *length }; let len = bytes.len() as size_t; *length = len; let ptr = bytes.as_ptr(); mem::forget(bytes); ptr } } ffi_fn! { fn dmbc_tx_exchange_create( wrapper: *mut ExchangeOfferWrapper, signature: *const c_char, error: *mut Error, ) -> *mut ExchangeWrapper { let wrapper = match ExchangeOfferWrapper::from_ptr(wrapper) { Ok(wrapper) => wrapper, Err(err) => { unsafe { if !error.is_null() { *error = err; } return ptr::null_mut(); } } }; let signature = match parse_signature(signature) { Ok(sig) => sig, Err(err) => { unsafe { if !error.is_null() { *error = err; } return ptr::null_mut(); } } }; let wrapper = wrapper.unwrap().clone(); let tx = ExchangeWrapper::new(wrapper, &signature); Box::into_raw(Box::new(tx)) } } ffi_fn! { fn dmbc_tx_exchange_free(wrapper: *const ExchangeWrapper) { if !wrapper.is_null() { unsafe { Box::from_raw(wrapper as *mut ExchangeWrapper); } } } } ffi_fn! { fn dmbc_tx_exchange_into_bytes( wrapper: *mut ExchangeWrapper, length: *mut size_t, error: *mut Error ) -> *const u8 { let wrapper = match ExchangeWrapper::from_ptr(wrapper) { Ok(wrapper) => wrapper, Err(err) => { unsafe { if !error.is_null() { *error = err; } return ptr::null(); } } }; let bytes = wrapper.unwrap().raw().body().to_vec(); assert!(bytes.len() == bytes.capacity()); let length = unsafe { &mut *length }; let len = bytes.len() as size_t; *length = len; let ptr = bytes.as_ptr(); mem::forget(bytes); ptr } }
#![feature(async_await)] use async_std::{io, task}; use async_trait::async_trait; use h1::{Handler, Params, Request, Response, H1}; pub struct PlaintextRoute; #[async_trait] impl Handler for PlaintextRoute { async fn call(&self, _request: Request<'_>, _params: Params<'_>) -> io::Result<Response> { let mut resp = Response::default(); resp.header("Content-Type", "text/plain") .body("Hello, World!"); Ok(resp) } } pub struct JsonRoute; #[async_trait] impl Handler for JsonRoute { async fn call(&self, _request: Request<'_>, _params: Params<'_>) -> io::Result<Response> { let mut resp = Response::default(); let json = serde_json::to_string(&serde_json::json!({ "message": "Hello, World!" })) .unwrap(); resp.header("Content-Type", "application/json").body(&json); Ok(resp) } } fn main() -> io::Result<()> { task::block_on(async { let app = H1::default() .get("/json", JsonRoute) .get("/plaintext", PlaintextRoute) .listen("localhost:3000") .await?; println!("Listening on http://localhost:3000"); app.run().await?; Ok(()) }) }
use lexer::Lexer; use lexer::Token; use parser::ParseNode; use parser::Type; use parser::GrammarItem; use errors::error_index::{Error}; pub type ParseError = Error; pub type ParseResult = Result<ParseNode, ParseError>; pub struct Parser<'a>{ lexer: Lexer<'a> } impl<'a> Parser<'a>{ pub fn new(input: Lexer<'a>) -> Parser<'a>{ Parser { lexer: input } } pub fn reset_lexer(&mut self){ self.lexer.reset(); } pub fn parse(&mut self) -> ParseResult{ let mut assignments: Vec<ParseNode> = Vec::new(); while let Ok(assign) = self.parse_toplevel_assignment() { assignments.push(assign); } let tok = self.lexer.next_token(); match tok { Token::EOF => Ok(ParseNode::new( GrammarItem::Program(assignments), Type::Unknown )), _ => Err(Error::ExpectedEOF(tok)) } /* self.parse_toplevel_assignment().and_then( |x| match self.lexer.next_token() { Token::EOF => Ok(x), _ => Err(0) //Expected EOF } ) */ } pub fn parse_toplevel_assignment(&mut self) -> ParseResult{ let tok = self.lexer.next_token(); match tok { Token::LIdent(id) => { self.consume(Token::Assign)?; self.parse_expr().and_then( |expr| Ok(ParseNode::new( GrammarItem::Assignment(id, Box::new(expr)), Type::Unknown )), ) }, _ => Err(Error::ExpectedToken(Token::LIdent("".to_string()), tok)) } } pub fn parse_expr(&mut self) -> ParseResult{ self.parse_base_expr().and_then( |expr| self.parse_expr_prime(expr) ) } pub fn is_empty(&mut self) -> bool { self.lexer.is_empty() } fn parse_base_expr(&mut self) -> ParseResult{ let tok = self.lexer.next_token(); match tok { Token::LParen => self.parse_paren_expr(), Token::LIdent(id) => self.parse_identifier_expr(id), Token::Integer(s) => self.parse_literal_int(s), Token::Backslash => self.parse_abstraction_expr(), Token::Illegal => Err(Error::IllegalToken(tok)), Token::EOF => Err(Error::UnexpectedEOF), _ => { self.lexer.put_back(tok.clone()); Err(Error::IllegalToken(tok)) } } } fn parse_paren_expr(&mut self) -> ParseResult{ self.parse_expr().and_then( |expr| { let tok = self.lexer.next_token(); match tok { Token::RParen => Ok(expr), _ => Err(Error::ExpectedToken(Token::RParen, tok)) } } ) } fn parse_literal_int(&mut self, num_string: String) -> ParseResult{ match num_string.parse() { Ok(num) => Ok(ParseNode::new(GrammarItem::LiteralInt(num), Type::Unknown)), Err(_) => Err(Error::IntegerParseError) } } fn parse_identifier_expr(&mut self, id: String) -> ParseResult{ Ok(ParseNode::new(GrammarItem::Variable(id), Type::Unknown)) } fn parse_abstraction_expr(&mut self) -> ParseResult{ let tok = self.lexer.next_token(); match tok { Token::LIdent(id) => { let t = self.parse_type()?; self.consume(Token::Dot)?; self.parse_expr().and_then( |expr| Ok(ParseNode::new( GrammarItem::Abstraction(id, Box::new(expr)), t)) ) } _ => Err(Error::ExpectedToken(Token::LIdent("".to_string()), tok)) //Expected identifier } } fn parse_type(&mut self) -> Result<Type, ParseError> { Ok(Type::Unknown) } fn parse_expr_prime(&mut self, left: ParseNode) -> ParseResult{ let tok = self.lexer.next_token(); match tok { Token::LParen | Token::Backslash | Token::LIdent(_) | Token::Integer(_) => { self.lexer.put_back(tok); self.parse_base_expr().and_then( |expr| self.parse_expr_prime(ParseNode::new( GrammarItem::Application(Box::new(left), Box::new(expr)), Type::Unknown )) ) }, _ => { self.lexer.put_back(tok); Ok(left) } } } fn consume(&mut self, tok : Token) -> Result<Token, ParseError> { let new_tok = self.lexer.next_token(); if new_tok == tok { Ok(new_tok) } else { Err(Error::ExpectedToken(tok, new_tok)) } } } /* * expr * : ID expr' * | (expr) expr' * | \ID (: Type)? . expr expr' * * expr' * : expr expr' * | $ */ #[test] fn parse_variable(){ let input = r#"a"#; let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let node = parser.parse_expr(); assert_eq!(Ok(ParseNode::new( GrammarItem::Variable("a".to_string()), Type::Unknown )), node); } #[test] fn parse_literal_int(){ let input = r#"1234567890"#; let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let node = parser.parse_expr(); assert_eq!(Ok(ParseNode::new( GrammarItem::LiteralInt(1234567890), Type::Unknown )), node); } #[test] fn parse_expr_test_application(){ let input = r#"a b c"#; let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let node = parser.parse_expr(); assert_eq!(Ok(ParseNode::new( GrammarItem::Application( Box::new(ParseNode::new( GrammarItem::Application( Box::new(ParseNode::new( GrammarItem::Variable("a".to_string()), Type::Unknown )), Box::new(ParseNode::new( GrammarItem::Variable("b".to_string()), Type::Unknown )), ), Type::Unknown )), Box::new(ParseNode::new( GrammarItem::Variable("c".to_string()), Type::Unknown )) ), Type::Unknown )), node); } #[test] fn parse_expr_test_abstraction(){ let input = r#"\a. \b. a"#; let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let node = parser.parse_expr(); assert_eq!(Ok(ParseNode::new( GrammarItem::Abstraction( "a".to_string(), Box::new(ParseNode::new( GrammarItem::Abstraction( "b".to_string(), Box::new(ParseNode::new( GrammarItem::Variable("a".to_string()), Type::Unknown )) ), Type::Unknown )) ), Type::Unknown )), node); } #[test] fn parse_expr_test_paren(){ let input = r#"a (b c)"#; let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let node = parser.parse_expr(); assert_eq!(Ok(ParseNode::new( GrammarItem::Application( Box::new(ParseNode::new( GrammarItem::Variable("a".to_string()), Type::Unknown )), Box::new(ParseNode::new( GrammarItem::Application( Box::new(ParseNode::new( GrammarItem::Variable("b".to_string()), Type::Unknown )), Box::new(ParseNode::new( GrammarItem::Variable("c".to_string()), Type::Unknown )) ), Type::Unknown )) ), Type::Unknown )), node); } #[test] fn parse_expr_test_error_2(){ let input = r#"(a b"#; let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let node = parser.parse_expr(); assert_eq!(Err(Error::ExpectedToken(Token::RParen, Token::EOF)), node); } #[test] fn parse_expr_test_error_3(){ let input = r#"\. a"#; let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let node = parser.parse_expr(); assert_eq!(Err(Error::ExpectedToken(Token::LIdent("".to_string()), Token::Dot)), node); } #[test] fn parse_expr_test_error_4(){ let input = r#"\a( a"#; let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let node = parser.parse_expr(); assert_eq!(Err(Error::ExpectedToken(Token::Dot, Token::LParen)), node); } #[test] fn parse_expr_test_error_5(){ let input = r#"$"#; let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let node = parser.parse_expr(); assert_eq!(Err(Error::IllegalToken(Token::Illegal)), node); } #[test] fn parse_expr_test_error_6(){ let input = r#"\a. "#; let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let node = parser.parse_expr(); assert_eq!(Err(Error::UnexpectedEOF), node); }
#![no_std] #![no_main] #![feature(isa_attribute)] use gba::prelude::*; const BLACK: Color = Color::from_rgb(0, 0, 0); const RED: Color = Color::from_rgb(31, 0, 0); const GREEN: Color = Color::from_rgb(0, 31, 0); const BLUE: Color = Color::from_rgb(0, 0, 31); const YELLOW: Color = Color::from_rgb(31, 31, 0); const PINK: Color = Color::from_rgb(31, 0, 31); #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } fn start_timers() { let init_val: u16 = u32::wrapping_sub(0x1_0000, 64) as u16; const TIMER_SETTINGS: TimerControl = TimerControl::new().with_irq_on_overflow(true).with_enabled(true); TIMER0_RELOAD.write(init_val); TIMER0_CONTROL.write(TIMER_SETTINGS.with_prescaler_selection(3)); TIMER1_RELOAD.write(init_val); TIMER1_CONTROL.write(TIMER_SETTINGS.with_prescaler_selection(1)); } #[no_mangle] fn main() -> ! { DISPCNT.write(DisplayControl::new().with_display_mode(3).with_display_bg2(true)); mode3::dma3_clear_to(BLACK); // Set the IRQ handler to use. unsafe { USER_IRQ_HANDLER.write(Some(irq_handler_a32)) }; // Enable all interrupts that are set in the IE register. unsafe { IME.write(true) }; // Request that VBlank, HBlank and VCount will generate IRQs. const DISPLAY_SETTINGS: DisplayStatus = DisplayStatus::new() .with_vblank_irq_enabled(true) .with_hblank_irq_enabled(true) .with_vcount_irq_enabled(true); DISPSTAT.write(DISPLAY_SETTINGS); // Start two timers with overflow IRQ generation. start_timers(); loop { let this_frame_keys: Keys = KEYINPUT.read().into(); // The VBlank IRQ must be enabled at minimum, or else the CPU will halt // at the call to vblank_interrupt_wait() as the VBlank IRQ will never // be triggered. let mut flags = InterruptFlags::new().with_vblank(true); // Enable interrupts based on key input. if this_frame_keys.a() { flags = flags.with_hblank(true); } if this_frame_keys.b() { flags = flags.with_vcount(true); } if this_frame_keys.l() { flags = flags.with_timer0(true); } if this_frame_keys.r() { flags = flags.with_timer1(true); } unsafe { IE.write(flags) }; // Puts the CPU into low power mode until a VBlank IRQ is received. This // will yield considerably better power efficiency as opposed to spin // waiting. unsafe { VBlankIntrWait() }; } } static mut PIXEL: usize = 0; fn write_pixel(color: Color) { unsafe { (0x0600_0000 as *mut Color).wrapping_offset(PIXEL as isize).write_volatile(color); PIXEL += 1; if PIXEL == (mode3::WIDTH * mode3::HEIGHT) { PIXEL = 0; } } } #[instruction_set(arm::a32)] extern "C" fn irq_handler_a32() { // we just use this a32 function to jump over back to t32 code. irq_handler_t32() } fn irq_handler_t32() { // disable Interrupt Master Enable to prevent an interrupt during the handler unsafe { IME.write(false) }; // read which interrupts are pending, and "filter" the selection by which are // supposed to be enabled. let which_interrupts_to_handle = IRQ_PENDING.read() & IE.read(); // read the current IntrWait value. It sorta works like a running total, so // any interrupts we process we'll enable in this value, which we write back // at the end. let mut intr_wait_flags = INTR_WAIT_ACKNOWLEDGE.read(); if which_interrupts_to_handle.vblank() { vblank_handler(); intr_wait_flags.set_vblank(true); } if which_interrupts_to_handle.hblank() { hblank_handler(); intr_wait_flags.set_hblank(true); } if which_interrupts_to_handle.vcount() { vcount_handler(); intr_wait_flags.set_vcount(true); } if which_interrupts_to_handle.timer0() { timer0_handler(); intr_wait_flags.set_timer0(true); } if which_interrupts_to_handle.timer1() { timer1_handler(); intr_wait_flags.set_timer1(true); } // acknowledge that we did stuff. IRQ_ACKNOWLEDGE.write(which_interrupts_to_handle); // write out any IntrWait changes. unsafe { INTR_WAIT_ACKNOWLEDGE.write(intr_wait_flags) }; // re-enable as we go out. unsafe { IME.write(true) }; } fn vblank_handler() { write_pixel(BLUE); } fn hblank_handler() { write_pixel(GREEN); } fn vcount_handler() { write_pixel(RED); } fn timer0_handler() { write_pixel(YELLOW); } fn timer1_handler() { write_pixel(PINK); }
use aoc::*; fn main() -> Result<()> { let mut ip = 0; let mut mem: Vec<usize> = input("2.txt")? .split(',') .map(|s| s.parse().unwrap()) .collect(); mem[1] = 12; mem[2] = 2; loop { match mem[ip] { 1 => { let dst = mem[ip + 3]; mem[dst] = mem[mem[ip + 1]] + mem[mem[ip + 2]]; ip += 4; } 2 => { let dst = mem[ip + 3]; mem[dst] = mem[mem[ip + 1]] * mem[mem[ip + 2]]; ip += 4; } 99 => break, _ => unreachable!(), } } Ok(println!("ip: {} mem: {:?}", ip, mem)) }
/// Register numbers used in bytecode operations have different meaning according to their ranges: /// 0x80000000-0xFFFFFFFF Negative indices from the CallFrame pointer are entries in the call frame. /// 0x00000000-0x3FFFFFFF Forwards indices from the CallFrame pointer are local vars and temporaries with the function's callframe. /// 0x40000000-0x7FFFFFFF Positive indices from 0x40000000 specify entries in the constant pool on the CodeBlock. pub const FIRST_CONSTANT_REGISTER_INDEX: i32 = 0x4000000; pub const FIRST_CONSTANT_REGISTER_INDEX8: i32 = 16; pub const FIRST_CONSTANT_REGISTER_INDEX16: i32 = 64; pub const FIRST_CONSTANT_REGISTER_INDEX32: i32 = FIRST_CONSTANT_REGISTER_INDEX; pub const fn is_local(operand: i32) -> bool { operand < 0 } pub const fn is_argument(operand: i32) -> bool { operand >= 0 } #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] pub struct VirtualRegister { pub virtual_register: i32, } impl VirtualRegister { pub const INVALID: VirtualRegister = VirtualRegister { virtual_register: 0x3fffffff, }; const fn local_to_operand(local: i32) -> i32 { -1 - local } const fn operand_to_local(operand: i32) -> i32 { -1 - operand } const fn operand_to_argument(operand: i32) -> i32 { operand } const fn argument_to_operand(arg: i32) -> i32 { arg } pub const fn offset(self) -> i32 { self.virtual_register } pub const fn offset_in_bytes(self) -> i32 { self.virtual_register * 8 } pub const fn to_local(self) -> i32 { Self::operand_to_local(self.virtual_register) } pub const fn to_argument(self) -> i32 { Self::operand_to_argument(self.virtual_register) } pub const fn new_constant_index(i: i32) -> Self { Self { virtual_register: i + FIRST_CONSTANT_REGISTER_INDEX, } } pub fn new_argument(i: i32) -> Self { Self { virtual_register: i, } } pub const fn to_constant_index(self) -> i32 { self.virtual_register - FIRST_CONSTANT_REGISTER_INDEX } pub const fn is_valid(self) -> bool { self.virtual_register != Self::INVALID.virtual_register } pub const fn is_local(self) -> bool { is_local(self.virtual_register) } pub const fn is_argument(self) -> bool { is_argument(self.virtual_register) } pub const fn is_constant(self) -> bool { self.virtual_register >= FIRST_CONSTANT_REGISTER_INDEX } } #[inline(always)] pub const fn virtual_register_for_local(local: i32) -> VirtualRegister { return VirtualRegister { virtual_register: VirtualRegister::local_to_operand(local), }; } #[inline(always)] pub const fn virtual_register_for_argument_including_this( argument: i32, offset: i32, ) -> VirtualRegister { VirtualRegister { virtual_register: VirtualRegister::argument_to_operand(argument) + offset, } } use std::fmt; impl fmt::Display for VirtualRegister { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if !self.is_valid() { return write!(f, "<invalid>"); } if self.is_constant() { return write!(f, "const{}", self.to_constant_index()); } if self.is_argument() { return write!(f, "arg{}", self.to_argument()); } write!(f, "loc{}", self.to_local()) } } impl fmt::Debug for VirtualRegister { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self) } }
let joao = Funcionario { nome : "João", salario : 1000 }; //https://pt.stackoverflow.com/q/347484/101
use std::cell::{RefCell, RefMut}; use std::fmt; use std::mem; use std::ptr; use alloc::rc::Rc; use kernel_std::cpu::stack::Stack; #[derive(Debug, Clone, Copy)] pub enum Context { Empty, Kernel { // SYSV callee-saved registers rip: u64, rbx: u64, rsp: u64, rbp: u64, r12: u64, r13: u64, r14: u64, r15: u64 }, Spawn { // relevant stack frame and execution location entry: u64, stack: u64, // the arguments we want to pass arguments: SpawnArgs } } #[derive(Debug, Clone, Copy)] pub struct SpawnArgs { task: *mut RefCell<TaskInner>, previous: *mut RefCell<TaskInner>, entry: extern fn(current: Task) -> ! } #[derive(Debug)] pub struct LoadHook<'a> { outer: RefMut<'a, TaskInner>, inner: RefMut<'a, TaskInner> } #[derive(Debug)] pub struct Task { inner: Rc<RefCell<TaskInner>>, previous: Handle } #[derive(Debug)] pub struct Handle { inner: Rc<RefCell<TaskInner>> } struct TaskInner { context: Context, entry: extern fn(current: Task) -> !, stack: Stack } impl fmt::Debug for TaskInner { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "TaskInner {{ context: {:?}, entry: 0x{:x}, stack: {:?} }}", self.context, self.entry as u64, self.stack) } } #[no_mangle] pub unsafe extern "C" fn load_context(hook: *mut LoadHook) -> ! { // copy the info we need out of the hook object let hook = ptr::read(hook); // copy out the context to the stack let context = hook.inner.context; // unlock the locks held while saving the context mem::drop(hook); if let Context::Kernel { ref rip, ref rbx, ref rsp, ref rbp, ref r12, ref r13, ref r14, ref r15 } = context { // clobbers is ommitted below to avoid generating code to save registers that we already saved asm!(concat!( "mov rbx, $0;", "mov rsp, $1;", "mov rbp, $2;", "mov r12, $3;", "mov r13, $4;", "mov r14, $5;", "mov r15, $6;", "jmp $7" ) :: "*m"(rbx), "*m"(rsp), "*m"(rbp), "*m"(r12), "*m"(r13), "*m"(r14), "*m"(r15), "*m"(rip) :: "intel", "volatile"); } else if let Context::Spawn { ref entry, ref stack, ref arguments } = context { // clobbers is ommitted below to avoid generating code to save registers that we already saved asm!(concat!( "mov rdi, $0;", "mov rsi, $1;", "push 0x0;", // simulate a function call "jmp $2" ) :: "m"(arguments), "*m"(stack), "*m"(entry) :: "intel", "volatile"); } else { panic!("load_context called with non-kernel task!"); } unreachable!("returned from context switch"); } extern fn empty_entry(_: Task) -> ! { unreachable!("Empty entry called"); } unsafe extern fn spawn_entry(args: *const SpawnArgs) { let args = args.as_ref().unwrap(); let task = Task { inner: Rc::from_raw(args.task), previous: Handle { inner: Rc::from_raw(args.previous) } }; (args.entry)(task) } fn switch(mut hook: LoadHook) { // save our context and execute the other task match hook.outer.context { Context::Empty | Context::Spawn { .. } => { hook.outer.context = Context::Kernel { rip: 0, rbx: 0, rsp: 0, rbp: 0, r12: 0, r13: 0, r14: 0, r15: 0 }; } _ => {} } unsafe { // What we're doing doesn't violate borrowing rules because we only use the // mutable references to the context fields before calling load_context. let hook_ptr = &mut hook as *mut _; if let Context::Kernel { ref mut rip, ref mut rbx, ref mut rsp, ref mut rbp, ref mut r12, ref mut r13, ref mut r14, ref mut r15 } = hook.outer.context { asm!(concat!( "mov $0, rbx;", "mov $1, rsp;", "mov $2, rbp;", "mov $3, r12;", "mov $4, r13;", "mov $5, r14;", "mov $6, r15;", "lea rdi, .continue;", "mov $7, rdi;", "mov rdi, $8;", "call load_context;", ".continue: nop" ) : "=*m"(rbx), "=*m"(rsp), "=*m"(rbp), "=*m"(r12), "=*m"(r13), "=*m"(r14), "=*m"(r15), "=*m"(rip) : "m"(hook_ptr) : "rdi" : "intel", "volatile"); } else { unimplemented!(); } // IMPORTANT: hook has been "moved" at this point, so forget the value // to avoid running the destructor twice. mem::forget(hook); } } impl Task { pub unsafe fn empty() -> Task { Task { inner: Rc::new(RefCell::new(TaskInner::empty())), previous: Handle { inner: Rc::new(RefCell::new(TaskInner::empty())) } } } pub fn spawn(&self, entry: extern fn(task: Task) -> !, stack: Stack) -> Handle { let stack_ptr = stack.get_ptr(); let task = Task { inner: Rc::new(RefCell::new(TaskInner { context: Context::Empty, stack: stack, entry: entry })), previous: Handle { inner: self.inner.clone() } }; let arguments = SpawnArgs { task: Rc::into_raw(task.inner.clone()), previous: Rc::into_raw(task.previous.inner.clone()), entry: entry }; let context = Context::Spawn { entry: spawn_entry as u64, stack: stack_ptr as u64, arguments: arguments }; task.inner.borrow_mut().context = context; Handle { inner: task.inner // previous is saved in the context of the Handle, to be used on spawn } } pub fn yield_back(&mut self) { // these locks need to be unlocked after the context switch let hook = LoadHook { outer: self.inner.borrow_mut(), inner: self.previous.inner.borrow_mut() }; switch(hook); } pub fn switch(&mut self, into: &mut Handle) { // these locks need to be unlocked after the context switch let hook = LoadHook { outer: self.inner.borrow_mut(), inner: into.inner.borrow_mut() }; switch(hook); } } impl TaskInner { unsafe fn empty() -> TaskInner { TaskInner { context: Context::Empty, entry: empty_entry, stack: Stack::empty() } } }
extern crate yaml_rust; use self::yaml_rust::{YamlLoader, Yaml}; use file; pub struct Configuration { pub packages: Vec<String>, pub files: Vec<file::FileResource>, pub hostname: String } impl Configuration { pub fn is_valid(&self) -> bool { let mut files_valid = true; for file_result in self.files.iter().map(|f| f.is_valid()) { if !file_result { files_valid = false; break; } } files_valid } pub fn error_messages(&self) -> Vec<String> { let mut error_messages = Vec::new(); let file_errors = self.files.iter() .flat_map(|f| f.error_messages()) .collect::<Vec<_>>(); error_messages.extend(file_errors); error_messages .iter() .map(|s| s.to_string()) .collect::<Vec<_>>() } } fn convert_yaml_string(yaml_str: &yaml_rust::yaml::Yaml) -> String { if let Some(s) = yaml_str.as_str() { s.into() } else { String::new() } } fn extract_file_resources(file_list: &yaml_rust::yaml::Yaml) -> Vec<file::FileResource> { let mut file_resources = Vec::new(); match file_list.as_vec() { Some(lst) => { file_resources = lst.iter() .map(|e| file::FileResource{ content: convert_yaml_string(e.as_hash().unwrap().get(&Yaml::from_str("content")).unwrap()), path: convert_yaml_string(e.as_hash().unwrap().get(&Yaml::from_str("path")).unwrap()) }) .collect::<Vec<_>>() } None => {} } return file_resources; } pub fn extract_hostname(document: &yaml_rust::yaml::Yaml) -> String { let doc_hash = document.as_hash().unwrap(); let keys :Vec<yaml_rust::yaml::Yaml>= doc_hash.keys().cloned().collect(); match keys.first() { Some(host_name) => host_name.as_str().unwrap().into(), None => String::new() } } pub fn from_yaml(yaml_file: String) -> Configuration { let docs = YamlLoader::load_from_str(&yaml_file).unwrap(); let doc = &docs[0]; let hostname = extract_hostname(&doc); let default_node = doc.as_hash().unwrap().get(&Yaml::from_str(&hostname[..])).unwrap(); let empty_list = Yaml::Array(Vec::new()); let package_list = default_node.as_hash().unwrap().get(&Yaml::from_str("packages")).unwrap_or(&empty_list); let file_list = default_node.as_hash().unwrap().get(&Yaml::from_str("files")).unwrap_or(&empty_list); let mut yaml_packages = Vec::new(); match package_list.as_vec() { Some(lst) => { yaml_packages = lst.iter() .map(|e| e.as_str().expect("expected string").to_string()) .collect::<Vec<_>>() }, None => { } } let file_resources = extract_file_resources(file_list); Configuration { packages: yaml_packages, files: file_resources, hostname: hostname } }
#[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, #[doc = "0x08 - control register 3"] pub cr3: CR3, #[doc = "0x0c - TAMP filter control register"] pub fltcr: FLTCR, #[doc = "0x10 - TAMP active tamper control register 1"] pub atcr1: ATCR1, #[doc = "0x14 - TAMP active tamper seed register"] pub atseedr: ATSEEDR, #[doc = "0x18 - TAMP active tamper output register"] pub ator: ATOR, #[doc = "0x1c - TAMP active tamper control register 2"] pub atcr2: ATCR2, #[doc = "0x20 - TAMP secure mode register"] pub smcr: SMCR, #[doc = "0x24 - TAMP privilege mode control register"] pub privcr: PRIVCR, _reserved10: [u8; 0x04], #[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, #[doc = "0x38 - TAMP secure masked interrupt status register"] pub smisr: SMISR, #[doc = "0x3c - TAMP status clear register"] pub scr: SCR, #[doc = "0x40 - TAMP monotonic counter register"] pub countr: COUNTR, _reserved16: [u8; 0x0c], #[doc = "0x50 - TAMP configuration register"] pub cfgr: CFGR, _reserved17: [u8; 0xac], #[doc = "0x100..0x180 - TAMP backup register"] pub bkpr: [BKPR; 32], } #[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 = "CR3 (rw) register accessor: control register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr3::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 [`cr3::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 [`cr3`] module"] pub type CR3 = crate::Reg<cr3::CR3_SPEC>; #[doc = "control register 3"] pub mod cr3; #[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 = "ATCR1 (rw) register accessor: TAMP active tamper control register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`atcr1::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 [`atcr1::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 [`atcr1`] module"] pub type ATCR1 = crate::Reg<atcr1::ATCR1_SPEC>; #[doc = "TAMP active tamper control register 1"] pub mod atcr1; #[doc = "ATSEEDR (w) register accessor: TAMP active tamper seed 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 [`atseedr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`atseedr`] module"] pub type ATSEEDR = crate::Reg<atseedr::ATSEEDR_SPEC>; #[doc = "TAMP active tamper seed register"] pub mod atseedr; #[doc = "ATOR (r) register accessor: TAMP active tamper output register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ator::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ator`] module"] pub type ATOR = crate::Reg<ator::ATOR_SPEC>; #[doc = "TAMP active tamper output register"] pub mod ator; #[doc = "ATCR2 (rw) register accessor: TAMP active tamper control register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`atcr2::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 [`atcr2::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 [`atcr2`] module"] pub type ATCR2 = crate::Reg<atcr2::ATCR2_SPEC>; #[doc = "TAMP active tamper control register 2"] pub mod atcr2; #[doc = "SMCR (rw) register accessor: TAMP secure mode register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`smcr::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 [`smcr::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 [`smcr`] module"] pub type SMCR = crate::Reg<smcr::SMCR_SPEC>; #[doc = "TAMP secure mode register"] pub mod smcr; #[doc = "PRIVCR (rw) register accessor: TAMP privilege mode control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privcr::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 [`privcr::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 [`privcr`] module"] pub type PRIVCR = crate::Reg<privcr::PRIVCR_SPEC>; #[doc = "TAMP privilege mode control register"] pub mod privcr; #[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 = "SMISR (r) register accessor: TAMP secure masked interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`smisr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`smisr`] module"] pub type SMISR = crate::Reg<smisr::SMISR_SPEC>; #[doc = "TAMP secure masked interrupt status register"] pub mod smisr; #[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 = "COUNTR (r) register accessor: TAMP monotonic counter register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`countr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`countr`] module"] pub type COUNTR = crate::Reg<countr::COUNTR_SPEC>; #[doc = "TAMP monotonic counter register"] pub mod countr; #[doc = "CFGR (rw) register accessor: TAMP configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr::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 [`cfgr::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 [`cfgr`] module"] pub type CFGR = crate::Reg<cfgr::CFGR_SPEC>; #[doc = "TAMP configuration register"] pub mod cfgr; #[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;
use core::{ffi::c_void, marker::PhantomData, mem::size_of, ptr::null_mut}; use crate::alloc::{alloc_array, Allocator}; pub(crate) struct RawArray<T, A: Allocator> { pub(crate) ptr: *mut T, pub(crate) capacity: usize, pub(crate) alloc: A, _phantom: PhantomData<T>, } impl<T, A: Allocator> RawArray<T, A> { pub(crate) fn new(alloc: A) -> Self { let capacity = if size_of::<T>() == 0 { !0 } else { 0 }; Self { ptr: null_mut(), capacity, alloc, _phantom: PhantomData {}, } } pub(crate) fn reserve(&mut self, new_capacity: usize) { if new_capacity <= self.capacity { return; } let ptr = unsafe { alloc_array::<T>(&mut self.alloc, new_capacity) .expect("Allocation error") .as_ptr() }; if self.capacity > 0 { unsafe { ptr.copy_from(self.ptr, self.capacity); self.alloc.dealloc_aligned(self.ptr as *mut c_void); } } self.ptr = ptr; self.capacity = new_capacity; } } impl<T, A: Allocator> Drop for RawArray<T, A> { fn drop(&mut self) { if !self.ptr.is_null() { unsafe { self.alloc.dealloc_aligned(self.ptr as *mut c_void); } } } }
use std::fs; fn bsp(s: &str, n_lo: i32, n_hi: i32) -> i32 { s.chars().fold((n_lo, n_hi), |(lo, hi), c| { if c == 'F' || c == 'L' { (lo, (lo+hi)/2) } else { ((lo+hi)/2+1, hi) } }).0 } fn iter_ids<'a>(input: &'a [(&str, &str)]) -> impl Iterator<Item=i32> + 'a { input.iter() .map(|&(row, col)| (bsp(row, 0, 127), bsp(col, 0, 7))) .map(|(row, col)| row*8 + col) } fn part1(input: &[(&str, &str)]) { let max_id = iter_ids(input) .max() .unwrap(); println!("{}", max_id); } fn part2(input: &[(&str, &str)]) { let mut ids: Vec<i32> = iter_ids(input).collect(); ids.sort(); let missing = ids.windows(2) .find(|&w| w[1] - w[0] == 2) .map(|w| w[0] + 1) .unwrap(); println!("{}", missing); } fn main() { let input = fs::read_to_string("input").unwrap(); let passes: Vec<(&str, &str)> = input.lines() .map(|l| (&l[..7], &l[7..])) .collect(); part1(&passes); part2(&passes); }
pub const ID_LENGTH: usize = 9; macro_rules! make_id { ($name:ident, $($firstchar:expr),+) => { #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct $name { len: u8, buf: [u8; ID_LENGTH], } impl $name { #[inline] pub fn as_str(&self) -> &str { ::std::str::from_utf8(&self.buf[..self.len as usize]).unwrap() } } // TODO: This needs to eventually be TryFrom impl<'a> From<&'a str> for $name { #[inline] fn from(input: &'a str) -> Self { assert!(input.len() <= ID_LENGTH); match input.as_bytes().get(0) { $(|Some($firstchar))* => { let mut output = Self { len: input.len() as u8, buf: [0; ID_LENGTH], }; output.buf[..input.len()].copy_from_slice(&input.as_bytes()); output } _ => { panic!(concat!("Invalid start character for ", stringify!($name))); } } } } impl<'de> ::serde::Deserialize<'de> for $name { #[inline] fn deserialize<D>(deserializer: D) -> Result<$name, D::Error> where D: ::serde::Deserializer<'de>, { struct IdVisitor; impl<'de> ::serde::de::Visitor<'de> for IdVisitor { type Value = $name; #[inline] fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { formatter.write_str(&format!("a {}-byte str", ID_LENGTH)) } #[inline] fn visit_str<E>(self, input: &str) -> Result<$name, E> where E: ::serde::de::Error, { if input.len() > ID_LENGTH || input.len() == 0 { Err(E::custom(format!( "{} must be a 1-{} byte string starting with one of {:?}, found {:?}", stringify!($name), ID_LENGTH, [$($firstchar as char,)*], input ))) } else { match input.as_bytes().get(0) { $(|Some($firstchar))* => { let mut output = $name { len: input.len() as u8, buf: [0; ID_LENGTH], }; output.buf[..input.len()].copy_from_slice(&input.as_bytes()); Ok(output) } _ => { Err(E::custom(format!( "{} must be a {}-byte string starting with one of {:?}, found {:?}", stringify!($name), ID_LENGTH, [$($firstchar as char,)*], input ))) } } } } } deserializer.deserialize_str(IdVisitor) } } impl ::serde::Serialize for $name { #[inline] fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer, { serializer.serialize_str(::std::str::from_utf8(&self.buf[..self.len as usize]).unwrap()) } } impl ::std::fmt::Display for $name { #[inline] fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!( f, "{}", ::std::str::from_utf8(&self.buf[..self.len as usize]).unwrap() ).map(|_| ()) } } impl ::std::fmt::Debug for $name { #[inline] fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "{}", self) } } }; } make_id!(BotId, b'B'); make_id!(UserId, b'U', b'W'); make_id!(ChannelId, b'C'); make_id!(GroupId, b'G'); make_id!(DmId, b'D'); make_id!(TeamId, b'T'); make_id!(AppId, b'A'); make_id!(FileId, b'F'); make_id!(UsergroupId, b'S'); make_id!(ReminderId, b'R'); #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)] #[serde(untagged)] pub enum ConversationId { Channel(ChannelId), Group(GroupId), DirectMessage(DmId), } impl ConversationId { #[inline] pub fn as_str(&self) -> &str { match &self { ConversationId::Channel(id) => id.as_str(), ConversationId::Group(id) => id.as_str(), ConversationId::DirectMessage(id) => id.as_str(), } } } impl ::std::fmt::Display for ConversationId { #[inline] fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match &self { ConversationId::Channel(c) => write!(f, "{}", c), ConversationId::Group(g) => write!(f, "{}", g), ConversationId::DirectMessage(d) => write!(f, "{}", d), } } } impl ::std::convert::From<ChannelId> for ConversationId { #[inline] fn from(id: ChannelId) -> Self { ConversationId::Channel(id) } } impl ::std::convert::From<GroupId> for ConversationId { #[inline] fn from(id: GroupId) -> Self { ConversationId::Group(id) } } impl ::std::convert::From<DmId> for ConversationId { #[inline] fn from(id: DmId) -> Self { ConversationId::DirectMessage(id) } }
use std::mem; use std::ptr; use messages::Message; use libc::{c_char, size_t}; use assets::{Fees, MetaAsset}; use capi::common::*; use transactions::add_assets::AddAssetWrapper; use error::{Error, ErrorKind}; ffi_fn! { fn dmbc_tx_add_assets_create( public_key: *const c_char, seed: u64, error: *mut Error, ) -> *mut AddAssetWrapper { let public_key = match parse_public_key(public_key) { Ok(public_key) => public_key, Err(err) => { unsafe { if !error.is_null() { *error = err; } return ptr::null_mut(); } } }; Box::into_raw(Box::new(AddAssetWrapper::new(&public_key, seed))) } } ffi_fn! { fn dmbc_tx_add_asset_free(wrapper: *const AddAssetWrapper) { if !wrapper.is_null() { unsafe { Box::from_raw(wrapper as *mut AddAssetWrapper); } } } } ffi_fn! { fn dmbc_tx_add_assets_add_asset( wrapper: *mut AddAssetWrapper, name: *const c_char, count: u64, fees: *const Fees, receiver_key: *const c_char, error: *mut Error, ) -> bool { let wrapper = match AddAssetWrapper::from_ptr(wrapper) { Ok(wrapper) => wrapper, Err(err) => { unsafe { if !error.is_null() { *error = err; } return false; } } }; if fees.is_null() { unsafe { if !error.is_null() { *error = Error::new(ErrorKind::Text("Invalid fees pointer.".to_string())); } return false; } } let fees = Fees::from_ptr(fees); let receiver_key = match parse_public_key(receiver_key) { Ok(pk) => pk, Err(err) => { unsafe { if !error.is_null() { *error = err; } return false; } } }; let name = match parse_str(name) { Ok(name) => name, Err(err) => { unsafe { if !error.is_null() { *error = err; } return false; } } }; let meta = MetaAsset::new(&receiver_key, name, count, fees.clone()); wrapper.add_asset(meta); true } } ffi_fn! { fn dmbc_tx_add_assets_into_bytes( wrapper: *mut AddAssetWrapper, length: *mut size_t, error: *mut Error, ) -> *const u8 { let wrapper = match AddAssetWrapper::from_ptr(wrapper) { Ok(wrapper) => wrapper, Err(err) => { unsafe { if !error.is_null() { *error = err; } return ptr::null(); } } }; let bytes = wrapper.unwrap().raw().body().to_vec(); assert!(bytes.len() == bytes.capacity()); let length = unsafe { &mut *length }; let len = bytes.len() as size_t; *length = len; let ptr = bytes.as_ptr(); mem::forget(bytes); ptr } }
use kerla_runtime::arch::console_write; use kerla_runtime::print::{set_printer, Printer}; use kerla_utils::ring_buffer::RingBuffer; use crate::lang_items::PANICKED; use core::sync::atomic::Ordering; pub struct LoggedPrinter; pub const KERNEL_LOG_BUF_SIZE: usize = 8192; // We use spin::Mutex here because SpinLock's debugging features may cause a // problem (capturing a backtrace requires memory allocation). pub static KERNEL_LOG_BUF: spin::Mutex<RingBuffer<u8, KERNEL_LOG_BUF_SIZE>> = spin::Mutex::new(RingBuffer::new()); impl Printer for LoggedPrinter { fn print_bytes(&self, s: &[u8]) { console_write(s); // Don't write into the kernel log buffer as it may call a printk function // due to an assertion. if !PANICKED.load(Ordering::SeqCst) { KERNEL_LOG_BUF.lock().push_slice(s); } } } /// Prints a warning message only in the debug build. #[macro_export] macro_rules! debug_warn { ($fmt:expr) => { if cfg!(debug_assertions) { ::kerla_runtime::println!(concat!("\x1b[1;33mWARN: ", $fmt, "\x1b[0m")); } }; ($fmt:expr, $($arg:tt)*) => { if cfg!(debug_assertions) { ::kerla_runtime::println!(concat!("\x1b[1;33mWARN: ", $fmt, "\x1b[0m"), $($arg)*); } }; } /// Prints a warning message only once. #[macro_export] macro_rules! warn_once { ($fmt:expr) => {{ static ONCE: ::spin::Once<()> = ::spin::Once::new(); ONCE.call_once(|| { ::kerla_runtime::println!(concat!("\x1b[1;33mWARN: ", $fmt, "\x1b[0m")); }); }}; ($fmt:expr, $($arg:tt)*) => {{ static ONCE: ::spin::Once<()> = ::spin::Once::new(); ONCE.call_once(|| { ::kerla_runtime::println!(concat!("\x1b[1;33mWARN: ", $fmt, "\x1b[0m"), $($arg)*); }); }}; } /// Prints a warning message if it is `Err`. #[macro_export] macro_rules! warn_if_err { ($result:expr) => { if cfg!(debug_assertions) { if let Err(err) = $result { $crate::debug_warn!("{}:{}: error returned: {:?}", file!(), line!(), err); } } }; } pub fn init() { set_printer(&LoggedPrinter); }
use std::collections::HashMap; use anyhow::*; use lazy_static::lazy_static; use regex::Regex; const REQUIRED_FIELDS: [&str; 7] = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]; lazy_static! { static ref PATTERNS: HashMap<&'static str, Regex> = { let mut map = HashMap::new(); map.insert("byr", Regex::new(r"^\d{4}$").unwrap()); map.insert("iyr", Regex::new(r"^\d{4}$").unwrap()); map.insert("eyr", Regex::new(r"^\d{4}$").unwrap()); map.insert("hgt", Regex::new(r"^(\d+)(cm|in)$").unwrap()); map.insert("hcl", Regex::new(r"^#[0-9a-f]{6}$").unwrap()); map.insert("ecl", Regex::new(r"^(amb|blu|brn|gry|grn|hzl|oth)$").unwrap()); map.insert("pid", Regex::new(r"^\d{9}$").unwrap()); map }; } #[derive(Debug, Default)] pub struct Passport { fields: HashMap<String, String>, } impl Passport { pub fn add_field(&mut self, name: &str, value: &str) { self.fields.insert(name.to_string(), value.to_string()); } pub fn has_required_fields(&self) -> bool { // make sure all required fields are present REQUIRED_FIELDS.iter().all(|f| self.fields.contains_key(*f)) && (self.fields.len() == 7 || (self.fields.len() == 8 && self.fields.contains_key("cid"))) } pub fn are_fields_valid(&self) -> bool { fn check_year(input: &str, min: u16, max: u16) -> bool { if let Ok(year) = input.parse::<u16>() { return year >= min && year <= max; } else { return false; } } for req_field in &REQUIRED_FIELDS { if let Some(value) = self.fields.get(*req_field) { let pattern = PATTERNS.get(*req_field).unwrap(); let valid = match *req_field { "byr" => check_year(value, 1920, 2002), "iyr" => check_year(value, 2010, 2020), "eyr" => check_year(value, 2020, 2030), "hgt" => { if let Some(captures) = pattern.captures(value) { let v = captures .get(1) .map(|v| v.as_str()) .and_then(|v| v.parse::<u16>().ok()); let unit = captures.get(2).map(|v| v.as_str()); v.zip(unit) .map(|(v, unit)| match unit { "cm" => v >= 150 && v <= 193, "in" => v >= 59 && v <= 76, _ => false, }) .unwrap_or(false) } else { false } } "hcl" => pattern.is_match(value), "ecl" => pattern.is_match(value), "pid" => pattern.is_match(value), _ => false, }; if !valid { return false; } } else { return false; } } true } pub fn is_valid(&self) -> bool { self.has_required_fields() && self.are_fields_valid() } } pub fn parse_passports(input: &str) -> Result<Vec<Passport>> { let mut passports = Vec::new(); let mut current_passport = None; for line in input.lines() { if line.is_empty() { passports.push(current_passport.take().unwrap()); continue; } let p = current_passport.get_or_insert(Passport::default()); for entry in line.split(' ') { let mut fields = entry.split(':'); let name = fields .next() .ok_or(format_err!("invalid entry! entry={}", entry))?; let value = fields .next() .ok_or(format_err!("invalid entry! entry={}", entry))?; p.add_field(name, value); } } if let Some(p) = current_passport { passports.push(p); } Ok(passports) } fn main() -> Result<()> { let input = advent20::input_string()?; let passports = parse_passports(&input)?; let valid = passports.iter().filter(|p| p.has_required_fields()).count(); println!("part 1: {}", valid); let valid = passports .iter() .filter(|p| p.has_required_fields() && p.are_fields_valid()) .count(); println!("part 2: {}", valid); Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_invalid_passports() { let input = r"eyr:1972 cid:100 hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926 iyr:2019 hcl:#602927 eyr:1967 hgt:170cm ecl:grn pid:012533040 byr:1946 hcl:dab227 iyr:2012 ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277 hgt:59cm ecl:zzz eyr:2038 hcl:74454a iyr:2023 pid:3556412378 byr:2007"; let passports = parse_passports(input).unwrap(); assert_eq!(4, passports.len()); for p in &passports { assert_eq!(false, p.is_valid()); } } #[test] fn test_valid_passports() { let input = r"pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 hcl:#623a2f eyr:2029 ecl:blu cid:129 byr:1989 iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm hcl:#888785 hgt:164cm byr:2001 iyr:2015 cid:88 pid:545766238 ecl:hzl eyr:2022 iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719"; let passports = parse_passports(input).unwrap(); assert_eq!(4, passports.len()); for p in &passports { assert_eq!(true, p.is_valid(), "passport {:?} should be valid", p); } } }
#[doc = "Reader of register INTS0"] pub type R = crate::R<u32, super::INTS0>; #[doc = "Writer for register INTS0"] pub type W = crate::W<u32, super::INTS0>; #[doc = "Register INTS0 `reset()`'s with value 0"] impl crate::ResetValue for super::INTS0 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `INTS0`"] pub type INTS0_R = crate::R<u16, u16>; #[doc = "Write proxy for field `INTS0`"] pub struct INTS0_W<'a> { w: &'a mut W, } impl<'a> INTS0_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } impl R { #[doc = "Bits 0:15 - Indicates active channel interrupt requests which are currently causing IRQ 0 to be asserted.\\n Channel interrupts can be cleared by writing a bit mask here."] #[inline(always)] pub fn ints0(&self) -> INTS0_R { INTS0_R::new((self.bits & 0xffff) as u16) } } impl W { #[doc = "Bits 0:15 - Indicates active channel interrupt requests which are currently causing IRQ 0 to be asserted.\\n Channel interrupts can be cleared by writing a bit mask here."] #[inline(always)] pub fn ints0(&mut self) -> INTS0_W { INTS0_W { w: self } } }
/*! This crate provides a `FromStr` derive for newtypes on iterable collections on single types, such `Vec<T>` or `HashSet<T>`. The element is parsed by splitting the input along a pattern that you specify though the `#[item_separator]` attribute. The individual items are then parsed using their respective `FromStr` implementations. # Requirements - The macro will take the first field in your struct that has a type with a path argument `<T>` and assume that it is the inner type. It will assume that `T` in this example is the item type. - The item type `T` must not be an actual type (no trait type) that implements `FromStr`. - As inner type you can use any type that implements `FromIterator<Item = T>` (like `Vec<T>` or `HashSet<T>`). - `From` needs to be implemented between your newtype and its inner type. Crates like `derive_more` take easy care of that. # Example ```rust use collections_fromstr::FromStr; use derive_more::From; use std::str::FromStr; #[derive(From, FromStr, PartialEq)] #[item_separator = ","] struct NewVec(Vec<i32>); static VALUES: &str = "1,2,3,-3,-2,-1"; assert!(NewVec::from_str(VALUES).unwrap() == NewVec(vec![1,2,3,-3,-2,-1])); ``` ## Wait... you know that I could just use `Iterator::split` for this, right? Okay, hear me out. Say you've got data like this: ```text 1-3:B,I,U//43-60:I//83-87:I,U//99-104: B,I// [etc.] ``` Let's say this data represents text markup: You've got character ranges on the left of the colon `:`, and highlighting information on the right side (`B` = bold, `I` = italics, `U` = underline, but you'll probably expand it later once you get that hedgefund money), of which there might be multiple, separated by commas `,`. Each markup is separated by double slashes `//`. ... Now look at the magic of `FromStr` doing its thing: ```rust use std::collections::HashSet; use derive_more::From; use std::ops::Range; #[derive(parse_display::FromStr)] #[display("{0.start}-{0.end}")] struct CharRange(#[from_str(default)] Range<u32>); #[derive(parse_display::FromStr, Hash, PartialEq, Eq)] #[non_exhaustive] enum MarkupOperation { #[display("B")] Bold, #[display("I")] Italics, #[display("U")] Underline, } #[derive(From, collections_fromstr::FromStr)] #[item_separator=","] struct Operations(HashSet<MarkupOperation>); #[derive(parse_display::FromStr)] #[display("{range}:{operations}")] struct Markup{ range: CharRange, operations: Operations, } #[derive(From, collections_fromstr::FromStr)] #[item_separator="//"] struct MarkupVec(Vec<Markup>); ``` Look at this code. It's. So. Clean. 🥺 And you'll be less likely to produce bugs, like forgetting about the case of an empty input string. # License `collections-fromstr` is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See `LICENSE-APACHE` and `LICENSE-MIT` for details. */ #![deny( deprecated_in_future, exported_private_dependencies, future_incompatible, missing_copy_implementations, missing_crate_level_docs, missing_debug_implementations, missing_docs, private_in_public, rust_2018_compatibility, rust_2018_idioms, trivial_casts, trivial_numeric_casts, unsafe_code, unused_qualifications, trivial_casts, trivial_numeric_casts, unused_crate_dependencies, unused_lifetimes, variant_size_differences )] #![warn(clippy::pedantic)] use proc_macro::TokenStream as TokenStream1; mod derive_from_str; #[proc_macro_derive(FromStr, attributes(item_separator))] /// Derives `FromStr` for collections. The input will be split along a separator that is specified in a helper attribute like `#[item_separator=","]`. If the separator is a single character, it will be internally transformed into a `char`. pub fn derive_from_str(input: TokenStream1) -> TokenStream1 { derive_from_str::derive_from_str_inner(input) } #[cfg(test)] mod tests { use parse_display as _; // used in doctests #[test] fn compile_tests(){ use derive_more as _; use assert2 as _; use maplit as _; let t = trybuild::TestCases::new(); t.pass("trybuild_tests/01-newtype-vec.rs"); t.compile_fail("trybuild_tests/02-from-trait-missing.rs"); t.pass("trybuild_tests/03-derive-more.rs"); t.pass("trybuild_tests/04-named-newtype.rs"); t.pass("trybuild_tests/05-full-paths.rs"); t.pass("trybuild_tests/06-hashset.rs"); t.compile_fail("trybuild_tests/07-hashmap.rs"); t.compile_fail("trybuild_tests/08-missing-separator.rs"); t.compile_fail("trybuild_tests/09-empty-separator.rs"); t.pass("trybuild_tests/10-parse-vec-i32.rs"); t.pass("trybuild_tests/11-multibyte-separator.rs"); t.pass("trybuild_tests/12-string-separator.rs"); t.pass("trybuild_tests/13-parse-vec-string.rs"); t.pass("trybuild_tests/14-parse-hashset.rs"); t.pass("trybuild_tests/15-parse-single-value.rs"); t.pass("trybuild_tests/16-parse-empty.rs"); } }
pub mod fs; pub mod index; pub mod object; use chrono::{Local, TimeZone, Utc}; use fs::FileSystem; use index::{Entry, Index}; use index::diff::{diff_index, Diff}; use libflate::zlib::{Decoder, Encoder}; use object::blob::Blob; use object::commit; use object::commit::Commit; use object::tree; use object::tree::Tree; use object::GitObject; use std::io; use std::io::prelude::*; #[derive(Debug)] pub struct Git<F: FileSystem> { pub file_system: F, } impl<F: FileSystem> Git<F> { pub fn new(file_system: F) -> Self { Self { file_system } } pub fn read_index(&self) -> io::Result<Vec<u8>> { self.file_system.read(".git/index".to_string()) } pub fn write_index(&mut self, index: &Index) -> io::Result<()> { self.file_system .write(".git/index".to_string(), &index.as_bytes()) } pub fn read_object(&self, hash: String) -> io::Result<Vec<u8>> { let (sub_dir, file) = hash.split_at(2); self.file_system .read(format!(".git/objects/{}/{}", sub_dir, file)) } pub fn write_object(&mut self, object: &GitObject) -> io::Result<()> { let hash = hex::encode(object.calc_hash()); let (sub_dir, file) = hash.split_at(2); let path = format!(".git/objects/{}", sub_dir); // ディレクトリがなかったら if let Err(_) = self.file_system.stat(path.clone()) { self.file_system.create_dir(path.clone())?; } let path = format!("{}/{}", path, file); let mut encoder = Encoder::new(Vec::new())?; encoder.write_all(&object.as_bytes())?; let bytes = encoder.finish().into_result()?; self.file_system.write(path, &bytes) } pub fn head_ref(&self) -> io::Result<String> { let path = ".git/HEAD".to_string(); let file = self.file_system.read(path)?; let refs = String::from_utf8(file).map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?; let (prefix, path) = refs.split_at(5); if prefix != "ref: " { return Err(io::Error::from(io::ErrorKind::InvalidData)); } Ok(path.trim().to_string()) } pub fn read_ref(&self, path: String) -> io::Result<String> { let path = format!(".git/{}", path); let file = self.file_system.read(path)?; let hash = String::from_utf8(file).map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?; Ok(hash.trim().to_string()) } pub fn write_ref(&mut self, path: String, hash: &[u8]) -> io::Result<()> { let path = format!(".git/{}", path); self.file_system.write(path, hex::encode(hash).as_bytes()) } pub fn cat_file_p(&self, bytes: &[u8]) -> io::Result<GitObject> { let mut d = Decoder::new(&bytes[..])?; let mut buf = Vec::new(); d.read_to_end(&mut buf)?; GitObject::new(&buf).ok_or(io::Error::from(io::ErrorKind::InvalidData)) } pub fn ls_files_stage(&self, bytes: &[u8]) -> io::Result<Index> { Index::from(&bytes).ok_or(io::Error::from(io::ErrorKind::InvalidData)) } pub fn hash_object(&self, bytes: &[u8]) -> io::Result<Blob> { let blob = Blob::from(&bytes).ok_or(io::Error::from(io::ErrorKind::InvalidInput))?; Ok(blob) } pub fn update_index(&self, idx: Index, hash: &[u8], file_name: String) -> io::Result<Index> { let metadata = self.file_system.stat(file_name.clone())?; let entry = Entry::new( Utc.timestamp(metadata.ctime as i64, metadata.ctime_nsec), Utc.timestamp(metadata.mtime as i64, metadata.mtime_nsec), metadata.dev, metadata.ino, metadata.mode, metadata.uid, metadata.gid, metadata.size, Vec::from(hash), file_name.clone(), ); let mut entries: Vec<Entry> = idx .entries .into_iter() .filter(|x| x.name != entry.name && x.hash != entry.hash) .collect(); entries.push(entry); entries.sort_by(|a, b| a.name.cmp(&b.name)); Ok(Index::new(entries)) } pub fn write_tree(&self) -> io::Result<Tree> { let bytes = self.read_index()?; let index = self.ls_files_stage(&bytes)?; let contents = index .entries .iter() // TODO: 一旦modeは `100644` で固定 .map(|x| tree::File::new(100644, x.name.clone(), &x.hash)) .collect::<Vec<_>>(); Ok(Tree::new(contents)) } pub fn commit_tree( &self, name: String, email: String, tree_hash: String, message: String, ) -> io::Result<Commit> { let parent = self.head_ref().and_then(|x| self.read_ref(x)).ok(); let offs = { let local = Local::now(); *local.offset() }; let ts = offs.from_utc_datetime(&Utc::now().naive_utc()); let author = commit::User::new(name.clone(), email.clone(), ts); let commit = Commit::new(tree_hash, parent, author.clone(), author.clone(), message); Ok(commit) } pub fn update_ref(&mut self, path: String, hash: &[u8]) -> io::Result<()> { self.write_ref(path, hash) } pub fn reset_index(&mut self, hash: String) -> io::Result<Vec<Diff>> { let commit = self .read_object(hash) .and_then(|x| self.cat_file_p(&x)) .and_then(|x| match x { GitObject::Commit(commit) => Ok(commit), _ => Err(io::Error::from(io::ErrorKind::InvalidData)), })?; let prev_index = self.read_index().and_then(|x| self.ls_files_stage(&x))?; let next_index = self.tree2index(commit.tree.clone())?; Ok(diff_index(prev_index, next_index)) } pub fn diff_apply(&mut self, diff: Vec<Diff>) -> io::Result<()> { diff.iter().try_for_each(|d| match d { Diff::Add(e) => self.read_object(hex::encode(e.hash.clone())) .and_then(|x| self.cat_file_p(&x)) .and_then(|x| match x { GitObject::Blob(blob) => Ok(blob), _ => Err(io::Error::from(io::ErrorKind::InvalidData)), }) .and_then(|blob| self.file_system.write(e.name.clone(), blob.content.as_bytes())), Diff::Modify(e, _) => self.read_object(hex::encode(e.hash.clone())) .and_then(|x| self.cat_file_p(&x)) .and_then(|x| match x { GitObject::Blob(blob) => Ok(blob), _ => Err(io::Error::from(io::ErrorKind::InvalidData)), }) .and_then(|blob| self.file_system.write(e.name.clone(), blob.content.as_bytes())), Diff::Rename(n, p) => self.file_system.rename(p.name.clone(), n.name.clone()), Diff::Remove(e) => self.file_system.remove(e.name.clone()), Diff::None => Ok(()), }) } pub fn tree2index(&mut self, hash: String) -> io::Result<Index> { let idx = Index::new(Vec::new()); self.helper_tree2index(idx, hash, String::new()) } fn helper_tree2index(&mut self, idx: Index, hash: String, name: String) -> io::Result<Index> { let obj = self .read_object(hash.clone()) .and_then(|x| self.cat_file_p(&x))?; match obj { GitObject::Blob(blob) => { let meta = self.file_system.stat(name.clone()).unwrap_or(fs::Metadata { dev: 0, ino: 0, mode: 33188, uid: 0, gid: 0, size: 0, mtime: 0, mtime_nsec: 0, ctime: 0, ctime_nsec: 0, }); let entry = Entry::new( Utc.timestamp(meta.ctime as i64, meta.ctime_nsec), Utc.timestamp(meta.mtime as i64, meta.mtime_nsec), meta.dev, meta.ino, meta.mode, meta.uid, meta.gid, meta.size, blob.calc_hash(), name ); let mut entries: Vec<Entry> = idx .entries .into_iter() .filter(|x| x.name != entry.name || x.hash != entry.hash) .collect(); entries.push(entry); entries.sort_by(|a, b| a.name.cmp(&b.name)); Ok(Index::new(entries)) }, GitObject::Tree(tree) => tree.contents.iter().try_fold(idx, |acc, x| { self.helper_tree2index(acc, hex::encode(&x.hash), format!("{}{}{}", name, if name.is_empty() { "" } else { "/" }, x.name.clone())) }), _ => Err(io::Error::from(io::ErrorKind::InvalidData)), } } }
pub struct Point2D { pub x: i32, pub y: i32, } impl Point2D { pub fn move_relative(&self, x: i32, y: i32) -> Self { Point2D { x: self.x + x, y: self.y + y, } } } #[cfg(test)] mod test { use super::*; #[test] fn move_rel() { let p = Point2D { x: 0, y: 0 }.move_relative(5, 3); assert_eq!(p.x, 5); assert_eq!(p.y, 3); } }
pub mod feature; pub mod hotfix; pub mod release; pub mod setup;
use neon::prelude::*; fn get_cpu_num() -> u32 { match sys_info::cpu_num() { Ok(num) => num, Err(_) => 0 as u32, } } fn get_cpu_speed() -> u64 { match sys_info::cpu_speed() { Ok(speed) => speed, Err(_) => 0, } } fn get_os_type() -> String { match sys_info::os_type() { Ok(os_type) => os_type, Err(_) => String::new(), } } fn get_os_release() -> String { match sys_info::os_release() { Ok(release) => release, Err(_) => String::new(), } } fn get_mem_info() -> sys_info::MemInfo { match sys_info::mem_info() { Ok(info) => info, Err(_) => sys_info::MemInfo { total: 0, free: 0, avail: 0, buffers: 0, cached: 0, swap_total: 0, swap_free: 0, }, } } fn get_host_name() -> String { match sys_info::hostname() { Ok(name) => name, Err(_) => String::new(), } } fn get_load_average() -> sys_info::LoadAvg { match sys_info::loadavg() { Ok(info) => info, Err(_) => sys_info::LoadAvg { one: 0.0, five: 0.0, fifteen: 0.0, }, } } fn get_system_info(mut cx: FunctionContext) -> JsResult<JsObject> { let info = cx.empty_object(); let cpu = cx.empty_object(); let cpu_quantity = cx.number(get_cpu_num() as f64); let cpu_speed = cx.number(get_cpu_speed() as f64); let os = cx.empty_object(); let os_type = cx.string(get_os_type()); let os_release = cx.string(get_os_release()); let host = cx.empty_object(); let host_name = cx.string(get_host_name()); let memory = cx.empty_object(); let memory_info = get_mem_info(); let memory_total = cx.number(memory_info.total as f64); let memory_free = cx.number(memory_info.free as f64); let load = cx.empty_object(); let load_average = get_load_average(); let load_average_one = cx.number(load_average.one); let load_average_five = cx.number(load_average.five); let load_average_fifteen = cx.number(load_average.fifteen); cpu.set(&mut cx, "quantity", cpu_quantity)?; cpu.set(&mut cx, "speed", cpu_speed)?; os.set(&mut cx, "type", os_type)?; os.set(&mut cx, "release", os_release)?; host.set(&mut cx, "name", host_name)?; memory.set(&mut cx, "total", memory_total)?; memory.set(&mut cx, "free", memory_free)?; info.set(&mut cx, "cpu", cpu)?; info.set(&mut cx, "os", os)?; info.set(&mut cx, "host", host)?; info.set(&mut cx, "memory", memory)?; info.set(&mut cx, "load", load)?; Ok(info) } #[neon::main] fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("get", get_system_info)?; Ok(()) }
use std::{cell, collections, collections::VecDeque, env, error::Error, fs, rc::Rc}; type Result<T> = std::result::Result<T, Box<dyn Error>>; fn main() -> Result<()> { let code = fs::read_to_string(env::args().nth(1).ok_or("no file")?)? + " $"; eval_list(&default_env(), vec(&list(&mut tokenize(code))))?; Ok(()) } fn tokenize(mut code: String) -> VecDeque<String> { let cs = "()'".chars(); cs.for_each(|c| code = code.replace(c, &format!(" {} ", c))); code.split_whitespace().map(ToOwned::to_owned).collect() } fn list(tokens: &mut VecDeque<String>) -> V { match tokens.pop_front().expect("empty") { x if &x == ")" || &x == "$" => Nil().into(), x => Pair(value(tokens, Some(x)).into(), list(tokens).into()).into(), } } fn value(tokens: &mut VecDeque<String>, first: Option<String>) -> V { match &*first.unwrap_or_else(|| tokens.pop_front().expect("empty")) { "(" => list(tokens), "#t" => Bool(true).into(), "#f" => Bool(false).into(), "'" => Quote(value(tokens, None)).into(), x => match x.parse::<i64>() { Ok(i) => Int(i).into(), _ => Symbol(x.into()).into(), }, } } enum Val { Nil(), Bool(bool), Int(i64), Pair(cell::RefCell<V>, cell::RefCell<V>), Symbol(String), Quote(V), Func(Box<dyn Fn(Vec<V>) -> Result<V>>), Form(Box<dyn Fn(&Rc<Env>, Vec<V>) -> Result<V>>), } type V = Rc<Val>; use Val::*; impl Val { fn pair(&self) -> Result<(V, V)> { match self { Pair(x, y) => Ok((x.borrow().clone(), y.borrow().clone())), _ => Err("pair: not pair".into()), } } fn int(&self) -> Result<i64> { match self { Int(x) => Ok(*x), _ => Err("not int".into()), } } fn bool(&self) -> bool { !self.eq(&Bool(false)) } fn symbol(&self) -> Result<&str> { match self { Symbol(x) => Ok(x), _ => Err("not symbol".into()), } } fn eq(&self, other: &Self) -> bool { match (self, other) { (Nil(), Nil()) => true, (Bool(x), Bool(y)) => x == y, (Int(x), Int(y)) => x == y, (Quote(x), Quote(y)) => x.eq(y), (Symbol(x), Symbol(y)) => x == y, _ => false, } } } fn to_list(v: &[V]) -> V { if let Some(x) = v.last() { return Pair(x.clone().into(), to_list(&v[0..v.len() - 1]).into()).into(); } Nil().into() } fn vec(v: &V) -> Vec<V> { match v.pair() { Ok((x, y)) => [vec(&y), vec![x]].concat(), _ => vec![], } } impl std::fmt::Display for Val { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Nil() => write!(f, "()"), Bool(true) => write!(f, "#t"), Bool(false) => write!(f, "#f"), Int(i) => write!(f, "{}", i), Pair(x, y) => write!(f, "( {} {} )", x.borrow(), y.borrow()), Symbol(x) => write!(f, "{}", x), Quote(x) => write!(f, "'{}", x), Form(_) => write!(f, "<form>"), Func(_) => write!(f, "<func>"), } } } fn eval(e: &Rc<Env>, v: &V) -> Result<V> { Ok(match v.as_ref() { Nil() | Bool(_) | Int(_) => v.clone(), Pair(x, y) => match eval(e, &x.borrow())?.as_ref() { Form(f) => f(e, vec(&y.borrow()))?, Func(f) => { let u = vec(&y.borrow()).into_iter().map(|v| eval(e, &v)); f(u.collect::<Result<_>>()?)? } x => return Err(format!("not func: {}", x).into()), }, Symbol(x) => e.lookup(x)?, Quote(x) => x.clone(), _ => return Err(format!("{}", v).into()), }) } fn eval_list(e: &Rc<Env>, v: Vec<V>) -> Result<V> { let res = v.into_iter().rev().map(|x| eval(e, &x)).last(); res.unwrap_or(Err("empty".into())) } struct Env { m: cell::RefCell<collections::HashMap<String, V>>, next: Option<Rc<Env>>, } impl Env { fn lookup(&self, s: &str) -> Result<V> { match (self.m.borrow().get(s), self.next.as_ref()) { (Some(v), _) => Ok(v.clone()), (_, Some(e)) => e.lookup(s), _ => Err(format!("not found: {}", s).into()), } } fn ensure<T: Into<V>>(self: &Rc<Self>, s: &str, v: T) -> Rc<Self> { self.m.borrow_mut().insert(s.to_string(), v.into()); self.clone() } fn with_fold(self: Rc<Self>, s: &str, f: fn(V, V) -> Result<V>) -> Rc<Self> { let f = Func(Box::new(move |v| { let res = v.into_iter().map(Result::Ok).reduce(|x, y| f(x?, y?)); res.unwrap_or(Err("empty".into())) })); self.ensure(s, f) } fn with_func(self: Rc<Self>, s: &str, f: fn(Vec<V>) -> Result<V>) -> Rc<Env> { self.ensure(s, Func(Box::new(f))) } fn with_form(self: Rc<Self>, s: &str, f: fn(&Rc<Env>, Vec<V>) -> Result<V>) -> Rc<Self> { self.ensure(s, Form(Box::new(f))) } fn set(&self, s: &str, v: V) -> Result<()> { if let Some(x) = self.m.borrow_mut().get_mut(s) { *x = v; return Ok(()); } self.next.as_ref().ok_or("set: not found")?.set(s, v) } fn new(next: Option<Rc<Env>>) -> Rc<Self> { Rc::new(Env { m: collections::HashMap::new().into(), next, }) } } fn default_env() -> Rc<Env> { Env::new(None) .with_fold("+", |x, y| Ok(Int(x.int()? + y.int()?).into())) .with_fold("*", |x, y| Ok(Int(x.int()? * y.int()?).into())) .with_fold("and", |x, y| Ok(Bool(x.bool() && y.bool()).into())) .with_fold("or", |x, y| Ok(Bool(x.bool() || y.bool()).into())) .with_func("-", |v| Ok(Int(v[1].int()? - v[0].int()?).into())) .with_func("/", |v| Ok(Int(v[1].int()? / v[0].int()?).into())) .with_func("=", |v| Ok(Bool(v[1].int()? == v[0].int()?).into())) .with_func("<", |v| Ok(Bool(v[1].int()? < v[0].int()?).into())) .with_func("<=", |v| Ok(Bool(v[1].int()? <= v[0].int()?).into())) .with_func(">", |v| Ok(Bool(v[1].int()? > v[0].int()?).into())) .with_func(">=", |v| Ok(Bool(v[1].int()? >= v[0].int()?).into())) .with_func("eq?", |v| Ok(Bool(v[1].eq(&v[0])).into())) .with_func("cons", |v| { Ok(Pair(v[1].clone().into(), v[0].clone().into()).into()) }) .with_func("not", |v| Ok(Bool(!v[0].bool()).into())) .with_func("car", |v| Ok(v[0].pair()?.0)) .with_func("cdr", |v| Ok(v[0].pair()?.1)) .with_func("print", |v| { println!("{}", v[0]); Ok(Nil().into()) }) .with_form("begin", eval_list) .with_form("define", |e, mut v| { let name_params = v.pop().ok_or("empty")?; match vec(&name_params).as_slice() { [params @ .., name] => { let l = [v, vec![to_list(params), Symbol("lambda".into()).into()]].concat(); e.ensure(name.symbol()?, eval(e, &to_list(&l))?) } _ => e.ensure(name_params.symbol()?, eval(e, &v[0])?), }; Ok(Nil().into()) }) .with_form("lambda", |e, mut v| { let (e, params) = (e.clone(), v.pop().ok_or("empty")?); Ok(Rc::new(Form(Box::new(move |e2, mut args| { let (e, mut params) = (Env::new(Some(e.clone())), vec(&params)); while let (Some(x), Some(y)) = (params.pop(), args.pop()) { e.ensure(x.symbol()?, eval(e2, &y)?); } eval_list(&e, v.clone()) })))) }) .with_form("let", |e, v| do_let(e, v, 0)) .with_form("let*", |e, v| do_let(e, v, 1)) .with_form("letrec", |e, v| do_let(e, v, 2)) .with_form("if", |e, v| match eval(e, &v[2])?.bool() { true => eval(e, &v[1]), false => eval(e, &v[0]), }) .with_form("cond", |e, mut v| loop { let u = vec(&v.pop().ok_or("empty")?); if eval(e, &u[1])?.bool() { return eval(e, &u[0]); } }) .with_form("set!", |e, v| { e.set(v[1].symbol()?, eval(e, &v[0])?)?; Ok(Nil().into()) }) .with_form("set-car!", |e, v| set_pair(e, v, 0)) .with_form("set-cdr!", |e, v| set_pair(e, v, 1)) .ensure("else", Bool(true)) } fn do_let(e: &Rc<Env>, mut v: Vec<V>, env: usize) -> Result<V> { let (mut e2, mut kvs) = (Env::new(Some(e.clone())), vec(&v.pop().ok_or("empty")?)); while let Some(vk) = kvs.pop().map(|kv| (vec(&kv))) { let e3 = match env { 2 => Env::new(Some(e2.clone())).ensure(vk[1].symbol()?, Nil()), _ => Env::new(Some(e2.clone())), }; e2 = e3.ensure(vk[1].symbol()?, eval([e, &e2, &e3][env], &vk[0])?); } eval_list(&e2, v) } fn set_pair(e: &Rc<Env>, v: Vec<V>, i: usize) -> Result<V> { match eval(e, &v[1])?.as_ref() { Pair(x, y) => *[x, y][i].borrow_mut() = eval(e, &v[0])?, _ => return Err("set-cdr: not pair".into()), }; Ok(Nil().into()) }
#![feature(fixed_size_array)] #[macro_use] extern crate bitflags; extern crate core; pub mod cpu; pub mod memory;
// Copyright (c) 2019-2021 Georg Brandl. Licensed under the Apache License, // Version 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> // or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at // your option. This file may not be copied, modified, or distributed except // according to those terms. use std::fmt; use std::collections::HashMap; use strum_macros::Display; use crate::ast::*; /// Identifier for a parameter: either numeric or named. #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum Param { Num(u16), Named(String), } impl fmt::Display for Param { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Param::Num(n) => write!(f, "#{}", n), Param::Named(s) => write!(f, "#<{}>", s), } } } /// An axis supported by G-code. /// /// Concrete machines usually only support some subset of axes. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Display)] pub enum Axis { A, B, C, U, V, W, X, Y, Z, } impl Axis { pub(super) fn from_arg(arg: &Arg) -> Option<Self> { Some(match arg { Arg::AxisA => Axis::A, Arg::AxisB => Axis::B, Arg::AxisC => Axis::C, Arg::AxisU => Axis::U, Arg::AxisV => Axis::V, Arg::AxisW => Axis::W, Arg::AxisX => Axis::X, Arg::AxisY => Axis::Y, Arg::AxisZ => Axis::Z, _ => return None }) } pub fn is_linear(&self) -> bool { match self { Axis::A | Axis::B | Axis::C => false, _ => true } } } /// An arc center offset or coordinate. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Display)] pub enum Offset { I, J, K, } impl Offset { pub(super) fn from_arg(arg: &Arg) -> Option<Self> { Some(match arg { Arg::OffsetI => Offset::I, Arg::OffsetJ => Offset::J, Arg::OffsetK => Offset::K, _ => return None }) } } /// A generic argument word, such as `P`. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Display)] pub enum GenWord { D, E, H, L, P, Q, R, } impl GenWord { pub(super) fn from_arg(arg: &Arg) -> Option<Self> { Some(match arg { Arg::ParamD => GenWord::D, Arg::ParamE => GenWord::E, Arg::ParamH => GenWord::H, Arg::ParamL => GenWord::L, Arg::ParamP => GenWord::P, Arg::ParamQ => GenWord::Q, Arg::ParamR => GenWord::R, _ => return None }) } } /// A plane as selected by G17-G19. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Display)] pub enum Plane { XY, XZ, YZ, UV, UW, VW, } impl Default for Plane { fn default() -> Self { Plane::XY } } /// A collection of axis coordinates. /// /// All length measures are in millimeters. /// All angle measures are in degrees. #[derive(Clone, PartialEq)] pub struct Coords { pub rel: bool, pub map: HashMap<Axis, f64>, } impl Coords { pub fn new(map: HashMap<Axis, f64>, rel: bool) -> Self { Self { map, rel } } pub(crate) fn from_ijk(map: HashMap<Offset, f64>, rel: bool) -> Self { Self { rel, map: map.into_iter().map(|(k, v)| (match k { Offset::I => Axis::X, Offset::J => Axis::Y, Offset::K => Axis::Z, }, v)).collect() } } } impl fmt::Debug for Coords { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut i = 0; for (k, v) in self.map.iter() { i += 1; write!(f, "{}={}", k, v)?; if i < self.map.len() { write!(f, ", ")?; } } Ok(()) } } /// A spindle state. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum Spindle { Off, Cw, Ccw, } impl Default for Spindle { fn default() -> Self { Spindle::Off } } /// A coolant state. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)] pub struct Coolant { pub mist: bool, pub flood: bool, } /// A cutter compensation state. /// /// The value in Left/Right variants is the tool number to use. #[derive(Clone, PartialEq, Debug)] pub enum CutterComp { Off, LeftFromTool(Option<u16>), RightFromTool(Option<u16>), LeftDynamic(f64, u16), RightDynamic(f64, u16), } impl Default for CutterComp { fn default() -> Self { CutterComp::Off } } /// A length compensation state. /// /// The vector member contains additional tool offsets added with G43.2. #[derive(Clone, PartialEq, Debug)] pub enum LengthComp { Off, FromTool(Option<u16>, Vec<u16>), Dynamic(Coords, Vec<u16>), } impl Default for LengthComp { fn default() -> Self { LengthComp::Off } } /// A path control mode. #[derive(Clone, Copy, PartialEq, Debug)] pub enum PathMode { Exact, ExactStop, Blending(Option<f64>, Option<f64>), } impl Default for PathMode { fn default() -> Self { PathMode::Exact } } /// Center specification for a helix. #[derive(Clone, Debug)] pub enum HelixCenter { Center(Coords), Radius(f64), }
use crate::{ smallnum::{U1, U2, U3}, RegName8, }; /// Instruction prefix type #[allow(clippy::upper_case_acronyms)] #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Prefix { None, CB, DD, ED, FD, } impl Prefix { /// Returns prefix type from byte value pub fn from_byte(data: u8) -> Prefix { match data { 0xCB => Prefix::CB, 0xDD => Prefix::DD, 0xED => Prefix::ED, 0xFD => Prefix::FD, _ => Prefix::None, } } /// Transforms prefix back to byte pub fn to_byte(self) -> Option<u8> { match self { Prefix::DD => Some(0xDD), Prefix::FD => Some(0xFD), Prefix::ED => Some(0xED), Prefix::CB => Some(0xCB), Prefix::None => None, } } } /// Operand for 8-bit LD instructions pub enum LoadOperand8 { Indirect(u16), Reg(RegName8), } /// Operand for 8-bit Bit instructions pub enum BitOperand8 { Indirect(u16), Reg(RegName8), } /// Direction of address cahange in block functions pub enum BlockDir { Inc, Dec, } /// Opcode, devided in parts /// ```text /// xxyyyzzz /// xxppqzzz /// ``` /// Used for splitting opcode byte into parts #[derive(Clone, Copy)] pub struct Opcode { pub byte: u8, pub x: U2, pub y: U3, pub z: U3, pub p: U2, pub q: U1, } impl Opcode { /// splits opcode into parts pub(crate) fn from_byte(data: u8) -> Opcode { Opcode { byte: data, x: U2::from_byte(data, 6), y: U3::from_byte(data, 3), z: U3::from_byte(data, 0), p: U2::from_byte(data, 4), q: U1::from_byte(data, 3), } } }
// implements the Canny edge feature pub struct Canny { } impl Canny { } pub fn find_canny_edges(/*Image*/) /*-> Canny*/ { }
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate as libra_crypto; use crate::{ hash::{CryptoHash, CryptoHasher}, HashValue, }; use libra_crypto_derive::CryptoHasher; use tiny_keccak::{Hasher, Sha3}; /// This file tests the CryptoHasher derive macro defined in the crypto-derive /// crate. This macro, as the comments there indicate, is meant to derive an /// instance of CryptoHasher (see `crate::hash`) for any type, which /// domain-separation tag is precisely the fully-qualified name of the /// struct. Here, we create a struct, manually "compute" its tag and compare it /// to the generated one. #[derive(CryptoHasher)] pub struct Foo {} impl CryptoHash for Foo { type Hasher = FooHasher; fn hash(&self) -> HashValue { // we voluntarily keep the contents empty, since we just want to test // the hasher prefix let state = Self::Hasher::default(); state.finish() } } // workaround of crate::hash::LIBRA_HASH_SUFFIX being private // the const below should always be a copy of it const LIBRA_HASH_SUFFIX_FOR_TESTING: &[u8] = b"@@$$LIBRA$$@@"; #[test] fn test_cryptohasher_name() { let mut name = "libra_crypto::unit_tests::cryptohasher::Foo" .as_bytes() .to_vec(); name.extend_from_slice(LIBRA_HASH_SUFFIX_FOR_TESTING); let mut digest = Sha3::v256(); digest.update(HashValue::from_sha3_256(&name[..]).as_ref()); let expected = { let mut hasher_bytes = [0u8; 32]; digest.finalize(&mut hasher_bytes); hasher_bytes }; let foo_instance = Foo {}; let foo_hash = CryptoHash::hash(&foo_instance); let actual = foo_hash.as_ref(); assert_eq!( &expected, actual, "\nexpected: {} actual: {}", String::from_utf8_lossy(&expected), String::from_utf8_lossy(actual) ); }
use super::{CoBuchiAutomaton, StateId}; use hyperltl::HyperLTL; use pest::Parser; use smtlib; use std::cell::RefCell; use std::collections::HashMap; use std::convert::TryInto; use std::error::Error; use std::os::unix::process::CommandExt; use std::process::Command; #[derive(Parser)] #[grammar = "automata/neverclaim.pest"] struct NeverClaimParser; pub enum LTL2Automaton { Spot, } thread_local! {static cache: RefCell<HashMap<HyperLTL, CoBuchiAutomaton<smtlib::Term>>> = RefCell::new(HashMap::new())} impl LTL2Automaton { pub fn to_ucw(&self, spec: &HyperLTL) -> Result<CoBuchiAutomaton<smtlib::Term>, Box<Error>> { assert!(spec.is_quantifier_free()); // check if automaton is in cache if let Some(res) = cache.with(|cache_cell| -> Option<CoBuchiAutomaton<smtlib::Term>> { cache_cell.borrow().get(spec).cloned() }) { return Ok(res); } // make thr current process the leader of a new process group // thus, the child cwill be terminated on timeout as well unsafe { libc::setsid() }; let output = Command::new("ltl2tgba") .env("PATH", "../external/bin:./external/bin") .arg("-f") .arg(spec.to_spot()) .arg("--spin") .arg("--low") .output()?; //println!("{:?}", output); if !output.status.success() { let stderr = String::from_utf8(output.stderr)?; panic!("automaton construction failed:\n{}", stderr); } assert!(output.status.success()); let stdout = String::from_utf8(output.stdout)?; let mut automaton = CoBuchiAutomaton::from(&stdout, spec.get_occurrences().into_iter())?; automaton.remove_rejecting_sinks(); // insert into cache cache.with(|cache_cell| { cache_cell.borrow_mut().insert(spec.clone(), automaton.clone()) }); Ok(automaton) } } impl CoBuchiAutomaton<smtlib::Term> { fn from<'a>(neverclaim: &str, props: impl Iterator<Item = String>) -> Result<Self, Box<Error>> { let pairs = NeverClaimParser::parse(Rule::neverclaim, neverclaim)?; let mut instance = smtlib::Instance::new(); for prop in props { instance.declare_const(&prop, smtlib::Sort::BOOL); } let mut automaton = CoBuchiAutomaton::<smtlib::Term>::new(instance); let mut translation: HashMap<&str, StateId> = HashMap::new(); for pair in pairs { match pair.as_rule() { Rule::state => (), Rule::EOI => break, _ => unreachable!(), } let mut state_decl = pair.into_inner(); let name = state_decl.next().expect("mismatch in neverclaim parser"); assert!(name.as_rule() == Rule::identifier); let name = name.as_str(); let initial = name.ends_with("_init"); let rejecting = name.starts_with("accept_"); let entry = translation .entry(name) .or_insert_with(|| automaton.new_state()); let id = *entry; let state = automaton.get_state_mut(id); state.name = Some(name.to_string()); state.initial = initial; state.rejecting = rejecting; while let Some(transition) = state_decl.next() { if transition.as_rule() == Rule::skip { automaton.add_transition(id, id, smtlib::Term::TRUE); assert!(transition.into_inner().next() == None); break; } let mut transition = transition.into_inner(); let expression = transition .next() .expect("expected expression in transition"); let term = smtlib::parse::propositional::parse( &mut automaton.manager, expression.as_str(), )?; let target = transition.next().expect("expect traget node in transition"); let target_id = *(translation .entry(target.as_str()) .or_insert_with(|| automaton.new_state())); automaton.add_transition(id, target_id, term); } } Ok(automaton) } } #[cfg(test)] mod tests { use super::*; #[test] fn parse_never_claim() { let claim = "never { /* G!b M X(!a | !b) */ T0_init: if :: (true) -> goto T0_S1 :: (!(b)) -> goto accept_S2 fi; T0_S1: if :: ((!(a)) || (!(b))) -> goto T0_S1 :: (!(b)) -> goto accept_S2 fi; accept_S2: if :: (!(b)) -> goto accept_S2 fi; }"; NeverClaimParser::parse(Rule::neverclaim, claim).unwrap_or_else(|e| panic!("{}", e)); } #[test] fn convert_spot() -> Result<(), Box<Error>> { use hyperltl::Op::{Finally, Globally}; let ltl = HyperLTL::Appl( Globally, vec![HyperLTL::Appl( Finally, vec![HyperLTL::Prop("a".into(), None)], )], ); let converter = LTL2Automaton::Spot; let automaton = converter.to_ucw(&ltl)?; assert!(automaton.states.len() == 2); Ok(()) } }
/// An enum to represent all characters in the VerticalForms block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum VerticalForms { /// \u{fe10}: '︐' PresentationFormForVerticalComma, /// \u{fe11}: '︑' PresentationFormForVerticalIdeographicComma, /// \u{fe12}: '︒' PresentationFormForVerticalIdeographicFullStop, /// \u{fe13}: '︓' PresentationFormForVerticalColon, /// \u{fe14}: '︔' PresentationFormForVerticalSemicolon, /// \u{fe15}: '︕' PresentationFormForVerticalExclamationMark, /// \u{fe16}: '︖' PresentationFormForVerticalQuestionMark, /// \u{fe17}: '︗' PresentationFormForVerticalLeftWhiteLenticularBracket, /// \u{fe18}: '︘' PresentationFormForVerticalRightWhiteLenticularBrakcet, /// \u{fe19}: '︙' PresentationFormForVerticalHorizontalEllipsis, } impl Into<char> for VerticalForms { fn into(self) -> char { match self { VerticalForms::PresentationFormForVerticalComma => '︐', VerticalForms::PresentationFormForVerticalIdeographicComma => '︑', VerticalForms::PresentationFormForVerticalIdeographicFullStop => '︒', VerticalForms::PresentationFormForVerticalColon => '︓', VerticalForms::PresentationFormForVerticalSemicolon => '︔', VerticalForms::PresentationFormForVerticalExclamationMark => '︕', VerticalForms::PresentationFormForVerticalQuestionMark => '︖', VerticalForms::PresentationFormForVerticalLeftWhiteLenticularBracket => '︗', VerticalForms::PresentationFormForVerticalRightWhiteLenticularBrakcet => '︘', VerticalForms::PresentationFormForVerticalHorizontalEllipsis => '︙', } } } impl std::convert::TryFrom<char> for VerticalForms { type Error = (); fn try_from(c: char) -> Result<Self, Self::Error> { match c { '︐' => Ok(VerticalForms::PresentationFormForVerticalComma), '︑' => Ok(VerticalForms::PresentationFormForVerticalIdeographicComma), '︒' => Ok(VerticalForms::PresentationFormForVerticalIdeographicFullStop), '︓' => Ok(VerticalForms::PresentationFormForVerticalColon), '︔' => Ok(VerticalForms::PresentationFormForVerticalSemicolon), '︕' => Ok(VerticalForms::PresentationFormForVerticalExclamationMark), '︖' => Ok(VerticalForms::PresentationFormForVerticalQuestionMark), '︗' => Ok(VerticalForms::PresentationFormForVerticalLeftWhiteLenticularBracket), '︘' => Ok(VerticalForms::PresentationFormForVerticalRightWhiteLenticularBrakcet), '︙' => Ok(VerticalForms::PresentationFormForVerticalHorizontalEllipsis), _ => Err(()), } } } impl Into<u32> for VerticalForms { fn into(self) -> u32 { let c: char = self.into(); let hex = c .escape_unicode() .to_string() .replace("\\u{", "") .replace("}", ""); u32::from_str_radix(&hex, 16).unwrap() } } impl std::convert::TryFrom<u32> for VerticalForms { type Error = (); fn try_from(u: u32) -> Result<Self, Self::Error> { if let Ok(c) = char::try_from(u) { Self::try_from(c) } else { Err(()) } } } impl Iterator for VerticalForms { type Item = Self; fn next(&mut self) -> Option<Self> { let index: u32 = (*self).into(); use std::convert::TryFrom; Self::try_from(index + 1).ok() } } impl VerticalForms { /// The character with the lowest index in this unicode block pub fn new() -> Self { VerticalForms::PresentationFormForVerticalComma } /// The character's name, in sentence case pub fn name(&self) -> String { let s = std::format!("VerticalForms{:#?}", self); string_morph::to_sentence_case(&s) } }
use crate::{ buffer::start_buffer_highlights, buffer::Buffer, buffer::BufferId, buffer::BufferUIState, command::LapceUICommand, command::LAPCE_UI_COMMAND, command::{LapceCommand, LAPCE_COMMAND}, editor::EditorSplitState, editor::EditorUIState, editor::HighlightTextLayout, explorer::{FileExplorerState, ICONS_DIR}, keypress::KeyPressState, language::TreeSitter, lsp::LspCatalog, palette::PaletteState, palette::PaletteType, panel::PanelProperty, panel::PanelState, proxy::start_proxy_process, proxy::LapceProxy, source_control::SourceControlState, }; use anyhow::{anyhow, Result}; use druid::{ widget::SvgData, Color, Data, Env, EventCtx, ExtEventSink, KeyEvent, Modifiers, Target, WidgetId, WindowId, }; use git2::Oid; use git2::Repository; use lapce_proxy::dispatch::NewBufferResponse; use lazy_static::lazy_static; use lsp_types::Position; use parking_lot::Mutex; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::json; use serde_json::Value; use std::io::BufReader; use std::path::Path; use std::process::Child; use std::process::Command; use std::process::Stdio; use std::sync::mpsc::{channel, Receiver, Sender}; use std::{ collections::HashMap, fs::File, io::Read, path::PathBuf, str::FromStr, sync::Arc, thread, }; use toml; use xi_rpc::Handler; use xi_rpc::RpcLoop; use xi_rpc::RpcPeer; use xi_trace::enable_tracing; lazy_static! { //pub static ref LAPCE_STATE: LapceState = LapceState::new(); pub static ref LAPCE_APP_STATE: LapceAppState = LapceAppState::new(); } #[derive(PartialEq)] enum KeymapMatch { Full, Prefix, } #[derive(Clone, PartialEq)] pub enum LapceFocus { Palette, Editor, FileExplorer, } #[derive(Clone, PartialEq, Eq, Hash)] pub enum VisualMode { Normal, Linewise, Blockwise, } #[derive(Clone, PartialEq, Eq, Hash)] pub enum Mode { Insert, Visual, Normal, } #[derive(PartialEq, Eq, Hash, Default, Clone)] pub struct KeyPress { pub key: druid::keyboard_types::Key, pub mods: Modifiers, } #[derive(PartialEq, Eq, Hash, Clone)] pub struct KeyMap { pub key: Vec<KeyPress>, pub modes: Vec<Mode>, pub when: Option<String>, pub command: String, } #[derive(Clone)] pub struct LapceUIState { pub focus: LapceFocus, pub mode: Mode, pub buffers: Arc<HashMap<BufferId, Arc<BufferUIState>>>, pub editors: Arc<HashMap<WidgetId, EditorUIState>>, pub highlight_sender: Sender<(WindowId, WidgetId, BufferId, u64)>, } impl Data for LapceUIState { fn same(&self, other: &Self) -> bool { self.focus == other.focus && self.buffers.same(&other.buffers) && self.editors.same(&other.editors) } } impl LapceUIState { pub fn new(event_sink: ExtEventSink) -> LapceUIState { let mut editors = HashMap::new(); for (_, state) in LAPCE_APP_STATE.states.lock().iter() { for (_, state) in state.states.lock().iter() { for (_, editor) in state.editor_split.lock().editors.iter() { let editor_ui_state = EditorUIState::new(); editors.insert(editor.view_id, editor_ui_state); } } } let (sender, receiver) = channel(); let state = LapceUIState { mode: Mode::Normal, buffers: Arc::new(HashMap::new()), focus: LapceFocus::Editor, editors: Arc::new(editors), highlight_sender: sender, }; thread::spawn(move || { start_buffer_highlights(receiver, event_sink); }); state } pub fn get_buffer_mut(&mut self, buffer_id: &BufferId) -> &mut BufferUIState { Arc::make_mut(Arc::make_mut(&mut self.buffers).get_mut(buffer_id).unwrap()) } pub fn get_buffer(&self, buffer_id: &BufferId) -> &BufferUIState { self.buffers.get(buffer_id).unwrap() } pub fn new_editor(&mut self, editor_id: &WidgetId) { let editor_ui_state = EditorUIState::new(); Arc::make_mut(&mut self.editors).insert(editor_id.clone(), editor_ui_state); } pub fn get_editor_mut(&mut self, view_id: &WidgetId) -> &mut EditorUIState { Arc::make_mut(&mut self.editors).get_mut(view_id).unwrap() } pub fn get_editor(&self, view_id: &WidgetId) -> &EditorUIState { self.editors.get(view_id).unwrap() } } #[derive(Clone, Debug)] pub enum LapceWorkspaceType { Local, RemoteSSH(String, String), } #[derive(Clone, Debug)] pub struct LapceWorkspace { pub kind: LapceWorkspaceType, pub path: PathBuf, } #[derive(Clone, Debug, Default)] pub struct Counter(usize); impl Counter { pub fn next(&mut self) -> usize { let n = self.0; self.0 = n + 1; n + 1 } } #[derive(Clone)] pub struct LapceAppState { pub states: Arc<Mutex<HashMap<WindowId, LapceWindowState>>>, pub theme: HashMap<String, Color>, pub ui_sink: Arc<Mutex<Option<ExtEventSink>>>, id_counter: Arc<Mutex<Counter>>, } impl LapceAppState { pub fn new() -> LapceAppState { LapceAppState { states: Arc::new(Mutex::new(HashMap::new())), theme: Self::get_theme().unwrap_or(HashMap::new()), ui_sink: Arc::new(Mutex::new(None)), id_counter: Arc::new(Mutex::new(Counter::default())), } } fn get_theme() -> Result<HashMap<String, Color>> { let mut f = File::open("/Users/Lulu/lapce/.lapce/theme.toml")?; let mut content = vec![]; f.read_to_end(&mut content)?; let toml_theme: HashMap<String, String> = toml::from_slice(&content)?; let mut theme = HashMap::new(); for (name, hex) in toml_theme.iter() { if let Ok(color) = hex_to_color(hex) { theme.insert(name.to_string(), color); } } Ok(theme) } pub fn next_id(&self) -> usize { self.id_counter.lock().next() } pub fn set_ui_sink(&self, ui_event_sink: ExtEventSink) { *self.ui_sink.lock() = Some(ui_event_sink); } pub fn get_window_state(&self, window_id: &WindowId) -> LapceWindowState { self.states.lock().get(window_id).unwrap().clone() } pub fn get_active_tab_state(&self, window_id: &WindowId) -> LapceTabState { let window_state = self.get_window_state(window_id); let active = window_state.active.lock(); let tab_states = window_state.states.lock(); tab_states.get(&active).unwrap().clone() } pub fn get_tab_state( &self, window_id: &WindowId, tab_id: &WidgetId, ) -> LapceTabState { self.states .lock() .get(window_id) .unwrap() .states .lock() .get(tab_id) .unwrap() .clone() } pub fn submit_ui_command(&self, comand: LapceUICommand, widget_id: WidgetId) { self.ui_sink.lock().as_ref().unwrap().submit_command( LAPCE_UI_COMMAND, comand, Target::Widget(widget_id), ); } } #[derive(Clone)] pub struct LapceWindowState { pub window_id: WindowId, pub states: Arc<Mutex<HashMap<WidgetId, LapceTabState>>>, pub active: Arc<Mutex<WidgetId>>, } impl LapceWindowState { pub fn new() -> LapceWindowState { let window_id = WindowId::next(); let state = LapceTabState::new(window_id.clone()); let active = state.tab_id; let mut states = HashMap::new(); states.insert(active.clone(), state); LapceWindowState { window_id, states: Arc::new(Mutex::new(states)), active: Arc::new(Mutex::new(active)), } } pub fn get_active_state(&self) -> LapceTabState { self.states.lock().get(&self.active.lock()).unwrap().clone() } pub fn get_state(&self, tab_id: &WidgetId) -> LapceTabState { self.states.lock().get(tab_id).unwrap().clone() } } #[derive(Clone)] pub struct LapceTabState { pub window_id: WindowId, pub tab_id: WidgetId, pub status_id: WidgetId, pub workspace: Arc<Mutex<LapceWorkspace>>, pub palette: Arc<Mutex<PaletteState>>, pub keypress: Arc<Mutex<KeyPressState>>, pub focus: Arc<Mutex<LapceFocus>>, pub editor_split: Arc<Mutex<EditorSplitState>>, pub container: Option<WidgetId>, pub file_explorer: Arc<Mutex<FileExplorerState>>, pub source_control: Arc<Mutex<SourceControlState>>, pub panel: Arc<Mutex<PanelState>>, // pub plugins: Arc<Mutex<PluginCatalog>>, // pub lsp: Arc<Mutex<LspCatalog>>, // pub ssh_session: Arc<Mutex<Option<SshSession>>>, pub proxy: Arc<Mutex<Option<LapceProxy>>>, } impl LapceTabState { pub fn new(window_id: WindowId) -> LapceTabState { let workspace = LapceWorkspace { kind: LapceWorkspaceType::Local, path: PathBuf::from("/Users/Lulu/lapce"), }; //let workspace = LapceWorkspace { // kind: LapceWorkspaceType::RemoteSSH("10.132.0.2:22".to_string()), // path: PathBuf::from("/home/dz/cosmos"), //}; let tab_id = WidgetId::next(); let status_id = WidgetId::next(); let state = LapceTabState { window_id, tab_id: tab_id.clone(), status_id, workspace: Arc::new(Mutex::new(workspace.clone())), focus: Arc::new(Mutex::new(LapceFocus::Editor)), palette: Arc::new(Mutex::new(PaletteState::new( window_id.clone(), tab_id.clone(), ))), editor_split: Arc::new(Mutex::new(EditorSplitState::new( window_id.clone(), tab_id.clone(), ))), file_explorer: Arc::new(Mutex::new(FileExplorerState::new( window_id.clone(), tab_id.clone(), ))), source_control: Arc::new(Mutex::new(SourceControlState::new( window_id, tab_id, ))), container: None, keypress: Arc::new(Mutex::new(KeyPressState::new( window_id.clone(), tab_id.clone(), ))), panel: Arc::new(Mutex::new(PanelState::new(window_id, tab_id))), proxy: Arc::new(Mutex::new(None)), }; state.panel.lock().add(state.file_explorer.clone()); state.panel.lock().add(state.source_control.clone()); let local_state = state.clone(); thread::spawn(move || { local_state.start_proxy(); }); state } pub fn start_proxy(&self) { start_proxy_process( self.window_id, self.tab_id, self.workspace.lock().clone(), ); } pub fn stop(&self) { self.proxy.lock().as_ref().unwrap().stop(); } pub fn start_plugin(&self) { // let mut plugins = self.plugins.lock(); // plugins.reload_from_paths(&[PathBuf::from_str("./lsp").unwrap()]); // plugins.start_all(); } pub fn open( &self, ctx: &mut EventCtx, ui_state: &mut LapceUIState, path: &Path, ) { if path.is_dir() { *self.workspace.lock() = LapceWorkspace { kind: LapceWorkspaceType::Local, path: path.to_path_buf(), }; self.stop(); self.start_plugin(); ctx.request_paint(); } else { self.editor_split.lock().open_file( ctx, ui_state, path.to_str().unwrap(), ); } } pub fn get_icon(&self, name: &str) -> Option<&SvgData> { None } pub fn get_mode(&self) -> Mode { match *self.focus.lock() { LapceFocus::Palette => Mode::Insert, LapceFocus::Editor => self.editor_split.lock().get_mode(), LapceFocus::FileExplorer => Mode::Normal, } } pub fn get_ssh_session(&self, user: &str, host: &str) -> Result<()> { Ok(()) } pub fn insert( &self, ctx: &mut EventCtx, ui_state: &mut LapceUIState, content: &str, env: &Env, ) { match *self.focus.lock() { LapceFocus::Palette => { self.palette.lock().insert(ctx, ui_state, content, env); } LapceFocus::Editor => { self.editor_split.lock().insert(ctx, ui_state, content, env); } _ => (), } // ctx.request_layout(); } pub fn run_command( &self, ctx: &mut EventCtx, ui_state: &mut LapceUIState, count: Option<usize>, command: &str, env: &Env, ) -> Result<()> { let cmd = LapceCommand::from_str(command)?; match cmd { LapceCommand::Palette => { *self.focus.lock() = LapceFocus::Palette; self.palette.lock().run(None); ctx.request_layout(); } LapceCommand::PaletteLine => { *self.focus.lock() = LapceFocus::Palette; self.palette.lock().run(Some(PaletteType::Line)); ctx.request_layout(); } LapceCommand::PaletteSymbol => { *self.focus.lock() = LapceFocus::Palette; self.palette.lock().run(Some(PaletteType::DocumentSymbol)); ctx.request_layout(); } LapceCommand::PaletteCancel => { *self.focus.lock() = LapceFocus::Editor; self.palette.lock().cancel(ctx, ui_state); ctx.request_layout(); } LapceCommand::FileExplorer => { *self.focus.lock() = LapceFocus::FileExplorer; ctx.request_paint(); } LapceCommand::FileExplorerCancel => { *self.focus.lock() = LapceFocus::Editor; ctx.request_paint(); } _ => { let mut focus = self.focus.lock(); match *focus { LapceFocus::FileExplorer => { *focus = self .file_explorer .lock() .run_command(ctx, ui_state, count, cmd); } LapceFocus::Editor => { self.editor_split .lock() .run_command(ctx, ui_state, count, cmd, env); } LapceFocus::Palette => { let mut palette = self.palette.lock(); match cmd { LapceCommand::ListSelect => { palette.select(ctx, ui_state, env); *focus = LapceFocus::Editor; ctx.request_layout(); } LapceCommand::ListNext => { palette.change_index(ctx, ui_state, 1, env); } LapceCommand::ListPrevious => { palette.change_index(ctx, ui_state, -1, env); } LapceCommand::Left => { palette.move_cursor(ctx, -1); } LapceCommand::Right => { palette.move_cursor(ctx, 1); } LapceCommand::DeleteBackward => { palette.delete_backward(ctx, ui_state, env); } LapceCommand::DeleteToBeginningOfLine => { palette .delete_to_beginning_of_line(ctx, ui_state, env); } _ => (), }; } }; } }; ui_state.focus = self.focus.lock().clone(); Ok(()) } pub fn request_paint(&self) { LAPCE_APP_STATE.submit_ui_command(LapceUICommand::RequestPaint, self.tab_id); } pub fn check_condition(&self, condition: &str) -> bool { let or_indics: Vec<_> = condition.match_indices("||").collect(); let and_indics: Vec<_> = condition.match_indices("&&").collect(); if and_indics.is_empty() { if or_indics.is_empty() { return self.check_one_condition(condition); } else { return self.check_one_condition(&condition[..or_indics[0].0]) || self.check_condition(&condition[or_indics[0].0 + 2..]); } } else { if or_indics.is_empty() { return self.check_one_condition(&condition[..and_indics[0].0]) && self.check_condition(&condition[and_indics[0].0 + 2..]); } else { if or_indics[0].0 < and_indics[0].0 { return self.check_one_condition(&condition[..or_indics[0].0]) || self.check_condition(&condition[or_indics[0].0 + 2..]); } else { return self.check_one_condition(&condition[..and_indics[0].0]) && self.check_condition(&condition[and_indics[0].0 + 2..]); } } } } fn check_one_condition(&self, condition: &str) -> bool { let focus = self.focus.lock(); let editor_split = self.editor_split.lock(); match condition.trim() { "file_explorer_focus" => *focus == LapceFocus::FileExplorer, "palette_focus" => *focus == LapceFocus::Palette, "list_focus" => { *focus == LapceFocus::Palette || *focus == LapceFocus::FileExplorer || (*focus == LapceFocus::Editor && (editor_split.completion.len() > 0 || editor_split.code_actions_show)) } "editor_operator" => { *focus == LapceFocus::Editor && editor_split.has_operator() } _ => false, } } pub fn container_id(&self) -> WidgetId { self.container.unwrap().clone() } pub fn set_container(&mut self, container: WidgetId) { self.container = Some(container); } } pub fn hex_to_color(hex: &str) -> Result<Color> { let hex = hex.trim_start_matches("#"); let (r, g, b, a) = match hex.len() { 3 => ( format!("{}{}", &hex[0..0], &hex[0..0]), format!("{}{}", &hex[1..1], &hex[1..1]), format!("{}{}", &hex[2..2], &hex[2..2]), "ff".to_string(), ), 6 => ( hex[0..2].to_string(), hex[2..4].to_string(), hex[4..6].to_string(), "ff".to_string(), ), 8 => ( hex[0..2].to_string(), hex[2..4].to_string(), hex[4..6].to_string(), hex[6..8].to_string(), ), _ => return Err(anyhow!("invalid hex color")), }; Ok(Color::rgba8( u8::from_str_radix(&r, 16)?, u8::from_str_radix(&g, 16)?, u8::from_str_radix(&b, 16)?, u8::from_str_radix(&a, 16)?, )) } #[cfg(test)] mod tests { use xi_rope::Rope; use super::*; #[test] fn test_check_condition() { // let rope = Rope::from_str("abc\nabc\n").unwrap(); // assert_eq!(rope.len(), 9); // assert_eq!(rope.offset_of_line(1), 1); // assert_eq!(rope.line_of_offset(rope.len()), 9); } }
extern crate rust2018; use rust2018::do_thing; #[test] fn test() { do_thing(); }
use crate::app::App; use std::future::Future; use std::net::SocketAddr; pub struct Server { app: App, } impl Server { pub fn new(app: App) -> Self { Server { app } } pub fn run<T: Into<SocketAddr> + 'static>(&self, addr: T) -> impl Future<Output = ()> { warp::serve(router::routes(&self.app)).run(addr) } } mod router { use crate::app::App; use twitter2_api::{error::ServiceError, infra::jwt_handler}; use warp::{ filters::BoxedFilter, http::status::StatusCode, reply::{self, Json, Reply, WithStatus}, Filter, }; pub fn routes(app: &App) -> BoxedFilter<(impl Reply,)> { healthcheck().or(api(app)).boxed() } fn healthcheck() -> BoxedFilter<(String,)> { warp::path("healthcheck").map(|| "ok".into()).boxed() } fn api(app: &App) -> BoxedFilter<(impl Reply,)> { let api = warp::path("api"); let v1 = warp::path("v1"); api.and(v1.and(users(app).or(posts(app)))) .with(security::cors()) .boxed() } fn users(app: &App) -> BoxedFilter<(impl Reply,)> { let users = warp::path("users"); let app_c = app.clone(); let upsert = warp::put() .and(security::authorization()) .map(move |verification_result| { claims_handle_helper(verification_result, |claims| { let res = app_c.services.user_service.upsert(&claims.sub); match res { Ok(num) if num == 0 => { reply::with_status(reply::json(&"".to_string()), StatusCode::NO_CONTENT) } Ok(_) => reply::with_status( reply::json(&StatusCode::CREATED.to_string()), StatusCode::CREATED, ), Err(_) => reply::with_status( reply::json(&StatusCode::INTERNAL_SERVER_ERROR.to_string()), StatusCode::INTERNAL_SERVER_ERROR, ), } }) }); users.and(upsert).boxed() } fn posts(app: &App) -> BoxedFilter<(impl Reply,)> { let posts = warp::path("posts"); let app_c = app.clone(); let own_posts = warp::path("own") .and(security::authorization()) .map(move |verification_result| { claims_handle_helper(verification_result, |claims| { let res = app_c .services .post_service .pagenate_posts_of_user_by_sub_id(&claims.sub, 20, 0); match res { Ok(own_posts) => { reply::with_status(reply::json(&own_posts), StatusCode::OK) } Err(ServiceError::NotFound) => reply::with_status( reply::json(&StatusCode::NOT_FOUND.to_string()), StatusCode::NOT_FOUND, ), Err(ServiceError::DbQueryFailed(_)) => reply::with_status( reply::json(&StatusCode::INTERNAL_SERVER_ERROR.to_string()), StatusCode::INTERNAL_SERVER_ERROR, ), } }) }); posts.and(own_posts).boxed() } /// Inspects `verification_result` to early reply when it's JwtError, or else delegates handling the claims to `handler`. fn claims_handle_helper<F>( verification_result: Result<jwt_handler::Claims, jwt_handler::JwtError>, handler: F, ) -> WithStatus<Json> where F: Fn(jwt_handler::Claims) -> WithStatus<Json>, { let invalid_token_message = "Invalid token".to_string(); let claims = match verification_result { Ok(claims) => claims, Err(jwt_error) => match jwt_error { jwt_handler::JwtError::FetchJwks(_) => { return reply::with_status( reply::json(&StatusCode::INTERNAL_SERVER_ERROR.to_string()), StatusCode::INTERNAL_SERVER_ERROR, ); } jwt_handler::JwtError::DecodingFailed(_) | jwt_handler::JwtError::JwkNotFound | jwt_handler::JwtError::KidMissing => { return reply::with_status( reply::json(&invalid_token_message), StatusCode::UNAUTHORIZED, ); } }, }; handler(claims) } mod security { use std::convert::Infallible; use std::env; use twitter2_api::infra::jwt_handler; use warp::{filters::BoxedFilter, Filter}; pub fn authorization() -> BoxedFilter<(Result<jwt_handler::Claims, jwt_handler::JwtError>,)> { warp::header::<String>("authorization") .and_then(verify_token) .boxed() } async fn verify_token( autorization_token: String, ) -> Result<Result<jwt_handler::Claims, jwt_handler::JwtError>, Infallible> { let token = autorization_token .trim() .strip_prefix("Bearer ") .unwrap_or(""); let verification_result = jwt_handler::verify(token).await; Ok(verification_result) } pub fn cors() -> warp::cors::Builder { let allowed_origin = env::var("ALLOWED_ORIGIN").expect("ALLOWED_ORIGIN must be set"); warp::cors() .allow_origin(allowed_origin.as_str()) .allow_headers(vec!["authorization"]) .allow_methods(vec!["GET", "POST", "PUT", "DELETE"]) } } }
//! See the [parent crate documentation](https://docs.rs/serde_piecewise_default/) for more information. #![recursion_limit="512"] extern crate proc_macro; extern crate proc_macro2; #[macro_use] extern crate quote; extern crate syn; extern crate serde; use crate::proc_macro::TokenStream as RustTS; use crate::proc_macro2::TokenStream; use syn::*; use syn::spanned::Spanned; use proc_macro2::Span; /// See the [parent crate documentation](https://docs.rs/serde_piecewise_default/) for a high-level overview. /// /// # Implementation Details /// /// ```rust,no_run /// # use serde_piecewise_default_derive::DeserializePiecewiseDefault; /// # use serde::Deserialize; /// #[derive(DeserializePiecewiseDefault)] /// struct Example { /// item1: i8, /// item2: String, /// } /// # impl Default for Example { /// # fn default() -> Example { Example { item1: 10, item2: "Hi".to_string() }} /// # } /// ``` /// will expand to /// ```rust,no_run /// struct Example { /// item1: i8, /// item2: String, /// } /// # impl Default for Example { /// # fn default() -> Example { Example { item1: 10, item2: "Hi".to_string() }} /// # } /// /// # use serde::Deserialize; /// #[derive(Deserialize)] /// struct OptionExample { /// item1: Option<i8>, /// item2: Option<String>, /// } /// /// impl<'de> Deserialize<'de> for Example { /// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { /// <OptionExample as Deserialize>::deserialize(deserializer) /// .map(|raw_result| { /// let OptionExample { item1, item2 } = raw_result; /// let default = <Example as Default>::default(); /// let item1 = item1.unwrap_or(default.item1); /// let item2 = item2.unwrap_or(default.item2); /// Example { item1, item2 } /// }) /// } /// } /// ``` #[proc_macro_derive(DeserializePiecewiseDefault)] pub fn deserialize_piecewise_default_derive(input: RustTS) -> RustTS { let ast = parse_macro_input!(input as DeriveInput); impl_deserialize_piecewise_default(&ast).into() } fn impl_deserialize_piecewise_default(ast: &DeriveInput) -> TokenStream { let name = &ast.ident; match ast.data { Data::Struct(ref data) => { let optional_struct = make_optional_struct(data, name); let optional_name = get_optional_name(name); let field_binding = make_structure(data, &optional_name); let field_movements = make_field_movements(data); let result = make_structure(data, name); quote! { #optional_struct impl<'de> Deserialize<'de> for #name { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { <#optional_name as Deserialize>::deserialize(deserializer) .map(|raw_result| { let #field_binding = raw_result; let default = <#name as Default>::default(); #field_movements #result }) } } } }, _ => panic!("can only use piecewise default on structs") } } fn get_structure_name((i, field): (usize, &Field)) -> Ident { match field.ident { Some(ref ident) => ident.clone(), None => { let name = format!("f{}", i); Ident::new(&name, Span::call_site()) } } } fn get_optional_name(orig_name: &Ident) -> Ident { Ident::new(&format!("Option{}", orig_name), orig_name.span()) } fn make_optional_struct(data: &DataStruct, orig_name: &Ident) -> TokenStream { let new_name = get_optional_name(orig_name); let fields = data.fields.iter().map(make_field_optional).collect::<Vec<_>>(); let struct_decl_body = match data.fields { Fields::Named(_) => quote!{ { #(#fields),* } }, Fields::Unnamed(_) => { // wasn't my idea, serde itself doesn't like deserializing tuples of Option with some holes panic!("can only use piecewise default with named fields") } // quote!{ // (#(#fields),*); // }, Fields::Unit => quote!{;} }; quote! { #[derive(Deserialize)] struct #new_name #struct_decl_body } } fn make_field_optional(field: &Field) -> TokenStream { let Field { attrs, vis, ident, colon_token, ty } = field; let span = field.span(); quote_spanned!(span=> #(#attrs)* #vis #ident #colon_token Option<#ty>) } fn make_structure(data: &DataStruct, name: &Ident) -> TokenStream { let fields = data.fields.iter().enumerate().map(make_field_structure).collect::<Vec<_>>(); match data.fields { Fields::Unnamed(_) => quote!(#name(#(#fields),*)), Fields::Named(_) => quote!(#name{#(#fields),*}), Fields::Unit => quote!(#name()), } } fn make_field_structure((i, field): (usize, &Field)) -> TokenStream { let ident = get_structure_name((i, field)); quote!(#ident) } fn make_field_movements(data: &DataStruct) -> TokenStream { let movements = data.fields.iter().enumerate() .map(|x| (x, get_structure_name(x))) .map(make_field_movement) .collect::<Vec<_>>(); quote! { #(#movements )* } } fn make_field_movement((orig_field, structure_name): ((usize, &Field), Ident)) -> TokenStream { let orig_name = match orig_field.1.ident { Some(ref ident) => Member::Named(ident.clone()), None => Member::Unnamed(Index { index: orig_field.0 as u32, span: orig_field.1.span() }) }; quote!(let #structure_name = #structure_name.unwrap_or(default.#orig_name);) }
/* chapter 4 primitive types */ fn main() {} // output should be: /* */
use crate::lexer::Token; use thiserror::Error; pub type ParseResult<T, E = ParseError> = Result<T, E>; #[derive(Error, Debug, Clone, PartialEq)] pub enum ParseError { #[error("{0}")] Custom(&'static str), #[error("Bad number")] BadNumber, #[error("Unexpected end of file")] UnexpectedEof, #[error("No semicolon after statement was found")] NoSemicolon, #[error("Bad prefix operator `{op}`")] BadPrefixOperator { op: String, }, #[error("Bad postfix operator `{op}`")] BadPostfixOperator { op: String }, #[error("Expected semicolon, got `{got}`")] ExpectedSemicolon { got: String, }, #[error("Expected token `{token}`, got token `{got}`")] Expected { token: &'static str, got: &'static str, } }
use num::bigint::BigInt; use num::bigint::ToBigInt; // The modular_exponentiation() function takes three identical types // (which get cast to BigInt), and returns a BigInt: #[allow(dead_code)] pub fn mod_exp<T: ToBigInt>(n: &T, e: &T, m: &T) -> BigInt { // Convert n, e, and m to BigInt: let n = n.to_bigint().unwrap(); let e = e.to_bigint().unwrap(); let m = m.to_bigint().unwrap(); // Sanity check: Verify that the exponent is not negative: assert!(e >= Zero::zero()); use num::traits::{Zero, One}; // As most modular exponentiations do, return 1 if the exponent is 0: if e == Zero::zero() { return One::one() } // Now do the modular exponentiation algorithm: let mut result: BigInt = One::one(); let mut base = n % &m; let mut exp = e; // Loop until we can return out result: loop { if &exp % 2 == One::one() { result *= &base; result %= &m; } if exp == One::one() { return result } exp /= 2; base *= base.clone(); base %= &m; } } #[allow(dead_code)] pub fn mod_inv(a: isize, module: isize) -> isize { let mut mn = (module, a); let mut xy = (0, 1); while mn.1 != 0 { xy = (xy.1, xy.0 - (mn.0 / mn.1) * xy.1); mn = (mn.1, mn.0 % mn.1); } while xy.0 < 0 { xy.0 += module; } xy.0 }
bitflags! { pub struct Modules: i32 { const Io = 1 << 0; const Fs= 1 << 1; const Utils = 1 << 2; #[cfg(feature = "http")] const Http = 1 << 3; } } impl Default for Modules { fn default() -> Modules { Modules::Io | Modules::Fs | Modules::Utils } }
use std::path::PathBuf; use std::fs; use std::env; use std::process; use std::fs::DirEntry; use regex::Regex; use std::result::Result::Ok; use crate::tn::args::Command; use std::ffi::OsString; pub mod args; const APP_NAME: &str = "tn"; type Result<T> = ::std::result::Result<T, Box<::std::error::Error>>; pub fn run(args: std::env::Args) -> Result<()> { let cmd = Command::parse(args)?; let result = run_cmd(cmd)?; Ok(result) } fn run_cmd(cmd: Command) -> Result<()> { match cmd { Command::ShowNote(ref note_name) => cat_note(note_name), Command::EditNote(ref note_name) => edit_note(&note_name), Command::ListNotes => list_notes(), Command::RemoveNote(ref note_name) => remove_note(&note_name), Command::BashCompletion => bash_completion(), Command::Commands => commands(), } } fn note_dir() -> Result<PathBuf> { let mut data_dir = dirs::document_dir().ok_or("data dir not available")?; data_dir.push(APP_NAME); data_dir.push("notes"); fs::create_dir_all(&data_dir.as_path())?; Ok(data_dir) } fn path_for_name(note_name: &str) -> Result<PathBuf> { let mut note_path = note_dir()?; note_path.push(name_to_filename(note_name)); Ok(note_path) } fn name_to_filename(name: &str) -> String { format!("{}.md", name) } fn filename_to_name(filename: &str) -> String { let pattern = Regex::new("[.]md$").unwrap(); pattern.replace(filename, "").to_string() } fn editor() -> String { match env::var("EDITOR") { Ok(editor) => editor, Err(_) => "vim".to_string(), } } fn shell() -> String { match env::var("SHELL") { Ok(editor) => editor, Err(_) => "sh".to_string(), } } fn edit_cmd(path: PathBuf) -> process::Command { let mut edit_shell_cmd = OsString::from(editor()); edit_shell_cmd.push(" "); edit_shell_cmd.push(path); let mut edit_cmd = process::Command::new(shell()); edit_cmd.arg("-c"); edit_cmd.arg(edit_shell_cmd); edit_cmd } fn cat_note(note_name: &str) -> Result<()> { let path = path_for_name(note_name)?; let content = fs::read_to_string(path)?; println!("{}", content); Ok(()) } fn edit_note(note_name: &str) -> Result<()> { let mut edit_cmd = edit_cmd(path_for_name(note_name)?); Ok(match edit_cmd.status() { Ok(status) => if status.success() { Ok(()) } else { Err("command failed".to_string()) }, Err(e) => Err(e.to_string()) }?) } fn remove_note(note_name: &str) -> Result<()> { let path = path_for_name(note_name)?; fs::remove_file(path)?; Ok(()) } fn list_notes() -> Result<()> { let note_dir = note_dir()?; let dir = fs::read_dir(note_dir)?; let mut entries: Vec<DirEntry> = dir .filter(|e| e.is_ok()) .map(|e| e.unwrap()) .collect(); entries.sort_by(|a, b| { let a_modified = a.metadata().ok() .and_then(|m| m.modified().ok()); let b_modified = b.metadata().ok() .and_then(|m| m.modified().ok()); a_modified.cmp(&b_modified) }); let filenames: Vec<String> = entries.iter() .map(|e| e.file_name()) .map(|f| f.into_string()) .filter(|f| f.is_ok()) .map(|f| f.unwrap()) .filter(|f| f.ends_with(".md")) .collect(); for filename in filenames { println!("{}", filename_to_name(filename.as_str())); } Ok(()) } fn bash_completion() -> Result<()> { let script = r##" _tn_complete() { local cur prev opts COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} opts="" if [[ "$prev" == "$1" ]]; then opts=$(tn --commands) else case "$prev" in edit|remove|show) opts=$(tn list) ;; esac fi if [[ ! -z ${opts} ]] ; then COMPREPLY=( $(compgen -o nosort -W "${opts}" -- ${cur}) ) return 0 fi } complete -F _tn_complete tn "##; println!("{}", script); Ok(()) } fn commands() -> Result<()> { let commands = vec!( "edit", "list", "remove", "show", "--help", "--version", "--bash-completion", "--commands"); for c in commands { println!("{}", c); } Ok(()) }
use quote::quote_spanned; use super::{ FlowProperties, FlowPropertyVal, OperatorCategory, OperatorConstraints, OperatorInstance, OperatorWriteOutput, WriteContextArgs, RANGE_0, RANGE_1, }; /// > 0 input streams, 1 output stream /// /// > Arguments: [`Stream`](https://docs.rs/futures/latest/futures/stream/trait.Stream.html) /// /// Given a [`Stream`](https://docs.rs/futures/latest/futures/stream/trait.Stream.html) /// of `(serialized payload, addr)` pairs, deserializes the payload and emits each of the /// elements it receives downstream. /// /// ```rustbook /// async fn serde_in() { /// let addr = hydroflow::util::ipv4_resolve("localhost:9000".into()).unwrap(); /// let (outbound, inbound, _) = hydroflow::util::bind_udp_bytes(addr).await; /// let mut flow = hydroflow::hydroflow_syntax! { /// source_stream_serde(inbound) -> map(Result::unwrap) -> map(|(x, a): (String, std::net::SocketAddr)| x.to_uppercase()) /// -> for_each(|x| println!("{}", x)); /// }; /// flow.run_available(); /// } /// ``` pub const SOURCE_STREAM_SERDE: OperatorConstraints = OperatorConstraints { name: "source_stream_serde", categories: &[OperatorCategory::Source], hard_range_inn: RANGE_0, soft_range_inn: RANGE_0, hard_range_out: RANGE_1, soft_range_out: RANGE_1, num_args: 1, persistence_args: RANGE_0, type_args: RANGE_0, is_external_input: true, ports_inn: None, ports_out: None, properties: FlowProperties { deterministic: FlowPropertyVal::DependsOnArgs, monotonic: FlowPropertyVal::DependsOnArgs, inconsistency_tainted: false, }, input_delaytype_fn: |_| None, write_fn: |wc @ &WriteContextArgs { root, context, op_span, ident, op_inst: OperatorInstance { arguments, .. }, .. }, _| { let receiver = &arguments[0]; let stream_ident = wc.make_ident("stream"); let write_prologue = quote_spanned! {op_span=> let mut #stream_ident = Box::pin(#receiver); }; let write_iterator = quote_spanned! {op_span=> let #ident = std::iter::from_fn(|| { match #root::futures::stream::Stream::poll_next(#stream_ident.as_mut(), &mut std::task::Context::from_waker(&#context.waker())) { std::task::Poll::Ready(Some(std::result::Result::Ok((payload, addr)))) => Some(#root::util::deserialize_from_bytes(payload).map(|payload| (payload, addr))), std::task::Poll::Ready(Some(Err(_))) => None, std::task::Poll::Ready(None) => None, std::task::Poll::Pending => None, } }); }; Ok(OperatorWriteOutput { write_prologue, write_iterator, ..Default::default() }) }, };
// =============================================================================================== // Imports // =============================================================================================== use core::fmt; use core::fmt::Write; use core::ptr::Unique; use spin::{Mutex, RwLock}; // =============================================================================================== // Statics // =============================================================================================== pub static WRITER: Mutex<Writer> = Mutex::new(unsafe { unsafe_writer(DEFAULT_FG, DEFAULT_BG) }); pub static ENABLED: RwLock<bool> = RwLock::new(true); pub static CURSOR_UPDATE: RwLock<bool> = RwLock::new(true); // =============================================================================================== // General Constants // =============================================================================================== const SCREEN_WIDTH: usize = 80; const SCREEN_HEIGHT: usize = 25; // =============================================================================================== // CRT Ports & Register // =============================================================================================== const CRT_CMD: u16 = 0x3D4; const CRT_DAT: u16 = 0x3D5; #[repr(u8)] enum CRTRegister { CursorFmtHi = 0x0A, CursorFmtLo = 0x0B, ScreenStartHi = 0x0C, ScreenStartLo = 0x0D, CursorStartHi = 0x0E, CursorStartLo = 0x0F, } // =============================================================================================== // Color // =============================================================================================== pub const DEFAULT_FG: Color = Color::Cyan; pub const DEFAULT_BG: Color = Color::Black; #[repr(u8)] pub enum Color { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, Pink = 13, Yellow = 14, White = 15, } pub fn color_from_u8(color: u8) -> Color { match color { 00 => Color::Black, 01 => Color::Blue, 02 => Color::Green, 03 => Color::Cyan, 04 => Color::Red, 05 => Color::Magenta, 06 => Color::Brown, 07 => Color::LightGray, 08 => Color::DarkGray, 09 => Color::LightBlue, 10 => Color::LightGreen, 11 => Color::LightCyan, 12 => Color::LightRed, 13 => Color::Pink, 14 => Color::Yellow, _ => Color::White, } } // =============================================================================================== // Cursor // =============================================================================================== const CURSOR_LINE: u8 = 0x1F; const CURSOR_BLOCK: u8 = 0x03; pub struct Cursor {} impl Cursor { // ---------------------------------------------------- // Display / Format // ---------------------------------------------------- pub fn set(enable: bool, timing: bool, block: bool) { // Lo Bits 0 - 4 are upper end of cursor let lo: u8 = if block { CURSOR_BLOCK } else { CURSOR_LINE }; // Hi Bits 0 - 4 are lower end of cursor (0) // Hi Bits 5 & 6 are timing and enable let hi: u8 = (enable as u8) << 6 | (timing as u8) << 5; unsafe { // Update format high outb!(CRT_CMD, CRTRegister::CursorFmtHi as u8); outb!(CRT_DAT, hi); // Update format low outb!(CRT_CMD, CRTRegister::CursorFmtLo as u8); outb!(CRT_DAT, lo); }; } // ---------------------------------------------------- // Position // ---------------------------------------------------- pub fn position(column: u8, row: u8) { debug_assert!(column < SCREEN_WIDTH as u8 && row < SCREEN_HEIGHT as u8); let position: u16 = row as u16 * SCREEN_WIDTH as u16 + column as u16; unsafe { // Set position bits 8 - 15 outb!(CRT_CMD, CRTRegister::CursorStartHi as u8); outb!(CRT_DAT, (position >> 0x08) as u8); // Set position bits 0 - 7 outb!(CRT_CMD, CRTRegister::CursorStartLo as u8); outb!(CRT_DAT, (position & 0x00FF) as u8); } } } // =============================================================================================== // Color Code // =============================================================================================== #[derive(Clone, Copy)] pub struct ColorCode(u8); impl ColorCode { pub const fn new(foreground: Color, background: Color) -> ColorCode { ColorCode((background as u8) << 4 | (foreground as u8)) } pub fn set_bg(&mut self, color: Color) { self.0 &= 0x0F; self.0 |= (color as u8) << 4; } pub fn bg(&self) -> Color { color_from_u8(self.0 >> 4) } pub fn set_fg(&mut self, color: Color) { self.0 &= 0xF0; self.0 |= color as u8; } pub fn fg(&self) -> Color { color_from_u8(self.0 & 0x0F) } } // =============================================================================================== // Character // =============================================================================================== #[derive(Clone, Copy)] #[repr(C)] struct Character { ascii: u8, color: ColorCode, } // =============================================================================================== // Buffer // =============================================================================================== struct Buffer { chars: [[Character; SCREEN_WIDTH]; SCREEN_HEIGHT], } // =============================================================================================== // Writer // =============================================================================================== pub struct Writer { column: usize, color: ColorCode, buffer: Unique<Buffer>, } impl Writer { // ------------------------------------------------------------------------ // Initialization // ------------------------------------------------------------------------ pub const fn new(foreground: Color, background: Color, buffer: usize) -> Writer { Writer { column: 0, color: ColorCode::new(foreground, background), buffer: unsafe { Unique::new(buffer as *mut _) }, } } // ------------------------------------------------------------------------ // Writing // ------------------------------------------------------------------------ pub fn write_byte(&mut self, byte: u8) { match byte { b'\n' => self.new_line(), b'\t' => { let mut tab = self.column + 4; tab -= tab % 4; if tab >= 80 { self.new_line(); } else { let row = SCREEN_HEIGHT - 1; while self.column < tab { self.buffer().chars[row][self.column] = Character { ascii: b' ', color: self.color, }; self.column += 1; } } } byte => { let row = SCREEN_HEIGHT - 1; let col = self.column; self.buffer().chars[row][col] = Character { ascii: byte, color: self.color, }; self.column += 1; if self.column >= SCREEN_WIDTH { self.new_line(); } } } } // ------------------------------------------------------------------------ // Misc // ------------------------------------------------------------------------ pub fn new_line(&mut self) { for row in 0..(SCREEN_HEIGHT - 1) { let buffer = self.buffer(); buffer.chars[row] = buffer.chars[row + 1] } self.clear_row(SCREEN_HEIGHT - 1); self.column = 0; } fn buffer(&mut self) -> &mut Buffer { unsafe { self.buffer.get_mut() } } fn clear_row(&mut self, row: usize) { let blank = Character { ascii: b' ', color: self.color, }; self.buffer().chars[row] = [blank; SCREEN_WIDTH]; } pub fn clear(&mut self) { for row in 0..SCREEN_HEIGHT { self.clear_row(row); } } pub fn set_fg_color(&mut self, color: Color) -> Color { let old = self.color.fg(); self.color.set_fg(color); return old; } pub fn set_bg_color(&mut self, color: Color) -> Color { let old = self.color.bg(); self.color.set_bg(color); return old; } } impl ::core::fmt::Write for Writer { fn write_str(&mut self, s: &str) -> ::core::fmt::Result { for byte in s.bytes() { self.write_byte(byte) } if *(CURSOR_UPDATE.read()) == true { Cursor::position(self.column as u8, SCREEN_HEIGHT as u8 - 1); } Ok(()) } } // =============================================================================================== // Panic Printing // =============================================================================================== pub unsafe fn panic_print(fmt: fmt::Arguments) { let mut writer = unsafe_writer(Color::White, Color::Red); writer.new_line(); writer.write_fmt(fmt).is_ok(); } pub const unsafe fn unsafe_writer(fg: Color, bg: Color) -> Writer { Writer { column: 0, color: ColorCode::new(fg, bg), buffer: Unique::new(0xb8000 as *mut _), } } // =============================================================================================== // Printing Usage // =============================================================================================== pub fn is_enabled() -> bool { *(ENABLED.read()) } pub fn set_enabled(en: bool) { *(ENABLED.write()) = en; }
#![allow(dead_code)] #![allow(unused_imports)] use std::fmt; use std::mem; #[derive(Debug)] pub struct List<T> { head: ListEnum<T> } impl<T> Drop for List<T> { fn drop(&mut self) { println!("Drop list head.."); } } impl<T> List<T> { pub fn new() -> Self { List { head: ListEnum::Empty } } pub fn push(&mut self, elem: T) { let new_node = Box::new(Node { value: elem, next: mem::replace(&mut self.head, ListEnum::Empty), }); self.head = ListEnum::Elem(new_node); } pub fn pop(&mut self) -> Option<T> { match mem::replace(&mut self.head, ListEnum::Empty) { ListEnum::Empty => { None }, ListEnum::Elem(node) => { self.head = node.next; Some(node.value) } } } } #[derive(Debug)] pub struct Node<T> { value: T, next: ListEnum<T> } impl<T: std::fmt::Display> fmt::Display for Node<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}) ->", self.value) } } #[derive(Debug)] pub enum ListEnum<T> { Empty, Elem(Box<Node<T>>) } mod test { use super::List; use super::Node; use super::ListEnum; #[test] fn ll_take1_test_empty_list_pop() { let mut empty_list: List<f32> = List::new(); assert_eq!(empty_list.pop(), None); } #[test] fn ll_take1_test_insert_pop_list() { let mut l: List<f32> = List::new(); l.push(100.0); assert_eq!(l.pop(), Some(100.0)); } #[test] fn ll_take1_too_many_lists_test() { let n1 = Box::new(Node { value: 1.0, next: ListEnum::Empty }); let n2 = Box::new(Node { value: 2.0, next: ListEnum::Elem(n1) }); let l = List {head :ListEnum::Elem(n2) }; println!("{:?}", l); let mut empty_list: List<f32> = List::new(); println!("{:?}", empty_list); empty_list.push(10.0); println!("{:?}", empty_list); empty_list.push(11.0); println!("{:?}", empty_list); println!("Removed element .. {:?}", empty_list.pop()); println!("{:?}", empty_list); } }
use SafeWrapper; use ir::{User, Instruction, Value, CmpInst, FloatPredicateKind}; use sys; /// Integer comparison. pub struct FCmpInst<'ctx>(CmpInst<'ctx>); impl<'ctx> FCmpInst<'ctx> { /// Creates a new integer comparision instruction. pub fn new(predicate_kind: FloatPredicateKind, lhs: &Value, rhs: &Value) -> Self { unsafe { let inner = sys::LLVMRustCreateFCmpInst(predicate_kind, lhs.inner(), rhs.inner()); wrap_value!(inner => User => Instruction => CmpInst => FCmpInst) } } } impl_subtype!(FCmpInst => CmpInst);
#[doc = "Reader of register RCC_UART1CKSELR"] pub type R = crate::R<u32, super::RCC_UART1CKSELR>; #[doc = "Writer for register RCC_UART1CKSELR"] pub type W = crate::W<u32, super::RCC_UART1CKSELR>; #[doc = "Register RCC_UART1CKSELR `reset()`'s with value 0"] impl crate::ResetValue for super::RCC_UART1CKSELR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "UART1SRC\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum UART1SRC_A { #[doc = "0: pclk5 clock selected as kernel\r\n peripheral clock (default after\r\n reset)"] B_0X0 = 0, #[doc = "1: pll3_q_ck clock selected as kernel\r\n peripheral clock"] B_0X1 = 1, #[doc = "2: hsi_ker_ck clock selected as kernel\r\n peripheral clock"] B_0X2 = 2, #[doc = "3: csi_ker_ck clock selected as kernel\r\n peripheral clock"] B_0X3 = 3, #[doc = "4: pll4_q_ck clock selected as kernel\r\n peripheral clock"] B_0X4 = 4, #[doc = "5: hse_ker_ck clock selected as kernel\r\n peripheral clock"] B_0X5 = 5, } impl From<UART1SRC_A> for u8 { #[inline(always)] fn from(variant: UART1SRC_A) -> Self { variant as _ } } #[doc = "Reader of field `UART1SRC`"] pub type UART1SRC_R = crate::R<u8, UART1SRC_A>; impl UART1SRC_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, UART1SRC_A> { use crate::Variant::*; match self.bits { 0 => Val(UART1SRC_A::B_0X0), 1 => Val(UART1SRC_A::B_0X1), 2 => Val(UART1SRC_A::B_0X2), 3 => Val(UART1SRC_A::B_0X3), 4 => Val(UART1SRC_A::B_0X4), 5 => Val(UART1SRC_A::B_0X5), i => Res(i), } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == UART1SRC_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == UART1SRC_A::B_0X1 } #[doc = "Checks if the value of the field is `B_0X2`"] #[inline(always)] pub fn is_b_0x2(&self) -> bool { *self == UART1SRC_A::B_0X2 } #[doc = "Checks if the value of the field is `B_0X3`"] #[inline(always)] pub fn is_b_0x3(&self) -> bool { *self == UART1SRC_A::B_0X3 } #[doc = "Checks if the value of the field is `B_0X4`"] #[inline(always)] pub fn is_b_0x4(&self) -> bool { *self == UART1SRC_A::B_0X4 } #[doc = "Checks if the value of the field is `B_0X5`"] #[inline(always)] pub fn is_b_0x5(&self) -> bool { *self == UART1SRC_A::B_0X5 } } #[doc = "Write proxy for field `UART1SRC`"] pub struct UART1SRC_W<'a> { w: &'a mut W, } impl<'a> UART1SRC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: UART1SRC_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "pclk5 clock selected as kernel peripheral clock (default after reset)"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(UART1SRC_A::B_0X0) } #[doc = "pll3_q_ck clock selected as kernel peripheral clock"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(UART1SRC_A::B_0X1) } #[doc = "hsi_ker_ck clock selected as kernel peripheral clock"] #[inline(always)] pub fn b_0x2(self) -> &'a mut W { self.variant(UART1SRC_A::B_0X2) } #[doc = "csi_ker_ck clock selected as kernel peripheral clock"] #[inline(always)] pub fn b_0x3(self) -> &'a mut W { self.variant(UART1SRC_A::B_0X3) } #[doc = "pll4_q_ck clock selected as kernel peripheral clock"] #[inline(always)] pub fn b_0x4(self) -> &'a mut W { self.variant(UART1SRC_A::B_0X4) } #[doc = "hse_ker_ck clock selected as kernel peripheral clock"] #[inline(always)] pub fn b_0x5(self) -> &'a mut W { self.variant(UART1SRC_A::B_0X5) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07); self.w } } impl R { #[doc = "Bits 0:2 - UART1SRC"] #[inline(always)] pub fn uart1src(&self) -> UART1SRC_R { UART1SRC_R::new((self.bits & 0x07) as u8) } } impl W { #[doc = "Bits 0:2 - UART1SRC"] #[inline(always)] pub fn uart1src(&mut self) -> UART1SRC_W { UART1SRC_W { w: self } } }
pub mod include; pub use include::*;
//! Create HTML elements. Unfortunately at the moment this is the API – in the future we'll provide //! something a bit nicer to work with. use std::{borrow::Cow, collections::HashMap}; use super::listener::ListenerRef; pub mod diff; pub mod orchestrator; pub mod render; /// An HTML element. #[derive(Builder, Clone, Default, Debug, Eq, PartialEq)] pub struct Element { /// The id includes the ID of this element and all the parent elements. /// /// This might need to be changed in the future. pub id: Vec<u32>, #[builder(setter(into))] pub name: Cow<'static, str>, pub attributes: HashMap<Cow<'static, str>, Cow<'static, str>>, pub listeners: Vec<ListenerRef>, pub children: Vec<Element>, pub text: Option<Cow<'static, str>>, pub key: Option<String>, } impl Element { /// Return the unique ID of this element. /// /// At the moment this allocates way too much – at some point we should update this structure /// to use more indirection. fn id(&self) -> String { self.id .iter() .map(ToString::to_string) .map(|x| x + "-") .collect::<String>() } /// This function returns a builder type for this struct. pub fn build() -> ElementBuilder { ElementBuilder::default() } /// Create an `Element` using `Default::default()`, except for the API specified. pub fn default_with_id(id: Vec<u32>) -> Self { Self { id, ..Default::default() } } }
#[doc = "Register `RDATA` reader"] pub type R = crate::R<RDATA_SPEC>; #[doc = "Field `RES` reader - RES"] pub type RES_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - RES"] #[inline(always)] pub fn res(&self) -> RES_R { RES_R::new(self.bits) } } #[doc = "CORDIC result register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rdata::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct RDATA_SPEC; impl crate::RegisterSpec for RDATA_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`rdata::R`](R) reader structure"] impl crate::Readable for RDATA_SPEC {} #[doc = "`reset()` method sets RDATA to value 0"] impl crate::Resettable for RDATA_SPEC { const RESET_VALUE: Self::Ux = 0; }
use actix_web::{web, App, HttpRequest, HttpServer}; async fn index(req: HttpRequest) -> &'static str { "Hello world!" } #[actix_rt::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .service(web::resource("/").to(index)) }) // .backlog(1024) .bind("0.0.0.0:3003")? .run() .await }
use std::cmp::PartialOrd; struct Point<T> { x: T, y: T, } struct MixedPoint<T, U> { x: T, y: U, } impl<T, U> MixedPoint<T, U> { fn x(&self) -> &T { &self.x } fn y(&self) -> &U { &self.y } fn mixup<V, W>(self, other: MixedPoint<V, W>) -> MixedPoint<T, W> { MixedPoint { x: self.x, y: other.y, } } } impl<T> Point<T> { fn x(&self) -> &T { &self.x } fn y(&self) -> &T { &self.y } } impl Point<f32> { fn distance_from_origin(&self) -> f32 { (self.x.powi(2) + self.y.powi(2)).sqrt() } } fn largest<T: PartialOrd + Copy>(list: &[T]) -> T { let mut largest = list[0]; for &i in list { if i > largest { largest = i; } } largest } fn main() { let number_list = vec![34, 50, 25, 100, 65]; println!("largest: {}", largest(&number_list)); let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; println!("largest: {}", largest(&number_list)); let char_list = vec!['y', 'm', 'a', 'q']; println!("largest: {}", largest(&char_list)); let both_ints = Point { x: 5, y: 10 }; println!("both_ints: {}, {}", both_ints.x(), both_ints.y()); //println!("distance_from_origin: {}", both_ints.distance_from_origin()); let both_floats = Point { x: 1.0, y: 4.0 }; println!("both_floats: {}, {}", both_floats.x(), both_floats.y()); println!( "distance_from_origin: {}", both_floats.distance_from_origin() ); let int_and_float = MixedPoint { x: 5, y: 4.0 }; println!( "int_and_float: {}, {}", int_and_float.x(), int_and_float.y() ); let mp1 = MixedPoint { x: 5, y: 10.4 }; let mp2 = MixedPoint { x: "hello", y: 'c' }; let mp3 = mp1.mixup(mp2); println!("mp3.x = {}, mp3.y = {}", mp3.x, mp3.y); }
//! [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE-MIT) //! [![Apache License 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](./LICENSE-APACHE) //! [![docs.rs](https://docs.rs/x509-parser/badge.svg)](https://docs.rs/x509-parser) //! [![crates.io](https://img.shields.io/crates/v/x509-parser.svg)](https://crates.io/crates/x509-parser) //! [![Download numbers](https://img.shields.io/crates/d/x509-parser.svg)](https://crates.io/crates/x509-parser) //! [![Travis CI](https://travis-ci.org/rusticata/x509-parser.svg?branch=master)](https://travis-ci.org/rusticata/x509-parser) //! [![AppVeyor CI](https://ci.appveyor.com/api/projects/status/github/rusticata/x509-parser?svg=true)](https://ci.appveyor.com/project/chifflier/x509-parser) //! //! # X.509 Parser //! //! A X.509 v3 ([RFC5280]) parser, implemented with the [nom](https://github.com/Geal/nom) //! parser combinator framework. //! //! It is written in pure Rust, fast, and makes extensive use of zero-copy. A lot of care is taken //! to ensure security and safety of this crate, including design (recursion limit, defensive //! programming), tests, and fuzzing. It also aims to be panic-free. //! //! The code is available on [Github](https://github.com/rusticata/x509-parser) //! and is part of the [Rusticata](https://github.com/rusticata) project. //! //! The main parsing method is //! [`parse_x509_der`](https://docs.rs/x509-parser/latest/x509_parser/fn.parse_x509_der.html), //! which takes a DER-encoded //! certificate as input, and builds a //! [`X509Certificate`](https://docs.rs/x509-parser/latest/x509_parser/x509/struct.X509Certificate.html) //! object. //! //! For PEM-encoded certificates, use the //! [`pem`](https:///docs.rs/x509-parser/latest/x509_parser/pem/index.html) module. //! //! # Examples //! //! Parsing a certificate in DER format: //! //! ```rust //! use x509_parser::parse_x509_der; //! //! static IGCA_DER: &'static [u8] = include_bytes!("../assets/IGC_A.der"); //! //! # fn main() { //! let res = parse_x509_der(IGCA_DER); //! match res { //! Ok((rem, cert)) => { //! assert!(rem.is_empty()); //! // //! assert_eq!(cert.tbs_certificate.version, 2); //! }, //! _ => panic!("x509 parsing failed: {:?}", res), //! } //! # } //! ``` //! //! See also `examples/print-cert.rs`. //! //! [RFC5280]: https://tools.ietf.org/html/rfc5280 #![deny(/*missing_docs,*/ unstable_features, unused_import_braces, unused_qualifications)] #![forbid(unsafe_code)] pub use x509::*; pub mod x509; pub mod error; pub mod extensions; pub mod objects; pub mod pem; mod x509_parser; pub use crate::x509_parser::*;
use crate::network::disconnect_with_message; use crate::NetworkState; use ckb_logger::{debug, info}; use p2p::{ context::{ProtocolContext, ProtocolContextMutRef}, secio::PublicKey, traits::ServiceProtocol, }; use std::sync::Arc; /// Feeler /// Currently do nothing, CKBProtocol auto refresh peer_store after connected. pub(crate) struct Feeler { network_state: Arc<NetworkState>, } impl Feeler { pub(crate) fn new(network_state: Arc<NetworkState>) -> Self { Feeler { network_state } } } //TODO //1. report bad behaviours //2. set peer feeler flag impl ServiceProtocol for Feeler { fn init(&mut self, _context: &mut ProtocolContext) {} fn connected(&mut self, context: ProtocolContextMutRef, _: &str) { let session = context.session; let peer_id = session .remote_pubkey .as_ref() .map(PublicKey::peer_id) .expect("Secio must enabled"); self.network_state.with_peer_store_mut(|peer_store| { if let Err(err) = peer_store.add_connected_peer(peer_id.clone(), session.address.clone(), session.ty) { debug!( "Failed to add connected peer to peer_store {:?} {:?} {:?}", err, peer_id, session ); } }); info!("peer={} FeelerProtocol.connected", session.address); if let Err(err) = disconnect_with_message(context.control(), session.id, "feeler connection") { debug!("Disconnect failed {:?}, error: {:?}", session.id, err); } } fn disconnected(&mut self, context: ProtocolContextMutRef) { let session = context.session; let peer_id = session .remote_pubkey .as_ref() .map(PublicKey::peer_id) .expect("Secio must enabled"); self.network_state.with_peer_registry_mut(|reg| { reg.remove_feeler(&peer_id); }); info!("peer={} FeelerProtocol.disconnected", session.address); } }
use mrbgpdv2::peer::Peer; use mrbgpdv2::config::Config; use mrbgpdv2::routing::LocRib; use tokio::time::{sleep, Duration}; use tokio::sync::Mutex; use std::str::FromStr; use std::env; use std::sync::Arc; #[tokio::main] async fn main() { tracing_subscriber::fmt::init(); let config = env::args() .skip(1) .fold("".to_owned(), |mut acc, s| { acc += &(s.to_owned() + " "); acc }); let config = config.trim_end(); let configs = vec![ Config::from_str(&config).unwrap() ]; let loc_rib = Arc::new(Mutex::new( LocRib::new(&configs[0]) .await .expect("failed to create LocRib") )); let mut peers: Vec<Peer> = configs .into_iter() .map(|c| Peer::new(c, Arc::clone(&loc_rib))) .collect(); for peer in &mut peers { peer.start(); } let mut handles = vec![]; for mut peer in peers { let handle = tokio::spawn(async move { loop { peer.next().await; sleep(Duration::from_secs_f32(0.1)).await; } }); handles.push(handle); } for handle in handles { let _result = handle.await; } }
//! ECDH mechanism types use crate::error::{Error, Result}; use crate::types::Ulong; use cryptoki_sys::*; use log::error; use std::convert::TryFrom; use std::ffi::c_void; use std::ops::Deref; /// ECDH derivation parameters. /// /// The elliptic curve Diffie-Hellman (ECDH) key derivation mechanism /// is a mechanism for key derivation based on the Diffie-Hellman /// version of the elliptic curve key agreement scheme, as defined in /// ANSI X9.63, where each party contributes one key pair all using /// the same EC domain parameters. /// /// This structure wraps CK_ECDH1_DERIVE_PARAMS structure. #[derive(Copy, Debug, Clone)] #[repr(C)] pub struct Ecdh1DeriveParams { /// Key derivation function pub kdf: EcKdfType, /// Length of the optional shared data used by some of the key /// derivation functions pub shared_data_len: Ulong, /// Address of the optional data or `std::ptr::null()` of there is /// no shared data pub shared_data: *const c_void, /// Length of the other party's public key pub public_data_len: Ulong, /// Pointer to the other party public key pub public_data: *const c_void, } /// Key Derivation Function applied to derive keying data from a shared secret. /// /// The key derivation function will be used by the EC key agreement schemes. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(transparent)] pub struct EcKdfType { val: CK_EC_KDF_TYPE, } impl EcKdfType { /// The null transformation. The derived key value is produced by /// taking bytes from the left of the agreed value. The new key /// size is limited to the size of the agreed value. pub const NULL: EcKdfType = EcKdfType { val: CKD_NULL }; } impl Deref for EcKdfType { type Target = CK_EC_KDF_TYPE; fn deref(&self) -> &Self::Target { &self.val } } impl From<EcKdfType> for CK_EC_KDF_TYPE { fn from(ec_kdf_type: EcKdfType) -> Self { *ec_kdf_type } } impl TryFrom<CK_EC_KDF_TYPE> for EcKdfType { type Error = Error; fn try_from(ec_kdf_type: CK_EC_KDF_TYPE) -> Result<Self> { match ec_kdf_type { CKD_NULL => Ok(EcKdfType::NULL), other => { error!( "Key derivation function type {} is not one of the valid values.", other ); Err(Error::InvalidValue) } } } }
//! Public data structures for pack index files use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; /// The data for a single pack file #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PackFileRef { /// The path to the pack file relative to the installation pub path: String, } /// The data associated with each file #[derive(Debug, Copy, Clone, Serialize, Deserialize)] #[repr(C)] pub struct FileRef { /// The category of this file. The least significant byte indicates whether /// the file should be compressed. pub category: u32, /// The index of the pack file in [`PackIndexFile::archives`] pub pack_file: u32, } /// The entire data in a PKI file #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PackIndexFile { /// The list of PK archive paths pub archives: Vec<PackFileRef>, /// The map from CRC to file metadata pub files: BTreeMap<u32, FileRef>, }
#[cfg(test)] mod tests { use crate::intcode::{Intcode, Interrupt}; use crate::util; use crate::util::ListInput; #[test] fn test_advent_puzzle() { let mut output = None; let ListInput(rom) = util::load_input_file("day05.txt").unwrap(); let mut program = Intcode::new(&rom); loop { match program.run() { Interrupt::WaitingForInput => program.set_input(5), Interrupt::Output(o) => output = Some(o), _ => break, } } assert_eq!(output, Some(8805067)); } }
#![feature(proc_macro_hygiene)] #![feature(type_ascription)] use darkly; use darkly::{scanln, scanlns}; // note: should not be necessary since we add to macro // extern crate darkly_scanner; fn main() { // scanln!("hello {}foo", x: u32); // println!("you entered `{}`", x); // assert!(x == 42); // let x: u32 = scanln!("hello {}foo"); // println!("you entered `{}`", x); // assert!(x == 42); // for x in scanlns!("hello {}foo") { // println!("you entered `{}`", x: u32); // } // println!("done"); // for (x, y) in scanlns!("{}, {}") { // println!("you entered `{}, {}`", x: u32, y:i32); // } // println!("done"); // position=<-51031, 41143> velocity=< 5, -4> scanln!("position=< {}, {}> velocity=< {}, {}>", a, b, c, d); println!("{} {} {} {}", a: i32, b: i32, c: i32, d: i32); }
use std::{fmt}; use std::error::Error; #[derive(Debug)] pub(crate) struct SimpleError { desc: String, } impl From<&'static str> for SimpleError { fn from(s: &'static str) -> Self { Self{ desc: String::from(s), } } } impl From<char> for SimpleError { fn from(c: char) -> Self { Self{ desc: format!("\nerror writing char {}", c), } } } impl From<String> for SimpleError { fn from(s: String) -> Self { Self{ desc: s, } } } impl fmt::Display for SimpleError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.desc) } } impl Error for SimpleError { fn description(&self) -> &str { return self.desc.as_str() } fn cause(&self) -> Option<&Error> { return None } }
// q0064_minimum_path_sum struct Solution; impl Solution { pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 { let m = grid.len(); if m == 0 { return 0; } let n = grid[0].len(); if n == 0 { return 0; } let mut grid = grid; for i in (0..m - 1).rev() { grid[i][n - 1] += grid[i + 1][n - 1]; } for i in (0..n - 1).rev() { grid[m - 1][i] += grid[m - 1][i + 1]; } for i in (0..m - 1).rev() { for j in (0..n - 1).rev() { grid[i][j] += grid[i + 1][j].min(grid[i][j + 1]); } } grid[0][0] } } #[cfg(test)] mod tests { use super::Solution; #[test] fn it_works() { assert_eq!( 7, Solution::min_path_sum(vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]]) ); } }
// File: main.rs // Description: the file provides the overall program flow mod pdf; extern crate printpdf; use std::io::*; use pdf::*; fn main() { // Prints Greeting println!("\nWellcome to Receipt Creator!"); let reader = stdin(); let mut file_name = String::new(); print!("Data file: "); stdout().flush().unwrap(); reader.read_line(&mut file_name).unwrap(); file_name = file_name.trim().to_string(); // Gets all receipt info from a file let info = get_info(file_name); // Gets the payment period let mut period = String::new(); print!("Enter period: "); stdout().flush().unwrap(); reader.read_line(&mut period).unwrap(); period = period.trim().to_string(); // Request to wait for the work to be done println!("Please, wait!"); // Writes out all the receipts write_receipts(period, info); // Signifies completion of work println!("Work is Done! Exiting ...\n"); }
use aoc_runner_derive::{aoc, aoc_generator}; #[aoc_generator(day5)] fn parse_input_day5(input: &str) -> Result<Vec<String>, String> { Ok(input.lines().map(|s| s.to_owned()).collect()) } fn bisect(min: usize, max: usize, code: &str, index: usize) -> usize { if min == max { min } else { match code.chars().nth(index).unwrap_or('0') { 'F' | 'L' => bisect(min, (min + max) / 2, code, index + 1), 'R' | 'B' => bisect((min + max) / 2 + 1, max, code, index + 1), _ => 0, } } } #[aoc(day5, part1)] fn part1(codes: &[String]) -> Option<usize> { codes .iter() .map(|s| bisect(0, 127, &s[..7], 0) * 8 + bisect(0, 7, &s[7..], 0)) .max() } #[aoc(day5, part2)] fn part2(codes: &[String]) -> Option<usize> { let seats = codes .iter() .map(|s| bisect(0, 127, &s[..7], 0) * 8 + bisect(0, 7, &s[7..], 0)) .collect::<Vec<_>>(); (*seats.iter().min().unwrap_or(&0)..*seats.iter().max().unwrap_or(&1000)) .find(|s| !seats.contains(s)) }
pub const MSG_TYPE_LEN:usize = 3; #[derive(Debug)] pub enum SentenceType { AAM, // Waypoint Arrival Alarm ALM, // Almanac data APA, // Auto Pilot A sentence APB, // Auto Pilot B sentence BOD, // Bearing Origin to Destination BWC, // Bearing using Great Circle route DTM, // Datum being used. GGA, // Fix information GLL, // Lat/Lon data GRS, // GPS Range Residuals GSA, // Overall Satellite data GST, // GPS Pseudorange Noise Statistics GSV, // Detailed Satellite data MSK, // send control for a beacon receiver MSS, // Beacon receiver status information. RMA, // recommended Loran data RMB, // recommended navigation data for gps RMC, // recommended minimum data for gps RTE, // route message TRF, // Transit Fix Data STN, // Multiple Data ID VBW, // dual Ground / Water Spped VTG, // Vector track an Speed over the Ground WCV, // Waypoint closure velocity (Velocity Made Good) WPL, // Waypoint Location information XTC, // cross track error XTE, // measured cross track error ZTG, // Zulu (UTC) time and time to go (to destination) ZDA, // Date and Time } pub fn get_msg_type(data: &[u8; MSG_TYPE_LEN]) -> Option<SentenceType> { match data { b"AAM" => Some(SentenceType::AAM), b"ALM" => Some(SentenceType::ALM), b"APA" => Some(SentenceType::APA), b"APB" => Some(SentenceType::APB), b"BOD" => Some(SentenceType::BOD), b"BWC" => Some(SentenceType::BWC), b"DTM" => Some(SentenceType::DTM), b"GGA" => Some(SentenceType::GGA), b"GLL" => Some(SentenceType::GLL), b"GRS" => Some(SentenceType::GRS), b"GSA" => Some(SentenceType::GSA), b"GST" => Some(SentenceType::GST), b"GSV" => Some(SentenceType::GSV), b"MSK" => Some(SentenceType::MSK), b"MSS" => Some(SentenceType::MSS), b"RMA" => Some(SentenceType::RMA), b"RMB" => Some(SentenceType::RMB), b"RMC" => Some(SentenceType::RMC), b"RTE" => Some(SentenceType::RTE), b"TRF" => Some(SentenceType::TRF), b"STN" => Some(SentenceType::STN), b"VBW" => Some(SentenceType::VBW), b"VTG" => Some(SentenceType::VTG), b"WCV" => Some(SentenceType::WCV), b"WPL" => Some(SentenceType::WPL), b"XTC" => Some(SentenceType::XTC), b"XTE" => Some(SentenceType::XTE), b"ZTG" => Some(SentenceType::ZTG), b"ZDA" => Some(SentenceType::ZDA), _ => None, } }
use tokio_pty_process::AsyncPtyMaster; use tokio_pty_process::CommandExt; use std::process::Command; use tokio::io::{AsyncRead}; use std::io::{Read, Write,stdout}; use std::{thread, time}; use tokio; use passwd::Passwd; use tokio_file_unix; use failure::Error; use carrier::*; use futures::{Async, Future, Sink, Stream}; use libc; use std::io; use std::ptr; use std::ffi::CStr; use std::env; use axon; use futures; #[cfg(not(target_os = "android"))] pub fn ui(stream: channel::ChannelStream) -> impl Future<Item = (), Error = Error> { #[cfg(not(target_os = "android"))] into_raw_mode().expect("into raw mode"); let stdin = tokio_file_unix::raw_stdin().expect("raw stdin"); let stdin = tokio_file_unix::File::new_nb(stdin).expect("new_nb"); let stdin = stdin.into_reader(&tokio::reactor::Handle::current()).expect("stdin.into_reader"); #[cfg(not(target_os = "android"))] unsafe { libc::atexit(atexit); } IoBridge3 { r: stdin, w: stdout(), stream, } } use std::os::unix::io::{AsRawFd}; use std::fs; use std::mem; static mut ORIGINAL_TERMINAL_MODE: Option<libc::termios> = None; #[cfg(not(target_os = "android"))] pub extern fn atexit() { unsafe { if let Some(original) = ORIGINAL_TERMINAL_MODE { let tty_f = fs::File::open("/dev/tty").expect("opening /dev/tty"); let fd = tty_f.as_raw_fd(); libc::tcsetattr(fd, libc::TCSADRAIN, &original); } } } #[cfg(not(target_os = "android"))] pub fn into_raw_mode() -> Result<(), Error> { let tty_f = fs::File::open("/dev/tty")?; let fd = tty_f.as_raw_fd(); let mut termios : libc::termios = unsafe { mem::zeroed() }; unsafe { libc::tcgetattr(fd, &mut termios); } unsafe { if let None = ORIGINAL_TERMINAL_MODE { ORIGINAL_TERMINAL_MODE = Some(termios.clone()); } } unsafe { libc::cfmakeraw(&mut termios); libc::tcsetattr(fd, libc::TCSADRAIN, &termios); } Ok(()) } fn get_unix_username(uid: u32) -> Option<String> { unsafe { let mut result = ptr::null_mut(); let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) { n if n < 0 => 512 as usize, n => n as usize, }; let mut buf = Vec::with_capacity(amt); let mut passwd: libc::passwd = mem::zeroed(); match libc::getpwuid_r(uid, &mut passwd, buf.as_mut_ptr(), buf.capacity() as libc::size_t, &mut result) { 0 if !result.is_null() => { let ptr = passwd.pw_name as *const _; let username = CStr::from_ptr(ptr).to_str().unwrap().to_owned(); Some(username) }, _ => None } } } pub fn _main() { let mut io = axon::child(); let mut headerin = vec![0;0]; io.read(&mut headerin).expect("reading from axon failed"); let headers = headers::Headers::ok(); io.write(&headers.encode()).expect("sending on axon failed"); trace!("getting pty"); let pty = AsyncPtyMaster::open().expect("open pty master"); #[cfg(not(target_os = "android"))] let shell = "/bin/sh".to_string(); #[cfg(target_os = "android")] let shell = "/system/bin/sh".to_string(); let mut cmd = Command::new(&shell); cmd.arg("-l"); cmd.env_clear(); if let Some(username) = get_unix_username(unsafe{libc::getuid()}) { trace!("got unix username: {}", &username); #[cfg(not(target_os = "android"))] { if let Some(pwent) = Passwd::from_name(&username) { cmd.env("HOME", pwent.home_dir.clone()); cmd.env("PWD", pwent.home_dir.clone()); cmd.env("SHELL", pwent.shell); trace!("set cwd {:?}", pwent.home_dir); env::set_current_dir(pwent.home_dir).ok(); } } } trace!("spawning shell {}", &shell); let mut child = cmd .env("TERM", "xterm") .spawn_pty_async_pristine(&pty) .expect("spawning shell"); drop(cmd); let ten_millis = time::Duration::from_millis(10); thread::sleep(ten_millis); tokio::run(futures::lazy(move || { let mut io = io.into_async(&tokio::reactor::Handle::current()).expect("into async"); IoBridge2 {s1:pty,s2:io} .and_then(move |()| { info!("shell loop ends"); child.kill().expect("killing shell"); child.wait(); Ok(()) }) .map_err(|e|error!("shell loop: {}",e)) })); } struct IoBridge2<S1,S2> where S1: Write + AsyncRead, S2: Write + AsyncRead, { s1: S1, s2: S2, } impl<S1,S2> Future for IoBridge2<S1,S2> where S1: Write + AsyncRead, S2: Write + AsyncRead, { type Item = (); type Error = Error; fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> { loop { let mut buf = vec![0; 1024]; buf[0] = 1; match self.s1.poll_read(&mut buf[1..]) { Err(e) => return Err(Error::from(e)), Ok(Async::NotReady) => break, Ok(Async::Ready(l)) if l == 0 => { return Ok(Async::Ready(())); } Ok(Async::Ready(l)) => { buf.truncate(l + 1); self.s2.write(&buf)?; } } } loop { let mut buf = vec![0; 1024]; match self.s2.poll_read(&mut buf) { Err(e) => return Err(Error::from(e)), Ok(Async::NotReady) => return Ok(Async::NotReady), Ok(Async::Ready(l)) if l == 0 => { return Ok(Async::Ready(())); } Ok(Async::Ready(l)) => { if buf.len() > 0 && buf[0] == 1 { self.s1.write(&buf[1..l])?; } } } } } } struct IoBridge3<R,W> where W: Write, R: AsyncRead, { r: R, w: W, stream: channel::ChannelStream, } impl<R,W> Future for IoBridge3<R,W> where W: Write, R: AsyncRead, { type Item = (); type Error = Error; fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> { loop { let mut buf = vec![0;1024]; buf[0] = 1; match self.r.poll_read(&mut buf[1..]) { Err(e) => return Err(Error::from(e)), Ok(Async::NotReady) => break, Ok(Async::Ready(l)) if l == 0 => { return Ok(Async::Ready(())); } Ok(Async::Ready(l)) => { buf.truncate(l + 1); self.stream.start_send(buf.into())?; } } } loop { match self.stream.poll() { Err(e) => return Err(Error::from(e)), Ok(Async::NotReady) => return Ok(Async::NotReady), Ok(Async::Ready(None)) => return Ok(Async::Ready(())), Ok(Async::Ready(Some(b))) => { if b.len() > 0 && b[0] == 1 { let mut i = 0; loop { i += 1; if i > 100 { warn!("your terminal is too slow, dropping some output"); break; } if let Err(e) = self.w.write(&b[1..]) { if e.kind() == io::ErrorKind::WouldBlock { thread::sleep(time::Duration::from_millis(1)); continue; } else { return Err(Error::from(e)); } } break; } self.w.flush().ok(); } } } } } }
mod parse; #[cfg(target_os = "windows")] mod winapi_compare; use registry_pol::v1::RegistryValueType; #[test] fn reg_dword_little_endian() { assert_eq!(RegistryValueType::REG_DWORD_LITTLE_ENDIAN, RegistryValueType::REG_DWORD); } #[test] fn reg_qword_little_endian() { assert_eq!(RegistryValueType::REG_QWORD_LITTLE_ENDIAN, RegistryValueType::REG_QWORD); }
use crate::elements::Meta; /// A Capability Statement documents a set of capabilities (behaviors) of a FHIR Server for a particular version of FHIR that may be used as a statement of actual server functionality or a statement of required or desired server implementation. pub struct CapabilityStatement { /// The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes. pub id: Option<String>, /// The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content might not always be associated with version changes to the resource. pub meta: Option<Meta>, /// A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content. Often, this is a reference to an implementation guide that defines the special rules along with other profiles etc. pub implicit_rules: Option<String>, /// The base language in which the resource is written. pub language: Option<String>, /// A human-readable narrative that contains a summary of the resource and can be used to represent the content of the resource to a human. The narrative need not encode all the structured data, but is required to contain sufficient detail to make it &quot;clinically safe&quot; for a human to just read the narrative. Resource definitions may define what content should be represented in the narrative to ensure clinical safety. pub text: Option<String>, /// An absolute URI that is used to identify this capability statement when it is referenced in a specification, model, design or an instance; also called its canonical identifier. This SHOULD be globally unique and SHOULD be a literal address at which at which an authoritative instance of this capability statement is (or will be) published. This URL can be the target of a canonical reference. It SHALL remain the same when the capability statement is stored on different servers. pub url: Option<String>, }
#[derive(Clone, PartialEq, ::prost::Message)] pub struct Net { #[prost(message, optional, tag="1")] pub meta: ::std::option::Option<Meta>, #[prost(message, optional, tag="2")] pub ping: ::std::option::Option<PingPong>, #[prost(message, optional, tag="3")] pub pong: ::std::option::Option<PingPong>, #[prost(message, optional, tag="4")] pub request: ::std::option::Option<Request>, #[prost(message, optional, tag="5")] pub response: ::std::option::Option<Response>, } #[derive(Clone, PartialEq, ::prost::Message)] pub struct PingPong { } #[derive(Clone, PartialEq, ::prost::Message)] pub struct Meta { #[prost(bytes, required, tag="1")] pub nodeid: std::vec::Vec<u8>, } #[derive(Clone, PartialEq, ::prost::Message)] pub struct Request { #[prost(bytes, optional, tag="1")] pub procid: ::std::option::Option<std::vec::Vec<u8>>, #[prost(int64, optional, tag="2")] pub correlation: ::std::option::Option<i64>, #[prost(fixed32, required, tag="3")] pub methodid: u32, #[prost(bytes, required, tag="4")] pub body: std::vec::Vec<u8>, } #[derive(Clone, PartialEq, ::prost::Message)] pub struct Response { #[prost(int64, required, tag="1")] pub correlation: i64, /// TODO: make required #[prost(bytes, optional, tag="2")] pub body: ::std::option::Option<std::vec::Vec<u8>>, #[prost(enumeration="InvokeError", optional, tag="3")] pub error: ::std::option::Option<i32>, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum InvokeError { /// Process for invocation was not found ProcessNotFound = 1, /// Invocation target could not handle this method MethodNotFound = 2, /// Node specified in the message could not be found NodeNotFound = 3, /// Invocation args could not be deserialized MessageFormat = 4, /// Not sent but used internally, message handling timed out. Timeout = 5, }
use cosmwasm_std::{ coin, entry_point, from_binary, to_binary, BankMsg, Binary, CosmosMsg, Decimal, Deps, DepsMut, Env, MessageInfo, Order, Response, StdResult, Uint128, WasmMsg, }; use crate::cw721::{Cw721ExecuteMsg, Cw721ReceiveMsg}; use crate::error::ContractError; use crate::msg::{ CountResponse, ExecuteMsg, FeeResponse, InstantiateMsg, Offer, OffersResponse, QueryMsg, SellNft, }; use crate::state::{get_fund, increment_offerings, Offering, State, OFFERINGS, STATE}; use cw2::set_contract_version; use cw_storage_plus::Bound; use std::ops::{Mul, Sub}; // version info for migration info const CONTRACT_NAME: &str = "crates.io:cw-dsp-nft-market"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); const DEFAULT_LIMIT: u32 = 10; const MAX_LIMIT: u32 = 30; #[entry_point] pub fn instantiate( deps: DepsMut, _env: Env, info: MessageInfo, msg: InstantiateMsg, ) -> Result<Response, ContractError> { set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; let state = State { num_offerings: 0, fee: msg.fee, owner: info.sender, }; STATE.save(deps.storage, &state)?; Ok(Response::default()) } // And declare a custom Error variant for the ones where you will want to make use of it #[entry_point] pub fn execute( deps: DepsMut, _env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response, ContractError> { match msg { ExecuteMsg::Buy { offering_id } => execute_buy(deps, info, offering_id), ExecuteMsg::WithdrawNft { offering_id } => execute_withdraw(deps, info, offering_id), ExecuteMsg::ReceiveNft(msg) => execute_receive_nft(deps, info, msg), ExecuteMsg::WithdrawFees { amount, denom } => { execute_withdraw_fees(deps, info, amount, denom) } ExecuteMsg::ChangeFee { fee } => execute_change_fee(deps, info, fee), } } pub fn execute_buy( deps: DepsMut, info: MessageInfo, offering_id: String, ) -> Result<Response, ContractError> { // check if offering exists let off = OFFERINGS.load(deps.storage, &offering_id)?; if off.seller.eq(&info.sender) { return Err(ContractError::InvalidBuyer {}); } // check for enough coins let off_fund = get_fund(info.funds.clone(), off.list_price.denom)?; if off_fund.amount < off.list_price.amount { return Err(ContractError::InsufficientFunds {}); } let state = STATE.load(deps.storage)?; let net_amount = Decimal::one().sub(state.fee).mul(off_fund.amount); // create transfer msg let transfer_msg: CosmosMsg = BankMsg::Send { to_address: off.seller.clone().into(), amount: vec![coin(net_amount.u128(), off_fund.denom.clone())], } .into(); // create transfer cw721 msg let cw721_transfer = Cw721ExecuteMsg::TransferNft { recipient: info.sender.clone().into(), token_id: off.token_id.clone(), }; let cw721_transfer_msg: CosmosMsg = WasmMsg::Execute { contract_addr: off.contract.clone().into(), msg: to_binary(&cw721_transfer)?, funds: vec![], } .into(); OFFERINGS.remove(deps.storage, &offering_id); let price_string = format!("{}{}", off_fund.amount, off_fund.denom); let res = Response::new() .add_attribute("action", "buy_nft") .add_attribute("buyer", info.sender) .add_attribute("seller", off.seller) .add_attribute("paid_price", price_string) .add_attribute("token_id", off.token_id) .add_attribute("nft_contract", off.contract) .add_messages(vec![transfer_msg, cw721_transfer_msg]); Ok(res) } pub fn execute_withdraw( deps: DepsMut, info: MessageInfo, offering_id: String, ) -> Result<Response, ContractError> { let off = OFFERINGS.load(deps.storage, &offering_id)?; if off.seller.ne(&info.sender) { return Err(ContractError::Unauthorized {}); } let transfer_cw721_msg = Cw721ExecuteMsg::TransferNft { recipient: off.seller.into(), token_id: off.token_id.clone(), }; let exec_cw721_transfer: CosmosMsg = WasmMsg::Execute { contract_addr: off.contract.into(), msg: to_binary(&transfer_cw721_msg)?, funds: vec![], } .into(); OFFERINGS.remove(deps.storage, &offering_id); let res = Response::new() .add_attribute("action", "withdraw_nft") .add_attribute("seller", info.sender) .add_message(exec_cw721_transfer); Ok(res) } pub fn execute_receive_nft( deps: DepsMut, info: MessageInfo, wrapper: Cw721ReceiveMsg, ) -> Result<Response, ContractError> { let msg: SellNft = from_binary(&wrapper.msg)?; let id = increment_offerings(deps.storage)?.to_string(); // save Offering let off = Offering { contract: info.sender.clone(), token_id: wrapper.token_id, seller: deps.api.addr_validate(&wrapper.sender)?, list_price: msg.list_price.clone(), }; OFFERINGS.save(deps.storage, &id, &off)?; let price_string = format!("{}{}", msg.list_price.amount, msg.list_price.denom); let res = Response::new() .add_attribute("action", "sell_nft") .add_attribute("offering_id", id) .add_attribute("nft_contract", info.sender) .add_attribute("seller", off.seller) .add_attribute("list_price", price_string) .add_attribute("token_id", off.token_id); Ok(res) } pub fn execute_withdraw_fees( deps: DepsMut, info: MessageInfo, amount: Uint128, denom: String, ) -> Result<Response, ContractError> { let state = STATE.load(deps.storage)?; if state.owner.ne(&info.sender) { return Err(ContractError::Unauthorized {}); } let transfer: CosmosMsg = BankMsg::Send { to_address: state.owner.into(), amount: vec![coin(amount.into(), denom)], } .into(); Ok(Response::new().add_message(transfer)) } pub fn execute_change_fee( deps: DepsMut, info: MessageInfo, fee: Decimal, ) -> Result<Response, ContractError> { STATE.update(deps.storage, |mut state| -> Result<_, ContractError> { if state.owner.ne(&info.sender) { return Err(ContractError::Unauthorized {}); } state.fee = fee; Ok(state) })?; let res = Response::new() .add_attribute("action", "change_fee") .add_attribute("fee", fee.to_string()); Ok(res) } #[entry_point] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::GetCount {} => to_binary(&query_count(deps)?), QueryMsg::GetFee {} => to_binary(&query_fee(deps)?), QueryMsg::AllOffers { start_after, limit } => { to_binary(&query_all(deps, start_after, limit)?) } } } fn query_count(deps: Deps) -> StdResult<CountResponse> { let state = STATE.load(deps.storage)?; Ok(CountResponse { count: state.num_offerings, }) } fn query_fee(deps: Deps) -> StdResult<FeeResponse> { let state = STATE.load(deps.storage)?; Ok(FeeResponse { fee: state.fee }) } fn query_all( deps: Deps, start_after: Option<String>, limit: Option<u32>, ) -> StdResult<OffersResponse> { let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; let start = start_after.map(Bound::exclusive); let offers: StdResult<Vec<Offer>> = OFFERINGS .range(deps.storage, start, None, Order::Ascending) .take(limit) .map(|item| item.map(map_offer)) .collect(); Ok(OffersResponse { offers: offers? }) } fn map_offer((k, v): (Vec<u8>, Offering)) -> Offer { Offer { id: String::from_utf8_lossy(&k).to_string(), token_id: v.token_id, contract: v.contract, seller: v.seller, list_price: v.list_price, } } #[cfg(test)] mod tests { use super::*; use cosmwasm_std::testing::{ mock_dependencies, mock_dependencies_with_balance, mock_env, mock_info, }; use cosmwasm_std::{coins, Decimal, SubMsg}; fn setup(deps: DepsMut) { let msg = InstantiateMsg { fee: Decimal::percent(2), }; let info = mock_info("creator", &[]); // we can just call .unwrap() to assert this was a success instantiate(deps, mock_env(), info, msg).unwrap(); } #[test] fn proper_initialization() { let mut deps = mock_dependencies(); let msg = InstantiateMsg { fee: Decimal::percent(2), }; let info = mock_info("creator", &[]); // we can just call .unwrap() to assert this was a success let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); } #[test] fn sell_nft() { let mut deps = mock_dependencies(); setup(deps.as_mut()); let sell_msg = SellNft { list_price: coin(1000, "earth"), }; let msg = ExecuteMsg::ReceiveNft(Cw721ReceiveMsg { token_id: "1".into(), sender: "owner".into(), msg: to_binary(&sell_msg).unwrap(), }); let info = mock_info("nft-collectibles", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); let msg = QueryMsg::AllOffers { start_after: None, limit: None, }; let res = query(deps.as_ref(), mock_env(), msg).unwrap(); let value: OffersResponse = from_binary(&res).unwrap(); assert_eq!("1", value.offers.first().unwrap().token_id); } #[test] fn buy_nft() { let mut deps = mock_dependencies(); setup(deps.as_mut()); let sell_msg = SellNft { list_price: coin(1000, "earth"), }; let msg = ExecuteMsg::ReceiveNft(Cw721ReceiveMsg { token_id: "1".into(), sender: "owner".into(), msg: to_binary(&sell_msg).unwrap(), }); let info = mock_info("nft-collectibles", &[]); let res = execute(deps.as_mut(), mock_env(), info.clone(), msg.clone()).unwrap(); assert_eq!(0, res.messages.len()); let msg = ExecuteMsg::Buy { offering_id: "1".into(), }; let info = mock_info("owner", &coins(1000, "earth")); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()); match res { Err(ContractError::InvalidBuyer {}) => {} _ => panic!("Must return InvalidBuyer error"), } let info = mock_info("anyone", &coins(400, "earth")); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()); match res { Err(ContractError::InsufficientFunds {}) => {} _ => panic!("Must return InsufficientFunds error"), } let info = mock_info("anyone", &coins(1000, "earth")); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(2, res.messages.len()); assert_eq!( res.messages[0], SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: "owner".into(), amount: coins(980, "earth") })) ); } #[test] fn withdraw_fees() { let mut deps = mock_dependencies_with_balance(&coins(1000, "earth")); setup(deps.as_mut()); let msg = ExecuteMsg::WithdrawFees { amount: 1000u32.into(), denom: "earth".into(), }; let info = mock_info("anyone", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()); match res { Err(ContractError::Unauthorized {}) => {} _ => panic!("Must return Unauthorized error"), } let info = mock_info("creator", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(1, res.messages.len()); assert_eq!( res.messages[0], SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: "creator".into(), amount: coins(1000, "earth") })) ); } #[test] fn change_fee() { let mut deps = mock_dependencies(); setup(deps.as_mut()); let msg = ExecuteMsg::ChangeFee { fee: Decimal::percent(3), }; let info = mock_info("anyone", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg.clone()); match res { Err(ContractError::Unauthorized {}) => {} _ => panic!("Must return Unauthorized error"), } let info = mock_info("creator", &[]); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); let msg = QueryMsg::GetFee {}; let res = query(deps.as_ref(), mock_env(), msg).unwrap(); let value: FeeResponse = from_binary(&res).unwrap(); assert_eq!(Decimal::percent(3), value.fee); } }
type Link<T> = Option<Box<Item<T>>>; struct Item<T> { value: T, next: Link<T>, } pub struct List<T> { head_item: Link<T>, } impl<T> List<T> { pub fn new() -> List<T> { List { head_item: None} } pub fn prepend(&mut self, i: T) { let new_item = Some(Box::new(Item { value: i, next: self.head_item.take(), })); self.head_item = new_item; } pub fn take_head(&mut self) -> Option<T> { self.head_item.take().map(|nodea| { let node = *nodea; self.head_item = node.next; node.value }) } }
use super::*; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[repr(transparent)] pub struct NoiseFrequencyControl(u16); impl NoiseFrequencyControl { const_new!(); bitfield_int!(u16; 0..=2: u16, div_ratio, with_div_ratio, set_div_ratio); bitfield_bool!(u16; 3, counter_width, with_counter_width, set_counter_width); bitfield_int!(u16; 4..=7: u16, shift_frequency, with_shift_frequency, set_shift_frequency); bitfield_bool!(u16; 14, auto_stop, with_auto_stop, set_auto_stop); bitfield_bool!(u16; 15, restart, with_restart, set_restart); }
fn main() { { let mut xx = String::from("hello"); // 可变变量 println!("{:?}", xx); let some1 = &xx; // 不可变引用 println!("{:?}", some1); // 这里使用了不可变引用 let some2 = &mut xx; // 这里获取了可变引用, 这样可以, 因为当前作用域后面没有再使用 some1 } { let mut xx = String::from("hello"); // 注意必须是可变变量 println!("{:?}", xx); let some1 = &xx; // 不可变引用 let some2 = &mut xx; // 这里获取了可变引用, 但是下面一行还在使用 some1, 这里报错 println!("{:?}", some1); // 这里使用了不可变引用 some1 } // 其实最终规则如下 // https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#the-rules-of-references // 同一时间, 只能有多个不可变引用, 或者只能有一个可变引用 // 引用必须总是有效, 不能产生垂悬引用 }
extern crate cfg_if; use cfg_if::cfg_if; static mut GLOBAL_INT: i32 = 0; cfg_if! { // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. if #[cfg(feature = "wee_alloc")] { extern crate wee_alloc; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; } } // use std::env; #[no_mangle] pub extern "C" fn main() -> i32 { // let path = env::current_dir().unwrap(); // println!("The current directory is {}", path.display()); // println!("Hello macro!"); unsafe { GLOBAL_INT += 1 }; let smsg = unsafe { format!("Hello world! {}", GLOBAL_INT) }; let message = smsg.as_bytes(); unsafe { println(message.as_ptr(), message.len()); } 0 } extern "C" { pub fn alert(msg: *const u8, len: usize); pub fn println(msg: *const u8, len: usize); }
use core::ptr; use cortex_m::peripheral::NVIC; use atomic_polyfill::{compiler_fence, AtomicPtr, Ordering}; pub use embassy_macros::interrupt_declare as declare; pub use embassy_macros::interrupt_take as take; /// Implementation detail, do not use outside embassy crates. #[doc(hidden)] pub struct Handler { pub func: AtomicPtr<()>, pub ctx: AtomicPtr<()>, } impl Handler { pub const fn new() -> Self { Self { func: AtomicPtr::new(ptr::null_mut()), ctx: AtomicPtr::new(ptr::null_mut()), } } } #[derive(Clone, Copy)] pub(crate) struct NrWrap(pub(crate) u16); unsafe impl cortex_m::interrupt::InterruptNumber for NrWrap { fn number(self) -> u16 { self.0 } } pub unsafe trait Interrupt: crate::util::Unborrow<Target = Self> { type Priority: From<u8> + Into<u8> + Copy; fn number(&self) -> u16; unsafe fn steal() -> Self; /// Implementation detail, do not use outside embassy crates. #[doc(hidden)] unsafe fn __handler(&self) -> &'static Handler; } pub trait InterruptExt: Interrupt { fn set_handler(&self, func: unsafe fn(*mut ())); fn remove_handler(&self); fn set_handler_context(&self, ctx: *mut ()); fn enable(&self); fn disable(&self); #[cfg(not(armv6m))] fn is_active(&self) -> bool; fn is_enabled(&self) -> bool; fn is_pending(&self) -> bool; fn pend(&self); fn unpend(&self); fn get_priority(&self) -> Self::Priority; fn set_priority(&self, prio: Self::Priority); } impl<T: Interrupt + ?Sized> InterruptExt for T { fn set_handler(&self, func: unsafe fn(*mut ())) { compiler_fence(Ordering::SeqCst); let handler = unsafe { self.__handler() }; handler.func.store(func as *mut (), Ordering::Relaxed); compiler_fence(Ordering::SeqCst); } fn remove_handler(&self) { compiler_fence(Ordering::SeqCst); let handler = unsafe { self.__handler() }; handler.func.store(ptr::null_mut(), Ordering::Relaxed); compiler_fence(Ordering::SeqCst); } fn set_handler_context(&self, ctx: *mut ()) { let handler = unsafe { self.__handler() }; handler.ctx.store(ctx, Ordering::Relaxed); } #[inline] fn enable(&self) { compiler_fence(Ordering::SeqCst); unsafe { NVIC::unmask(NrWrap(self.number())); } } #[inline] fn disable(&self) { NVIC::mask(NrWrap(self.number())); compiler_fence(Ordering::SeqCst); } #[inline] #[cfg(not(armv6m))] fn is_active(&self) -> bool { NVIC::is_active(NrWrap(self.number())) } #[inline] fn is_enabled(&self) -> bool { NVIC::is_enabled(NrWrap(self.number())) } #[inline] fn is_pending(&self) -> bool { NVIC::is_pending(NrWrap(self.number())) } #[inline] fn pend(&self) { NVIC::pend(NrWrap(self.number())) } #[inline] fn unpend(&self) { NVIC::unpend(NrWrap(self.number())) } #[inline] fn get_priority(&self) -> Self::Priority { Self::Priority::from(NVIC::get_priority(NrWrap(self.number()))) } #[inline] fn set_priority(&self, prio: Self::Priority) { unsafe { cortex_m::peripheral::Peripherals::steal() .NVIC .set_priority(NrWrap(self.number()), prio.into()) } } }
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] Builds_List(#[from] builds::list::Error), #[error(transparent)] Builds_Get(#[from] builds::get::Error), #[error(transparent)] Builds_Update(#[from] builds::update::Error), #[error(transparent)] Builds_GetLogLink(#[from] builds::get_log_link::Error), #[error(transparent)] Builds_Cancel(#[from] builds::cancel::Error), #[error(transparent)] BuildSteps_List(#[from] build_steps::list::Error), #[error(transparent)] BuildSteps_Get(#[from] build_steps::get::Error), #[error(transparent)] BuildSteps_Create(#[from] build_steps::create::Error), #[error(transparent)] BuildSteps_Update(#[from] build_steps::update::Error), #[error(transparent)] BuildSteps_Delete(#[from] build_steps::delete::Error), #[error(transparent)] BuildSteps_ListBuildArguments(#[from] build_steps::list_build_arguments::Error), #[error(transparent)] BuildTasks_List(#[from] build_tasks::list::Error), #[error(transparent)] BuildTasks_Get(#[from] build_tasks::get::Error), #[error(transparent)] BuildTasks_Create(#[from] build_tasks::create::Error), #[error(transparent)] BuildTasks_Update(#[from] build_tasks::update::Error), #[error(transparent)] BuildTasks_Delete(#[from] build_tasks::delete::Error), #[error(transparent)] BuildTasks_ListSourceRepositoryProperties(#[from] build_tasks::list_source_repository_properties::Error), #[error(transparent)] Registries_QueueBuild(#[from] registries::queue_build::Error), #[error(transparent)] Registries_GetBuildSourceUploadUrl(#[from] registries::get_build_source_upload_url::Error), } pub mod builds { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, filter: Option<&str>, top: Option<i32>, skip_token: Option<&str>, ) -> std::result::Result<models::BuildListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/builds", operation_config.base_path(), subscription_id, resource_group_name, registry_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skip_token) = skip_token { url.query_pairs_mut().append_pair("$skipToken", skip_token); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BuildListResult = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => Err(list::Error::DefaultResponse { status_code }), } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_id: &str, ) -> std::result::Result<models::Build, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/builds/{}", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_id ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Build = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => Err(get::Error::DefaultResponse { status_code }), } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_id: &str, build_update_parameters: &models::BuildUpdateParameters, ) -> std::result::Result<update::Response, update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/builds/{}", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_id ); let mut url = url::Url::parse(url_str).map_err(update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(build_update_parameters).map_err(update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(update::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Build = serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::Build = serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(update::Response::Created201(rsp_value)) } status_code => Err(update::Error::DefaultResponse { status_code }), } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Build), Created201(models::Build), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get_log_link( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_id: &str, ) -> std::result::Result<models::BuildGetLogResult, get_log_link::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/builds/{}/getLogLink", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_id ); let mut url = url::Url::parse(url_str).map_err(get_log_link::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_log_link::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get_log_link::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_log_link::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BuildGetLogResult = serde_json::from_slice(rsp_body).map_err(|source| get_log_link::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => Err(get_log_link::Error::DefaultResponse { status_code }), } } pub mod get_log_link { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn cancel( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_id: &str, ) -> std::result::Result<cancel::Response, cancel::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/builds/{}/cancel", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_id ); let mut url = url::Url::parse(url_str).map_err(cancel::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(cancel::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(cancel::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(cancel::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(cancel::Response::Ok200), http::StatusCode::ACCEPTED => Ok(cancel::Response::Accepted202), status_code => Err(cancel::Error::DefaultResponse { status_code }), } } pub mod cancel { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, Accepted202, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod build_steps { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_task_name: &str, ) -> std::result::Result<models::BuildStepList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/buildTasks/{}/steps", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_task_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BuildStepList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => Err(list::Error::DefaultResponse { status_code }), } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_task_name: &str, step_name: &str, ) -> std::result::Result<models::BuildStep, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/buildTasks/{}/steps/{}", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_task_name, step_name ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BuildStep = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => Err(get::Error::DefaultResponse { status_code }), } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_task_name: &str, step_name: &str, build_step_create_parameters: &models::BuildStep, ) -> std::result::Result<create::Response, create::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/buildTasks/{}/steps/{}", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_task_name, step_name ); let mut url = url::Url::parse(url_str).map_err(create::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(build_step_create_parameters).map_err(create::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(create::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BuildStep = serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::BuildStep = serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create::Response::Created201(rsp_value)) } status_code => Err(create::Error::DefaultResponse { status_code }), } } pub mod create { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::BuildStep), Created201(models::BuildStep), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_task_name: &str, step_name: &str, build_step_update_parameters: &models::BuildStepUpdateParameters, ) -> std::result::Result<update::Response, update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/buildTasks/{}/steps/{}", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_task_name, step_name ); let mut url = url::Url::parse(url_str).map_err(update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(build_step_update_parameters).map_err(update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(update::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BuildStep = serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::BuildStep = serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(update::Response::Created201(rsp_value)) } status_code => Err(update::Error::DefaultResponse { status_code }), } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::BuildStep), Created201(models::BuildStep), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_task_name: &str, step_name: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/buildTasks/{}/steps/{}", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_task_name, step_name ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::ACCEPTED => Ok(delete::Response::Accepted202), status_code => Err(delete::Error::DefaultResponse { status_code }), } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, Accepted202, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn list_build_arguments( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_task_name: &str, step_name: &str, ) -> std::result::Result<models::BuildArgumentList, list_build_arguments::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/buildTasks/{}/steps/{}/listBuildArguments" , operation_config . base_path () , subscription_id , resource_group_name , registry_name , build_task_name , step_name) ; let mut url = url::Url::parse(url_str).map_err(list_build_arguments::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_build_arguments::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_build_arguments::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_build_arguments::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BuildArgumentList = serde_json::from_slice(rsp_body) .map_err(|source| list_build_arguments::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => Err(list_build_arguments::Error::DefaultResponse { status_code }), } } pub mod list_build_arguments { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod build_tasks { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, filter: Option<&str>, skip_token: Option<&str>, ) -> std::result::Result<models::BuildTaskListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/buildTasks", operation_config.base_path(), subscription_id, resource_group_name, registry_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(skip_token) = skip_token { url.query_pairs_mut().append_pair("$skipToken", skip_token); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BuildTaskListResult = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => Err(list::Error::DefaultResponse { status_code }), } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_task_name: &str, ) -> std::result::Result<models::BuildTask, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/buildTasks/{}", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_task_name ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BuildTask = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => Err(get::Error::DefaultResponse { status_code }), } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_task_name: &str, build_task_create_parameters: &models::BuildTask, ) -> std::result::Result<create::Response, create::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/buildTasks/{}", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_task_name ); let mut url = url::Url::parse(url_str).map_err(create::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(build_task_create_parameters).map_err(create::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(create::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BuildTask = serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::BuildTask = serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create::Response::Created201(rsp_value)) } status_code => Err(create::Error::DefaultResponse { status_code }), } } pub mod create { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::BuildTask), Created201(models::BuildTask), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_task_name: &str, build_task_update_parameters: &models::BuildTaskUpdateParameters, ) -> std::result::Result<update::Response, update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/buildTasks/{}", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_task_name ); let mut url = url::Url::parse(url_str).map_err(update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(build_task_update_parameters).map_err(update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(update::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BuildTask = serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::BuildTask = serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(update::Response::Created201(rsp_value)) } status_code => Err(update::Error::DefaultResponse { status_code }), } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::BuildTask), Created201(models::BuildTask), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_task_name: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/buildTasks/{}", operation_config.base_path(), subscription_id, resource_group_name, registry_name, build_task_name ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::ACCEPTED => Ok(delete::Response::Accepted202), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => Err(delete::Error::DefaultResponse { status_code }), } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, Accepted202, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn list_source_repository_properties( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_task_name: &str, ) -> std::result::Result<models::SourceRepositoryProperties, list_source_repository_properties::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/buildTasks/{}/listSourceRepositoryProperties" , operation_config . base_path () , subscription_id , resource_group_name , registry_name , build_task_name) ; let mut url = url::Url::parse(url_str).map_err(list_source_repository_properties::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_source_repository_properties::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .map_err(list_source_repository_properties::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_source_repository_properties::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::SourceRepositoryProperties = serde_json::from_slice(rsp_body) .map_err(|source| list_source_repository_properties::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => Err(list_source_repository_properties::Error::DefaultResponse { status_code }), } } pub mod list_source_repository_properties { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod registries { use super::{models, API_VERSION}; pub async fn queue_build( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, build_request: &models::QueueBuildRequest, ) -> std::result::Result<queue_build::Response, queue_build::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/queueBuild", operation_config.base_path(), subscription_id, resource_group_name, registry_name ); let mut url = url::Url::parse(url_str).map_err(queue_build::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(queue_build::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(build_request).map_err(queue_build::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(queue_build::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(queue_build::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Build = serde_json::from_slice(rsp_body).map_err(|source| queue_build::Error::DeserializeError(source, rsp_body.clone()))?; Ok(queue_build::Response::Ok200(rsp_value)) } http::StatusCode::ACCEPTED => Ok(queue_build::Response::Accepted202), status_code => Err(queue_build::Error::DefaultResponse { status_code }), } } pub mod queue_build { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Build), Accepted202, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get_build_source_upload_url( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, registry_name: &str, ) -> std::result::Result<models::SourceUploadDefinition, get_build_source_upload_url::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerRegistry/registries/{}/getBuildSourceUploadUrl", operation_config.base_path(), subscription_id, resource_group_name, registry_name ); let mut url = url::Url::parse(url_str).map_err(get_build_source_upload_url::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_build_source_upload_url::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .map_err(get_build_source_upload_url::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_build_source_upload_url::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::SourceUploadDefinition = serde_json::from_slice(rsp_body) .map_err(|source| get_build_source_upload_url::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => Err(get_build_source_upload_url::Error::DefaultResponse { status_code }), } } pub mod get_build_source_upload_url { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } }
// Example code that deserializes and serializes the model. // extern crate serde; // #[macro_use] // extern crate serde_derive; // extern crate serde_json; // // use generated_module::[object Object]; // // fn main() { // let json = r#"{"answer": 42}"#; // let model: [object Object] = serde_json::from_str(&json).unwrap(); // } extern crate serde_json; pub type Gdp = Vec<GdpUnion>; #[derive(Serialize, Deserialize)] pub struct PurpleGdp { #[serde(rename = "indicator")] indicator: Country, #[serde(rename = "country")] country: Country, #[serde(rename = "value")] value: String, #[serde(rename = "decimal")] decimal: String, #[serde(rename = "date")] date: String, } #[derive(Serialize, Deserialize)] pub struct Country { #[serde(rename = "id")] id: Id, #[serde(rename = "value")] value: Value, } #[derive(Serialize, Deserialize)] pub struct FluffyGdp { #[serde(rename = "page")] page: i64, #[serde(rename = "pages")] pages: i64, #[serde(rename = "per_page")] per_page: String, #[serde(rename = "total")] total: i64, } #[derive(Serialize, Deserialize)] #[serde(untagged)] pub enum GdpUnion { FluffyGdp(FluffyGdp), PurpleGdpArray(Vec<PurpleGdp>), } #[derive(Serialize, Deserialize)] pub enum Id { #[serde(rename = "CN")] Cn, #[serde(rename = "NY.GDP.MKTP.CD")] NyGdpMktpCd, #[serde(rename = "US")] Us, } #[derive(Serialize, Deserialize)] pub enum Value { #[serde(rename = "China")] China, #[serde(rename = "GDP (current US$)")] GdpCurrentUs, #[serde(rename = "United States")] UnitedStates, }
fn main() { /* Code as notes (splited into functions) here. */ slice_basic_usage(); detect_first_space_ie_word(); detect_first_space_ie_word_then_return(); string_slices_as_param(); other_slices_basic(); } // ----- ----- ----- ----- --- FIRST --- ----- ----- ----- ----- fn detect_first_space_ie_word() { /* TAG: main */ let word = String::from("ab cd"); let word_without_space = String::from("abcd"); println!( "| {}\n| {}", return_index_of_first_space(&word), return_index_of_first_space(&word_without_space) ); } fn return_index_of_first_space(s: &String) -> usize { /* TAG: helper */ let bytes = s.as_bytes(); // int <=> char for (idx, &item) in bytes.iter().enumerate() { if item == b' ' { return idx; } } s.len() } // ----- ----- ----- ----- --- FIRST --- ----- ----- ----- ----- // ----- ----- ----- ----- --- SECOND --- ----- ----- ----- ----- fn slice_basic_usage() { /* TAG: main */ let a_string = String::from("hey,golang"); /* Internally, the slice stores => the starting position 1st byte of the pointer => the length of slice = (end - start) */ let grt = &a_string[..=2]; // => hey let obj = &a_string[4..]; // => golang let usin_var_as_idx = a_string.len(); println!("|| {}, {}", grt, obj); println!("|| {}", &a_string[4..usin_var_as_idx]); } // ----- ----- ----- ----- --- SECOND --- ----- ----- ----- ----- // ----- ----- ----- ----- --- THIRD --- ----- ----- ----- ----- fn detect_first_space_ie_word_then_return() { /* TAG: main */ let word = String::from("ab cd"); let word_without_space = String::from("abcd"); println!( "||| {}\n||| {}", combine_prev2func_return_1st_word(&word), combine_prev2func_return_1st_word(&word_without_space) ); } fn combine_prev2func_return_1st_word(s: &str) -> &str { /* TAG: helper */ /* There's basically two cases: Find a space -> FROM zero To that-idx thus first word Didn't find it -> FROM zero TO the-end equiv to one word */ let bytes = s.as_bytes(); for (idx, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..idx]; // 0..idx (no idx), exactly wat-we-need } } &s[..] } // ----- ----- ----- ----- --- THIRD --- ----- ----- ----- ----- // ----- ----- ----- ----- --- FOURTH --- ----- ----- ----- ----- fn string_slices_as_param() { /* TAG: main */ /* These are notes that not categorized well, -> my mind is such a FUSS right now, sorry :) String literals being stored in the binary (quite ?definite) Slices definite literals which < points to specifc addr > 'hello' -> literal -> ?definite addr -> immutable String::from("hello") -> uncertain -> could be mut/imutable That is, we can use 'slices' as "index". */ let aha_str = "world"; println!( "|||| {}\n|||| {}", combine_prev2func_return_1st_word(&aha_str[..]), combine_prev2func_return_1st_word(&aha_str), ) } // ----- ----- ----- ----- --- FOURTH --- ----- ----- ----- ----- // ----- ----- ----- ----- --- FIFTH --- ----- ----- ----- ----- fn other_slices() { // #TODO Vectors in Chapter08 } // ----- ----- ----- ----- --- FIFTH --- ----- ----- ----- -----
use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct NewPostRequest { pub title: String, pub content: String, } #[derive(Debug, Serialize, Deserialize)] pub struct LoginRequest { pub login: String, pub password: String, } #[derive(Debug, Serialize, Deserialize)] pub struct RegisterRequest { pub login: String, pub password: String, pub name: String, } #[derive(Debug, Serialize, Deserialize)] pub struct LoginResponse { pub token: String, pub rights: String, }
#[doc = "Register `RWD` reader"] pub type R = crate::R<RWD_SPEC>; #[doc = "Field `WDC` reader - Watchdog configuration"] pub type WDC_R = crate::FieldReader; #[doc = "Field `WDV` reader - Watchdog value"] pub type WDV_R = crate::FieldReader; impl R { #[doc = "Bits 0:7 - Watchdog configuration"] #[inline(always)] pub fn wdc(&self) -> WDC_R { WDC_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 8:15 - Watchdog value"] #[inline(always)] pub fn wdv(&self) -> WDV_R { WDV_R::new(((self.bits >> 8) & 0xff) as u8) } } #[doc = "FDCAN RAM Watchdog Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rwd::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct RWD_SPEC; impl crate::RegisterSpec for RWD_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`rwd::R`](R) reader structure"] impl crate::Readable for RWD_SPEC {} #[doc = "`reset()` method sets RWD to value 0"] impl crate::Resettable for RWD_SPEC { const RESET_VALUE: Self::Ux = 0; }
pub mod debug; pub mod math;
pub fn count_brute_inversions(arr: &[u64]) -> u64 { let n = arr.len(); let mut count = 0; for i in 0..n { for j in (i+1)..n { if arr[i] > arr[j] { count += 1; } } } count } //use std::cmp::max; pub fn sort_and_count_inversions(arr: &[u64]) -> (Vec<u64>, u64) { let n = arr.len(); //println!("arry length {:} for {:?}", n, arr); if n == 1 { return (arr.to_vec(), 0); } let mid = n/2; //(n as f64 / 2).floor() as usize; //println!("splitting at index {:?} out of {:?}", mid, n); let (left_sorted, x) = sort_and_count_inversions(&arr[0..mid]); let (right_sorted, y) = sort_and_count_inversions(&arr[mid..n]); let (full_sorted, z) = count_split_inversions(&left_sorted, &right_sorted); //let mut sorted = arr.to_vec(); //sorted.sort(); (full_sorted, x + y + z) } fn count_split_inversions(left: &[u64], right: &[u64]) -> (Vec<u64>, u64) { let n_left = left.len(); let n_right = right.len(); let mut count = 0; let mut left_index = 0; let mut right_index = 0; let mut full_sorted = Vec::new(); while left_index < n_left || right_index < n_right { // TOIMPROVE // these first two closing cases are unelegant if left_index >= n_left { full_sorted.push(right[right_index]); right_index += 1; continue; } if right_index >= n_right { full_sorted.push(left[left_index]); left_index += 1; continue; } if left[left_index] < right[right_index] { full_sorted.push(left[left_index]); left_index += 1; continue; } // we have an inversion, and so all remaining elements // in the left will also be inversions full_sorted.push(right[right_index]); right_index += 1; count += n_left as u64 - left_index as u64; } //println!("found {:?} inversions across {:?} and {:?}", count, left, right); //println!("full sorted version is {:?}", full_sorted); (full_sorted, count) } #[test] #[ignore] fn test_brute() { println!("testing counting inversions"); let arr = vec![3,6,5,1]; let brute = count_brute_inversions(&arr); assert_eq!(brute, 4, "array {:?} has {:?} inversions", arr, brute); } #[test] #[ignore] fn test_split() { println!("testing split inversions"); let left = vec![11,22,32,4324]; let right = vec![21, 563, 987, 2321]; let (full_split, split) = count_split_inversions(&left, &right); let full = [&left[..], &right[..]].concat(); let mut full_sorted = full[..].to_vec(); full_sorted.sort(); // check sorting works assert_eq!(full_split, full_sorted, "manually sorted version {:?}", full_split); // chech counting works let brute = count_brute_inversions(&full); assert_eq!(split, brute, "split counted {:?} inversions, brute counted {:?}", split, brute); } #[test] #[ignore] fn test_efficient() { let arr = vec![32,4324,11,22,3454,21,563,987,5634,2321]; let brute = count_brute_inversions(&arr); let (_, efficient) = sort_and_count_inversions(&arr); assert_eq!(brute, efficient); }
//! This crate is specifically used for one thing: turning expressions inside of a string //! into a value. This crate acts as a scientific calculator, and includes several functions. //! //! If you need a portion of the calculator changed or removed, please fork it, and make your //! changes. We encourage others to change RSC to their liking. You do not need to attribute //! anything to us. This is MIT licensed software. //! //! Anyone can easily create a [Computer](computer/struct.Computer.html) and begin working with expressions. Computers //! also remember variables using a HashMap. You can create and begin using the preconfigured Computer like so: //! ``` //! use rsc::computer::Computer; //! //! fn main() { //! let mut c = Computer::<f64>::default(); //! // or //! // let mut c: Computer<f64> = Default::default(); //! //! assert!(c.eval("x = 5").unwrap() == 5.0); //! assert!(c.eval("x^2").unwrap() == 25.0); //! } //! ``` //! //! # //! In most cases a simple `eval` should be all you need, but just as many times you may need //! to directly access the tokens and AST. Some reasons may include: //! * For performance or caching; lexing and parsing an expression only once, to calculate it later hundreds //! of times in a loop. //! * Better error messages or visual information for what is happening. //! ``` //! use rsc::{ //! lexer::tokenize, //! parser::{parse, Expr}, //! computer::Computer, //! }; //! //! fn main() { //! let tokens = tokenize("x^2", true).unwrap(); //! let ast = parse(&tokens).unwrap(); //! let mut computer = Computer::<f64>::default(); //! //! for x in 2..=5 { //! let mut ast = ast.clone(); //! //! // Replace instances of variable reference 'x' with f64 value x from loop //! ast.replace(&Expr::Identifier("x".to_owned()), &Expr::Constant(x as f64), false); //! //! // or this could be done like: //! // computer.variables. //! //! println!("{}", computer.compute(&ast).unwrap()); //! } //! } //! //! // Output: //! // 4 //! // 9 //! // 16 //! // 25 //! ``` //! //! # Creating an *Empty* Computer //! Constructing a Computer with `Computer::<f64>::default()` will initialize it with default //! variables: PI and E, and default functions: `sin`, `cos`, `tan`, `log`, and `sqrt`. //! To get a Computer with absolutely no default values, please construct one like so: //! ``` //! let mut c = Computer::new(); //! /// ... using the computer //! ``` pub mod computer; pub mod lexer; pub mod parser; use crate::computer::Num; use std::ops::*; impl Num for f64 { fn zero() -> Self { 0.0 } fn one() -> Self { 1.0 } fn is_integer(&self) -> bool { self.fract() <= 0.0 } fn abs(&self) -> Self { f64::abs(*self) } fn pow(&self, other: &Self) -> Self { self.powf(*other) } } /// An error that groups together all three error types: [computer::ComputeError](computer/enum.ComputeError.html), /// [parser::ParserError](parser/enum.ParserError.html), and [lexer::LexerError](lexer/enum.LexerError.html). Produced when using `eval` helper functions. #[derive(Debug, Clone)] pub enum EvalError<'a, T: Clone + std::fmt::Debug> { ComputeError(computer::ComputeError), ParserError(parser::ParserError<'a, T>), LexerError(lexer::LexerError), } /// Turn an expression inside a string into a number. /// If you are looking for more control, you may want to use /// the [lexer](lexer/index.html), [parser](parser/index.html), and [computer](computer/index.html) modules individually. /// /// This creates the computer using `Computer::new()`. If you are looking /// to do simple `eval` on a preconfigured Computer, please call [`eval` /// on the computer](computer/struct.Computer.html#method.eval). For example: /// ``` /// let mut computer = Computer::<f64>::default(); /// assert!(computer.eval("3.1 + 2.2").unwrap() == 5.3); /// ``` /// /// # Example /// ``` /// use rsc::eval; /// assert!(eval("3.1 + 2.2").unwrap() == 5.3); /// ``` pub fn eval<'a, T: std::fmt::Debug>(input: &'a str) -> Result<T, EvalError<T>> where T: Num + std::str::FromStr + Clone + PartialOrd + Neg<Output = T> + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T>{ match lexer::tokenize(input) { Ok(tokens) => match parser::parse(&tokens) { Ok(ast) => match computer::Computer::new().compute(&ast) { Ok(num) => Ok(num), Err(compute_err) => Err(EvalError::ComputeError(compute_err)), }, Err(parser_err) => Err(EvalError::ParserError(parser_err)), }, Err(lexer_err) => Err(EvalError::LexerError(lexer_err)), } }
use {EventEntry, now_micro}; use std::fmt; use std::time::{SystemTime, UNIX_EPOCH}; use std::cmp::{Ord, Ordering}; use std::collections::HashMap; use rbtree::RBTree; extern crate libc; extern crate time; pub struct Timer { timer_queue: RBTree<TreeKey, EventEntry>, time_maps: HashMap<u32, u64>, time_id: u32, time_max_id: u32, } #[derive(PartialEq, Eq)] struct TreeKey(u64, u32); impl Ord for TreeKey { fn cmp(&self, other: &Self) -> Ordering { if self.0 != other.0 { return self.0.cmp(&other.0); } other.1.cmp(&self.1) } } impl PartialOrd for TreeKey { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Timer { pub fn new(time_max_id: u32) -> Timer { Timer { timer_queue: RBTree::new(), time_maps: HashMap::new(), time_id: 0, time_max_id: time_max_id, } } /// 添加定时器, 非定时器, 通常是重复定时器结束后进行的调用 pub fn add_timer(&mut self, mut entry: EventEntry) -> u32 { if entry.tick_step == 0 { return 0; } if entry.time_id == 0 { entry.time_id = self.calc_new_id(); }; let time_id = entry.time_id; entry.tick_ms = now_micro() + entry.tick_step; self.time_maps.insert(time_id, entry.tick_ms); self.timer_queue.insert( TreeKey(entry.tick_ms, time_id), entry, ); time_id } /// 添加首次的定时器, 不用step校验, 如果是重复定时器, 则第二次添加到定时器被检验 pub fn add_first_timer(&mut self, mut entry: EventEntry) -> u32 { entry.time_id = self.calc_new_id(); let time_id = entry.time_id; self.time_maps.insert(time_id, entry.tick_ms); self.timer_queue.insert( TreeKey(entry.tick_ms, time_id), entry, ); time_id } /// 根据定时器的id删除指定的定时器 pub fn del_timer(&mut self, time_id: u32) -> Option<EventEntry> { if !self.time_maps.contains_key(&time_id) { return None; } let key = TreeKey(self.time_maps[&time_id], time_id); self.time_maps.remove(&time_id); self.timer_queue.remove(&key) } /// 取出时间轴最小的一个值 pub fn tick_first(&self) -> Option<u64> { self.timer_queue .get_first() .map(|(key, _)| Some(key.0)) .unwrap_or(None) } /// 判断到指定时间是否有小于该指定值的实例 pub fn tick_time(&mut self, tm: u64) -> Option<EventEntry> { if tm < self.tick_first().unwrap_or(tm + 1) { return None; } if let Some((key, entry)) = self.timer_queue.pop_first() { self.time_maps.remove(&key.1); Some(entry) } else { None } } /// 取出不冲突新的定时器id, 如果和已分配的定时器id重复则继续寻找下一个 fn calc_new_id(&mut self) -> u32 { loop { self.time_id = self.time_id.overflowing_add(1).0; if self.time_id > self.time_max_id { self.time_id = 1; } if self.time_maps.contains_key(&self.time_id) { continue; } break; } self.time_id } } impl fmt::Debug for Timer { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (_, entry) in self.timer_queue.iter() { let _ = writeln!(f, "{:?}", entry); } write!(f, "") } }
use super::{ backend::Backend, entity::Entity, repository::{GetEntityFuture, ListEntitiesFuture, ListEntityIdsStream, Repository}, }; use futures_util::stream::{self, StreamExt}; use std::future::Future; pub fn relation_and_then< 'a, B: Backend + 'a, F: FnOnce(M1) -> Option<M2::Id> + Send + 'a, M1: Entity + 'a, M2: Entity + 'a, R1: Repository<M1, B> + Send + 'a, R2: Repository<M2, B> + Send + Sync + 'a, >( repo: R1, foreign: R2, id: M1::Id, f: F, ) -> GetEntityFuture<'a, M2, B::Error> where B::Error: Send, { Box::pin(async move { let fut = repo.get(id); let foreign_id = if let Some(foreign_id) = fut.await?.and_then(|e| f(e)) { foreign_id } else { return Ok(None); }; foreign.get(foreign_id).await }) } pub fn relation_map< 'a, B: Backend + 'a, F: FnOnce(M1) -> M2::Id + Send + 'a, M1: Entity + 'a, M2: Entity + 'a, R1: Repository<M1, B> + Send + 'a, R2: Repository<M2, B> + Send + Sync + 'a, >( repo: R1, foreign: R2, id: M1::Id, f: F, ) -> GetEntityFuture<'a, M2, B::Error> where B::Error: Send, { Box::pin(async move { let fut = repo.get(id); let foreign_id = if let Some(entity) = fut.await? { f(entity) } else { return Ok(None); }; foreign.get(foreign_id).await }) } pub fn stream< 'a, B: Backend + 'a, F: FnOnce(M1) -> I + Send + 'a, I: Iterator<Item = M2::Id> + Send + 'a, M1: Entity + 'a, M2: Entity + 'a, R1: Repository<M1, B> + Send + 'a, R2: Repository<M2, B> + Send + 'a, >( repo: R1, foreign: R2, id: M1::Id, f: F, ) -> ListEntitiesFuture<'a, M2, B::Error> { struct StreamState<I, R2> { foreign: R2, ids: I, } Box::pin(async move { let fut = repo.get(id); let foreign_ids = if let Some(entity) = fut.await? { f(entity) } else { return Ok(stream::empty().boxed()); }; let state = StreamState { foreign, ids: foreign_ids, }; Ok(stream::unfold(state, |mut state| async move { loop { let id = state.ids.next()?; let fut = state.foreign.get(id); match fut.await { Ok(Some(e)) => return Some((Ok(e), state)), Ok(None) => continue, Err(why) => return Some((Err(why), state)), } } }) .boxed()) }) } pub fn stream_ids< 'a, B: Backend + 'a, I: Future<Output = Result<ListEntityIdsStream<'a, M2::Id, B::Error>, B::Error>> + Send + 'a, M2: Entity + 'a, R: Repository<M2, B> + Send + 'a, >( ids_future: I, foreign: R, ) -> ListEntitiesFuture<'a, M2, B::Error> { struct StreamState<'a, R, I, E> { foreign: R, ids: ListEntityIdsStream<'a, I, E>, } Box::pin(async move { let foreign_ids = ids_future.await?; let state = StreamState { foreign, ids: foreign_ids.boxed(), }; Ok(stream::unfold(state, |mut state| async move { loop { let id = match state.ids.next().await? { Ok(id) => id, Err(why) => return Some((Err(why), state)), }; let fut = state.foreign.get(id); match fut.await { Ok(Some(e)) => return Some((Ok(e), state)), Ok(None) => continue, Err(why) => return Some((Err(why), state)), } } }) .boxed()) }) }
#[doc = "Reader of register FMC_BCHIER"] pub type R = crate::R<u32, super::FMC_BCHIER>; #[doc = "Writer for register FMC_BCHIER"] pub type W = crate::W<u32, super::FMC_BCHIER>; #[doc = "Register FMC_BCHIER `reset()`'s with value 0"] impl crate::ResetValue for super::FMC_BCHIER { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DUEIE`"] pub type DUEIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DUEIE`"] pub struct DUEIE_W<'a> { w: &'a mut W, } impl<'a> DUEIE_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 `DERIE`"] pub type DERIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DERIE`"] pub struct DERIE_W<'a> { w: &'a mut W, } impl<'a> DERIE_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 `DEFIE`"] pub type DEFIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DEFIE`"] pub struct DEFIE_W<'a> { w: &'a mut W, } impl<'a> DEFIE_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 `DSRIE`"] pub type DSRIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DSRIE`"] pub struct DSRIE_W<'a> { w: &'a mut W, } impl<'a> DSRIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `EPBRIE`"] pub type EPBRIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EPBRIE`"] pub struct EPBRIE_W<'a> { w: &'a mut W, } impl<'a> EPBRIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } impl R { #[doc = "Bit 0 - DUEIE"] #[inline(always)] pub fn dueie(&self) -> DUEIE_R { DUEIE_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - DERIE"] #[inline(always)] pub fn derie(&self) -> DERIE_R { DERIE_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - DEFIE"] #[inline(always)] pub fn defie(&self) -> DEFIE_R { DEFIE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - DSRIE"] #[inline(always)] pub fn dsrie(&self) -> DSRIE_R { DSRIE_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - EPBRIE"] #[inline(always)] pub fn epbrie(&self) -> EPBRIE_R { EPBRIE_R::new(((self.bits >> 4) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - DUEIE"] #[inline(always)] pub fn dueie(&mut self) -> DUEIE_W { DUEIE_W { w: self } } #[doc = "Bit 1 - DERIE"] #[inline(always)] pub fn derie(&mut self) -> DERIE_W { DERIE_W { w: self } } #[doc = "Bit 2 - DEFIE"] #[inline(always)] pub fn defie(&mut self) -> DEFIE_W { DEFIE_W { w: self } } #[doc = "Bit 3 - DSRIE"] #[inline(always)] pub fn dsrie(&mut self) -> DSRIE_W { DSRIE_W { w: self } } #[doc = "Bit 4 - EPBRIE"] #[inline(always)] pub fn epbrie(&mut self) -> EPBRIE_W { EPBRIE_W { w: self } } }
use std::error::Error; use regex::Regex; use crate::model::*; use super::common; pub fn change_tags(git_project: &mut GitProject, message: &str) -> Result<(), Box<dyn Error>> { let change_tags_command_format = Regex::new(r"\[([^\[\]\s]+)(?:@([^\[\]\s]+))?((?:[\s]+(?:[+-][\S]+))+)\]")?; // [my-task +bug], [my-task@ios -blocked +important] for command in change_tags_command_format.captures_iter(message) { let command_str = command.get(0).unwrap().as_str(); let task_id: Id = if let Some(task_id) = command.get(1) { task_id.as_str().into() } else { continue }; // shouldn't reach the continue here, as pattern should not match let tags: &str = if let Some(tags) = command.get(3) { tags.as_str() } else { continue }; let project = common::resolve_project(git_project, &task_id, None, command.get(2), command_str)?; let mut task = if let Some(task) = project.task_with_id(&task_id) { task.clone() } else { eprintln!("No task was found with ID {} in project {}, referenced in command {}", task_id, project.id(), command_str); std::process::exit(1); }; for tag in tags.split(|ch: char| ch.is_whitespace()).filter(|s| !s.is_empty()) { eprintln!("match: {:?}", tag); match tag.split_at(1) { ("+", tag) => task.add_tag(tag), ("-", tag) => task.remove_tag(tag), _ => (), } } project.replace_task(&task_id, task, None); } Ok(()) }
#[allow(dead_code)] pub fn run(){ }// fn add ()
use crate::lib::environment::Environment; use crate::lib::error::DfxResult; use crate::lib::identity::identity_utils::call_sender; use crate::lib::provider::create_agent_environment; use clap::Clap; use tokio::runtime::Runtime; mod call; mod create; mod delete; mod deposit_cycles; mod id; mod info; mod install; mod request_status; mod send; mod sign; mod start; mod status; mod stop; mod uninstall_code; mod update_settings; /// Manages canisters deployed on a network replica. #[derive(Clap)] #[clap(name("canister"))] pub struct CanisterOpts { /// Override the compute network to connect to. By default, the local network is used. /// A valid URL (starting with `http:` or `https:`) can be used here, and a special /// ephemeral network will be created specifically for this request. E.g. /// "http://localhost:12345/" is a valid network name. #[clap(long)] network: Option<String>, /// Specify a wallet canister id to perform the call. /// If none specified, defaults to use the selected Identity's wallet canister. #[clap(long)] wallet: Option<String>, /// Performs the call with the user Identity as the Sender of messages. /// Bypasses the Wallet canister. #[clap(long, conflicts_with("wallet"))] no_wallet: bool, #[clap(subcommand)] subcmd: SubCommand, } #[derive(Clap)] enum SubCommand { Call(call::CanisterCallOpts), Create(create::CanisterCreateOpts), Delete(delete::CanisterDeleteOpts), DepositCycles(deposit_cycles::DepositCyclesOpts), Id(id::CanisterIdOpts), Info(info::InfoOpts), Install(install::CanisterInstallOpts), RequestStatus(request_status::RequestStatusOpts), Send(send::CanisterSendOpts), Sign(sign::CanisterSignOpts), Start(start::CanisterStartOpts), Status(status::CanisterStatusOpts), Stop(stop::CanisterStopOpts), UninstallCode(uninstall_code::UninstallCodeOpts), UpdateSettings(update_settings::UpdateSettingsOpts), } pub fn exec(env: &dyn Environment, opts: CanisterOpts) -> DfxResult { let agent_env = create_agent_environment(env, opts.network.clone())?; let runtime = Runtime::new().expect("Unable to create a runtime"); let default_wallet_proxy = match opts.subcmd { SubCommand::Call(_) | SubCommand::Send(_) | SubCommand::Sign(_) => false, _ => true, }; runtime.block_on(async { let call_sender = call_sender( &agent_env, &opts.wallet, opts.no_wallet, default_wallet_proxy, ) .await?; match opts.subcmd { SubCommand::Call(v) => call::exec(&agent_env, v, &call_sender).await, SubCommand::Create(v) => create::exec(&agent_env, v, &call_sender).await, SubCommand::Delete(v) => delete::exec(&agent_env, v, &call_sender).await, SubCommand::DepositCycles(v) => deposit_cycles::exec(&agent_env, v, &call_sender).await, SubCommand::Id(v) => id::exec(&agent_env, v).await, SubCommand::Install(v) => install::exec(&agent_env, v, &call_sender).await, SubCommand::Info(v) => info::exec(&agent_env, v).await, SubCommand::RequestStatus(v) => request_status::exec(&agent_env, v).await, SubCommand::Send(v) => send::exec(&agent_env, v, &call_sender).await, SubCommand::Sign(v) => sign::exec(&agent_env, v, &call_sender).await, SubCommand::Start(v) => start::exec(&agent_env, v, &call_sender).await, SubCommand::Status(v) => status::exec(&agent_env, v, &call_sender).await, SubCommand::Stop(v) => stop::exec(&agent_env, v, &call_sender).await, SubCommand::UninstallCode(v) => uninstall_code::exec(&agent_env, v, &call_sender).await, SubCommand::UpdateSettings(v) => { update_settings::exec(&agent_env, v, &call_sender).await } } }) }
use crate::{ ast::*, error::{marked_in_orig, ParseError}, lexer::{Lexer, Token, TokenType}, Options, }; #[derive(Debug)] pub struct Parser<'a> { text: &'a str, tokens: Vec<Token>, pos: usize, } macro_rules! return_binary_clause { ($self: ident, $operator: expr, $curr_token: ident) => { return Ok(UserAST::BinaryClause(Box::new($curr_token), $operator, Box::new($self._parse()?))); }; } pub(crate) fn get_text_for_token(text: &str, start: u32, stop: u32) -> &str { &text[start as usize..stop as usize] } pub fn parse(text: &str) -> Result<UserAST, ParseError> { Parser::new(text)?._parse() } pub fn parse_with_opt(text: &str, options: Options) -> Result<UserAST, ParseError> { Parser::new_with_opt(text, options)?._parse() } impl<'a> Parser<'a> { pub fn new(text: &'a str) -> Result<Self, ParseError> { let tokens = Lexer::new(text).get_tokens()?; Ok(Parser { tokens, pos: 0, text }) } pub fn new_with_opt(text: &'a str, options: Options) -> Result<Self, ParseError> { let tokens = Lexer::new_with_opt(text, options).get_tokens()?; Ok(Parser { tokens, pos: 0, text }) } fn unexpected_token_type(&self, message: &'static str, allowed_types: Option<&[Option<TokenType>]>) -> Result<(), ParseError> { // generate snippet let [start, stop] = self .tokens .get(self.pos) .map(|next_token| [next_token.byte_start_pos as usize, next_token.byte_stop_pos as usize]) .unwrap_or_else(|| [self.text.len(), self.text.len()]); let marked_in_orig = marked_in_orig(self.text, start, stop); let err = if message.is_empty() { let message = format!( "{} Unexpected token_type, got {}{:?}", message, self.get_type().map(|el| format!("{:?}", el)).unwrap_or_else(|| "EOF".to_string()), allowed_types.map(|el| format!(" allowed_types: {:?}", el)).unwrap_or_else(|| "".to_string()) ); ParseError::UnexpectedTokenType(marked_in_orig, message) } else { ParseError::UnexpectedTokenType(marked_in_orig, message.to_string()) }; Err(err) } fn assert_allowed_types(&self, message: &'static str, allowed_types: &[Option<TokenType>]) -> Result<(), ParseError> { if !allowed_types.contains(&self.get_type()) { self.unexpected_token_type(message, Some(allowed_types))?; } Ok(()) } fn next_token(&mut self) -> Result<Token, ParseError> { let token = self.tokens.get(self.pos).unwrap(); self.pos += 1; Ok(*token) } fn parse_user_filter(&mut self, curr_token: Token) -> Result<UserFilter, ParseError> { let mut curr_ast = UserFilter { levenshtein: None, phrase: get_text_for_token(self.text, curr_token.byte_start_pos, curr_token.byte_stop_pos).to_string(), }; // Optional: Define Levenshtein distance if self.is_type(TokenType::Tilde) { self.next_token()?; // Remove Tilde self.assert_allowed_types("Expecting a levenshtein number after a \'~\' ", &[Some(TokenType::Literal)])?; let lev_token = self.next_token()?; // Remove levenshtein number let levenshtein: u8 = get_text_for_token(self.text, lev_token.byte_start_pos, lev_token.byte_stop_pos) .parse() .map_err(|_e| ParseError::ExpectedNumber(format!("Expected number after tilde to define levenshtein distance but got {:?}", lev_token)))?; curr_ast.levenshtein = Some(levenshtein); } Ok(curr_ast) } fn parse_sub_expression(&mut self, curr_ast: UserAST) -> Result<UserAST, ParseError> { self.assert_allowed_types( "", &[ Some(TokenType::AttributeLiteral), Some(TokenType::Literal), Some(TokenType::ParenthesesOpen), Some(TokenType::ParenthesesClose), Some(TokenType::And), Some(TokenType::Or), None, ], )?; if let Some(next_token_type) = self.get_type() { match next_token_type { TokenType::AttributeLiteral | TokenType::Literal => { return_binary_clause!(self, Operator::Or, curr_ast); } TokenType::Or => { self.next_token()?; return_binary_clause!(self, Operator::Or, curr_ast); } TokenType::And => { self.next_token()?; return_binary_clause!(self, Operator::And, curr_ast); } TokenType::ParenthesesOpen | TokenType::Tilde => unimplemented!(), TokenType::ParenthesesClose => Ok(curr_ast), } } else { Ok(curr_ast) // is last one } } fn _parse(&mut self) -> Result<UserAST, ParseError> { let curr_token = self.next_token()?; match curr_token.token_type { TokenType::AttributeLiteral => { //Check if attribute covers whole ast or only next literal match self.get_type() { Some(TokenType::ParenthesesOpen) => { return Ok(UserAST::Attributed( get_text_for_token(self.text, curr_token.byte_start_pos, curr_token.byte_stop_pos).to_string(), Box::new(self._parse()?), )) } Some(TokenType::Literal) => { let token2 = self.next_token()?; let curr_ast = self.parse_user_filter(token2)?; let attributed_ast = UserAST::Attributed( get_text_for_token(self.text, curr_token.byte_start_pos, curr_token.byte_stop_pos).to_string(), Box::new(UserAST::Leaf(Box::new(curr_ast))), ); return self.parse_sub_expression(attributed_ast); } _ => self.unexpected_token_type( "only token or ( allowed after attribute ('attr:') ", Some(&[Some(TokenType::Literal), Some(TokenType::ParenthesesOpen)]), )?, }; } TokenType::Literal => { let curr_ast = self.parse_user_filter(curr_token)?; return self.parse_sub_expression(UserAST::Leaf(Box::new(curr_ast))); } TokenType::ParenthesesOpen => { let parenthesed_ast = self._parse()?; self.assert_allowed_types("", &[Some(TokenType::ParenthesesClose)])?; self.next_token()?; return self.parse_sub_expression(parenthesed_ast); } TokenType::ParenthesesClose => unimplemented!(), TokenType::Tilde => { self.unexpected_token_type("", None)?; // IMPOSSIBURU!, should be covered by lookeaheads } TokenType::Or | TokenType::And => { unimplemented!() // IMPOSSIBURU!, should be covered by lookeaheads } } unreachable!() } fn is_type(&self, token_type: TokenType) -> bool { self.get_type().map(|el| el == token_type).unwrap_or(false) } fn get_type(&self) -> Option<TokenType> { self.tokens.get(self.pos).map(|el| el.token_type) } } #[cfg(test)] mod tests { use super::*; use crate::parser::Operator::*; #[test] fn simple() { assert_eq!(parse("hallo").unwrap(), "hallo".into()); } #[test] fn test_invalid() { assert!(parse("field:what:ok").is_err()); // Err(UnexpectedTokenType("Expecting a levenshtein number after a \'~\' at position 2, but got None".to_string()))); } #[test] fn test_phrases() { assert_eq!(parse("\"cool\")").unwrap(), ("cool".into())); assert_eq!(parse("\"cooles teil\")").unwrap(), ("cooles teil".into())); } #[test] fn test_parentheses() { assert_eq!(parse("(cool)").unwrap(), ("cool".into())); assert_eq!(parse("((((((cool))))))").unwrap(), ("cool".into())); assert_eq!(parse("((((((cool)))))) AND ((((((cool))))))").unwrap(), ("cool".into(), And, "cool".into()).into()); assert_eq!( parse("(super AND cool) OR fancy").unwrap(), ((("super".into(), And, "cool".into()).into()), Or, "fancy".into()).into() ); assert_eq!( parse("(super AND cool) OR (fancy)").unwrap(), ((("super".into(), And, "cool".into()).into()), Or, "fancy".into()).into() ); assert_eq!( parse("((super AND cool)) OR (fancy)").unwrap(), ((("super".into(), And, "cool".into()).into()), Or, "fancy".into()).into() ); // println!("{:?}", parse("(cool)")); } #[test] fn test_parentheses_disabled() { let opt_no_parentheses = Options { no_parentheses: true, ..Default::default() }; assert_eq!(parse_with_opt("(cool)", opt_no_parentheses).unwrap(), ("(cool)".into())); assert_eq!( parse_with_opt("((((((cool)))))) AND ((((((cool))))))", opt_no_parentheses).unwrap(), ("((((((cool))))))".into(), And, "((((((cool))))))".into()).into() ); // println!("{:?}", parse("(cool)")); } #[test] fn test_and_or() { assert_eq!( parse("super AND cool OR fancy").unwrap(), ("super".into(), And, ("cool".into(), Or, "fancy".into()).into()).into() // BinaryClause("super".into(), And, Box::new(("cool", Operator::Or, "fancy").into())) ); // println!("asd {:?}", parse("super OR cool AND fancy")); assert_eq!( parse("super OR cool AND fancy").unwrap(), ("super".into(), Or, ("cool".into(), And, "fancy".into()).into()).into() ); } #[test] fn test_implicit_or() { assert_eq!( parse("super cool OR fancy").unwrap(), ("super".into(), Or, ("cool".into(), Or, "fancy".into()).into()).into() ); assert_eq!(parse("super cool").unwrap(), ("super".into(), Or, "cool".into()).into()); assert_eq!(parse("super cool").unwrap(), parse("super OR cool").unwrap()); } #[test] fn test_levenshtein() { assert_eq!( parse("fancy~1").unwrap(), UserAST::Leaf(Box::new(UserFilter { // field_name: None, phrase: "fancy".to_string(), levenshtein: Some(1), })) ); assert_eq!( parse("fancy~"), Err(ParseError::UnexpectedTokenType( "fancy~﹏﹏".to_string(), "Expecting a levenshtein number after a \'~\' ".to_string() )) ); assert_eq!(parse("fancy~1").unwrap(), "fancy~1".into()); assert_eq!( parse("super cool OR fancy~1").unwrap(), ("super".into(), Or, ("cool".into(), Or, "fancy~1".into()).into()).into() ); } #[test] fn test_levenshtein_disabled() { let opt = Options { no_levensthein: true, ..Default::default() }; assert_eq!( parse_with_opt("fancy~1", opt).unwrap(), UserAST::Leaf(Box::new(UserFilter { // field_name: None, phrase: "fancy~1".to_string(), levenshtein: None, })) ); } #[test] fn test_attribute_and_levenshtein() { assert_eq!( parse("field:fancy~1").unwrap(), UserAST::Attributed( "field".to_string(), Box::new(UserAST::Leaf(Box::new(UserFilter { phrase: "fancy".to_string(), levenshtein: Some(1), }))) ) ); assert_eq!( parse("field:fancy~1").unwrap(), UserAST::Attributed( "field".to_string(), Box::new(UserAST::Leaf(Box::new(UserFilter { phrase: "fancy".to_string(), levenshtein: Some(1), }))) ) ); assert_eq!(parse("field:fancy~1").unwrap(), "field:fancy~1".into()); } #[test] fn test_attribute_and_implicit_or_on_all() { assert_eq!( parse("\"field\":fancy unlimited").unwrap(), (UserAST::Attributed("field".to_string(), "fancy".into()), Or, "unlimited".into()).into() ); } #[test] fn test_attribute_quoted_field() { assert_eq!( parse("\"field\":fancy unlimited").unwrap(), (UserAST::Attributed("field".to_string(), "fancy".into()), Or, "unlimited".into()).into() ); } #[test] fn test_quote_on_quote() { assert_eq!( parse("\"field\"\"cool\"").unwrap(), // there should be a space ("field".into(), Or, "cool".into()).into() ); } // #[test] // fn test_disabled_attribute_quoted_field() { // let opt_no_attr = Options{no_attributes:true, ..Default::default()}; // assert_eq!( // parse_with_opt("\"field\":fancy unlimited", opt_no_attr).unwrap(), // ("field:fancy".into(), Or, "unlimited".into()).into() // ); // } #[test] fn test_attribute_simple() { assert_eq!(parse("field:fancy").unwrap(), "field:fancy".into()); assert_eq!( parse("field:fancy").unwrap(), UserAST::Attributed( "field".to_string(), Box::new(UserAST::Leaf(Box::new(UserFilter { phrase: "fancy".to_string(), levenshtein: None, }))) ) ); } #[test] fn test_disabled_attribute_simple() { let opt_no_attr = Options { no_attributes: true, ..Default::default() }; assert_eq!( parse_with_opt("field:fancy", opt_no_attr).unwrap(), UserAST::Leaf(Box::new(UserFilter { phrase: "field:fancy".to_string(), levenshtein: None, })) ); } #[test] fn test_attribute_after_text() { assert_eq!( parse("freestyle myattr:(super cool)").unwrap(), ( "freestyle".into(), Or, (UserAST::Attributed("myattr".to_string(), Box::new(("super".into(), Or, "cool".into()).into()))) ) .into() ); } #[test] fn test_attribute_errors() { assert_eq!( parse("fancy:"), Err(ParseError::UnexpectedTokenType( "fancy:﹏﹏".to_string(), "only token or ( allowed after attribute ('attr:') ".to_string() )) // Err(UnexpectedTokenType("Expecting a levenshtein number after a \'~\' at position 2, but got None".to_string())) ); } #[test] fn test_attributed_block_1() { assert_eq!( parse("field:(fancy unlimited)").unwrap(), UserAST::Attributed("field".to_string(), Box::new(("fancy".into(), Or, "unlimited".into()).into())) ); } fn test_parse_query_to_ast_helper(query: &str, expected: &str) { let query_str = parse(query).unwrap(); assert_eq!(format!("{:?}", query_str), expected); } #[test] fn test_attributed_block() { test_parse_query_to_ast_helper("field:(fancy unlimited)", "field:(\"fancy\" OR \"unlimited\")"); } #[test] fn test_multi_spaces() { test_parse_query_to_ast_helper("a AND b", "(\"a\" AND \"b\")"); } #[test] fn test_special_chars() { test_parse_query_to_ast_helper("die drei ???", "(\"die\" OR (\"drei\" OR \"???\"))"); test_parse_query_to_ast_helper("a+", "\"a+\""); } #[test] fn test_multi_and_to_flat() { test_parse_query_to_ast_helper("a AND b AND c", "(\"a\" AND (\"b\" AND \"c\"))"); // not flat } #[test] fn test_multi_or_to_flat() { test_parse_query_to_ast_helper("a OR b OR c", "(\"a\" OR (\"b\" OR \"c\"))"); // not flat } #[test] fn test_parse_query() { test_parse_query_to_ast_helper("a AND b", "(\"a\" AND \"b\")"); test_parse_query_to_ast_helper("a:b", "a:\"b\""); test_parse_query_to_ast_helper("a:b OR c", "(a:\"b\" OR \"c\")"); test_parse_query_to_ast_helper("a", "\"a\""); test_parse_query_to_ast_helper("食べる AND b", "(\"食べる\" AND \"b\")"); //no precendence yet test_parse_query_to_ast_helper("a OR b AND c", "(\"a\" OR (\"b\" AND \"c\"))"); } #[test] fn test_parse_multi_literals() { test_parse_query_to_ast_helper("a b", "(\"a\" OR \"b\")"); test_parse_query_to_ast_helper("\"a b\"", "\"a b\""); test_parse_query_to_ast_helper("feld:10 b", "(feld:\"10\" OR \"b\")"); } }
use chrono::{Duration, NaiveDate}; use db::plant::Plant; use rusqlite::types::*; use rusqlite::Connection; /// Tracking the growth and harvest of a specific plant pub struct Crop { /// Number of plants sown pub num_plants: u32, /// The date that the plants were planted pub date_planted: NaiveDate, /// The id of the plant sown pub plant_id: i64, /// Unique id for the crop pub id: i64, } impl Crop { /// Create a new crop instance fn new(conn: &Connection, plant_id: i64, num_plants: u32, date_planted: NaiveDate) -> Self { conn.execute( "INSERT INTO crops (num_plants, date_planted, plant_id) VALUES (?1, ?2, ?3)", &[&num_plants, &date_planted as &dyn ToSql, &plant_id], ) .unwrap(); Crop { id: conn.last_insert_rowid(), plant_id, num_plants, date_planted, } } /// Provides the ideal harvest date based on planting date and time to maturity fn planned_harvest_date(&self, conn: &Connection) -> NaiveDate { let plant = Plant::get_plant_by_id(&conn, self.plant_id).unwrap(); self.date_planted + Duration::days(plant.days_to_maturity) } } #[cfg(test)] mod tests { use super::*; use db::plant::PlantType; use db::DataMgr; #[test] fn new_crop() { let mgr = DataMgr::new(String::from("./data/green-thumb-test-new_crop.db")); let plant = Plant::new(&mgr.conn, String::from("Bean"), 75, PlantType::Annual); let crop = Crop::new(&mgr.conn, plant.id, 5, NaiveDate::from_ymd(2018, 5, 6)); assert_eq!(5, crop.num_plants); assert_eq!(NaiveDate::from_ymd(2018, 5, 6), crop.date_planted); assert_eq!(plant.id, crop.plant_id); } #[test] fn harvest_date() { let mgr = DataMgr::new(String::from("./data/green-thumb-test-harvest_date.db")); let plant = Plant::new(&mgr.conn, String::from("Bean"), 75, PlantType::Annual); let crop = Crop::new(&mgr.conn, plant.id, 5, NaiveDate::from_ymd(2018, 5, 6)); assert_eq!( NaiveDate::from_ymd(2018, 7, 20), crop.planned_harvest_date(&mgr.conn) ); } }
use influxdb::{Client, Query, Timestamp}; use influxdb::InfluxDbWriteable; use chrono::{DateTime, Utc}; #[async_std::main] // or #[tokio::main] if you prefer async fn main() { // Connect to db `test` on `http://localhost:8086` let client = Client::new("http://192.168.2.116:8086", "test"); #[derive(InfluxDbWriteable)] struct WeatherReading { time: DateTime<Utc>, humidity: i32, #[influxdb(tag)] wind_direction: String, } // Let's write some data into a measurement called `weather` let weather_reading = WeatherReading { time: Timestamp::Hours(1).into(), humidity: 30, wind_direction: String::from("north"), }; let write_result = client .query(&weather_reading.into_query("weather")) .await; assert!(write_result.is_ok(), "Write result was not okay"); // Let's see if the data we wrote is there let read_query = Query::raw_read_query("SELECT * FROM weather"); let read_result = client.query(&read_query).await; assert!(read_result.is_ok(), "Read result was not ok"); println!("{}", read_result.unwrap()); }
#![windows_subsystem = "console"] #![allow(unused_imports)] #![allow(dead_code)] #![allow(unused_parens)] #![allow(non_snake_case)] #![allow(unused_mut)] #![allow(unused_variables)] extern crate winapi; //extern crate widestring; //use winapi::um::minwinbase::*; //use std::cmp; //use std::io; use winapi::shared::minwindef::*; use winapi::um::synchapi::*; mod common; mod filewin32; use crate::common::*; use crate::filewin32::*; fn main() { let op_promt = r#" test: 1: read by 4k 2: read whole file w: alertable sleep 1sec c: cleanup 0: another file ? "#; loop { let mut filepath: String = gets("file name? "); if(""==filepath) { break; } if("z"==filepath) {filepath = String::from("C:\\Users\\dkord\\Downloads\\wix311.exe");} else { match FileWin32::getFullPath(&filepath) { Err(ec) => { println!("{}", str_win32err(ec)); continue } Ok(fp) => { filepath=fp.0 } } } println!("{}", filepath); let mut thefile = FileWin32::new(); match thefile.open(&filepath) { Err(ec) => { println!("{}", str_win32err(ec)); continue } Ok(_) => { } } let mut flsize = thefile.getSize(); println!("{} opened, {} bytes", filepath, flsize); if(flsize<=0) { continue; } let mut tests: Vec<Box<OvlReader>> = Vec::with_capacity(64); loop { fn start_read(thefile: &FileWin32, tests: &mut Vec<Box<OvlReader>>, size:isize, chunk:isize) { match thefile.read(0, size as u64, chunk as u64, Ovl_op_complete) { Err(ec) => { println!("{}", str_win32err(ec)) } Ok(rdr) => { tests.push(rdr) } } } let uinp: String = gets(op_promt); match uinp.to_lowercase().as_ref() { "0" | "" => { break } "w" => { println!("{}", time_mark()); unsafe { SleepEx(1000, TRUE); } }, "2" => { start_read(&thefile, &mut tests, flsize, flsize) }, "1" => { start_read(&thefile, &mut tests, flsize, 4096) }, "c" => { tests.clear() }, _ => { } } } } } fn Ovl_op_complete(callee: *const OvlReader) { println!("{}, IO completed.", time_mark()) }
const INPUT: &str = include_str!("../input"); fn main() { let parsed_input = parse_input(INPUT); println!("{}", find_part_one_solution(parsed_input)); println!("{}", find_part_two_solution(parsed_input)); } fn parse_input(input: &str) -> &str { input.trim() } fn find_part_one_solution(polymer: &str) -> usize { fully_react_polymer(polymer).len() } fn find_part_two_solution(polymer: &str) -> usize { (b'a'..b'z') .map(|removed_unit| { let remaining_units = polymer .bytes() .filter(|b| b.to_ascii_lowercase() != removed_unit) .collect(); let edited_polymer = String::from_utf8(remaining_units).unwrap(); fully_react_polymer(&edited_polymer).len() }) .min() .unwrap() } fn fully_react_polymer(polymer: &str) -> String { let mut current_polymer = String::from(polymer); let mut previous_polymer: Option<String> = None; while previous_polymer.is_none() || *previous_polymer.unwrap() != current_polymer { previous_polymer = Some(current_polymer.clone()); current_polymer = current_polymer .chars() .fold(String::new(), |mut result, unit| { match result.chars().last() { Some(previous_unit) if is_reacting_pair(unit, previous_unit) => { result.pop(); } _ => { result.push(unit); } }; result }); } current_polymer } fn is_reacting_pair(a: char, b: char) -> bool { a != b && a.to_ascii_lowercase() == b.to_ascii_lowercase() } #[cfg(test)] mod tests { use super::*; #[test] fn it_removes_newline() { assert_eq!(parse_input("aA\n").len(), 2); } #[test] fn it_finds_correct_part_one_solution() { let sample_input = "dabAcCaCBAcCcaDA"; assert_eq!(find_part_one_solution(sample_input), 10); } #[test] fn it_finds_correct_part_two_solution() { let sample_input = "dabAcCaCBAcCcaDA"; assert_eq!(find_part_two_solution(sample_input), 4); } }
//! This crate is a rust port of the [official ProtonVPN python cli](https://github.com/ProtonVPN/linux-cli). We aim for feature parity and to track changes from the official cli. This crate's only non-rust dependency is `openvpn.` You'll need to install it using your system's package manager. //! //! This crate **does not** aim to have the same command line interface, or use the same config files / format. // TODO examples #![deny(missing_docs)] #![deny(broken_intra_doc_links)] use crate::{ cli::{configure, connect, initialize, CliOptions}, constants::APP_NAME, utils::project_dirs, vpn::util::Config, }; use anyhow::{Context, Result}; use confy::ConfyError; use dialoguer::console::Term; use std::io::Write; use CliOptions::*; /// This module contains all the structs for storing args passed in from the command line. /// /// `cli`'s submodules each correspond to one of the cli subcommands. Each submodule contains a function which wraps all the others in its module. This module reexports that function for use in the cli. pub mod cli; /// Assorted constants for use throughout the crate. Mostly strings and a map for looking up countries. pub mod constants; /// Miscellaneous functions. See the documentation for this module's members instead pub(crate) mod utils; /// Functions for interacting with the `openvpn` binary, including starting / stopping a connection, and creating config files. pub mod vpn; /// This module contains a wrapper type, [settings::Settings]. It has methods for creating setters, as well as an impl containing special setters for when it is UserConfig being wrapped. pub mod settings; /// The main function in main.rs is a wrapper of this function. pub fn main( opt: CliOptions, config_res: Result<Config, ConfyError>, terminal: &mut Term, ) -> Result<()> { let pdir = project_dirs(); if let Ok(mut config) = config_res { match opt { Init => { initialize(&mut config.user, &pdir, terminal)?; confy::store(APP_NAME, config.user).context("Couldn't store your configuration")?; } Connect(flags) => { let _connection = connect(&flags, &mut config, &pdir)?; } Reconnect => {} Disconnect => {} Status => {} Configure => { configure(&mut config.user, terminal)?; confy::store(APP_NAME, config.user).context("Couldn't store your configuration")?; } Refresh => {} Examples => {} }; } else { if let Init = opt { initialize(&mut Default::default(), &pdir, terminal)?; } else { writeln!( terminal, "Unable to load your profile. Try running `protonvpn init` again." )?; } } Ok(()) }
use async_graphql::{ http::{playground_source, GraphQLPlaygroundConfig}, EmptyMutation, EmptySubscription, Schema, }; use async_graphql_rocket::{Query, Request, Response}; use rocket::{response::content, routes, State}; use starwars::{QueryRoot, StarWars}; pub type StarWarsSchema = Schema<QueryRoot, EmptyMutation, EmptySubscription>; #[rocket::get("/")] fn graphql_playground() -> content::Html<String> { content::Html(playground_source(GraphQLPlaygroundConfig::new("/graphql"))) } #[rocket::get("/graphql?<query..>")] async fn graphql_query(schema: &State<StarWarsSchema>, query: Query) -> Response { query.execute(schema).await } #[rocket::post("/graphql", data = "<request>", format = "application/json")] async fn graphql_request(schema: &State<StarWarsSchema>, request: Request) -> Response { request.execute(schema).await } #[rocket::launch] fn rocket() -> _ { let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription) .data(StarWars::new()) .finish(); rocket::build().manage(schema).mount( "/", routes![graphql_query, graphql_request, graphql_playground], ) }
#[doc = "Register `TIMCCR2` reader"] pub type R = crate::R<TIMCCR2_SPEC>; #[doc = "Register `TIMCCR2` writer"] pub type W = crate::W<TIMCCR2_SPEC>; #[doc = "Field `DCDE` reader - Dual Channel DAC trigger enable"] pub type DCDE_R = crate::BitReader; #[doc = "Field `DCDE` writer - Dual Channel DAC trigger enable"] pub type DCDE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DCDS` reader - Dual Channel DAC Step trigger"] pub type DCDS_R = crate::BitReader; #[doc = "Field `DCDS` writer - Dual Channel DAC Step trigger"] pub type DCDS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DCDR` reader - Dual Channel DAC Reset trigger"] pub type DCDR_R = crate::BitReader; #[doc = "Field `DCDR` writer - Dual Channel DAC Reset trigger"] pub type DCDR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `UDM` reader - Up-Down Mode"] pub type UDM_R = crate::BitReader; #[doc = "Field `UDM` writer - Up-Down Mode"] pub type UDM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ROM` reader - Roll-Over Mode"] pub type ROM_R = crate::FieldReader; #[doc = "Field `ROM` writer - Roll-Over Mode"] pub type ROM_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `OUTROM` reader - Output Roll-Over Mode"] pub type OUTROM_R = crate::FieldReader; #[doc = "Field `OUTROM` writer - Output Roll-Over Mode"] pub type OUTROM_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `ADROM` reader - ADC Roll-Over Mode"] pub type ADROM_R = crate::FieldReader; #[doc = "Field `ADROM` writer - ADC Roll-Over Mode"] pub type ADROM_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `BMROM` reader - Burst Mode Roll-Over Mode"] pub type BMROM_R = crate::FieldReader; #[doc = "Field `BMROM` writer - Burst Mode Roll-Over Mode"] pub type BMROM_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `FEROM` reader - Fault and Event Roll-Over Mode"] pub type FEROM_R = crate::FieldReader; #[doc = "Field `FEROM` writer - Fault and Event Roll-Over Mode"] pub type FEROM_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `GTCMP1` reader - Greater than Compare 1 PWM mode"] pub type GTCMP1_R = crate::BitReader; #[doc = "Field `GTCMP1` writer - Greater than Compare 1 PWM mode"] pub type GTCMP1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `GTCMP3` reader - Greater than Compare 3 PWM mode"] pub type GTCMP3_R = crate::BitReader; #[doc = "Field `GTCMP3` writer - Greater than Compare 3 PWM mode"] pub type GTCMP3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TRGHLF` reader - Triggered-half mode"] pub type TRGHLF_R = crate::BitReader; #[doc = "Field `TRGHLF` writer - Triggered-half mode"] pub type TRGHLF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - Dual Channel DAC trigger enable"] #[inline(always)] pub fn dcde(&self) -> DCDE_R { DCDE_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Dual Channel DAC Step trigger"] #[inline(always)] pub fn dcds(&self) -> DCDS_R { DCDS_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Dual Channel DAC Reset trigger"] #[inline(always)] pub fn dcdr(&self) -> DCDR_R { DCDR_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 4 - Up-Down Mode"] #[inline(always)] pub fn udm(&self) -> UDM_R { UDM_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bits 6:7 - Roll-Over Mode"] #[inline(always)] pub fn rom(&self) -> ROM_R { ROM_R::new(((self.bits >> 6) & 3) as u8) } #[doc = "Bits 8:9 - Output Roll-Over Mode"] #[inline(always)] pub fn outrom(&self) -> OUTROM_R { OUTROM_R::new(((self.bits >> 8) & 3) as u8) } #[doc = "Bits 10:11 - ADC Roll-Over Mode"] #[inline(always)] pub fn adrom(&self) -> ADROM_R { ADROM_R::new(((self.bits >> 10) & 3) as u8) } #[doc = "Bits 12:13 - Burst Mode Roll-Over Mode"] #[inline(always)] pub fn bmrom(&self) -> BMROM_R { BMROM_R::new(((self.bits >> 12) & 3) as u8) } #[doc = "Bits 14:15 - Fault and Event Roll-Over Mode"] #[inline(always)] pub fn ferom(&self) -> FEROM_R { FEROM_R::new(((self.bits >> 14) & 3) as u8) } #[doc = "Bit 16 - Greater than Compare 1 PWM mode"] #[inline(always)] pub fn gtcmp1(&self) -> GTCMP1_R { GTCMP1_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - Greater than Compare 3 PWM mode"] #[inline(always)] pub fn gtcmp3(&self) -> GTCMP3_R { GTCMP3_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 20 - Triggered-half mode"] #[inline(always)] pub fn trghlf(&self) -> TRGHLF_R { TRGHLF_R::new(((self.bits >> 20) & 1) != 0) } } impl W { #[doc = "Bit 0 - Dual Channel DAC trigger enable"] #[inline(always)] #[must_use] pub fn dcde(&mut self) -> DCDE_W<TIMCCR2_SPEC, 0> { DCDE_W::new(self) } #[doc = "Bit 1 - Dual Channel DAC Step trigger"] #[inline(always)] #[must_use] pub fn dcds(&mut self) -> DCDS_W<TIMCCR2_SPEC, 1> { DCDS_W::new(self) } #[doc = "Bit 2 - Dual Channel DAC Reset trigger"] #[inline(always)] #[must_use] pub fn dcdr(&mut self) -> DCDR_W<TIMCCR2_SPEC, 2> { DCDR_W::new(self) } #[doc = "Bit 4 - Up-Down Mode"] #[inline(always)] #[must_use] pub fn udm(&mut self) -> UDM_W<TIMCCR2_SPEC, 4> { UDM_W::new(self) } #[doc = "Bits 6:7 - Roll-Over Mode"] #[inline(always)] #[must_use] pub fn rom(&mut self) -> ROM_W<TIMCCR2_SPEC, 6> { ROM_W::new(self) } #[doc = "Bits 8:9 - Output Roll-Over Mode"] #[inline(always)] #[must_use] pub fn outrom(&mut self) -> OUTROM_W<TIMCCR2_SPEC, 8> { OUTROM_W::new(self) } #[doc = "Bits 10:11 - ADC Roll-Over Mode"] #[inline(always)] #[must_use] pub fn adrom(&mut self) -> ADROM_W<TIMCCR2_SPEC, 10> { ADROM_W::new(self) } #[doc = "Bits 12:13 - Burst Mode Roll-Over Mode"] #[inline(always)] #[must_use] pub fn bmrom(&mut self) -> BMROM_W<TIMCCR2_SPEC, 12> { BMROM_W::new(self) } #[doc = "Bits 14:15 - Fault and Event Roll-Over Mode"] #[inline(always)] #[must_use] pub fn ferom(&mut self) -> FEROM_W<TIMCCR2_SPEC, 14> { FEROM_W::new(self) } #[doc = "Bit 16 - Greater than Compare 1 PWM mode"] #[inline(always)] #[must_use] pub fn gtcmp1(&mut self) -> GTCMP1_W<TIMCCR2_SPEC, 16> { GTCMP1_W::new(self) } #[doc = "Bit 17 - Greater than Compare 3 PWM mode"] #[inline(always)] #[must_use] pub fn gtcmp3(&mut self) -> GTCMP3_W<TIMCCR2_SPEC, 17> { GTCMP3_W::new(self) } #[doc = "Bit 20 - Triggered-half mode"] #[inline(always)] #[must_use] pub fn trghlf(&mut self) -> TRGHLF_W<TIMCCR2_SPEC, 20> { TRGHLF_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 = "HRTIM Timerx Control Register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`timccr2::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 [`timccr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct TIMCCR2_SPEC; impl crate::RegisterSpec for TIMCCR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`timccr2::R`](R) reader structure"] impl crate::Readable for TIMCCR2_SPEC {} #[doc = "`write(|w| ..)` method takes [`timccr2::W`](W) writer structure"] impl crate::Writable for TIMCCR2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets TIMCCR2 to value 0"] impl crate::Resettable for TIMCCR2_SPEC { const RESET_VALUE: Self::Ux = 0; }