text stringlengths 8 4.13M |
|---|
use challenges::chal39::{RsaKeyPair, RsaPubKey, SHA1_PKCS1_DIGESTINFO_PREFIX};
use num::pow::Pow;
use num::{BigUint, One};
use sha1::{Digest, Sha1};
use std::cmp::Ordering;
fn main() {
println!("🔓 Challenge 42");
let msg = b"hi mom".to_vec();
let pk = RsaKeyPair::default().pubKey;
let forged_sig = forgey_attack(&msg, &pk);
assert!(pk.broken_sig_verify(&msg, &forged_sig));
println!("Successfully forged a signature!");
}
fn forgey_attack(msg: &[u8], pk: &RsaPubKey) -> Vec<u8> {
let mod_byte = pk.n.bits() as usize / 8;
let mut h = Sha1::default();
h.input(&msg);
let hash = h.result().to_vec();
let forged_pt_prefix = b"\x00\x01\xff\xff\xff\xff\xff\xff\xff\xff".to_vec();
let forged_pt_payload = [b"\x00".to_vec(), SHA1_PKCS1_DIGESTINFO_PREFIX.to_vec(), hash].concat();
let garbage_len_max = mod_byte - forged_pt_prefix.len() - forged_pt_payload.len();
for garbage_len in 0..garbage_len_max + 1 {
let extra_xff_len = garbage_len_max - garbage_len;
let forged_pt_min = BigUint::from_bytes_be(
&[
forged_pt_prefix.clone(),
vec![255 as u8; extra_xff_len].to_vec(),
forged_pt_payload.clone(),
vec![0 as u8; garbage_len],
]
.concat(),
);
let forged_pt_max = &forged_pt_min + (BigUint::one() << (garbage_len * 8));
if let Some(cub) = next_cub(&forged_pt_min, &forged_pt_max) {
return BigUint::to_bytes_be(&cub.cbrt());
}
}
panic!("Failed!");
}
// return the next perfect cubic number between [a, b)
fn next_cub(a: &BigUint, b: &BigUint) -> Option<BigUint> {
let cbrt = a.cbrt();
match Pow::pow(&cbrt, 3 as u32).cmp(&a) {
Ordering::Equal => Some(a.to_owned()),
Ordering::Greater => panic!("should never happen"),
Ordering::Less => {
let next = Pow::pow(cbrt + BigUint::one(), 3 as u32);
match next.cmp(&b) {
Ordering::Less => Some(next),
_ => None,
}
}
}
}
|
pub mod qqmlparserstatus;
pub use self::qqmlparserstatus::QQmlParserStatus;
pub mod qqmlpropertymap;
pub use self::qqmlpropertymap::QQmlPropertyMap;
pub mod qqmlcomponent;
pub use self::qqmlcomponent::QQmlComponent;
pub mod qjsvalueiterator;
pub use self::qjsvalueiterator::QJSValueIterator;
pub mod qqmlextensionplugin;
pub use self::qqmlextensionplugin::QQmlExtensionPlugin;
pub mod qqmllist;
pub use self::qqmllist::QQmlListReference;
pub mod qqmlfileselector;
pub use self::qqmlfileselector::QQmlFileSelector;
pub mod qqmlextensioninterface;
pub use self::qqmlextensioninterface::QQmlTypesExtensionInterface;
pub mod qqmlincubator;
pub use self::qqmlincubator::QQmlIncubationController;
pub mod qqmlproperty;
pub use self::qqmlproperty::QQmlProperty;
pub mod qqmlcontext;
pub use self::qqmlcontext::QQmlContext;
pub mod qqmlengine;
pub use self::qqmlengine::QQmlEngine;
pub mod qqmlabstracturlinterceptor;
pub use self::qqmlabstracturlinterceptor::QQmlAbstractUrlInterceptor;
pub mod qqmlscriptstring;
pub use self::qqmlscriptstring::QQmlScriptString;
pub mod qqmlerror;
pub use self::qqmlerror::QQmlError;
pub mod qqmlpropertyvaluesource;
pub use self::qqmlpropertyvaluesource::QQmlPropertyValueSource;
pub mod qqmldebug;
pub use self::qqmldebug::QQmlDebuggingEnabler;
pub use self::qqmlincubator::QQmlIncubator;
pub mod qqmlnetworkaccessmanagerfactory;
pub use self::qqmlnetworkaccessmanagerfactory::QQmlNetworkAccessManagerFactory;
pub mod qjsvalue;
pub use self::qjsvalue::QJSValue;
pub mod qqmlfile;
pub use self::qqmlfile::QQmlFile;
pub mod qqmlinfo;
pub use self::qqmlinfo::QQmlInfo;
pub mod qqmlexpression;
pub use self::qqmlexpression::QQmlExpression;
pub mod qqmlapplicationengine;
pub use self::qqmlapplicationengine::QQmlApplicationEngine;
pub mod qjsengine;
pub use self::qjsengine::QJSEngine;
pub use self::qqmlextensioninterface::QQmlExtensionInterface;
pub use self::qqmlengine::QQmlImageProviderBase;
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use std::convert::TryInto;
use anyhow::*;
use liblumen_alloc::erts::exception::{self, *};
use liblumen_alloc::erts::process::trace::Trace;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::Term;
/// `//2` infix operator. Unlike `+/2`, `-/2` and `*/2` always promotes to `float` returns the
/// `float`.
#[native_implemented::function(erlang:/ /2)]
pub fn result(process: &Process, dividend: Term, divisor: Term) -> exception::Result<Term> {
let dividend_f64: f64 = dividend.try_into().map_err(|_| {
badarith(
Trace::capture(),
Some(anyhow!("dividend ({}) cannot be promoted to a float", dividend).into()),
)
})?;
let divisor_f64: f64 = divisor.try_into().map_err(|_| {
badarith(
Trace::capture(),
Some(anyhow!("divisor ({}) cannot be promoted to a float", divisor).into()),
)
})?;
if divisor_f64 == 0.0 {
Err(badarith(
Trace::capture(),
Some(anyhow!("divisor ({}) cannot be zero", divisor).into()),
)
.into())
} else {
let quotient_f64 = dividend_f64 / divisor_f64;
let quotient_term = process.float(quotient_f64);
Ok(quotient_term)
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use common_base::base::tokio;
use common_exception::Result;
use sharing_endpoint::models::DatabaseSpec;
use sharing_endpoint::models::LambdaInput;
use sharing_endpoint::models::ShareSpec;
use sharing_endpoint::models::SharingConfig;
use sharing_endpoint::models::TableSpec;
// mock some SharingConfig
// and test on SharingConfig get_tables method
#[tokio::test(flavor = "multi_thread")]
async fn test_get_tables() -> Result<()> {
let mut config = SharingConfig {
share_specs: HashMap::new(),
};
config.share_specs.insert("share1".to_string(), ShareSpec {
name: "share1".to_string(),
share_id: 0,
version: 0,
database: DatabaseSpec {
name: "db1".to_string(),
location: "s3://db1".to_string(),
id: 0,
},
tables: vec![
TableSpec {
name: "table1".to_string(),
location: "s3://db1/table1".to_string(),
database_id: 0,
table_id: 0,
presigned_url_timeout: "".to_string(),
},
TableSpec {
name: "table2".to_string(),
location: "s3://db1/table2".to_string(),
database_id: 0,
table_id: 1,
presigned_url_timeout: "".to_string(),
},
],
tenants: vec!["t1".to_string()],
});
let input = LambdaInput {
authorization: "".to_string(),
tenant_id: "t1".to_string(),
share_name: "share1".to_string(),
table_name: "table1".to_string(),
request_files: vec![],
request_id: "123".to_string(),
};
let table = config.get_tables(&input)?;
assert!(table.is_some());
assert_eq!(table.as_ref().unwrap().table, "table1");
assert_eq!(table.as_ref().unwrap().location, "s3://db1/table1");
Ok(())
}
|
use sp_std::prelude::*;
#[cfg(feature = "std")]
use std::fmt;
use codec::{Compact, Decode, Encode, Error, Input};
use sp_core::{blake2_256,H256,};
use sp_runtime::{generic::Era, MultiSignature,AccountId32 as AccountId};
pub type AccountIndex = u64;
pub type GenericAddress =AccountId; // crate::multiaddress::MultiAddress<AccountId, ()>
/// Simple generic extra mirroring the SignedExtra currently used in extrinsics. Does not implement
/// the SignedExtension trait. It simply encodes to the same bytes as the real SignedExtra. The
/// Order is (CheckVersion, CheckGenesis, Check::Era, CheckNonce, CheckWeight, transactionPayment::ChargeTransactionPayment).
/// This can be locked up in the System module. Fields that are merely PhantomData are not encoded and are
/// therefore omitted here.
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(Decode, Encode, Clone, Eq, PartialEq)]
pub struct GenericExtra(Era, Compact<u32>, Compact<u128>);
impl GenericExtra {
pub fn new(era: Era, nonce: u32) -> GenericExtra {
GenericExtra(era, Compact(nonce), Compact(0_u128))
}
pub fn get_nonce(&self)->u32{
self.1.0
}
}
impl Default for GenericExtra {
fn default() -> Self {
Self::new(Era::Immortal, 0)
}
}
/// additionalSigned fields of the respective SignedExtra fields.
/// Order is the same as declared in the extra.
pub type AdditionalSigned = (u32, u32, H256, H256, (), (), ());
#[derive(Encode, Clone)]
pub struct SignedPayload<Call>((Call, GenericExtra, AdditionalSigned));
impl<Call> SignedPayload<Call>
where
Call: Encode,
{
pub fn from_raw(call: Call, extra: GenericExtra, additional_signed: AdditionalSigned) -> Self {
Self((call, extra, additional_signed))
}
/// Get an encoded version of this payload.
///
/// Payloads longer than 256 bytes are going to be `blake2_256`-hashed.
pub fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
self.0.using_encoded(|payload| {
if payload.len() > 256 {
let hash = blake2_256(payload);
f(&hash[..])
} else {
f(payload)
}
})
}
}
/// Mirrors the currently used Extrinsic format (V3) from substrate. Has less traits and methods though.
/// The SingedExtra used does not need to implement SingedExtension here.
#[derive(Clone, PartialEq)]
pub struct UncheckedExtrinsicV4<Call> {
pub signature: Option<(GenericAddress, MultiSignature, GenericExtra)>,
pub function: Call,
}
impl<Call> UncheckedExtrinsicV4<Call>
where
Call: Encode,
{
pub fn new_signed(
function: Call,
signed: GenericAddress,
signature: MultiSignature,
extra: GenericExtra,
) -> Self {
UncheckedExtrinsicV4 {
signature: Some((signed, signature, extra)),
function,
}
}
#[cfg(feature = "std")]
pub fn hex_encode(&self) -> String {
let mut hex_str = hex::encode(self.encode());
hex_str.insert_str(0, "0x");
hex_str
}
}
#[cfg(feature = "std")]
impl<Call> fmt::Debug for UncheckedExtrinsicV4<Call>
where
Call: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"UncheckedExtrinsic({:?}, {:?})",
self.signature.as_ref().map(|x| (&x.0, &x.2)),
self.function
)
}
}
const V4: u8 = 4;
impl<Call> Encode for UncheckedExtrinsicV4<Call>
where
Call: Encode,
{
fn encode(&self) -> Vec<u8> {
encode_with_vec_prefix::<Self, _>(|v| {
match self.signature.as_ref() {
Some(s) => {
v.push(V4 | 0b1000_0000);
s.encode_to(v);
}
None => {
v.push(V4 & 0b0111_1111);
}
}
self.function.encode_to(v);
})
}
}
impl<Call> Decode for UncheckedExtrinsicV4<Call>
where
Call: Decode + Encode,
{
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
// This is a little more complicated than usual since the binary format must be compatible
// with substrate's generic `Vec<u8>` type. Basically this just means accepting that there
// will be a prefix of vector length (we don't need
// to use this).
let _length_do_not_remove_me_see_above: Vec<()> = Decode::decode(input)?;
let version = input.read_byte()?;
let is_signed = version & 0b1000_0000 != 0;
let version = version & 0b0111_1111;
if version != V4 {
return Err("Invalid transaction version".into());
}
Ok(UncheckedExtrinsicV4 {
signature: if is_signed {
Some(Decode::decode(input)?)
} else {
None
},
function: Decode::decode(input)?,
})
}
}
#[derive(Debug)]
pub struct RawExtrinsic {
pub module_index:u8,
pub call_index:u8,
pub args:Vec<u8>,
}
#[derive(Debug)]
pub struct CheckedExtrinsic{
pub signature: Option<(GenericAddress, MultiSignature, GenericExtra)>,
pub function: RawExtrinsic,
}
/// Mirrors the currently used Extrinsic format from substrate UncheckedExtrinsicV4. Has less traits and methods though.
/// The SingedExtra used does not need to implement SingedExtension here.
/// Construct a data format that meets the requirements of the chain through transactions constructed by external methods.
#[derive(Clone, PartialEq)]
pub struct UncheckedExtrinsicFromOuter{
pub signature: Option<(GenericAddress, MultiSignature, GenericExtra)>,
pub function: Vec<u8>,
}
impl UncheckedExtrinsicFromOuter
{
pub fn new_signed(
function: Vec<u8>,
signed: GenericAddress,
signature: MultiSignature,
extra: GenericExtra,
) -> Self {
UncheckedExtrinsicFromOuter {
signature: Some((signed, signature, extra)),
function,
}
}
#[cfg(feature = "std")]
pub fn hex_encode(&self) -> String {
let mut hex_str = hex::encode(self.encode());
hex_str.insert_str(0, "0x");
hex_str
}
}
#[cfg(feature = "std")]
impl fmt::Debug for UncheckedExtrinsicFromOuter
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"UncheckedExtrinsic({:?}, {:?})",
self.signature.as_ref().map(|x| (&x.0, &x.2)),
self.function
)
}
}
impl Encode for UncheckedExtrinsicFromOuter
{
fn encode(&self) -> Vec<u8> {
encode_with_vec_prefix::<Self, _>(|v| {
match self.signature.as_ref() {
Some(s) => {
v.push(V4 | 0b1000_0000);
s.encode_to(v);
}
None => {
v.push(V4 & 0b0111_1111);
}
}
let func_len = self.function.len();
let func_encode_vec = self.function.encode();
let offset_start = func_encode_vec.len()-func_len;
v.extend_from_slice(&func_encode_vec[offset_start..]);
})
}
}
impl Decode for CheckedExtrinsic
{
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
// This is a little more complicated than usual since the binary format must be compatible
// with substrate's generic `Vec<u8>` type. Basically this just means accepting that there
// will be a prefix of vector length (we don't need
// to use this).
let _length_do_not_remove_me_see_above: Vec<()> = Decode::decode(input)?;
let version = input.read_byte()?;
let is_signed = version & 0b1000_0000 != 0;
let version = version & 0b0111_1111;
if version != V4 {
return Err("Invalid transaction version".into());
}
let sig = if is_signed {
let sig : (GenericAddress, MultiSignature, GenericExtra) = Decode::decode(input)?;
Some(sig)
}else {
None
};
let module_index = input.read_byte()?;
let call_index = input.read_byte()?;
let len = input.remaining_len().unwrap().unwrap();
let mut func_args = vec![0u8;len];
input.read( &mut func_args)?;
// func_args.clone_from_slice(input.);
let raw_tx = RawExtrinsic{
module_index,
call_index,
args: func_args
};
let checked_tx = CheckedExtrinsic{
signature:sig,
function:raw_tx,
};
Ok(checked_tx)
}
}
pub fn get_func_prefix_len(func_data:&[u8])->usize{
let len = match func_data.len(){
1..=0b0100_0000 => 1,//1-64 real func data range is 0-63
0b0100_0010..=0b0100_0000_0000_0001 => 2,// 66-(2**14+1) real func data range is 64-(2**14-1)
_ => 4,
};
// prefix = array length + version code
len+1
}
/// Same function as in primitives::generic. Needed to be copied as it is private there.
fn encode_with_vec_prefix<T: Encode, F: Fn(&mut Vec<u8>)>(encoder: F) -> Vec<u8> {
let size = sp_std::mem::size_of::<T>();
let reserve = match size {
0..=0b0011_1111 => 1,
0b0100_0000..=0b0011_1111_1111_1111 => 2,
_ => 4,
};
let mut v = Vec::with_capacity(reserve + size);
v.resize(reserve, 0);
encoder(&mut v);
// need to prefix with the total length to ensure it's binary compatible with
// Vec<u8>.
let mut length: Vec<()> = Vec::new();
length.resize(v.len() - reserve, ());
length.using_encoded(|s| {
v.splice(0..reserve, s.iter().cloned());
});
v
}
#[cfg(test)]
mod tests {
use super::*;
use crate::extrinsic::xt_primitives::{GenericAddress, GenericExtra};
use sp_runtime::MultiSignature;
#[test]
fn encode_decode_roundtrip_works() {
let xt = UncheckedExtrinsicV4::new_signed(
vec![1, 1, 1],
GenericAddress::default(),
MultiSignature::default(),
GenericExtra::default(),
);
let xt_enc = xt.encode();
assert_eq!(xt, Decode::decode(&mut xt_enc.as_slice()).unwrap())
}
}
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// pretty-expanded FIXME #23616
pub mod two_tuple {
pub trait T { fn dummy(&self) { } }
pub struct P<'a>(&'a (T + 'a), &'a (T + 'a));
pub fn f<'a>(car: &'a T, cdr: &'a T) -> P<'a> {
P(car, cdr)
}
}
pub mod two_fields {
pub trait T { fn dummy(&self) { } }
pub struct P<'a> { car: &'a (T + 'a), cdr: &'a (T + 'a) }
pub fn f<'a>(car: &'a T, cdr: &'a T) -> P<'a> {
P{ car: car, cdr: cdr }
}
}
fn main() {}
|
use svg::{Document};
use svg::node::element::Circle;
use svg::node::element::Rectangle;
use svg::node;
use svg::node::element;
// lets do this on an 8.5 by 8.5 square cause itll fit on my paper
const DOCUMENT_HEIGHT: f64 = 8.5;
pub const BAR_WIDTH: f64 = 0.01; // fractions
pub const BAR_LENGTH: f64 = 0.03;
const ALIGNER_INNER_RADIUS: f64 = 0.05;
pub const ALIGNER_OUTER_RADIUS: f64 = 0.05*10./7.;
const TEMPLATE_COLOR: &'static str = "#CFE2F3"; // blue light enough that the image parser will ignore it
const TITLE_FONT_SIZE: f64 = 0.13;
pub const FIELD_FONT_SIZE: f64 = 0.05;
// numbers in here are expressed as percentages of the document width
pub struct ScanSheetElements {
elements: Vec<Element>,
}
impl ScanSheetElements {
pub fn empty() -> ScanSheetElements {
ScanSheetElements {
elements: Vec::new()
}
}
pub fn add_element(&mut self, element: Element) {
self.elements.push(element);
}
pub fn to_svg(&self) -> Document {
let mut doc = Document::new()
.set("width", format!("{}in", DOCUMENT_HEIGHT))
.set("height", format!("{}in", DOCUMENT_HEIGHT));
for element in self.elements.iter() {
doc = element.add_to_document(doc);
}
doc
}
}
pub struct Element {
pub x: f64,
pub y: f64,
pub kind: ElementKind,
}
impl Element {
fn add_to_document(&self, doc: Document) -> Document {
match self.kind {
ElementKind::Aligner => {
let outer = Circle::new()
.set("cx", percentize(self.x+ALIGNER_OUTER_RADIUS))
.set("cy", percentize(self.y+ALIGNER_OUTER_RADIUS))
.set("r", percentize(ALIGNER_OUTER_RADIUS))
.set("fill", "black");
let inner = Circle::new()
.set("cx", percentize(self.x+ALIGNER_OUTER_RADIUS))
.set("cy", percentize(self.y+ALIGNER_OUTER_RADIUS))
.set("r", percentize(ALIGNER_INNER_RADIUS))
.set("fill", "white");
doc.add(outer).add(inner)
},
ElementKind::HorizontalBar | ElementKind::VerticalBar => {
let (w, h) = if let ElementKind::VerticalBar = self.kind {
(BAR_WIDTH, BAR_LENGTH)
} else {
(BAR_LENGTH, BAR_WIDTH)
};
let rect = Rectangle::new()
.set("x", percentize(self.x))
.set("y", percentize(self.y))
.set("width", percentize(w))
.set("height", percentize(h))
.set("fill", TEMPLATE_COLOR);
doc.add(rect)
},
ElementKind::FieldDescriptor(ref s) | ElementKind::Title(ref s) => {
let font_size = if self.kind.is_title() { TITLE_FONT_SIZE } else { FIELD_FONT_SIZE };
let text = element::Text::new()
.add(node::Text::new(s.clone()))
.set("x", percentize(self.x))
.set("y", percentize(self.y+font_size)) // for some reason text position is relative to bottom left corner
.set("fill", TEMPLATE_COLOR)
.set("font-size", to_points(font_size))
.set("font-family", "monospace");
doc.add(text)
},
}
}
}
#[derive(PartialEq)]
pub enum ElementKind {
Aligner,
HorizontalBar,
VerticalBar,
FieldDescriptor(String),
Title(String),
}
impl ElementKind {
fn is_title(&self) -> bool {
match *self {
ElementKind::Title(_) => true,
_ => false,
}
}
}
// n is a fraction between 0 and 1
fn percentize(n: f64) -> String {
format!("{:.2}%", 100.0*n) // the text of our svg is less readable if we don't truncate
}
fn to_points(fraction: f64) -> String {
// the input is a height fraction from 0 to 1, and the output is the size of text in points
// 72 to points is one inch, and our square is 8.5 inches
let height = 8.5*fraction; // in inches
format!("{}", 72.0*height)
}
|
use super::Forwarder;
use super::TxType;
use failure::Error;
use log::{error, info};
use std::net::SocketAddr;
use std::result::Result;
use futures_03::prelude::*;
use stream_cancel::{Trigger, Tripwire};
use tokio::net::UdpSocket;
use std::cell::RefCell;
use std::rc::Rc;
type LongLive = Rc<RefCell<UdpServer>>;
type ForwarderType = Rc<RefCell<Forwarder>>;
pub struct UdpServer {
listen_addr: String,
tx: (Option<TxType>, Option<Trigger>),
}
impl UdpServer {
pub fn new(addr: &str) -> LongLive {
info!("[UdpServer]new server, addr:{}", addr);
Rc::new(RefCell::new(UdpServer {
listen_addr: addr.to_string(),
tx: (None, None),
}))
}
pub fn start(&mut self, fw: &Forwarder, forward: ForwarderType) -> Result<(), Error> {
let listen_addr = &self.listen_addr;
let addr: SocketAddr = listen_addr.parse().map_err(|e| Error::from(e))?;
let socket_udp = std::net::UdpSocket::bind(addr)?;
let a = UdpSocket::from_std(socket_udp)?;
let udp_framed = tokio_util::udp::UdpFramed::new(a, tokio_util::codec::BytesCodec::new());
let (a_sink, a_stream) = udp_framed.split();
let forwarder1 = forward.clone();
let forwarder2 = forward.clone();
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let (trigger, tripwire) = Tripwire::new();
self.set_tx(tx, trigger);
fw.on_dns_udp_created(self, forward);
// send future
let send_fut = rx.map(move |x| Ok(x)).forward(a_sink);
let receive_fut = async move {
let mut a_stream = a_stream.take_until(tripwire);
while let Some(rr) = a_stream.next().await {
match rr {
Ok((message, addr)) => {
let rf = forwarder1.borrow();
// post to manager
if rf.on_dns_udp_msg(message, addr) {
} else {
error!("[UdpServer] on_dns_udp_msg failed");
break;
}
}
Err(e) => {
error!("[UdpServer] a_stream.next failed:{}", e);
break;
}
};
}
};
// Wait for one future to complete.
let select_fut = async move {
future::select(receive_fut.boxed_local(), send_fut).await;
info!("[UdpServer] udp both future completed");
let rf = forwarder2.borrow();
rf.on_dns_udp_closed();
};
tokio::task::spawn_local(select_fut);
Ok(())
}
fn set_tx(&mut self, tx2: TxType, trigger: Trigger) {
self.tx = (Some(tx2), Some(trigger));
}
pub fn get_tx(&self) -> Option<TxType> {
let tx = &self.tx;
let tx = &tx.0;
match tx {
Some(tx) => Some(tx.clone()),
None => None,
}
}
pub fn stop(&mut self) {
self.tx = (None, None);
}
pub fn reply(&self, bm: bytes::Bytes, sa: SocketAddr) {
match self.get_tx() {
Some(tx) => match tx.send((bm, sa)) {
Err(e) => {
error!("[UdpServer]unbounded_send error:{}", e);
}
_ => {}
},
None => {}
}
}
}
|
#![allow(dead_code)]
use super::Payload;
use serde::{de::DeserializeOwned, Serialize};
use std::io;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpStream,
};
use tokio_util::codec::{Decoder, Encoder};
pub(crate) struct Conn<T>
where
T: Serialize,
{
buf: bytes::BytesMut,
payload: Payload<T>,
stream: TcpStream,
}
impl<T> Conn<T>
where
T: Serialize + DeserializeOwned,
{
pub(crate) fn new(stream: TcpStream) -> Conn<T>
where
T: Serialize + DeserializeOwned,
{
Conn {
buf: bytes::BytesMut::new(),
payload: Payload::new(),
stream,
}
}
}
pub(crate) async fn send<T>(comm: &mut Conn<T>, frame: T) -> io::Result<usize>
where
T: Serialize + DeserializeOwned,
{
comm.payload.encode(frame, &mut comm.buf)?;
comm.stream.write_buf(&mut comm.buf).await
}
pub(crate) async fn receive<T>(comm: &mut Conn<T>) -> io::Result<T>
where
T: Serialize + DeserializeOwned,
{
loop {
if 0 == comm.stream.read_buf(&mut comm.buf).await? && comm.buf.is_empty() {
break Err(io::Error::new(io::ErrorKind::UnexpectedEof, "EOF"));
}
match comm.payload.decode(&mut comm.buf) {
Ok(Some(frame)) => break Ok(frame),
Ok(None) => continue,
Err(e) => break Err(e),
}
}
}
|
#[doc = "Reader of register CSICFGR"]
pub type R = crate::R<u32, super::CSICFGR>;
#[doc = "Writer for register CSICFGR"]
pub type W = crate::W<u32, super::CSICFGR>;
#[doc = "Register CSICFGR `reset()`'s with value 0"]
impl crate::ResetValue for super::CSICFGR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `CSITRIM`"]
pub type CSITRIM_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `CSITRIM`"]
pub struct CSITRIM_W<'a> {
w: &'a mut W,
}
impl<'a> CSITRIM_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x3f << 24)) | (((value as u32) & 0x3f) << 24);
self.w
}
}
#[doc = "Reader of field `CSICAL`"]
pub type CSICAL_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `CSICAL`"]
pub struct CSICAL_W<'a> {
w: &'a mut W,
}
impl<'a> CSICAL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01ff) | ((value as u32) & 0x01ff);
self.w
}
}
impl R {
#[doc = "Bits 24:29 - CSI clock trimming"]
#[inline(always)]
pub fn csitrim(&self) -> CSITRIM_R {
CSITRIM_R::new(((self.bits >> 24) & 0x3f) as u8)
}
#[doc = "Bits 0:8 - CSI clock calibration"]
#[inline(always)]
pub fn csical(&self) -> CSICAL_R {
CSICAL_R::new((self.bits & 0x01ff) as u16)
}
}
impl W {
#[doc = "Bits 24:29 - CSI clock trimming"]
#[inline(always)]
pub fn csitrim(&mut self) -> CSITRIM_W {
CSITRIM_W { w: self }
}
#[doc = "Bits 0:8 - CSI clock calibration"]
#[inline(always)]
pub fn csical(&mut self) -> CSICAL_W {
CSICAL_W { w: self }
}
}
|
use super::data_filtering::{build_filter_plan, FilterPlan, PartialResults, Types};
use super::error::PolarResult;
use super::events::*;
use super::kb::*;
use super::messages::*;
use super::parser;
use super::rewrites::*;
use super::roles_validation::{validate_roles_config, VALIDATE_ROLES_CONFIG_RESOURCES};
use super::runnable::Runnable;
use super::sources::*;
use super::terms::*;
use super::vm::*;
use super::warnings::{check_ambiguous_precedence, check_singletons};
use std::sync::{Arc, RwLock};
pub struct Query {
runnable_stack: Vec<(Box<dyn Runnable>, u64)>, // Tuple of Runnable + call_id.
vm: PolarVirtualMachine,
term: Term,
done: bool,
}
impl Query {
pub fn new(vm: PolarVirtualMachine, term: Term) -> Self {
Self {
runnable_stack: vec![],
vm,
term,
done: false,
}
}
#[cfg(target_arch = "wasm32")]
pub fn set_logging_options(&mut self, rust_log: Option<String>, polar_log: Option<String>) {
self.vm.set_logging_options(rust_log, polar_log);
}
/// Runnable lifecycle
///
/// 1. Get Runnable A from the top of the Runnable stack, defaulting to the VM.
/// 2. If Runnable A emits a Run event containing Runnable B, push Runnable B onto the stack.
/// 3. Immediately request the next event, which will execute Runnable B.
/// 4. When Runnable B emits a Done event, pop Runnable B off the stack and return its result as
/// an answer to Runnable A.
pub fn next_event(&mut self) -> PolarResult<QueryEvent> {
let mut counter = self.vm.id_counter();
let qe = match self.top_runnable().run(Some(&mut counter)) {
Ok(e) => e,
Err(e) => self.top_runnable().handle_error(e)?,
};
self.recv_event(qe)
}
fn recv_event(&mut self, qe: QueryEvent) -> PolarResult<QueryEvent> {
match qe {
QueryEvent::None => self.next_event(),
QueryEvent::Run { runnable, call_id } => {
self.push_runnable(runnable, call_id);
self.next_event()
}
QueryEvent::Done { result } => {
if let Some((_, result_call_id)) = self.pop_runnable() {
self.top_runnable()
.external_question_result(result_call_id, result)?;
self.next_event()
} else {
// VM is done.
assert!(self.runnable_stack.is_empty());
Ok(QueryEvent::Done { result })
}
}
ev => Ok(ev),
}
}
fn top_runnable(&mut self) -> &mut (dyn Runnable) {
self.runnable_stack
.last_mut()
.map(|b| b.0.as_mut())
.unwrap_or(&mut self.vm)
}
fn push_runnable(&mut self, runnable: Box<dyn Runnable>, call_id: u64) {
self.runnable_stack.push((runnable, call_id));
}
fn pop_runnable(&mut self) -> Option<(Box<dyn Runnable>, u64)> {
self.runnable_stack.pop()
}
pub fn call_result(&mut self, call_id: u64, value: Option<Term>) -> PolarResult<()> {
self.top_runnable().external_call_result(call_id, value)
}
pub fn question_result(&mut self, call_id: u64, result: bool) -> PolarResult<()> {
self.top_runnable()
.external_question_result(call_id, result)
}
pub fn application_error(&mut self, message: String) -> PolarResult<()> {
self.vm.external_error(message)
}
pub fn debug_command(&mut self, command: &str) -> PolarResult<()> {
self.top_runnable().debug_command(command)
}
pub fn next_message(&self) -> Option<Message> {
self.vm.messages.next()
}
pub fn source_info(&self) -> String {
self.vm.term_source(&self.term, true)
}
pub fn bind(&mut self, name: Symbol, value: Term) -> PolarResult<()> {
self.vm.bind(&name, value)
}
}
// Query as an iterator returns `None` after the first time `Done` is seen
impl Iterator for Query {
type Item = PolarResult<QueryEvent>;
fn next(&mut self) -> Option<PolarResult<QueryEvent>> {
if self.done {
return None;
}
let event = self.next_event();
if let Ok(QueryEvent::Done { .. }) = event {
self.done = true;
}
Some(event)
}
}
const ROLES_POLICY: &str = include_str!("roles.polar");
pub struct Polar {
pub kb: Arc<RwLock<KnowledgeBase>>,
messages: MessageQueue,
}
impl Default for Polar {
fn default() -> Self {
Self::new()
}
}
impl Polar {
pub fn new() -> Self {
Self {
kb: Arc::new(RwLock::new(KnowledgeBase::new())),
messages: MessageQueue::new(),
}
}
pub fn load(&self, src: &str, filename: Option<String>) -> PolarResult<()> {
let source = Source {
filename,
src: src.to_owned(),
};
let mut kb = self.kb.write().unwrap();
let source_id = kb.add_source(source.clone())?;
// we extract this into a separate function
// so that any errors returned with `?` are captured
fn load_source(
source_id: u64,
source: &Source,
kb: &mut KnowledgeBase,
) -> PolarResult<Vec<String>> {
let mut lines = parser::parse_lines(source_id, &source.src)
.map_err(|e| e.set_context(Some(source), None))?;
lines.reverse();
let mut warnings = vec![];
while let Some(line) = lines.pop() {
match line {
parser::Line::Rule(rule) => {
let mut rule_warnings = check_singletons(&rule, &*kb)?;
warnings.append(&mut rule_warnings);
warnings.append(&mut check_ambiguous_precedence(&rule, &*kb)?);
let rule = rewrite_rule(rule, kb);
kb.add_rule(rule);
}
parser::Line::Query(term) => {
kb.inline_queries.push(term);
}
parser::Line::RulePrototype(prototype) => {
// make sure prototype doesn't have anything that needs to be rewritten in the head
let prototype = rewrite_rule(prototype, kb);
if !matches!(
prototype.body.value(),
Value::Expression(
Operation {
operator: Operator::And,
args
}
) if args.is_empty()
) {
return Err(kb.set_error_context(
&prototype.body,
error::ValidationError::InvalidPrototype {
prototype: prototype.to_polar(),
msg: "\nPrototypes cannot contain dot lookups.".to_owned(),
},
));
}
kb.add_rule_prototype(prototype);
}
parser::Line::Namespace(namespace) => {
namespace.add_to_kb(kb)?;
}
}
}
// Rewrite namespace implications _before_ validating rule prototypes.
kb.rewrite_implications()?;
// check rules are valid against rule prototypes
kb.validate_rules()?;
Ok(warnings)
}
// if any of the lines fail to load, we need to remove the source from
// the knowledge base
match load_source(source_id, &source, &mut kb) {
Ok(warnings) => {
self.messages.extend(warnings.iter().map(|m| Message {
kind: MessageKind::Warning,
msg: m.to_owned(),
}));
Ok(())
}
Err(e) => {
kb.remove_source(source_id);
Err(e)
}
}
}
// Used in integration tests
pub fn load_str(&self, src: &str) -> PolarResult<()> {
self.load(src, None)
}
pub fn remove_file(&self, filename: &str) -> Option<String> {
let mut kb = self.kb.write().unwrap();
kb.remove_file(filename)
}
/// Clear rules from the knowledge base
pub fn clear_rules(&self) {
let mut kb = self.kb.write().unwrap();
kb.clear_rules();
}
pub fn next_inline_query(&self, trace: bool) -> Option<Query> {
let term = { self.kb.write().unwrap().inline_queries.pop() };
term.map(|t| self.new_query_from_term(t, trace))
}
pub fn new_query(&self, src: &str, trace: bool) -> PolarResult<Query> {
let source = Source {
filename: None,
src: src.to_owned(),
};
let term = {
let mut kb = self.kb.write().unwrap();
let src_id = kb.new_id();
let term =
parser::parse_query(src_id, src).map_err(|e| e.set_context(Some(&source), None))?;
kb.sources.add_source(source, src_id);
term
};
Ok(self.new_query_from_term(term, trace))
}
pub fn new_query_from_term(&self, mut term: Term, trace: bool) -> Query {
{
let mut kb = self.kb.write().unwrap();
term = rewrite_term(term, &mut kb);
}
let query = Goal::Query { term: term.clone() };
let vm =
PolarVirtualMachine::new(self.kb.clone(), trace, vec![query], self.messages.clone());
Query::new(vm, term)
}
// @TODO: Direct load_rules endpoint.
pub fn get_external_id(&self) -> u64 {
self.kb.read().unwrap().new_id()
}
pub fn register_constant(&self, name: Symbol, value: Term) {
self.kb.write().unwrap().constant(name, value)
}
pub fn register_mro(&self, name: Symbol, mro: Vec<u64>) -> PolarResult<()> {
self.kb.write().unwrap().add_mro(name, mro)
}
pub fn next_message(&self) -> Option<Message> {
self.messages.next()
}
/// Load the Polar roles policy idempotently.
pub fn enable_roles(&self) -> PolarResult<()> {
let result = match self.load(ROLES_POLICY, Some("Built-in Polar Roles Policy".to_owned())) {
Err(error::PolarError {
kind: error::ErrorKind::Runtime(error::RuntimeError::FileLoading { .. }),
..
}) => Ok(()),
result => result,
};
// Push inline queries to validate config.
let src_id = self.kb.read().unwrap().new_id();
let term = parser::parse_query(src_id, VALIDATE_ROLES_CONFIG_RESOURCES)?;
self.kb.write().unwrap().inline_queries.push(term);
result
}
pub fn validate_roles_config(&self, results: Vec<Vec<ResultEvent>>) -> PolarResult<()> {
validate_roles_config(self.kb.read().unwrap().get_rules(), results)
}
pub fn build_filter_plan(
&self,
types: Types,
partial_results: PartialResults,
variable: &str,
class_tag: &str,
) -> PolarResult<FilterPlan> {
build_filter_plan(types, partial_results, variable, class_tag)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn can_load_and_query() {
let polar = Polar::new();
let _query = polar.new_query("1 = 1", false);
let _ = polar.load_str("f(_);");
}
#[test]
fn roles_policy_loads_idempotently() {
let polar = Polar::new();
assert!(polar.enable_roles().is_ok());
{
let kb = polar.kb.read().unwrap();
assert_eq!(kb.loaded_files.len(), 1);
assert_eq!(kb.loaded_content.len(), 1);
}
assert!(polar.enable_roles().is_ok());
{
let kb = polar.kb.read().unwrap();
assert_eq!(kb.loaded_files.len(), 1);
assert_eq!(kb.loaded_content.len(), 1);
}
}
#[test]
fn load_remove_files() {
let polar = Polar::new();
polar
.load("f(x) if x = 1;", Some("test.polar".to_string()))
.unwrap();
polar.remove_file("test.polar");
// loading works after removing
polar
.load("f(x) if x = 1;", Some("test.polar".to_string()))
.unwrap();
polar.remove_file("test.polar");
// load a broken file
polar
.load("f(x) if x", Some("test.polar".to_string()))
.unwrap_err();
// can still load files again
polar
.load("f(x) if x = 1;", Some("test.polar".to_string()))
.unwrap();
}
}
|
use crate::models::launch::LaunchID;
use serenity::builder::{CreateActionRow, CreateButton, CreateComponents};
use serenity::model::prelude::message_component::ButtonStyle;
pub struct RemindComponent<'a> {
launch_id: &'a LaunchID,
}
impl<'a> RemindComponent<'a> {
pub fn new(launch_id: &'a LaunchID) -> RemindComponent {
Self { launch_id }
}
fn button(&self) -> CreateButton {
let mut b = CreateButton::default();
b.custom_id(self.launch_id);
b.label("Remind Me");
b.style(ButtonStyle::Primary);
b
}
fn action_row(&self) -> CreateActionRow {
let mut ar = CreateActionRow::default();
ar.add_button(self.button());
ar
}
}
pub fn create_basic_components() -> CreateComponents {
CreateComponents::default()
}
pub fn create_launch_components(launch_id: &LaunchID) -> CreateComponents {
let mut c = create_basic_components();
let rc = RemindComponent::new(launch_id);
c.add_action_row(rc.action_row());
c
}
|
extern crate markdown;
extern crate serde_json;
#[macro_use]
extern crate tera;
use std::collections::HashMap;
use tera::{Context, Result, Value, to_value};
pub fn markdown_filter(value: Value, _: HashMap<String, Value>) -> Result<Value> {
let s = try_get_value!("upper", "value", String, value);
Ok(to_value(markdown::to_html(s.as_str()))?)
}
const LIPSUM: &'static str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut \
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco \
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in \
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat \
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
fn main() {
println!("24 days of Rust vol. 2 - tera");
let mut tera = compile_templates!("templates/**/*");
let mut ctx = Context::new();
ctx.add("title", &"hello world!");
ctx.add("content", &LIPSUM);
ctx.add(
"todos",
&vec!["buy milk", "walk the dog", "write about tera"],
);
let rendered = tera.render("index.html", &ctx).expect(
"Failed to render template",
);
println!("{}", rendered);
tera.register_filter("markdown", markdown_filter);
let mut ctx = Context::new();
ctx.add("content", &"**bold** and `beautiful`");
let rendered = tera.render("blog.html", &ctx).expect(
"Failed to render template",
);
println!("{}", rendered);
let mut config = HashMap::new();
config.insert("hostname", "127.0.0.1");
config.insert("user", "root");
config.insert("email", "NAME@example.com");
let mut ctx = Context::new();
ctx.add("config", &config);
let rendered = tera.render("config.ini", &ctx).expect(
"Failed to render template",
);
println!("{}", rendered);
}
|
use super::util::{is_name_char, take_char};
use super::value::value_expression;
use super::{input_to_str, input_to_string};
use nom::alphanumeric;
use nom::types::CompleteByteSlice as Input;
use sass::{SassString, StringPart};
use value::Quotes;
named!(pub sass_string<Input, SassString>,
map!(
many1!(alt_complete!(
string_part_interpolation |
map!(selector_string, StringPart::Raw))),
|p| SassString::new(p, Quotes::None)));
named!(pub sass_string_ext<Input, SassString>,
map!(
many1!(alt_complete!(
string_part_interpolation |
extended_part)),
|p| SassString::new(p, Quotes::None)));
named!(pub sass_string_dq<Input, SassString>,
map!(delimited!(tag!("\""),
many0!(alt_complete!(
simple_qstring_part |
string_part_interpolation |
map!(hash_no_interpolation,
|s| StringPart::Raw(s.to_string())) |
value!(StringPart::Raw("\"".to_string()),
tag!("\\\"")) |
value!(StringPart::Raw("'".to_string()),
tag!("'")) |
extra_escape)),
tag!("\"")),
|p| SassString::new(p, Quotes::Double)));
named!(pub sass_string_sq<Input, SassString>,
map!(delimited!(tag!("'"),
many0!(alt_complete!(
simple_qstring_part |
string_part_interpolation |
map!(hash_no_interpolation,
|s| StringPart::Raw(s.to_string())) |
value!(StringPart::Raw("'".to_string()),
tag!("\\'")) |
value!(StringPart::Raw("\"".to_string()),
tag!("\"")) |
extra_escape
)),
tag!("'")),
|p| SassString::new(p, Quotes::Single)));
named!(
string_part_interpolation<Input, StringPart>,
map!(
delimited!(tag!("#{"), value_expression, tag!("}")),
StringPart::Interpolation
)
);
named!(
simple_qstring_part<Input, StringPart>,
map!(map_res!(is_not!("\\#'\""), input_to_string), StringPart::Raw)
);
named!(
selector_string<Input, String>,
fold_many1!(
alt_complete!(
selector_plain_part
| selector_escaped_part
| hash_no_interpolation
),
String::new(),
|mut acc: String, item: &str| {
acc.push_str(item);
acc
}
)
);
named!(
selector_plain_part<Input, &str>,
map_res!(is_not!("\n\t >$\"'\\#+*/()[]{}:;,=!&@"), input_to_str)
);
named!(
selector_escaped_part<Input, &str>,
map_res!(
recognize!(preceded!(
tag!("\\"),
alt!(value!((), many_m_n!(1, 3, hexpair)) | value!((), take!(1)))
)),
input_to_str
)
);
named!(
hexpair<Input, Input>,
recognize!(do_parse!(
one_of!("0123456789ABCDEFabcdef")
>> one_of!("0123456789ABCDEFabcdef")
>> ()
))
);
named!(
hash_no_interpolation<Input, &str>,
map_res!(terminated!(tag!("#"), peek!(not!(tag!("{")))), input_to_str)
);
named!(
extra_escape<Input, StringPart>,
map!(
map_res!(
preceded!(
tag!("\\"),
alt!(
alphanumeric
| tag!(" ")
| tag!("'")
| tag!("\"")
| tag!("\\")
| tag!("#")
)
),
input_to_string
),
|s| StringPart::Raw(format!("\\{}", s))
)
);
named!(
pub extended_part<Input, StringPart>,
map!(
map_res!(
recognize!(pair!(
verify!(take_char, is_ext_str_start_char),
many0!(verify!(take_char, is_ext_str_char))
)),
input_to_string
),
StringPart::Raw
)
);
fn is_ext_str_start_char(c: char) -> bool {
is_name_char(c)
|| c == '*'
|| c == '+'
|| c == '.'
|| c == '/'
|| c == ':'
|| c == '='
|| c == '?'
|| c == '|'
}
fn is_ext_str_char(c: char) -> bool {
is_name_char(c)
|| c == '*'
|| c == '+'
|| c == ','
|| c == '.'
|| c == '/'
|| c == ':'
|| c == '='
|| c == '?'
|| c == '|'
}
|
use super::BodyId;
use crate::{
builtin_functions::BuiltinFunction,
hir,
id::CountableId,
impl_countable_id, impl_display_via_richir,
rich_ir::{ReferenceKey, RichIrBuilder, ToRichIr, TokenType},
};
use derive_more::{From, TryInto};
use enumset::EnumSet;
use itertools::Itertools;
use num_bigint::BigInt;
use rustc_hash::FxHashMap;
use std::fmt::{self, Debug, Display, Formatter};
use strum_macros::EnumIs;
// ID
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ConstantId(usize);
impl_countable_id!(ConstantId);
impl Debug for ConstantId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "%{}", self.0)
}
}
impl Display for ConstantId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "%{}", self.0)
}
}
impl ToRichIr for ConstantId {
fn build_rich_ir(&self, builder: &mut RichIrBuilder) {
let range = builder.push(self.to_string(), TokenType::Constant, EnumSet::empty());
builder.push_reference(*self, range);
}
}
// Constants
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Constants(Vec<Constant>);
impl Constants {
pub fn get(&self, id: ConstantId) -> &Constant {
&self.0[id.to_usize()]
}
pub fn push(&mut self, constant: impl Into<Constant>) -> ConstantId {
let id = ConstantId::from_usize(self.0.len());
self.0.push(constant.into());
id
}
pub fn ids_and_constants(&self) -> impl Iterator<Item = (ConstantId, &Constant)> {
self.0
.iter()
.enumerate()
.map(|(index, it)| (ConstantId(index), it))
}
}
impl ToRichIr for Constants {
fn build_rich_ir(&self, builder: &mut RichIrBuilder) {
builder.push_custom_multiline(self.ids_and_constants(), |builder, (id, constant)| {
let range = builder.push(id.to_string(), TokenType::Constant, EnumSet::empty());
builder.push_definition(*id, range);
builder.push(" = ", None, EnumSet::empty());
constant.build_rich_ir(builder);
})
}
}
// Constant
// TODO: `impl Hash for Constant`
#[derive(Clone, Debug, EnumIs, Eq, From, PartialEq, TryInto)]
pub enum Constant {
Int(BigInt),
Text(String),
Tag {
symbol: String,
value: Option<ConstantId>,
},
Builtin(BuiltinFunction),
List(Vec<ConstantId>),
Struct(FxHashMap<ConstantId, ConstantId>),
HirId(hir::Id),
Function(BodyId),
}
impl_display_via_richir!(Constant);
impl ToRichIr for Constant {
fn build_rich_ir(&self, builder: &mut RichIrBuilder) {
match self {
Constant::Int(int) => {
int.build_rich_ir(builder);
}
Constant::Text(text) => {
let range =
builder.push(format!(r#""{}""#, text), TokenType::Text, EnumSet::empty());
builder.push_reference(text.to_owned(), range);
}
Constant::Tag { symbol, value } => {
let range = builder.push(symbol, TokenType::Symbol, EnumSet::empty());
builder.push_reference(ReferenceKey::Symbol(symbol.to_owned()), range);
if let Some(value) = value {
builder.push(" ", None, EnumSet::empty());
value.build_rich_ir(builder);
}
}
Constant::Builtin(builtin) => {
builtin.build_rich_ir(builder);
}
Constant::List(items) => {
builder.push("(", None, EnumSet::empty());
builder.push_children(items, ", ");
if items.len() <= 1 {
builder.push(",", None, EnumSet::empty());
}
builder.push(")", None, EnumSet::empty());
}
Constant::Struct(fields) => {
builder.push("[", None, EnumSet::empty());
builder.push_children_custom(
fields.iter().collect_vec(),
|builder, (key, value)| {
key.build_rich_ir(builder);
builder.push(": ", None, EnumSet::empty());
value.build_rich_ir(builder);
},
", ",
);
builder.push("]", None, EnumSet::empty());
}
Constant::HirId(id) => {
let range = builder.push(id.to_string(), TokenType::Symbol, EnumSet::empty());
builder.push_reference(id.to_owned(), range);
}
Constant::Function(body_id) => {
builder.push("{ ", None, EnumSet::empty());
body_id.build_rich_ir(builder);
builder.push(" }", None, EnumSet::empty());
}
}
}
}
|
use lucet_runtime::{DlModule, Limits, MmapRegion, Region};
fn main() {
let module = DlModule::load("./wasm.out").expect("load failed");
let limits = Limits {
heap_memory_size: 1024 * 1024 * 64,
heap_address_space_size: 0x200000000,
stack_size: 128 * 1024,
globals_size: 4096,
};
let region = MmapRegion::create(1, &limits).expect("mmap region fail");
let mut inst = region.new_instance(module).expect("instance creation failed");
let retval = inst.run("add_one", &[5i32.into()]).expect("add one failed").unwrap_returned();
println!("{:?}", i32::from(retval));
}
|
mod enumerator;
mod mem_access;
mod open_options;
mod process;
mod record;
use crate::sys::process as imp;
pub use enumerator::ProcessEnumerator;
pub use mem_access::MemAccess;
pub use open_options::ProcessOpenOptions;
pub use process::Process;
pub use record::ProcessRecord;
#[derive(Clone, Copy)]
pub struct Pid {
inner: imp::Pid,
}
impl From<imp::Pid> for Pid {
fn from(inner: imp::Pid) -> Self {
Pid { inner }
}
}
impl From<Pid> for imp::Pid {
fn from(outer: Pid) -> Self {
outer.inner
}
}
|
// ignore-compare-mode-nll
// revisions: base nll
// [nll]compile-flags: -Zborrowck=mir
fn bar<F>(blk: F) where F: FnOnce() + 'static {
}
fn foo(x: &()) {
bar(|| {
//[base]~^ ERROR `x` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement [E0759]
//[nll]~^^ ERROR borrowed data escapes
//[nll]~| ERROR closure may outlive
let _ = x;
})
}
fn main() {
}
|
extern crate core;
fn map_symbol_to_value(symbol: &str) -> u64 {
match symbol {
"A" | "X" => 0,
"B" | "Y" => 1,
"C" | "Z" => 2,
_ => panic!("unexpected symbol"),
}
}
fn calculate_score(other: u64, own: u64) -> u64 {
let win_score = (other as i64 - own as i64) % 3;
let win_score = match win_score {
1 | -2 => 0,
2 | -1 => 6,
0 => 3,
_ => panic!("unexpected score: {}", win_score),
};
win_score + own + 1
}
fn map_goal_to_num(goal: &str, other_hand: u64) -> u64 {
// stupid +3 offset because negative values have negative remainder
match goal {
"X" => (other_hand + 2) % 3,
"Y" => other_hand,
"Z" => (other_hand + 4) % 3,
_ => panic!("unexpected goal: {}", goal),
}
}
fn part1(input: &str) -> u64 {
input
.trim()
.split('\n')
.map(|line| {
let pairs: Vec<u64> = line.split(' ').map(map_symbol_to_value).take(2).collect();
calculate_score(pairs[0], pairs[1])
})
.sum()
}
fn part2(input: &str) -> u64 {
input
.trim()
.split('\n')
.map(|line| {
let pairs: Vec<&str> = line.split(' ').take(2).collect();
let other = map_symbol_to_value(pairs[0]);
calculate_score(other, map_goal_to_num(pairs[1], other))
})
.sum()
}
fn main() {
let example = include_str!(r"../../resources/day2-example.txt");
let input = include_str!(r"../../resources/day2-input.txt");
rustaoc2022::run_matrix(part1, part2, example, input);
}
#[cfg(test)]
mod day2 {
use crate::{part1, part2};
#[test]
fn test_example() {
let input = include_str!(r"../../resources/day2-example.txt");
assert_eq!(15, part1(input));
assert_eq!(12, part2(input));
}
#[test]
fn test_input() {
let input = include_str!(r"../../resources/day2-input.txt");
assert_eq!(12276, part1(input));
assert_eq!(9975, part2(input));
}
}
|
pub use crate::az_core::*;
pub use crate::az_return_codes::AzReturnCode;
use azsys;
use std::slice;
use std::str;
pub struct HubClientBuilder<'a> {
host_name: Option<&'a str>,
device_id: Option<&'a str>,
client_options: Option<HubClientOptions>,
}
pub struct HubClient {
inner: azsys::az_iot_hub_client,
}
impl<'a> HubClientBuilder<'a> {
pub fn new() -> HubClientBuilder<'static> {
HubClientBuilder {
host_name: Option::None,
device_id: Option::None,
client_options: Option::None,
}
}
pub fn host_name(&mut self, host_name: &'a str) -> &mut HubClientBuilder<'a> {
self.host_name = Option::Some(&host_name);
self
}
pub fn device_id(&mut self, device_id: &'a str) -> &mut HubClientBuilder<'a> {
self.device_id = Option::Some(device_id);
self
}
pub fn client_options(
&mut self,
client_options: HubClientOptions,
) -> &mut HubClientBuilder<'a> {
self.client_options = Option::Some(client_options);
self
}
pub fn finalize(&mut self) -> Result<HubClient, AzReturnCode> {
if None == self.host_name || None == self.device_id {
panic!("Missing required parameters");
}
let options_work: *const azsys::az_iot_hub_client_options;
match &self.client_options {
Some(o) => options_work = &o.inner,
None => options_work = std::ptr::null(),
}
let mut result = HubClient::new_empty();
let rc = unsafe {
azsys::az_iot_hub_client_init(
&mut result.inner,
get_span_from_str(&self.host_name.as_ref().unwrap()),
get_span_from_str(&self.device_id.as_ref().unwrap()),
options_work,
)
};
if rc != azsys::az_result_core_AZ_OK {
Err(AzReturnCode::from_i32(rc))
} else {
Ok(result)
}
}
}
pub enum TopicType {
C2D(ClientC2DRequest),
Method(ClientMethodRequest),
Unknown,
}
fn capacity_increase_policy(current: usize) -> usize {
let result = current + (current / 50);
result
}
impl HubClient {
pub const DEFAULT_MQTT_CONNECT_PORT: u32 = azsys::AZ_IOT_DEFAULT_MQTT_CONNECT_PORT as u32;
pub fn new(
host_name: &str,
device_id: &str,
options: Option<HubClientOptions>,
) -> Result<HubClient, AzReturnCode> {
let options_work: *const azsys::az_iot_hub_client_options;
match options {
Some(o) => options_work = &o.inner,
None => options_work = std::ptr::null(),
}
let mut client: HubClient = HubClient::new_empty();
let rc = unsafe {
azsys::az_iot_hub_client_init(
&mut client.inner,
get_span_from_str(host_name),
get_span_from_str(device_id),
options_work,
)
};
if rc != azsys::az_result_core_AZ_OK {
Err(AzReturnCode::from_i32(rc))
} else {
Ok(client)
}
}
pub fn new_empty() -> HubClient {
HubClient {
inner: azsys::az_iot_hub_client {
_internal: azsys::az_iot_hub_client__bindgen_ty_1 {
iot_hub_hostname: get_empty_span(),
device_id: get_empty_span(),
options: HubClientOptions::default_new().inner,
},
},
}
}
pub fn get_client_id(&self) -> Result<String, AzReturnCode> {
let mut capacity: usize = 100;
let mut result = String::with_capacity(capacity);
loop {
let rc = self.ll_get_client_id(&mut result);
match rc {
AzReturnCode::AzResultCoreErrorNotEnoughSpace => {
capacity = capacity_increase_policy(capacity);
result = String::with_capacity(capacity);
continue;
}
AzReturnCode::AzResultCoreOk => {
result.shrink_to_fit();
return Ok(result);
}
_ => {
return Err(rc);
}
}
}
}
pub fn ll_get_client_id(&self, result: &mut String) -> AzReturnCode {
let mut len: u64 = 0;
let len_ptr: *mut u64 = &mut len;
let rc = unsafe {
azsys::az_iot_hub_client_get_client_id(
&self.inner,
result.as_mut_vec().as_mut_ptr() as *mut i8,
result.capacity() as u64,
len_ptr,
)
};
if rc == azsys::az_result_core_AZ_OK {
unsafe { result.as_mut_vec().set_len(len as usize) };
}
AzReturnCode::from_i32(rc)
}
pub fn get_user_name(&self) -> Result<String, AzReturnCode> {
let mut capacity: usize = 100;
let mut result = String::with_capacity(capacity);
loop {
let rc = self.ll_get_user_name(&mut result);
match rc {
AzReturnCode::AzResultCoreErrorNotEnoughSpace => {
capacity = capacity_increase_policy(capacity);
result = String::with_capacity(capacity);
continue;
}
AzReturnCode::AzResultCoreOk => {
result.shrink_to_fit();
return Ok(result);
}
_ => {
return Err(rc);
}
}
}
}
pub fn ll_get_user_name(&self, result: &mut String) -> AzReturnCode {
let mut len: u64 = 0;
let len_ptr: *mut u64 = &mut len;
let rc = unsafe {
azsys::az_iot_hub_client_get_user_name(
&self.inner,
result.as_mut_vec().as_mut_ptr() as *mut i8,
result.capacity() as u64,
len_ptr,
)
};
if rc == azsys::az_result_core_AZ_OK {
unsafe { result.as_mut_vec().set_len(len as usize) };
}
AzReturnCode::from_i32(rc)
}
pub fn get_c2d_subscribe_topic() -> &'static str {
static AZ_IOT_HUB_CLIENT_C2D_SUBSCRIBE_TOPIC: &str = "devices/+/messages/devicebound/#";
AZ_IOT_HUB_CLIENT_C2D_SUBSCRIBE_TOPIC
}
pub fn c2d_parse_received_topic(&self, topic: &str) -> Result<ClientC2DRequest, AzReturnCode> {
let mut result: ClientC2DRequest = ClientC2DRequest::new_empty();
let rc = unsafe {
azsys::az_iot_hub_client_c2d_parse_received_topic(
&self.inner,
get_span_from_str(topic),
&mut result.inner,
)
};
if rc != azsys::az_result_core_AZ_OK {
Err(AzReturnCode::from_i32(rc))
} else {
Ok(result)
}
}
pub fn get_method_subscribe_topic() -> &'static str {
static AZ_IOT_HUB_CLIENT_METHODS_SUBSCRIBE_TOPIC: &str = "$iothub/methods/POST/#";
AZ_IOT_HUB_CLIENT_METHODS_SUBSCRIBE_TOPIC
}
pub fn methods_parse_received_topic(
&self,
topic: &str,
) -> Result<ClientMethodRequest, AzReturnCode> {
let mut result: ClientMethodRequest = ClientMethodRequest::new_empty();
let rc = unsafe {
azsys::az_iot_hub_client_methods_parse_received_topic(
&self.inner,
get_span_from_str(topic),
&mut result.inner,
)
};
if rc != azsys::az_result_core_AZ_OK {
Err(AzReturnCode::from_i32(rc))
} else {
Ok(result)
}
}
pub fn methods_response_get_publish_topic(&self, request_id: &str, status: u16) -> Result<String, AzReturnCode> {
let mut capacity: usize = 100;
let mut result = String::with_capacity(capacity);
loop {
let rc = self.ll_methods_response_get_publish_topic(&request_id, status, &mut result);
match rc {
AzReturnCode::AzResultCoreErrorNotEnoughSpace => {
capacity = capacity_increase_policy(capacity);
result = String::with_capacity(capacity);
continue;
}
AzReturnCode::AzResultCoreOk => {
result.shrink_to_fit();
return Ok(result);
}
_ => {
return Err(rc);
}
}
}
}
pub fn ll_methods_response_get_publish_topic(&self, request_id: &str, status: u16, result: &mut String) -> AzReturnCode {
let request_id_span = get_span_from_str(request_id);
let mut len: u64 = 0;
let len_ptr: *mut u64 = &mut len;
let rc = unsafe { azsys::az_iot_hub_client_methods_response_get_publish_topic(
&self.inner,
request_id_span,
status,
result.as_mut_vec().as_mut_ptr() as *mut i8,
result.capacity() as u64,
len_ptr,
) };
if rc == azsys::az_result_core_AZ_OK {
unsafe { result.as_mut_vec().set_len(len as usize) };
}
AzReturnCode::from_i32(rc)
}
pub fn get_twin_respnse_subscribe_topic() -> &'static str {
static AZ_IOT_HUB_CLIENT_TWIN_RESPONSE_SUBSCRIBE_TOPIC: &str = "$iothub/twin/res/#";
AZ_IOT_HUB_CLIENT_TWIN_RESPONSE_SUBSCRIBE_TOPIC
}
pub fn get_twin_patch_subscribe_topic() -> &'static str {
static AZ_IOT_HUB_CLIENT_TWIN_PATCH_SUBSCRIBE_TOPIC: &str =
"$iothub/twin/PATCH/properties/desired/#";
AZ_IOT_HUB_CLIENT_TWIN_PATCH_SUBSCRIBE_TOPIC
}
pub fn get_topic_type(&self, topic: &str) -> Result<TopicType, AzReturnCode> {
match self.c2d_parse_received_topic(topic) {
Ok(val) => { return Ok(TopicType::C2D(val)); },
Err(rc) => {
if rc != AzReturnCode::AzResultIoTErrorTopicNoMatch {
return Err(rc);
}
},
}
match self.methods_parse_received_topic(topic) {
Ok(val) => { return Ok(TopicType::Method(val)); },
Err(rc) => {
if rc != AzReturnCode::AzResultIoTErrorTopicNoMatch {
return Err(rc);
}
},
}
Ok(TopicType::Unknown)
}
pub fn get_telemetry_publish_topic(
&self,
message_properties: Option<MessageProperties>,
) -> Result<String, AzReturnCode> {
let mut capacity: usize = 100;
let mut result = String::with_capacity(capacity);
loop {
let rc = self.ll_get_telemetry_publish_topic(&message_properties, &mut result);
match rc {
AzReturnCode::AzResultCoreErrorNotEnoughSpace => {
capacity = capacity_increase_policy(capacity);
result = String::with_capacity(capacity);
continue;
}
AzReturnCode::AzResultCoreOk => {
result.shrink_to_fit();
return Ok(result);
}
_ => {
return Err(rc);
}
}
}
}
pub fn ll_get_telemetry_publish_topic(
&self,
message_properties: &Option<MessageProperties>,
result: &mut String,
) -> AzReturnCode {
let mut len: u64 = 0;
let len_ptr: *mut u64 = &mut len;
let m_prop_work: *const azsys::az_iot_message_properties = match message_properties {
Some(m) => &m.inner,
None => std::ptr::null(),
};
let rc = unsafe {
azsys::az_iot_hub_client_telemetry_get_publish_topic(
&self.inner,
m_prop_work,
result.as_mut_vec().as_mut_ptr() as *mut i8,
result.capacity() as u64,
len_ptr,
)
};
if rc == azsys::az_result_core_AZ_OK {
unsafe { result.as_mut_vec().set_len(len as usize) };
}
AzReturnCode::from_i32(rc)
}
pub fn get_sas_signature(&self, ttl: u64) -> Result<Vec<u8>, AzReturnCode> {
let mut capacity: usize = 200;
let mut result: Vec<u8> = Vec::with_capacity(capacity);
loop {
let rc = self.ll_get_sas_signature(ttl, &mut result);
match rc {
AzReturnCode::AzResultCoreErrorNotEnoughSpace => {
capacity = capacity_increase_policy(capacity);
result = Vec::with_capacity(capacity);
continue;
}
AzReturnCode::AzResultCoreOk => {
result.shrink_to_fit();
return Ok(result);
}
_ => {
return Err(rc);
}
}
}
}
pub fn ll_get_sas_signature(&self, ttl: u64, result: &mut Vec<u8>) -> AzReturnCode {
let result_span = get_span_from_vector(&result);
let mut work = get_empty_span();
let rc = unsafe {
azsys::az_iot_hub_client_sas_get_signature(&self.inner, ttl, result_span, &mut work)
};
if rc == azsys::az_result_core_AZ_OK {
unsafe { result.set_len(get_span_size(&work) as usize) };
}
AzReturnCode::from_i32(rc)
}
pub fn get_sas_password(&self, ttl: u64, sas: &str) -> Result<String, AzReturnCode> {
let mut capacity: usize = 300;
let mut result = String::with_capacity(capacity);
loop {
let rc = self.ll_get_sas_password(ttl, sas, &mut result);
match rc {
AzReturnCode::AzResultCoreErrorNotEnoughSpace => {
capacity = capacity_increase_policy(capacity);
result = String::with_capacity(capacity);
continue;
}
AzReturnCode::AzResultCoreOk => {
result.shrink_to_fit();
return Ok(result);
}
_ => {
return Err(rc);
}
}
}
}
pub fn ll_get_sas_password(&self, ttl: u64, sas: &str, result: &mut String) -> AzReturnCode {
// TODO: Add key_name option
let mut len: u64 = 0;
let len_ptr: *mut u64 = &mut len;
let rc = unsafe {
azsys::az_iot_hub_client_sas_get_password(
&self.inner,
ttl,
get_span_from_str(sas),
get_empty_span(),
result.as_mut_ptr() as *mut i8,
result.capacity() as u64,
len_ptr,
)
};
if rc == azsys::az_result_core_AZ_OK {
unsafe { result.as_mut_vec().set_len(len as usize) };
}
AzReturnCode::from_i32(rc)
}
pub fn calculate_retry_delay(
operation_msec: i32,
attempt: i16,
min_retry_delay_msec: i32,
max_retry_delay_msec: i32,
jitter: i32,
) -> i32 {
unsafe { azsys::az_iot_calculate_retry_delay(operation_msec, attempt, min_retry_delay_msec, max_retry_delay_msec, jitter) }
}
}
pub struct HubClientOptions {
inner: azsys::az_iot_hub_client_options,
}
impl HubClientOptions {
pub fn default_new() -> HubClientOptions {
HubClientOptions {
inner: unsafe { azsys::az_iot_hub_client_options_default() },
}
}
}
pub struct MessagePropertiesBuilder {
props: Vec<u8>,
}
impl MessagePropertiesBuilder {
pub fn new() -> MessagePropertiesBuilder {
MessagePropertiesBuilder::with_capacity(200)
}
pub fn with_capacity(capacity: usize) -> MessagePropertiesBuilder {
MessagePropertiesBuilder {
props: Vec::with_capacity(capacity),
}
}
pub fn add(mut self, keyword: &str, value: &str) -> MessagePropertiesBuilder {
if self.props.len() != 0 {
self.props.push('&' as u8);
}
self.props.append(&mut keyword.as_bytes().to_vec().as_mut_slice().to_vec());
self.props.push('=' as u8);
self.props.append(&mut value.as_bytes().to_vec().as_mut_slice().to_vec());
self
}
pub fn finialize(self) -> Result<MessageProperties, AzReturnCode> {
let len = self.props.len() as i32;
MessageProperties::new(self.props, len)
}
}
pub struct MessageProperties {
props: Vec<u8>,
inner: azsys::az_iot_message_properties,
}
impl MessageProperties {
pub fn new(buffer: Vec<u8>, written_length: i32) -> Result<MessageProperties, AzReturnCode> {
let mut message_properties = MessageProperties::new_empty(buffer);
let rc = unsafe {
azsys::az_iot_message_properties_init(
&mut message_properties.inner,
message_properties.get_props_span(),
written_length,
)
};
if rc != azsys::az_result_core_AZ_OK {
Err(AzReturnCode::from_i32(rc))
} else {
Ok(message_properties)
}
}
pub fn new_empty(buffer: Vec<u8>) -> MessageProperties {
let message_properties: MessageProperties = MessageProperties {
props: buffer,
inner: azsys::az_iot_message_properties {
_internal: azsys::az_iot_message_properties__bindgen_ty_1 {
properties_buffer: get_empty_span(),
properties_written: 0,
current_property_index: 0,
},
},
};
message_properties
}
pub fn append(&mut self, k: &str, v: &str) -> Result<&mut MessageProperties, AzReturnCode> {
let rc = unsafe {
azsys::az_iot_message_properties_append(
&mut self.inner,
get_span_from_str(k),
get_span_from_str(v),
)
};
if rc != azsys::az_result_core_AZ_OK {
Err(AzReturnCode::from_i32(rc))
} else {
Ok(self)
}
}
pub fn find(&mut self, k: &str) -> Result<&str, AzReturnCode> {
let mut out = get_empty_span();
let rc = unsafe {
azsys::az_iot_message_properties_find(&mut self.inner, get_span_from_str(k), &mut out)
};
if rc != azsys::az_result_core_AZ_OK {
Err(AzReturnCode::from_i32(rc))
} else {
let slice =
unsafe { slice::from_raw_parts(out._internal.ptr, out._internal.size as usize) };
// let r = unsafe {
// let slice = slice::from_raw_parts(out._internal.ptr, out._internal.size as usize);
// str::from_utf8(slice)
// };
Ok(str::from_utf8(slice).expect("Value is not in UTF8"))
}
}
pub fn into_array(&mut self) -> Result<Vec<(&str, &str)>, AzReturnCode> {
let mut out: Vec<(&str, &str)> = Vec::new();
let mut k = get_empty_span();
let mut v = get_empty_span();
loop {
let rc = unsafe {
azsys::az_iot_message_properties_next(&mut self.inner, &mut k, &mut v)
as ::std::os::raw::c_int
};
if rc == azsys::az_result_core_AZ_OK {
let slicek =
unsafe { slice::from_raw_parts(k._internal.ptr, k._internal.size as usize) };
let slicev =
unsafe { slice::from_raw_parts(v._internal.ptr, v._internal.size as usize) };
let ks = str::from_utf8(slicek).expect("keyword is not in UTF8");
let vs = str::from_utf8(slicev).expect("Value is not in UTF8");
out.push((ks, vs));
} else if rc == azsys::az_result_iot_AZ_ERROR_IOT_END_OF_PROPERTIES {
break;
} else {
return Err(AzReturnCode::from_i32(rc));
}
}
Ok(out)
}
fn get_props_span(&self) -> azsys::az_span {
get_span_from_vector(&self.props)
}
pub(crate) fn get_inner(&self) -> azsys::az_iot_message_properties {
self.inner
}
}
pub struct ClientC2DRequest {
message_props: MessageProperties,
inner: azsys::az_iot_hub_client_c2d_request,
}
impl ClientC2DRequest {
pub fn new_empty() -> ClientC2DRequest {
let null_vec: Vec<u8> = Vec::new();
ClientC2DRequest {
message_props: MessageProperties::new(null_vec, 0).unwrap(),
inner: azsys::az_iot_hub_client_c2d_request {
properties: azsys::az_iot_message_properties {
_internal: azsys::az_iot_message_properties__bindgen_ty_1 {
properties_buffer: get_empty_span(),
properties_written: 0,
current_property_index: 0,
},
},
},
}
}
pub fn from_message_properties(props: MessageProperties) -> ClientC2DRequest {
let mut result = ClientC2DRequest {
message_props: props,
inner: azsys::az_iot_hub_client_c2d_request {
properties: azsys::az_iot_message_properties {
_internal: azsys::az_iot_message_properties__bindgen_ty_1 {
properties_buffer: get_empty_span(),
properties_written: 0,
current_property_index: 0,
},
},
}
};
result.inner.properties = result.message_props.get_inner();
result
}
pub fn get_message_properties(&self) -> MessageProperties {
MessageProperties {
props: Vec::new(),
inner: azsys::az_iot_message_properties {
_internal: azsys::az_iot_message_properties__bindgen_ty_1 {
properties_buffer: self.inner.properties._internal.properties_buffer,
properties_written: self.inner.properties._internal.properties_written,
current_property_index: self.inner.properties._internal.current_property_index,
},
},
}
}
}
pub struct ClientMethodRequest {
inner: azsys::az_iot_hub_client_method_request,
}
impl ClientMethodRequest {
pub fn new_empty() -> ClientMethodRequest {
ClientMethodRequest {
inner: azsys::az_iot_hub_client_method_request {
request_id: get_empty_span(),
name: get_empty_span(),
},
}
}
pub fn get_request_id(&self) -> &str {
let slice = unsafe {
slice::from_raw_parts(
get_span_ptr(&self.inner.request_id),
get_span_size(&self.inner.request_id) as usize,
)
};
str::from_utf8(&slice).expect("Request Id contains unprintable characters")
}
pub fn get_name(&self) -> &str {
let slice = unsafe {
slice::from_raw_parts(
get_span_ptr(&self.inner.name),
get_span_size(&self.inner.name) as usize,
)
};
str::from_utf8(&slice).expect("Request Id contains unprintable characters")
}
}
#[cfg(test)]
mod tests {
use super::*;
static HOST_NAME: &str = "testhost.azure-devices.net";
static DEVICE_ID: &str = "test1";
#[test]
fn client_init() {
let client = HubClient::new(HOST_NAME, DEVICE_ID, Option::None).unwrap();
let test: String = unsafe {
String::from_raw_parts(
client.inner._internal.iot_hub_hostname._internal.ptr,
client.inner._internal.iot_hub_hostname._internal.size as usize,
client.inner._internal.iot_hub_hostname._internal.size as usize,
)
};
assert_eq!(HOST_NAME, test);
let _test = std::mem::ManuallyDrop::new(test);
let test: String = unsafe {
String::from_raw_parts(
client.inner._internal.device_id._internal.ptr,
client.inner._internal.device_id._internal.size as usize,
client.inner._internal.device_id._internal.size as usize,
)
};
assert_eq!(DEVICE_ID, test);
let _test = std::mem::ManuallyDrop::new(test);
}
#[test]
fn client_builder() {
let client = HubClientBuilder::new()
.host_name(&HOST_NAME)
.device_id(&DEVICE_ID)
.finalize()
.unwrap();
let test: String = unsafe {
String::from_raw_parts(
client.inner._internal.iot_hub_hostname._internal.ptr,
client.inner._internal.iot_hub_hostname._internal.size as usize,
client.inner._internal.iot_hub_hostname._internal.size as usize,
)
};
assert_eq!(HOST_NAME, test);
let _test = std::mem::ManuallyDrop::new(test);
let test: String = unsafe {
String::from_raw_parts(
client.inner._internal.device_id._internal.ptr,
client.inner._internal.device_id._internal.size as usize,
client.inner._internal.device_id._internal.size as usize,
)
};
assert_eq!(DEVICE_ID, test);
let _test = std::mem::ManuallyDrop::new(test);
}
#[test]
fn client_get_client_id() {
let client = HubClient::new(HOST_NAME, DEVICE_ID, Option::None).unwrap();
let output = client.get_client_id().unwrap();
assert_eq!(DEVICE_ID, output);
assert_eq!(output.len(), output.capacity());
}
#[test]
fn client_ll_get_client_id() {
let client = HubClient::new(HOST_NAME, DEVICE_ID, Option::None).unwrap();
let mut out: String = String::with_capacity(200);
let rc = client.ll_get_client_id(&mut out);
assert_eq!(rc, AzReturnCode::AzResultCoreOk);
assert_eq!(DEVICE_ID, out);
}
#[test]
fn client_ll_get_client_id_fail() {
let client = HubClient::new(HOST_NAME, DEVICE_ID, Option::None).unwrap();
let mut out: String = String::with_capacity(2);
let rc = client.ll_get_client_id(&mut out);
assert_eq!(rc, AzReturnCode::AzResultCoreErrorNotEnoughSpace);
}
#[test]
fn client_get_user_name() {
let client = HubClient::new(HOST_NAME, DEVICE_ID, Option::None).unwrap();
let user_name = format!("{}/{}/?api-version=2020-09-30&DeviceClientType=c%2F1.1.0-beta.2", HOST_NAME, DEVICE_ID);
assert_eq!(user_name, client.get_user_name().unwrap());
}
#[test]
fn client_ll_get_user_name() {
let client = HubClient::new(HOST_NAME, DEVICE_ID, Option::None).unwrap();
let user_name = format!("{}/{}/?api-version=2020-09-30&DeviceClientType=c%2F1.1.0-beta.2", HOST_NAME, DEVICE_ID);
let mut out: String = String::with_capacity(200);
let rc = client.ll_get_user_name(&mut out);
assert_eq!(rc, AzReturnCode::AzResultCoreOk);
assert_eq!(user_name, out);
}
#[test]
fn client_get_telemetry_publish_topic() {
let client = HubClient::new(HOST_NAME, DEVICE_ID, Option::None).unwrap();
let topic = "devices/".to_string() + DEVICE_ID + "/messages/events/";
assert_eq!(
topic,
client.get_telemetry_publish_topic(Option::None).unwrap()
);
}
#[test]
fn client_ll_get_telemetry_publish_topic() {
let client = HubClient::new(HOST_NAME, DEVICE_ID, Option::None).unwrap();
let topic = "devices/".to_string() + DEVICE_ID + "/messages/events/";
let mut out = String::with_capacity(200);
let rc = client.ll_get_telemetry_publish_topic(&Option::None, &mut out);
assert_eq!(rc, AzReturnCode::AzResultCoreOk);
assert_eq!(topic, out);
}
#[test]
fn client_get_sas_signature() {
let client = HubClient::new(HOST_NAME, DEVICE_ID, Option::None).unwrap();
let signature = HOST_NAME.to_string() + "%2Fdevices%2F" + DEVICE_ID + "\n100"; // &DeviceClientType=c%2F1.0.0";
assert_eq!(
String::from_utf8_lossy(&client.get_sas_signature(100).unwrap()),
signature
);
}
#[test]
fn client_ll_get_sas_signature() {
let client = HubClient::new(HOST_NAME, DEVICE_ID, Option::None).unwrap();
let signature = HOST_NAME.to_string() + "%2Fdevices%2F" + DEVICE_ID + "\n100"; // &DeviceClientType=c%2F1.0.0";
let mut out: Vec<u8> = Vec::with_capacity(200);
let rc = client.ll_get_sas_signature(100, &mut out);
assert_eq!(rc, AzReturnCode::AzResultCoreOk);
assert_eq!(String::from_utf8_lossy(&out), signature);
}
#[test]
fn client_get_sas_password() {
let client = HubClient::new(HOST_NAME, DEVICE_ID, Option::None).unwrap();
let sas = "NotReallyASASToken";
let password = "SharedAccessSignature sr=".to_string()
+ HOST_NAME
+ "%2Fdevices%2F"
+ DEVICE_ID
+ "&sig="
+ sas
+ "&se=100";
assert_eq!(&password, &client.get_sas_password(100, sas).unwrap());
}
#[test]
fn client_ll_get_sas_password() {
let client = HubClient::new(HOST_NAME, DEVICE_ID, Option::None).unwrap();
let sas = "NotReallyASASToken";
let password = "SharedAccessSignature sr=".to_string()
+ HOST_NAME
+ "%2Fdevices%2F"
+ DEVICE_ID
+ "&sig="
+ sas
+ "&se=100";
let mut out = String::with_capacity(200);
let rc = client.ll_get_sas_password(100, sas, &mut out);
assert_eq!(rc, AzReturnCode::AzResultCoreOk);
assert_eq!(out, password);
}
#[test]
fn client_get_c2d_subscribe_topic() {
assert_eq!(
HubClient::get_c2d_subscribe_topic(),
"devices/+/messages/devicebound/#"
);
}
#[test]
fn client_get_method_subscribe_topic() {
assert_eq!(
HubClient::get_method_subscribe_topic(),
"$iothub/methods/POST/#"
);
}
#[test]
fn test_message_properties() {
let buf: Vec<u8> = Vec::with_capacity(200);
let mut mp = MessageProperties::new(buf, 0).unwrap();
mp.append("LastName", "Thomas").unwrap();
mp.append("MiddleName", "Richard").unwrap();
mp.append("FirstName", "Harold").unwrap();
assert_eq!(Ok("Richard"), mp.find("MiddleName"));
assert_eq!(Ok("Harold"), mp.find("FirstName"));
assert_eq!(Ok("Thomas"), mp.find("LastName"));
// Pending bug fix in azure-sdk-for-c
let out = mp.into_array().unwrap();
assert_eq!(out.len(), 3);
for val in out {
match val.0 {
"LastName" => assert_eq!(val.1, "Thomas"),
"MiddleName" => assert_eq!(val.1, "Richard"),
"FirstName" => assert_eq!(val.1, "Harold"),
_ => assert!(false),
}
}
}
#[test]
fn test_message_properties_builder() {
let mut mp = MessagePropertiesBuilder::new()
.add("LastName", "Thomas")
.add("MiddleName", "Richard")
.add("FirstName", "Harold")
.finialize().unwrap();
assert_eq!(Ok("Richard"), mp.find("MiddleName"));
assert_eq!(Ok("Harold"), mp.find("FirstName"));
assert_eq!(Ok("Thomas"), mp.find("LastName"));
// Pending bug fix in azure-sdk-for-c
let out = mp.into_array().unwrap();
assert_eq!(out.len(), 3);
for val in out {
match val.0 {
"LastName" => assert_eq!(val.1, "Thomas"),
"MiddleName" => assert_eq!(val.1, "Richard"),
"FirstName" => assert_eq!(val.1, "Harold"),
_ => assert!(false),
}
}
}
#[test]
fn test_c2d_request() {
let mp = MessagePropertiesBuilder::new()
.add("LastName", "Thomas")
.add("MiddleName", "Richard")
.add("FirstName", "Harold")
.finialize().unwrap();
let req = ClientC2DRequest::from_message_properties(mp);
let mut mp2 = req.get_message_properties();
assert_eq!(Ok("Richard"), mp2.find("MiddleName"));
assert_eq!(Ok("Harold"), mp2.find("FirstName"));
assert_eq!(Ok("Thomas"), mp2.find("LastName"));
}
}
|
#[macro_use]
extern crate log;
mod support;
use self::support::*;
#[test]
fn outbound_asks_controller_api() {
let _ = env_logger::init();
let srv = server::new().route("/", "hello").route("/bye", "bye").run();
let ctrl = controller::new()
.destination("test.conduit.local", srv.addr)
.run();
let proxy = proxy::new().controller(ctrl).outbound(srv).run();
let client = client::new(proxy.outbound, "test.conduit.local");
assert_eq!(client.get("/"), "hello");
assert_eq!(client.get("/bye"), "bye");
}
#[test]
fn outbound_reconnects_if_controller_stream_ends() {
let _ = env_logger::init();
let srv = server::new().route("/recon", "nect").run();
let ctrl = controller::new()
.destination_close("test.conduit.local")
.destination("test.conduit.local", srv.addr)
.run();
let proxy = proxy::new().controller(ctrl).outbound(srv).run();
let client = client::new(proxy.outbound, "test.conduit.local");
assert_eq!(client.get("/recon"), "nect");
}
#[test]
#[ignore]
fn outbound_times_out() {
// Currently, the outbound router will wait forever until discovery tells
// it where to send the request. It should probably time out eventually.
}
|
use std::ops::Deref;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use crate::node::{NetworkGraph, RoutingPeerManager};
use crate::persist::SenseiPersister;
use lightning_rapid_gossip_sync::RapidGossipSync;
use super::router::AnyScorer;
const PING_TIMER: u64 = 10;
/// Prune the network graph of stale entries hourly.
const NETWORK_PRUNE_TIMER: u64 = 60 * 60;
const FIRST_NETWORK_PRUNE_TIMER: u64 = 60;
const SCORER_PERSIST_TIMER: u64 = 30;
const RAPID_GOSSIP_SYNC_TIMER: u64 = 60 * 60;
const FIRST_RAPID_GOSSIP_SYNC_TIMER: u64 = 0;
pub struct BackgroundProcessor {
peer_manager: Option<Arc<RoutingPeerManager>>,
scorer: Arc<Mutex<AnyScorer>>,
network_graph: Arc<NetworkGraph>,
persister: Arc<SenseiPersister>,
stop_signal: Arc<AtomicBool>,
rapid_gossip_sync_server_host: Option<String>,
}
impl BackgroundProcessor {
pub fn new(
peer_manager: Option<Arc<RoutingPeerManager>>,
scorer: Arc<Mutex<AnyScorer>>,
network_graph: Arc<NetworkGraph>,
persister: Arc<SenseiPersister>,
stop_signal: Arc<AtomicBool>,
rapid_gossip_sync_server_host: Option<String>,
) -> Self {
Self {
peer_manager,
scorer,
network_graph,
persister,
stop_signal,
rapid_gossip_sync_server_host,
}
}
pub async fn process(&self) {
let mut last_prune_call = Instant::now();
let mut last_scorer_persist_call = Instant::now();
let mut last_ping_call = Instant::now();
let mut last_rgs_sync_call = Instant::now();
let mut have_pruned = false;
let mut have_rapid_gossip_synced = false;
let mut interval = tokio::time::interval(Duration::from_millis(50));
loop {
interval.tick().await;
if let Some(peer_manager) = &self.peer_manager {
if last_ping_call.elapsed().as_secs() > PING_TIMER {
peer_manager.process_events();
peer_manager.timer_tick_occurred();
last_ping_call = Instant::now();
}
}
// Note that we want to run a graph prune once not long after startup before
// falling back to our usual hourly prunes. This avoids short-lived clients never
// pruning their network graph. We run once 60 seconds after startup before
// continuing our normal cadence.
if last_prune_call.elapsed().as_secs()
> if have_pruned {
NETWORK_PRUNE_TIMER
} else {
FIRST_NETWORK_PRUNE_TIMER
}
{
self.network_graph.remove_stale_channels();
if let Err(e) = self.persister.persist_graph(&self.network_graph) {
println!("Error: Failed to persist network graph, check your disk and permissions {}", e);
}
last_prune_call = Instant::now();
have_pruned = true;
}
if let Some(rapid_gossip_sync_server_host) = &self.rapid_gossip_sync_server_host {
if last_rgs_sync_call.elapsed().as_secs()
> if have_rapid_gossip_synced {
RAPID_GOSSIP_SYNC_TIMER
} else {
FIRST_RAPID_GOSSIP_SYNC_TIMER
}
{
let rapid_sync = RapidGossipSync::new(self.network_graph.clone());
let last_rapid_gossip_sync_timestamp = self
.network_graph
.get_last_rapid_gossip_sync_timestamp()
.unwrap_or(0);
let rapid_gossip_sync_uri = format!(
"{}/snapshot/{}",
rapid_gossip_sync_server_host, last_rapid_gossip_sync_timestamp
);
let update_data = match reqwest::get(&rapid_gossip_sync_uri).await {
Ok(response) => {
match response.bytes().await {
Ok(bytes) => Some(bytes.to_vec()),
Err(e) => {
eprintln!("failed to convert rapid gossip sync response to bytes: {:?}", e);
None
}
}
}
Err(e) => {
eprintln!(
"failed to fetch rapid gossip sync update at {} with error: {:?}",
rapid_gossip_sync_uri, e
);
None
}
};
if let Some(update_data) = update_data {
if let Err(e) = rapid_sync.update_network_graph(&update_data[..]) {
eprintln!(
"failed to update network graph with rapid gossip sync data: {:?}",
e
);
}
}
last_rgs_sync_call = Instant::now();
have_rapid_gossip_synced = true;
}
}
if last_scorer_persist_call.elapsed().as_secs() > SCORER_PERSIST_TIMER {
let scorer = self.scorer.lock().unwrap();
if let AnyScorer::Local(scorer) = scorer.deref() {
if self.persister.persist_scorer(scorer).is_err() {
// Persistence errors here are non-fatal as channels will be re-scored as payments
// fail, but they may indicate a disk error which could be fatal elsewhere.
eprintln!(
"Warning: Failed to persist scorer, check your disk and permissions"
);
}
}
last_scorer_persist_call = Instant::now();
}
if self.stop_signal.load(Ordering::Acquire) {
break;
}
}
let scorer = self.scorer.lock().unwrap();
if let AnyScorer::Local(scorer) = scorer.deref() {
if self.persister.persist_scorer(scorer).is_err() {
// Persistence errors here are non-fatal as channels will be re-scored as payments
// fail, but they may indicate a disk error which could be fatal elsewhere.
eprintln!("Warning: Failed to persist scorer, check your disk and permissions");
}
}
if let Err(_e) = self.persister.persist_graph(&self.network_graph) {
eprintln!("Warning: Failed to persist graph, check your disk and permissions");
}
}
}
|
pub struct Solution;
impl Solution {
pub fn calculate_minimum_hp(dungeon: Vec<Vec<i32>>) -> i32 {
let mut dungeon = dungeon;
let m = dungeon.len();
let n = dungeon[0].len();
for i in (0..m).rev() {
for j in (0..n).rev() {
let next = match (i + 1 < m, j + 1 < n) {
(true, true) => dungeon[i + 1][j].min(dungeon[i][j + 1]),
(true, false) => dungeon[i + 1][j],
(false, true) => dungeon[i][j + 1],
(false, false) => 1,
};
dungeon[i][j] = 1.max(next - dungeon[i][j])
}
}
dungeon[0][0]
}
}
#[test]
fn test0174() {
fn case(dungeon: Vec<Vec<i32>>, want: i32) {
assert_eq!(Solution::calculate_minimum_hp(dungeon), want);
}
case(vec![vec![-2, -3, 3], vec![-5, -10, 1], vec![10, 30, -5]], 7);
case(vec![vec![2], vec![1]], 1);
}
|
mod util;
use self::util::test_script;
#[test]
fn test_upvalue() {
test_script(
r#"
local i = 0
local function inc(amt)
i = i + amt
end
inc(1)
inc(2)
inc(3)
return i
"#,
6,
);
}
#[test]
fn test_upvalue_multi() {
test_script(
r#"
local i = 0
local j = 0
local k = 0
local function inc(amt)
i = i + amt
j = j + 1
k = 2 + k
end
inc(1)
inc(2)
inc(3)
return i + j + k
"#,
15,
);
}
#[test]
fn test_upvalue_outer() {
test_script(
r#"
local i = 0
local inc
local function make()
local k = 4
local function f()
i = i + k
end
inc = f
end
make()
inc()
inc()
inc()
return i
"#,
12,
);
}
|
use std::sync::{Mutex, Arc};
use std::thread;
fn main() {
// creating a variable to an i32
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
// spawn 10 threads
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
// ith acquisition of lock
let mut num = counter.lock().unwrap();
*num += 1;
// subsequent release of lock
});
handles.push(handle);
}
for handle in handles {
// ensure that all handles have finished
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
|
use std::ffi::CString;
use ash::{extensions::khr, vk};
use super::{
error::{GraphicsError, GraphicsResult},
surface,
};
pub struct PoolsWrapper {
pub commandpool_graphics: vk::CommandPool,
}
impl PoolsWrapper {
pub fn init(
logical_device: &ash::Device,
queue_families: &QueueFamilies,
) -> GraphicsResult<Self> {
let graphics_commandpool_info = vk::CommandPoolCreateInfo::builder()
.queue_family_index(queue_families.graphics_q_index)
.flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER);
let commandpool_graphics =
unsafe { logical_device.create_command_pool(&graphics_commandpool_info, None) }?;
Ok(Self {
commandpool_graphics,
})
}
pub fn cleanup(&self, logical_device: &ash::Device) {
unsafe {
logical_device.destroy_command_pool(self.commandpool_graphics, None);
}
}
}
pub fn create_commandbuffers(
logical_device: &ash::Device,
pools: &PoolsWrapper,
amount: usize,
) -> GraphicsResult<Vec<vk::CommandBuffer>> {
let commandbuf_allocate_info = vk::CommandBufferAllocateInfo::builder()
.command_pool(pools.commandpool_graphics)
.command_buffer_count(amount as u32);
unsafe { Ok(logical_device.allocate_command_buffers(&commandbuf_allocate_info)?) }
}
pub struct QueueFamilies {
pub graphics_q_index: u32,
}
impl QueueFamilies {
pub fn init(
instance: &ash::Instance,
physical_device: vk::PhysicalDevice,
surface: &surface::SurfaceWrapper,
) -> GraphicsResult<QueueFamilies> {
let queues = QueueFamilies::find_suitable_queue_family(instance, physical_device, surface)?;
Ok(QueueFamilies {
graphics_q_index: queues,
})
}
fn find_suitable_queue_family(
instance: &ash::Instance,
physical_device: vk::PhysicalDevice,
surface: &surface::SurfaceWrapper,
) -> GraphicsResult<u32> {
let queuefamilyproperties =
unsafe { instance.get_physical_device_queue_family_properties(physical_device) };
let mut found_graphics_q_index = None;
for (index, qfam) in queuefamilyproperties.iter().enumerate() {
let surface_support =
surface.get_physical_device_surface_support(physical_device, index)?;
if qfam.queue_flags.contains(vk::QueueFlags::GRAPHICS) && surface_support {
// found perfect queue family, break
found_graphics_q_index = Some(index as u32);
}
}
if let Some(index) = found_graphics_q_index {
Ok(index)
} else {
Err(GraphicsError::NoSuitableQueueFamily)
}
}
}
pub struct Queues {
pub graphics_queue: vk::Queue,
}
pub fn init_device_and_queues(
instance: &ash::Instance,
physical_device: vk::PhysicalDevice,
queue_families: &QueueFamilies,
ext_memory_budget: bool,
) -> GraphicsResult<(ash::Device, Queues)> {
let ext_memory_budget_name = CString::new("VK_EXT_memory_budget").unwrap();
let device_extension_names_raw = [
khr::Swapchain::name().as_ptr(),
ext_memory_budget_name.as_ptr(),
];
// https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkPhysicalDeviceFeatures.html
// required for wireframe fill mode
let features = vk::PhysicalDeviceFeatures::builder().fill_mode_non_solid(true); // TODO: check if feature is supported before force-enabling it
let priorities = [1.0];
let queue_info = [vk::DeviceQueueCreateInfo::builder()
.queue_family_index(queue_families.graphics_q_index)
.queue_priorities(&priorities)
.build()];
let device_create_info = vk::DeviceCreateInfo::builder()
.queue_create_infos(&queue_info)
.enabled_extension_names(if ext_memory_budget {
&device_extension_names_raw
} else {
&device_extension_names_raw[0..=0]
})
.enabled_features(&features);
let logical_device: ash::Device =
unsafe { instance.create_device(physical_device, &device_create_info, None) }?;
let graphics_queue =
unsafe { logical_device.get_device_queue(queue_families.graphics_q_index, 0) };
Ok((logical_device, Queues { graphics_queue }))
}
|
use darling::ast::Data;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{Error, LitInt};
use crate::{
args::{self, RenameTarget},
utils::{get_crate_name, get_rustdoc, visible_fn, GeneratorResult},
};
pub fn generate(object_args: &args::MergedSubscription) -> GeneratorResult<TokenStream> {
let crate_name = get_crate_name(object_args.internal);
let ident = &object_args.ident;
let extends = object_args.extends;
let gql_typename = if !object_args.name_type {
let name = object_args
.name
.clone()
.unwrap_or_else(|| RenameTarget::Type.rename(ident.to_string()));
quote!(::std::borrow::Cow::Borrowed(#name))
} else {
quote!(<Self as #crate_name::TypeName>::type_name())
};
let desc = get_rustdoc(&object_args.attrs)?
.map(|s| quote! { ::std::option::Option::Some(::std::string::ToString::to_string(#s)) })
.unwrap_or_else(|| quote! {::std::option::Option::None});
let s = match &object_args.data {
Data::Struct(e) => e,
_ => {
return Err(Error::new_spanned(
ident,
"MergedSubscription can only be applied to an struct.",
)
.into())
}
};
let types: Vec<_> = s.fields.iter().map(|field| &field.ty).collect();
let create_field_stream: proc_macro2::TokenStream = (0..types.len())
.map(|i| {
let n = LitInt::new(&i.to_string(), Span::call_site());
quote!(.or_else(|| #crate_name::SubscriptionType::create_field_stream(&self.#n, ctx)))
})
.collect();
let merged_type = types.iter().fold(
quote!(#crate_name::MergedObjectTail),
|obj, ty| quote!(#crate_name::MergedObject::<#ty, #obj>),
);
let visible = visible_fn(&object_args.visible);
let expanded = quote! {
#[allow(clippy::all, clippy::pedantic)]
impl #crate_name::SubscriptionType for #ident {
fn type_name() -> ::std::borrow::Cow<'static, ::std::primitive::str> {
#gql_typename
}
fn create_type_info(registry: &mut #crate_name::registry::Registry) -> ::std::string::String {
registry.create_subscription_type::<Self, _>(|registry| {
let mut fields = ::std::default::Default::default();
if let #crate_name::registry::MetaType::Object {
fields: obj_fields,
..
} = registry.create_fake_subscription_type::<#merged_type>() {
fields = obj_fields;
}
#crate_name::registry::MetaType::Object {
name: ::std::borrow::Cow::into_owned(#gql_typename),
description: #desc,
fields,
cache_control: ::std::default::Default::default(),
extends: #extends,
keys: ::std::option::Option::None,
visible: #visible,
shareable: false,
inaccessible: false,
tags: ::std::default::Default::default(),
is_subscription: true,
rust_typename: ::std::option::Option::Some(::std::any::type_name::<Self>()),
}
})
}
fn create_field_stream<'__life>(
&'__life self,
ctx: &'__life #crate_name::Context<'__life>
) -> ::std::option::Option<::std::pin::Pin<::std::boxed::Box<dyn #crate_name::futures_util::stream::Stream<Item = #crate_name::Response> + ::std::marker::Send + '__life>>> {
::std::option::Option::None #create_field_stream
}
}
};
Ok(expanded.into())
}
|
use std::collections::BTreeMap;
use std::fs::File;
use std::path::Path;
use std::io::Read;
pub fn parse<P>(path: P) -> super::Result<BTreeMap<String, String>>
where P: AsRef<Path>
{
let mut map = BTreeMap::new();
let mut f = try!(File::open(path));
let mut s = String::new();
try!(f.read_to_string(&mut s));
let values = s.lines()
.filter(|l| !l.starts_with("#"))
.map(|l| l.split("=").take(2).collect::<Vec<&str>>())
.collect::<Vec<Vec<&str>>>();
for pair in values.iter() {
if pair.len() == 2 {
map.insert(pair[0].trim().to_owned(), pair[1].trim().to_owned());
}
}
Ok(map)
}
|
pub mod gameplay;
pub mod def;
pub mod winner;
pub const ARENA_HEIGHT: f32 = 1000.0;
pub const ARENA_WIDTH: f32 = 1000.0; |
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::io::Cursor;
#[derive(PartialEq, Debug, Clone)]
pub enum Message {
KeepAlive,
Choke,
Unchoke,
Interested,
NotInterested,
Bitfield(Vec<u8>),
Request(u32, u32, u32),
Have(u32),
Piece(u32, u32, Vec<u8>), // index * offset * block
Cancel(u32, u32, u32),
Port(u16),
}
impl Message {
pub fn deserialize(buf: &[u8]) -> Option<Message> {
let mut cx = Cursor::new(buf);
match cx.read_u8().ok()? {
0 => Some(Message::Choke),
1 => Some(Message::Unchoke),
2 => Some(Message::Interested),
3 => Some(Message::NotInterested),
4 => {
let i = cx.read_u32::<BigEndian>().ok()?;
Some(Message::Have(i))
}
5 => Some(Message::Bitfield(cx.into_inner()[1..].to_vec())),
6 => {
let i = cx.read_u32::<BigEndian>().ok()?;
let s = cx.read_u32::<BigEndian>().ok()?;
let len = cx.read_u32::<BigEndian>().ok()?;
Some(Message::Request(i, s, len))
}
7 => {
let i = cx.read_u32::<BigEndian>().ok()?;
let s = cx.read_u32::<BigEndian>().ok()?;
Some(Message::Piece(i, s, cx.into_inner()[9..].to_vec()))
}
8 => {
let i = cx.read_u32::<BigEndian>().ok()?;
let s = cx.read_u32::<BigEndian>().ok()?;
let len = cx.read_u32::<BigEndian>().ok()?;
Some(Message::Cancel(i, s, len))
}
9 => {
let p = cx.read_u16::<BigEndian>().ok()?;
Some(Message::Port(p))
}
_ => None,
}
}
// serializes message to byte array
// consumes self
pub fn serialize(self) -> Vec<u8> {
let mut buf = vec![];
match self {
Message::Choke => {
WriteBytesExt::write_u8(&mut buf, 0).unwrap();
}
Message::Unchoke => {
WriteBytesExt::write_u8(&mut buf, 1).unwrap();
}
Message::Interested => {
WriteBytesExt::write_u8(&mut buf, 2).unwrap();
}
Message::NotInterested => {
WriteBytesExt::write_u8(&mut buf, 3).unwrap();
}
Message::Have(i) => {
WriteBytesExt::write_u8(&mut buf, 4).unwrap();
WriteBytesExt::write_u32::<BigEndian>(&mut buf, i).unwrap();
}
Message::Bitfield(v) => {
WriteBytesExt::write_u8(&mut buf, 5).unwrap();
buf.extend(v);
}
Message::Request(i, s, len) => {
WriteBytesExt::write_u8(&mut buf, 6).unwrap();
WriteBytesExt::write_u32::<BigEndian>(&mut buf, i).unwrap();
WriteBytesExt::write_u32::<BigEndian>(&mut buf, s).unwrap();
WriteBytesExt::write_u32::<BigEndian>(&mut buf, len).unwrap();
}
Message::Piece(i, s, payload) => {
WriteBytesExt::write_u8(&mut buf, 7).unwrap();
WriteBytesExt::write_u32::<BigEndian>(&mut buf, i).unwrap();
WriteBytesExt::write_u32::<BigEndian>(&mut buf, s).unwrap();
buf.extend(payload)
}
_ => {}
}
buf
// let mut res = vec![];
// WriteBytesExt::write_u32::<BigEndian>(&mut res, buf.len() as u32).unwrap();
// res.extend(buf);
// res
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_serialize() {}
}
|
use crate::utils::*;
use rand;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use rstris::figure::*;
use rstris::movement::*;
use rstris::playfield::*;
use rstris::position::Position;
#[derive(Debug, Clone)]
struct MoveAndTime {
movement: Movement,
time: u64,
}
impl Ord for MoveAndTime {
fn cmp(&self, other: &MoveAndTime) -> Ordering {
other.time.cmp(&self.time)
}
}
impl PartialOrd for MoveAndTime {
fn partial_cmp(&self, other: &MoveAndTime) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for MoveAndTime {}
impl PartialEq for MoveAndTime {
fn eq(&self, other: &MoveAndTime) -> bool {
self.time == other.time
}
}
struct MoveQueue {
// Queues of moves to be executed
queue: BinaryHeap<MoveAndTime>,
// Keep track of when last move was dequeued
last_move_time: [u64; 6],
}
impl MoveQueue {
fn new() -> Self {
MoveQueue {
queue: BinaryHeap::new(),
last_move_time: [0; 6],
}
}
fn movement_to_index(movement: Movement) -> usize {
match movement {
Movement::MoveLeft => 0,
Movement::MoveRight => 1,
Movement::MoveDown => 2,
Movement::MoveUp => 3,
Movement::RotateCW => 4,
Movement::RotateCCW => 5,
}
}
fn add_move(&mut self, movement: Movement, ticks: u64) {
let move_time = MoveAndTime {
movement,
time: ticks,
};
self.queue.push(move_time);
}
pub fn pop_next_move(&mut self, ticks: u64) -> Option<MoveAndTime> {
if let Some(move_and_time) = self.queue.peek() {
if move_and_time.time <= ticks {
self.last_move_time[Self::movement_to_index(move_and_time.movement)] =
move_and_time.time;
return self.queue.pop();
}
}
None
}
pub fn time_last_move(&self, movement: Movement) -> u64 {
self.last_move_time[Self::movement_to_index(movement)]
}
pub fn time_since_move(&self, ticks: u64, movement: Movement) -> i64 {
ticks as i64 - self.time_last_move(movement) as i64
}
pub fn clear(&mut self) {
self.queue.clear();
}
}
pub struct Game {
pf: Playfield,
down_step_time: u64,
// All available figures
available_figures: Vec<Figure>,
// Next figure to be played
next_figure: Figure,
// Current figure being played
current_figure: Option<(Figure, Position)>,
game_over: bool,
// Queues of moves to be executed
move_queue: MoveQueue,
}
impl Game {
pub fn new(pf: Playfield, available_figures: Vec<Figure>, down_step_time: u64) -> Self {
Game {
pf,
down_step_time,
next_figure: Self::randomize_figure(&available_figures).clone(),
available_figures,
current_figure: None,
game_over: false,
move_queue: MoveQueue::new(),
}
}
fn randomize_figure(figures: &[Figure]) -> &Figure {
let next_figure = (rand::random::<u8>() % figures.len() as u8) as usize;
&figures[next_figure]
}
pub fn playfield(&self) -> &Playfield {
&self.pf
}
pub fn current_figure(&self) -> &Option<(Figure, Position)> {
&self.current_figure
}
pub fn next_figure(&self) -> &Figure {
&self.next_figure
}
pub fn game_is_over(&self) -> bool {
self.game_over
}
pub fn down_step_time(&self) -> u64 {
self.down_step_time
}
pub fn add_move(&mut self, movement: Movement, ticks: u64) {
self.move_queue.add_move(movement, ticks);
}
fn execute_move(&mut self, movement: Movement) {
if let Some((fig, mut pos)) = self.current_figure.take() {
let test_pos = Position::apply_move(&pos, movement);
let collision = fig.test_collision(&self.pf, test_pos);
if collision && movement == Movement::MoveDown {
// Figure has landed
fig.place(&mut self.pf, pos);
} else {
if !collision {
// Move was executed
pos = test_pos;
}
self.current_figure = Some((fig, pos));
}
}
}
pub fn update(&mut self, ticks: u64) {
if self.game_over {
return;
}
if self.current_figure.is_some() {
let time_since_down = self.move_queue.time_since_move(ticks, Movement::MoveDown);
if time_since_down >= self.down_step_time as i64 {
// Let the figure fall
self.add_move(Movement::MoveDown, ticks);
}
// Execute enqueued moves
while let Some(move_and_time) = self.move_queue.pop_next_move(ticks) {
self.execute_move(move_and_time.movement);
}
} else {
self.move_queue.clear();
// Throw away full lines
let mut full_lines = self.pf.locked_lines();
full_lines.sort();
for line in &full_lines {
self.pf.throw_line(*line);
}
// Place the next figure
let new_figure = self.next_figure.clone();
let new_pos = Position::new(((self.pf.width() / 2 - 1) as i32, 0, 0));
if new_figure.test_collision(&self.pf, new_pos) {
console_log!("Game over");
self.game_over = true;
} else {
self.next_figure = Self::randomize_figure(&self.available_figures).clone();
self.current_figure = Some((new_figure, new_pos));
}
}
}
}
|
use std::any::{Any, TypeId};
use std::borrow::Borrow;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::process::exit;
use std::result::Result;
use fuzzcheck_common::arg::{Arguments, FuzzerCommand};
use fuzzcheck_common::{FuzzerEvent, FuzzerStats};
use libc::{SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGINT, SIGSEGV, SIGTERM, SIGTRAP};
use crate::data_structures::RcSlab;
use crate::sensors_and_pools::{
AndSensorAndPool, NoopSensor, TestFailure, TestFailurePool, TestFailureSensor, UnitPool, TEST_FAILURE,
};
use crate::signals_handler::set_signal_handlers;
use crate::subvalue_provider::{CrossoverSubValueProvider, Generation, SubValueProviderId};
use crate::traits::{CorpusDelta, Mutator, SaveToStatsFolder, SensorAndPool, Serializer};
use crate::world::World;
use crate::{CSVField, SubValueProvider, ToCSV};
static WRITE_STATS_ERROR: &str = "the stats could not be written to the file system";
static WORLD_NEW_ERROR: &str = "an IO operation failed when setting up the fuzzer";
static SERIALIZER_FROM_DATA_ERROR: &str = "the file could not be decoded into a valid input";
static READ_INPUT_FILE_ERROR: &str = "the input file could not be read";
static SAVE_ARTIFACTS_ERROR: &str = "the artifact could not be saved";
static UPDATE_CORPUS_ERROR: &str = "the corpus could not be updated on the file system";
static mut DID_FIND_ANY_TEST_FAILURE: bool = false;
/// The result of a fuzz test, if it ends.
///
/// It contains two fields:
/// 1. [`found_test_failure`](Self::found_test_failure) is `true` if the fuzzer found any failing test case
/// 2. [`reason_for_stopping`](Self::reason_for_stopping) gives the reason why the fuzzer stopped.
///
/// If the fuzzer stopped because it found a failing test case, then `reason_for_stopping` has the
/// value [`ReasonForStopping::TestFailure(T)`](crate::ReasonForStopping::TestFailure) where `T` is the
/// failing test case.
#[derive(Debug, Clone)]
pub struct FuzzingResult<T> {
pub found_test_failure: bool,
pub reason_for_stopping: ReasonForStopping<T>,
}
#[derive(Debug, Clone)]
pub enum ReasonForStopping<T> {
TestFailure(T),
ExhaustedAllPossibleMutations,
MaxIterationsReached,
MaxDurationReached,
}
/// The index to a test case in the fuzzer’s storage.
#[cfg_attr(feature = "serde_json_serializer", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PoolStorageIndex(usize);
// #[cfg(test)]
impl PoolStorageIndex {
#[no_coverage]
pub fn mock(idx: usize) -> Self {
Self(idx)
}
}
enum FuzzerInputIndex<T> {
None,
Temporary(T),
Pool(PoolStorageIndex),
}
struct FuzzedInputAndSubValueProvider<T, M>
where
T: Clone + 'static,
M: Mutator<T>,
{
input: FuzzedInput<T, M>,
subvalues: CrossoverSubValueProvider<T, M>,
}
/**
* A struct that stores the value, cache, and mutation step of an input.
* It is used for convenience.
*/
struct FuzzedInput<T: Clone + 'static, Mut: Mutator<T>> {
value: T,
cache: Mut::Cache,
mutation_step: Mut::MutationStep,
generation: Generation,
}
impl<T: Clone + 'static, Mut: Mutator<T>> Clone for FuzzedInput<T, Mut> {
fn clone(&self) -> Self {
Self {
value: self.value.clone(),
cache: self.cache.clone(),
mutation_step: self.mutation_step.clone(),
generation: self.generation,
}
}
}
impl<T: Clone + 'static, Mut: Mutator<T>> FuzzedInput<T, Mut> {
#[no_coverage]
fn new(value: T, cache: Mut::Cache, mutation_step: Mut::MutationStep, generation: Generation) -> Self {
Self {
value,
cache,
mutation_step,
generation,
}
}
#[no_coverage]
fn new_source(&self, m: &Mut, generation: Generation) -> Self {
let cache = m.validate_value(&self.value).unwrap();
let mutation_step = m.default_mutation_step(&self.value, &cache);
Self::new(self.value.clone(), cache, mutation_step, generation)
}
#[no_coverage]
fn complexity(&self, m: &Mut) -> f64 {
m.complexity(&self.value, &self.cache)
}
#[no_coverage]
fn mutate(
&mut self,
m: &Mut,
subvalue_provider: &dyn SubValueProvider,
max_cplx: f64,
) -> Option<(Mut::UnmutateToken, f64)> {
m.ordered_mutate(
&mut self.value,
&mut self.cache,
&mut self.mutation_step,
subvalue_provider,
max_cplx,
)
}
#[no_coverage]
fn unmutate(&mut self, m: &Mut, t: Mut::UnmutateToken) {
m.unmutate(&mut self.value, &mut self.cache, t);
}
}
struct FuzzerState<T: Clone + 'static, M: Mutator<T>> {
mutator: M,
sensor_and_pool: Box<dyn SensorAndPool>,
pool_storage: RcSlab<FuzzedInputAndSubValueProvider<T, M>>,
/// The step given to the mutator when the fuzzer wants to create a new arbitrary test case
arbitrary_step: M::ArbitraryStep,
/// The index of the test case that is being tested
input_idx: FuzzerInputIndex<FuzzedInput<T, M>>,
/// Various statistics about the fuzzer run
fuzzer_stats: FuzzerStats,
settings: Arguments,
serializer: Box<dyn Serializer<Value = T>>,
/// The world handles effects
world: World,
rng: fastrand::Rng,
signal_handler_alt_stack: Option<(*mut u8, std::alloc::Layout)>,
}
impl<T: Clone + 'static, M: Mutator<T>> Drop for FuzzerState<T, M> {
#[no_coverage]
fn drop(&mut self) {
unsafe {
crate::signals_handler::reset_signal_handlers();
if let Some((stack_ptr, stack_layout)) = self.signal_handler_alt_stack {
std::alloc::dealloc(stack_ptr, stack_layout);
}
}
}
}
impl<T: Clone + 'static, M: Mutator<T>> FuzzerState<T, M> {
#[no_coverage]
fn get_input<'a>(
fuzzer_input_idx: &'a FuzzerInputIndex<FuzzedInput<T, M>>,
pool_storage: &'a RcSlab<FuzzedInputAndSubValueProvider<T, M>>,
) -> Option<&'a FuzzedInput<T, M>> {
match fuzzer_input_idx {
FuzzerInputIndex::None => None,
FuzzerInputIndex::Temporary(input) => Some(input),
FuzzerInputIndex::Pool(idx) => Some(&pool_storage[idx.0].input),
}
}
}
#[no_coverage]
fn update_fuzzer_stats(stats: &mut FuzzerStats, world: &mut World) {
let microseconds = world.elapsed_time_since_last_checkpoint();
let nbr_runs = stats.total_number_of_runs - stats.number_of_runs_since_last_reset_time;
let nbr_runs_times_million = nbr_runs * 1_000_000;
if microseconds != 0 {
stats.exec_per_s = nbr_runs_times_million / microseconds;
}
if microseconds > 1_000_000 {
world.set_checkpoint_instant();
stats.number_of_runs_since_last_reset_time = stats.total_number_of_runs;
}
}
impl<T: Clone + 'static, M: Mutator<T>> SaveToStatsFolder for FuzzerState<T, M>
where
Self: 'static,
{
#[no_coverage]
fn save_to_stats_folder(&self) -> Vec<(std::path::PathBuf, Vec<u8>)> {
let mut contents = self.sensor_and_pool.save_to_stats_folder();
contents.extend(self.world.save_to_stats_folder());
contents
}
}
impl<T: Clone + 'static, M: Mutator<T>> FuzzerState<T, M>
where
Self: 'static,
{
#[no_coverage]
fn write_stats(&mut self) -> Result<(), std::io::Error> {
self.world.write_stats_content(self.save_to_stats_folder())
}
#[no_coverage]
fn receive_signal(&mut self, signal: i32) -> ! {
self.world.report_event(
FuzzerEvent::CaughtSignal(signal as i32),
Some((&self.fuzzer_stats, self.sensor_and_pool.stats().as_ref())),
);
match signal {
SIGABRT | SIGBUS | SIGSEGV | SIGFPE | SIGALRM | SIGTRAP => {
if let Some(input) = Self::get_input(&self.input_idx, &self.pool_storage) {
let input = input.new_source(&self.mutator, Generation(0));
let cplx = input.complexity(&self.mutator);
let content = self.serializer.to_data(&input.value);
let _ = self.world.save_artifact(content, cplx, self.serializer.extension());
self.write_stats().expect(WRITE_STATS_ERROR);
exit(TerminationStatus::Crash as i32);
} else {
self.world.report_event(
FuzzerEvent::CrashNoInput,
Some((&self.fuzzer_stats, self.sensor_and_pool.stats().as_ref())),
);
exit(TerminationStatus::Crash as i32);
}
}
SIGINT | SIGTERM => {
self.write_stats().expect(WRITE_STATS_ERROR);
self.world.stop()
}
_ => exit(TerminationStatus::Unknown as i32),
}
}
#[no_coverage]
fn arbitrary_input(&mut self) -> Option<(FuzzedInput<T, M>, f64)> {
if let Some((v, cplx)) = self
.mutator
.ordered_arbitrary(&mut self.arbitrary_step, self.settings.max_input_cplx)
{
let cache = self.mutator.validate_value(&v).unwrap();
let step = self.mutator.default_mutation_step(&v, &cache);
Some((FuzzedInput::new(v, cache, step, Generation(0)), cplx))
} else {
None
}
}
#[no_coverage]
unsafe fn set_up_signal_handler(&mut self) {
let ptr = self as *mut Self;
let (stack_ptr, stack_size) = set_signal_handlers(
#[no_coverage]
move |sig| (*ptr).receive_signal(sig),
);
self.signal_handler_alt_stack = Some((stack_ptr, stack_size));
}
}
pub struct Fuzzer<T, M>
where
T: Clone + 'static,
M: Mutator<T>,
Self: 'static,
{
state: FuzzerState<T, M>,
test: Box<dyn Fn(&T) -> bool>,
}
impl<T, M> Fuzzer<T, M>
where
T: Clone + 'static,
M: Mutator<T>,
Self: 'static,
{
#[no_coverage]
fn new(
test: Box<dyn Fn(&T) -> bool>,
mutator: M,
serializer: Box<dyn Serializer<Value = T>>,
sensor_and_pool: Box<dyn SensorAndPool>,
settings: Arguments,
world: World,
) -> Self {
let arbitrary_step = mutator.default_arbitrary_step();
Fuzzer {
state: FuzzerState {
sensor_and_pool,
pool_storage: RcSlab::new(),
mutator,
arbitrary_step,
input_idx: FuzzerInputIndex::None,
fuzzer_stats: FuzzerStats::default(),
settings,
serializer,
world,
rng: fastrand::Rng::new(),
signal_handler_alt_stack: None,
},
test,
}
}
#[no_coverage]
fn test_and_process_input(&mut self, cplx: f64) -> Result<(), ReasonForStopping<T>> {
let Fuzzer {
state:
FuzzerState {
mutator,
sensor_and_pool,
pool_storage,
input_idx,
fuzzer_stats,
serializer,
world,
settings,
..
},
test,
..
} = self;
// we have verified in the caller function that there is an input
let input = FuzzerState::<T, M>::get_input(input_idx, pool_storage).unwrap();
std::panic::set_hook(Box::new(
#[no_coverage]
move |panic_info| {
let mut hasher = DefaultHasher::new();
panic_info.location().hash(&mut hasher);
unsafe {
TEST_FAILURE = Some(TestFailure {
display: format!("{}", panic_info),
id: hasher.finish(),
});
}
},
));
if settings.detect_infinite_loop {
let _old_time_left = unsafe { libc::alarm(1) };
// TODO: I think setitimer should be prefered, but libc
// doesn't support it on linux, see:
// https://github.com/rust-lang/libc/issues/1347#event-3879031340
// let success = unsafe {
// let t = itimerval {
// it_interval: libc::timeval { tv_sec: 0, tv_usec: 0 },
// it_value: libc::timeval { tv_sec: 1, tv_usec: 0 },
// };
// libc::setitimer(ITIMER_REAL, &t, std::ptr::null_mut())
// };
// assert!(success == 0);
}
sensor_and_pool.start_recording();
let result = catch_unwind(AssertUnwindSafe(
#[no_coverage]
|| (test)(input.value.borrow()),
));
let _ = std::panic::take_hook();
let test_failure = match result {
Ok(false) => unsafe {
TEST_FAILURE = Some(TestFailure {
display: "test function returned false".to_string(),
id: 0,
});
true
},
Err(_) => {
// the panic handler already changed the value of TEST_FAILURE
// so we don't need to do anything
true
}
Ok(true) => false,
};
if test_failure {
unsafe {
DID_FIND_ANY_TEST_FAILURE = true;
}
}
sensor_and_pool.stop_recording();
if test_failure && self.state.settings.stop_after_first_failure {
let serialized_input = serializer.to_data(&input.value);
self.state
.world
.save_artifact(serialized_input, cplx, serializer.extension())
.expect(SAVE_ARTIFACTS_ERROR);
return Err(ReasonForStopping::TestFailure(input.value.clone()));
}
fuzzer_stats.total_number_of_runs += 1;
let input_id = PoolStorageIndex(pool_storage.next_slot());
let deltas = sensor_and_pool.process(input_id, cplx);
if !deltas.is_empty() {
let add_ref_count = deltas.iter().fold(
0,
#[no_coverage]
|acc, delta| if delta.add { acc + 1 } else { acc },
);
update_fuzzer_stats(fuzzer_stats, world);
let event = CorpusDelta::fuzzer_event(&deltas);
let content = if add_ref_count > 0 {
serializer.to_data(&input.value)
} else {
vec![]
};
world
.update_corpus(input_id, content, &deltas, serializer.extension())
.expect(UPDATE_CORPUS_ERROR);
world.report_event(event, Some((fuzzer_stats, sensor_and_pool.stats().as_ref())));
if add_ref_count > 0 {
let generation = Generation(fuzzer_stats.total_number_of_runs);
let input = input.new_source(mutator, generation);
// check that the mutator's handling of the complexity is correct
let serialised = String::from_utf8(serializer.to_data(&input.value)).unwrap();
assert!(
(input.complexity(mutator) - cplx).abs() < 0.01,
"The mutator used by the fuzz test does not evaluate the complexity of the test cases consistently.
This is a bug in the implementation of {}
=============
{serialised}
=============
",
std::any::type_name::<M>()
);
let mut subvalues: HashMap<TypeId, Vec<(*const dyn Any, f64)>> = HashMap::default();
let mut act_on_subvalue = #[no_coverage]
|subvalue: &dyn Any, complexity| {
subvalues
.entry(subvalue.type_id())
.or_default()
.push((subvalue as *const _, complexity));
};
mutator.visit_subvalues(&input.value, &input.cache, &mut act_on_subvalue);
let storage_idx_1 = pool_storage.next_slot();
let subvalues = CrossoverSubValueProvider::new(
SubValueProviderId {
idx: storage_idx_1,
generation,
},
&input.value,
&input.cache,
mutator,
);
let stored_input = FuzzedInputAndSubValueProvider { input, subvalues };
let storage_idx_2 = pool_storage.insert(stored_input, add_ref_count);
assert_eq!(storage_idx_1, storage_idx_2);
}
for delta in deltas {
for r in delta.remove {
pool_storage.remove(r.0);
}
}
}
Ok(())
}
#[no_coverage]
fn get_input_and_subvalue_provider<'a>(
pool_storage: &'a mut RcSlab<FuzzedInputAndSubValueProvider<T, M>>,
sensor_and_pool: &mut dyn SensorAndPool,
rng: &fastrand::Rng,
idx: PoolStorageIndex,
) -> (&'a mut FuzzedInput<T, M>, &'a (impl SubValueProvider + 'a)) {
let idx_cross = sensor_and_pool.get_random_index().unwrap();
if idx == idx_cross || rng.u8(..5) == 0 {
let FuzzedInputAndSubValueProvider { input, subvalues } = &mut pool_storage[idx.0];
(input, subvalues)
} else {
// crossover of two different test cases
let (input, FuzzedInputAndSubValueProvider { subvalues, .. }) =
pool_storage.get_mut_and_ref(idx.0, idx_cross.0).unwrap();
(&mut input.input, subvalues)
}
}
#[no_coverage]
fn process_next_input(&mut self) -> Result<(), ReasonForStopping<T>> {
let FuzzerState {
pool_storage,
sensor_and_pool,
input_idx,
mutator,
settings,
rng,
fuzzer_stats,
world,
..
} = &mut self.state;
if let Some(idx) = sensor_and_pool.get_random_index() {
*input_idx = FuzzerInputIndex::Pool(idx);
let (input, subvalue_provider) =
Self::get_input_and_subvalue_provider(pool_storage, sensor_and_pool.as_mut(), rng, idx);
let generation = input.generation;
if let Some((unmutate_token, complexity)) =
input.mutate(mutator, subvalue_provider, settings.max_input_cplx)
{
//drop(subvalue_provider);
if complexity < self.state.settings.max_input_cplx {
self.test_and_process_input(complexity)?;
}
// Retrieving the input may fail because the input may have been deleted
if let Some(input) = self.state.pool_storage.get_mut(idx.0).map(
#[no_coverage]
|x| &mut x.input,
) && input.generation == generation {
input.unmutate(&self.state.mutator, unmutate_token);
}
Ok(())
} else {
world.report_event(FuzzerEvent::End, Some((fuzzer_stats, sensor_and_pool.stats().as_ref())));
Err(ReasonForStopping::ExhaustedAllPossibleMutations)
}
} else if let Some((input, cplx)) = self.state.arbitrary_input() {
self.state.input_idx = FuzzerInputIndex::Temporary(input);
if cplx < self.state.settings.max_input_cplx {
self.test_and_process_input(cplx)?;
}
Ok(())
} else {
self.state.world.report_event(
FuzzerEvent::End,
Some((&self.state.fuzzer_stats, self.state.sensor_and_pool.stats().as_ref())),
);
Err(ReasonForStopping::ExhaustedAllPossibleMutations)
}
}
#[no_coverage]
fn process_initial_inputs(&mut self) -> Result<(), ReasonForStopping<T>> {
let mut inputs: Vec<FuzzedInput<T, M>> = self
.state
.world
.read_input_corpus()
.expect(READ_INPUT_FILE_ERROR)
.into_iter()
.filter_map(
#[no_coverage]
|value| {
let value = self.state.serializer.from_data(&value)?;
let cache = self.state.mutator.validate_value(&value)?;
let mutation_step = self.state.mutator.default_mutation_step(&value, &cache);
Some(FuzzedInput::new(value, cache, mutation_step, Generation(0)))
},
)
.collect();
for _ in 0..100 {
if let Some((input, _)) = self.state.arbitrary_input() {
inputs.push(input);
} else {
break;
}
}
inputs.retain(
#[no_coverage]
|i| i.complexity(&self.state.mutator) <= self.state.settings.max_input_cplx,
);
// assert!(!inputs.is_empty());
self.state.world.set_checkpoint_instant();
for input in inputs {
let cplx = input.complexity(&self.state.mutator);
self.state.input_idx = FuzzerInputIndex::Temporary(input);
self.test_and_process_input(cplx)?;
}
Ok(())
}
#[no_coverage]
fn main_loop(&mut self, minify: bool) -> Result<!, ReasonForStopping<T>> {
self.state.world.report_event(
FuzzerEvent::Start,
Some((&self.state.fuzzer_stats, self.state.sensor_and_pool.stats().as_ref())),
);
if !minify {
self.process_initial_inputs()?;
self.state.world.report_event(
FuzzerEvent::DidReadCorpus,
Some((&self.state.fuzzer_stats, self.state.sensor_and_pool.stats().as_ref())),
);
}
self.state.world.set_checkpoint_instant();
let mut next_milestone = (self.state.fuzzer_stats.total_number_of_runs + 10) * 2;
loop {
let duration_since_beginning = self.state.world.elapsed_time_since_start();
if duration_since_beginning > self.state.settings.maximum_duration {
return Err(ReasonForStopping::MaxDurationReached);
}
if self.state.fuzzer_stats.total_number_of_runs >= self.state.settings.maximum_iterations {
return Err(ReasonForStopping::MaxIterationsReached);
}
self.process_next_input()?;
if self.state.fuzzer_stats.total_number_of_runs >= next_milestone {
update_fuzzer_stats(&mut self.state.fuzzer_stats, &mut self.state.world);
self.state.world.report_event(
FuzzerEvent::Pulse,
Some((&self.state.fuzzer_stats, self.state.sensor_and_pool.stats().as_ref())),
);
next_milestone = self.state.fuzzer_stats.total_number_of_runs * 2;
}
}
}
}
pub enum TerminationStatus {
Success = 0,
Crash = 1,
TestFailure = 2,
Unknown = 3,
}
#[no_coverage]
pub fn launch<T, M>(
test: Box<dyn Fn(&T) -> bool>,
mutator: M,
serializer: Box<dyn Serializer<Value = T>>,
sensor_and_pool: Box<dyn SensorAndPool>,
mut args: Arguments,
) -> FuzzingResult<T>
where
T: Clone + 'static,
M: Mutator<T>,
Fuzzer<T, M>: 'static,
{
let command = &args.command;
let reason_for_stopping = match command {
FuzzerCommand::Fuzz => {
if !args.stop_after_first_failure {
let test_failure_sensor = TestFailureSensor::default();
let test_failure_pool = TestFailurePool::new("test_failures");
let sensor_and_pool = AndSensorAndPool::new(
sensor_and_pool,
Box::new((test_failure_sensor, test_failure_pool)),
10.0,
1.0,
);
let mut fuzzer = Fuzzer::new(
test,
mutator,
serializer,
Box::new(sensor_and_pool),
args.clone(),
World::new(args.clone()).expect(WORLD_NEW_ERROR),
);
let mut stats_headers = vec![CSVField::String("time".to_string())];
stats_headers.extend(fuzzer.state.fuzzer_stats.csv_headers());
stats_headers.extend(fuzzer.state.sensor_and_pool.stats().csv_headers());
fuzzer
.state
.world
.append_stats_file(&stats_headers)
.expect(WRITE_STATS_ERROR);
unsafe { fuzzer.state.set_up_signal_handler() };
let reason_for_stopping = fuzzer.main_loop(false).unwrap_err();
fuzzer.state.write_stats().expect(WRITE_STATS_ERROR);
reason_for_stopping
} else {
let mut fuzzer = Fuzzer::new(
test,
mutator,
serializer,
sensor_and_pool,
args.clone(),
World::new(args.clone()).expect(WORLD_NEW_ERROR),
);
unsafe { fuzzer.state.set_up_signal_handler() };
let mut stats_headers = vec![CSVField::String("time".to_string())];
stats_headers.extend(fuzzer.state.fuzzer_stats.csv_headers());
stats_headers.extend(fuzzer.state.sensor_and_pool.stats().csv_headers());
fuzzer
.state
.world
.append_stats_file(&stats_headers)
.expect(WRITE_STATS_ERROR);
let reason_for_stopping = fuzzer.main_loop(false).unwrap_err();
fuzzer.state.write_stats().expect(WRITE_STATS_ERROR);
reason_for_stopping
}
}
FuzzerCommand::MinifyInput { input_file } => {
let world = World::new(args.clone()).expect(WORLD_NEW_ERROR);
let value = world.read_input_file(input_file).expect(READ_INPUT_FILE_ERROR);
let value = serializer.from_data(&value).expect(SERIALIZER_FROM_DATA_ERROR);
if let Some(cache) = mutator.validate_value(&value) {
let mutation_step = mutator.default_mutation_step(&value, &cache);
args.max_input_cplx = mutator.complexity(&value, &cache) - 0.01;
let noop_sensor = NoopSensor;
let unit_pool = UnitPool::new(PoolStorageIndex(0));
let sensor_and_pool =
// 100:1 might seem like an excessive ratio, but the second pool will never make progress,
// therefore its relative weight willl diminish over time
// if after 100 iterations, the first pool makes progress, then the ratio will be 1:1
// what the exact value should be and how the ratio should evolve is an open question to me
AndSensorAndPool::new(sensor_and_pool, Box::new((noop_sensor, unit_pool)), 1.0, 100.0);
let mut fuzzer = Fuzzer::new(
test,
mutator,
serializer,
Box::new(sensor_and_pool),
args.clone(),
world,
);
let mut subvalues: HashMap<TypeId, Vec<(*const dyn Any, f64)>> = HashMap::default();
let mut act_on_subvalue = #[no_coverage]
|subvalue: &dyn Any, complexity| {
subvalues
.entry(subvalue.type_id())
.or_default()
.push((subvalue as *const _, complexity));
};
fuzzer
.state
.mutator
.visit_subvalues(&value, &cache, &mut act_on_subvalue);
let storage_idx_1 = fuzzer.state.pool_storage.next_slot();
let generation = Generation(0);
let subvalues = CrossoverSubValueProvider::new(
SubValueProviderId {
idx: storage_idx_1,
generation,
},
&value,
&cache,
&fuzzer.state.mutator,
);
let stored_input = FuzzedInputAndSubValueProvider {
input: FuzzedInput::new(value, cache, mutation_step, generation),
subvalues,
};
let storage_idx_2 = fuzzer.state.pool_storage.insert(stored_input, 1);
assert_eq!(storage_idx_1, storage_idx_2);
unsafe { fuzzer.state.set_up_signal_handler() };
fuzzer.main_loop(true).unwrap_err()
} else {
// TODO: send a better error message saying some inputs in the corpus cannot be read
// TODO: there should be an option to ignore invalid values
panic!("A value in the input corpus is invalid.");
}
}
FuzzerCommand::Read { input_file } => {
// no signal handlers are installed, but that should be ok as the exit code won't be 0
let mut world = World::new(args.clone()).expect(WORLD_NEW_ERROR);
let value = world.read_input_file(input_file).expect(READ_INPUT_FILE_ERROR);
let value = serializer.from_data(&value).expect(SERIALIZER_FROM_DATA_ERROR);
if let Some(cache) = mutator.validate_value(&value) {
let mutation_step = mutator.default_mutation_step(&value, &cache);
let input = FuzzedInput::new(value, cache, mutation_step, Generation(0));
let cplx = input.complexity(&mutator);
if args.detect_infinite_loop {
let _old_time_left = unsafe { libc::alarm(1) };
// TODO: I think setitimer should be prefered, but libc
// doesn't support it on linux, see:
// https://github.com/rust-lang/libc/issues/1347#event-3879031340
// let success = unsafe {
// let t = itimerval {
// it_interval: libc::timeval { tv_sec: 0, tv_usec: 0 },
// it_value: libc::timeval { tv_sec: 1, tv_usec: 0 },
// };
// libc::setitimer(ITIMER_REAL, &t, std::ptr::null_mut())
// };
// assert!(success == 0);
}
let result = catch_unwind(AssertUnwindSafe(
#[no_coverage]
|| (test)(input.value.borrow()),
));
if result.is_err() || !result.unwrap() {
world.report_event(FuzzerEvent::TestFailure, None);
let content = serializer.to_data(&input.value);
world
.save_artifact(content, cplx, serializer.extension())
.expect(SAVE_ARTIFACTS_ERROR);
// in this case we really want to exit with a non-zero termination status here
// because the Read command is only used by the input minify command from cargo-fuzzcheck
// which checks that a crash happens by looking at the exit code
// so we don't want to handle any error
exit(TerminationStatus::TestFailure as i32);
} else {
exit(TerminationStatus::Success as i32);
}
} else {
// TODO: send a better error message saying some inputs in the corpus cannot be read
panic!("A value in the input corpus is invalid.");
}
}
};
let _ = std::panic::take_hook();
let found_test_failure =
unsafe { matches!(reason_for_stopping, ReasonForStopping::TestFailure(_)) || DID_FIND_ANY_TEST_FAILURE };
FuzzingResult {
found_test_failure,
reason_for_stopping,
}
}
|
pub(crate) trait CastTo<T: Copy> {
fn cast_to(self) -> T;
}
macro_rules! impl_cast_to {
($typ:ty) => {
impl CastTo<$typ> for $typ {
fn cast_to(self) -> $typ {
self
}
}
};
($src:ty, $dst:ty) => {
impl CastTo<$dst> for $src {
fn cast_to(self) -> $dst {
self as $dst
}
}
};
}
impl_cast_to!(u8);
impl_cast_to!(u8, u16);
impl_cast_to!(u8, u32);
impl_cast_to!(u8, u64);
impl_cast_to!(u8, i8);
impl_cast_to!(u8, i16);
impl_cast_to!(u8, i32);
impl_cast_to!(u8, i64);
impl_cast_to!(u16, u8);
impl_cast_to!(u16);
impl_cast_to!(u16, u32);
impl_cast_to!(u16, u64);
impl_cast_to!(u16, i8);
impl_cast_to!(u16, i16);
impl_cast_to!(u16, i32);
impl_cast_to!(u16, i64);
impl_cast_to!(u32, u8);
impl_cast_to!(u32, u16);
impl_cast_to!(u32);
impl_cast_to!(u32, u64);
impl_cast_to!(u32, i8);
impl_cast_to!(u32, i16);
impl_cast_to!(u32, i32);
impl_cast_to!(u32, i64);
impl_cast_to!(u64, u8);
impl_cast_to!(u64, u16);
impl_cast_to!(u64, u32);
impl_cast_to!(u64);
impl_cast_to!(u64, i8);
impl_cast_to!(u64, i16);
impl_cast_to!(u64, i32);
impl_cast_to!(u64, i64);
impl_cast_to!(i8, u8);
impl_cast_to!(i8, u16);
impl_cast_to!(i8, u32);
impl_cast_to!(i8, u64);
impl_cast_to!(i8);
impl_cast_to!(i8, i16);
impl_cast_to!(i8, i32);
impl_cast_to!(i8, i64);
impl_cast_to!(i16, u8);
impl_cast_to!(i16, u16);
impl_cast_to!(i16, u32);
impl_cast_to!(i16, u64);
impl_cast_to!(i16, i8);
impl_cast_to!(i16);
impl_cast_to!(i16, i32);
impl_cast_to!(i16, i64);
impl_cast_to!(i32, u8);
impl_cast_to!(i32, u16);
impl_cast_to!(i32, u32);
impl_cast_to!(i32, u64);
impl_cast_to!(i32, i8);
impl_cast_to!(i32, i16);
impl_cast_to!(i32);
impl_cast_to!(i32, i64);
impl_cast_to!(i64, u8);
impl_cast_to!(i64, u16);
impl_cast_to!(i64, u32);
impl_cast_to!(i64, u64);
impl_cast_to!(i64, i8);
impl_cast_to!(i64, i16);
impl_cast_to!(i64, i32);
impl_cast_to!(i64);
impl_cast_to!(f64);
impl_cast_to!(f64, f32);
impl_cast_to!(f32);
impl_cast_to!(f32, f64);
|
use colored::*;
//extern crate derive_more;
//use derive_more::{Add, Display, From, Into};
use indextree;
use std::cmp::PartialEq;
use std::fmt;
use unicode_segmentation::UnicodeSegmentation;
///This is a toy parser/compiler loosely taking inspiration from [Elm Parser](https://package.elm-lang.org/packages/elm/parser/latest/Parser) with the following methods so far...
///
///The goal is to have fun seeing if I can build a 'simple' parser syntax, similar in style Elm Parser, using the power of Rust, but without the visual/mental overhead of standard Rust code.
///
///Essentially, building a parser, to parse a new toy parser language
///
///# Examples of language syntax
///
/** ### Primitives (terse syntax is (mostly) 1 character)
| Syntax | Parser Name | Example Input String | Terse Syntax | (or) Written Syntax | Example Result |
|--------|----------------------------------------------|----------------------|--------------|----------------------------|--------------------------|
| > | [prim_next](#method.prim_next) | `1234` | `>>` | `(next)` | `12` (in Parser.chomp) |
| " | [prim_quote](#method.prim_quote) | `"test"` | `"` | `(quote)` | `\"` (in Parser.chomp) |
| 'word' | [prim_word](#method.prim_word) | `testing` | `'test'` | `(word test)` | `test` (in Parser.chomp) |
| @ | [prim_char](#method.prim_char) | `testing` | `@@@@` | `(char)(char)(char)(char)` | `test` (in Parser.chomp) |
| \# | [prim_digit](#method.prim_digit) | `1234` | `##` | `(0-9)(0-9)` | `12` (in Parser.chomp) |
| , | [prim_eols](#method.prim_eols) | ` ` | `,` | `(eols)` | true (in Parser.success) |
| | | `second line` | | | |
| . | [prim_eof](#method.prim_eof) | ` ` | `.` | `(eof)` | true (in Parser.success) |
| ; | [prim_eols_or_eof](#method.prim_eols_or_eof) | ` ` | `;` | `(eolseof)` | true (in Parser.success) |
| | | ` ` | | | |
| | | `third line` | | | |
### Combinators (terse syntax is 2 characters)
| Syntax | Parser Name | Example Input String | Terse Syntax | (or) Written Syntax | Example Result |
|--------|--------------------------------------------------------------------|----------------------|--------------|-----------------------------|----------------------------|
| 1+ | [combi_one_or_more_of](#method.combi_one_or_more_of) | `1234test` | `1+#` | `(one+ (0-9))` | `1234` (in Parser.chomp) |
| 0+ | [combi_zero_or_more_of](#method.combi_zero_or_more_of) | `"test1234"` | `0+@` | `(zero+ (char))` | `test` (in Parser.chomp) |
| !+ | [combi_until_first_do_second](#method.combi_until_first_do_second) | `testing` | `!+'i'@` | `(two!one (word i) (char))` | `test` (in Parser.chomp) |
| ?? | [combi_optional](#method.combi_optional) | `1test` | `??#` | `(option (0-9))` | `true` (in Parser.success) |
| [] | [combi_first_success_of](#method.combi_first_success_of) | `1234test` | `[# @]` | `(0-9)(char)` | `1` (in Parser.chomp) |
### Elements (terse syntax is 4 characters)
| Syntax | Parser Name | Example Input String | Terse Syntax | (or) Written Syntax | Example Result |
|--------|-------------------------------|----------------------|--------------|---------------------|-----------------------------------|
| $str | [el_str](#method.el_str) | `"1234"` | `$str` | `(el_str)` | `1234` (string element no name) |
| $int | [el_int](#method.el_int) | `-1234` | `$int` | `(el_int)` | `-1234` (integer element no name) |
| $flt | [el_float](#method.el_float) | `-123.45` | `$flt` | `(el_flt)` | `-123.45` (float element no name) |
| $var | [el_var](#method.el_var) | `= x "test"` | `$var` | `(el_var)` | `test` (string element named `x`) |
**/
/// ### Functions (perhaps these should be in userland?)
///[fn_var_assign (=)](#method.fn_var_assign),
///
///[fn_var_sum (+)](#method.fn_var_sum)
///<br /><br />
///Parser is initialised once using [new](#method.new) for each string you wish to parse.<br />
///Then it is passed through all the parser functions you have defined<br />
///This is the current 'state' of the parser at any one time during its passage through all the parser functions
///- input_original: always contains the initial string supplied to [new](#method.new)
///- input_remaining: is the current state of the remaining string to be parsed, as it passes through each parser function
///- output_arena: is a list of ParserElements (in an 'indextree' Arena) generated by your parser functions
///- output_arena_node_parent_id: refers to the current parent node in the indextree Arena
///- chomp: is the sub-string built up by a subgroup of the current parser functions.<br />
/// It can be cleared manually with [chomp_clear](#method.chomp_clear) and is usually used to build some fragment of a string for e.g. a variable name
///- success: is set to true or false by the current parser function. Currently, if a fail occurs, it is passed through all functions until the last one<br />
/// (TODO) use Results, and Panic during main parser functions
#[derive(Debug, Clone)]
pub struct Parser {
input_original: String,
input_remaining: String,
language_arena: indextree::Arena<ParserFunctionTypeAndParam>,
language_arena_node_parent_id: indextree::NodeId,
output_arena: indextree::Arena<ParserElement>,
output_arena_node_parent_id: indextree::NodeId,
chomp: String,
chomping: bool,
success: bool,
display_errors: bool,
}
#[derive(Debug, Clone)]
///Usually the end result of parsing a complete individual 'thing' within the whole parsed output<br /><br />
///
///A completed parse, should result in a vec of ParserElements in the parser.output<br /><br />
///
///All attributes are Options defining a single instance of a thing<br />
/// - el_type: the type of thing it is<br />
/// - what 'value' it should have depending on which are populated, here there are only 2 types<br />
/// - in64<br />
/// - float64<br />
/// - var_name: a string for the name if it is a variable
pub struct ParserElement {
el_type: Option<ParserElementType>,
int64: Option<i64>,
float64: Option<f64>,
string: Option<String>,
var_name: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ParserElementType {
Int64,
Float64,
Var,
Str,
}
impl ParserElement {
pub fn new() -> ParserElement {
ParserElement {
el_type: None,
int64: None,
float64: None,
string: None,
var_name: None,
}
}
}
//TODO tryout this simpler parser element
#[derive(Debug, Clone)]
pub struct ParserEl {
el_type: Option<ParserElementType>,
value: Option<ParserElValue>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ParserElValue {
I64(i64),
F64(f64),
Str(String),
Var(String),
}
impl ParserEl {
pub fn new() -> ParserEl {
ParserEl {
el_type: None,
value: None,
}
}
}
#[derive(Clone)]
pub enum ParserFunctionType {
None, //added while creating language_arena - might cause issue if not in match statements?
TakesParser(ParserFunction), //e.g. primitive except prim_word, element, function
TakesParserWord(ParserFunctionString), //e.g. prim_word
TakesParserFn(ParserFunctionParserFunction), //e.g. simple combinator like combi_parser_one_or_more
//TakesParserVecFn(ParserFunction, ParserFunctionParam::Avec(<Vec<ParserFunction>>)), //e.g. combi_until_first_do_second
//TakesParserBVecFn(ParserFunction, Vec<ParserFunction>), //e.g. combi_until_first_do_second
}
///None, String, Parser, VecParser
#[derive(Clone)]
pub enum ParserFunctionParam {
None,
String(String),
ParserFn(ParserFunction),
VecParserFn(Vec<ParserFunction>),
}
pub type ParserFunction = fn(Parser) -> Parser;
pub type ParserFunctionString = fn(Parser, &str) -> Parser;
pub type ParserFunctionParserFunction = fn(Parser, ParserFunction) -> Parser;
pub type ParserFunctionTypeAndParam = (ParserFunctionType, ParserFunctionParam);
///quick and dirty helper function to Debug function names
//https://users.rust-lang.org/t/get-the-name-of-the-function-a-function-pointer-points-to/14930
fn get_parserfn_name(f: fn(Parser) -> Parser) -> &'static str {
match f {
_ if f == Parser::prim_next => "prim_next",
_ => "unknown function name - manually add it to 'get_parserfn_name' to see it here!",
}
}
impl fmt::Debug for ParserFunctionType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ParserFunctionType::None => write!(f, "None"),
ParserFunctionType::TakesParser(p) => {
write!(f, "TakesParser {:?}", get_parserfn_name(p))
}
ParserFunctionType::TakesParserWord(_) => write!(f, "TakesParserWord"),
ParserFunctionType::TakesParserFn(_) => write!(f, "TakesParserFn"),
}
}
}
impl fmt::Debug for ParserFunctionParam {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ParserFunctionParam::None => write!(f, "None"),
ParserFunctionParam::String(_) => write!(f, "String"),
ParserFunctionParam::ParserFn(_) => write!(f, "ParserFn"),
ParserFunctionParam::VecParserFn(_) => write!(f, "VecParserFn"),
}
}
}
/// ## Main Methods
impl Parser {
///Initialises a new parser with the string you wish to parse
pub fn new(input_string: &str) -> Parser {
let mut output_arena: indextree::Arena<ParserElement> = indextree::Arena::new();
let output_arena_root: ParserElement = ParserElement::new();
let output_arena_node_parent_id = output_arena.new_node(output_arena_root);
let mut language_arena: indextree::Arena<ParserFunctionTypeAndParam> =
indextree::Arena::new();
let language_root: ParserFunctionTypeAndParam =
(ParserFunctionType::None, ParserFunctionParam::None);
let language_arena_node_parent_id = language_arena.new_node(language_root);
let new_parser = Parser {
input_original: input_string.to_string(),
input_remaining: input_string.to_string(),
chomp: "".to_string(),
chomping: true,
language_arena,
language_arena_node_parent_id,
output_arena,
output_arena_node_parent_id,
success: true,
display_errors: true,
};
new_parser
}
///Defines the parser to run, then runs it on the initialised parser from new
///for now it only contains a few things...
///'fn_var_assign' which itself calls sub-parsers like el_int, el_float, fn_var_sum
///'prim_eols' to allow separating the variable assignments
pub fn parse(mut self: Parser) -> Parser {
while self.success && self.input_remaining.len() > 0 {
self =
self.combi_first_success_of(&[Parser::fn_var_assign, Parser::prim_eols].to_vec());
}
self
}
///Initialises and runs the supplied parser functions (as a closure) on a supplied string
///
///### Example
///Using the parser to parse the string '= x 123' which is meant to describe assigning the value 123 to variable x
///'=' is the assign function which takes two parameters (variable name<String>, value<Integer>)
///```
///let my_parser = |p| rust_learning_parser_combinators::Parser::fn_var_assign(p);
///let string_to_parse = "= x 123";
///let parse_result = rust_learning_parser_combinators::Parser::new_and_parse(string_to_parse, my_parser);
///println!("{:?}",parse_result);
///```
///You can use a combinator to check for multiple options, e.g. the second line adds the 'sum' function taking two parameters, x and 456, and assigns that new value to x
///
///```
///let my_parser = |p| {
/// rust_learning_parser_combinators::Parser::combi_first_success_of(
/// p,
/// &[
/// rust_learning_parser_combinators::Parser::fn_var_assign,
/// rust_learning_parser_combinators::Parser::fn_var_sum,
/// ]
/// .to_vec(),
/// )
/// };
///let string_to_parse = "
///= x 123
///= x + x 456";
///let parse_result = rust_learning_parser_combinators::Parser::new_and_parse(string_to_parse, my_parser);
///println!("{:?}",parse_result);
///```
pub fn new_and_parse<F>(input_string: &str, func: F) -> Parser
where
F: Fn(Parser) -> Parser,
{
let new_parser = Parser::new(input_string);
func(new_parser)
}
pub fn new_and_parse_aliases(input_string: &str, parser_lang_string: &str) -> Parser {
//first, parse the parser_lang_string to get the series of your parser instructions
let mut parser_lang: Parser = Parser::new(parser_lang_string);
while parser_lang.success && parser_lang.input_remaining.len() > 0 {
parser_lang = parser_lang.lang_one_of_all_lang_parsers();
parser_lang
.clone()
.test_printing_functionTypeAndParam("last child added: ");
}
//second, parse the input_string using those instructions
let mut parser: Parser = Parser::new(input_string);
let language_arena = &mut parser_lang.clone().language_arena;
//let language_arena_current_parent_node_id =
// parser_lang.clone().language_arena_node_parent_id;
let list_of_nodes: Vec<&indextree::Node<ParserFunctionTypeAndParam>> = language_arena
.iter()
//exclude removed items
.filter(|n| !n.is_removed())
//exclude root item
.filter(|n| {
let (f, p) = n.get();
match (f, p) {
(ParserFunctionType::None, ParserFunctionParam::None) => false,
_ => true,
}
})
.collect();
for node in list_of_nodes.clone() {
let (f, param_option) = node.get();
println!(
"{:?} {:?} {:?}",
list_of_nodes.clone().len(),
f,
param_option
);
match f {
ParserFunctionType::TakesParser(fun) => {
parser = fun(parser);
}
ParserFunctionType::TakesParserWord(fun) => match param_option {
ParserFunctionParam::String(string) => {
parser = fun(parser, string.as_str());
}
_ => (),
},
_ => (),
}
}
parser
}
pub fn display_error(self: &Parser, from: &str) {
//only display a short 100 char excerpt of remaining string
let mut length = self.input_remaining.len();
let position = self.input_original.len() - length;
if length > 100 {
length = 100;
}
if self.display_errors {
println!(
"\r\n{}\r\n{} at {} position:{}\r\n{}\r\n{}\r\n{:?}\r\n{}",
"vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"
.yellow(),
"Parser Error".yellow(),
from.red(),
position,
self.input_remaining.get(0..length).unwrap(),
"Current Parser state looks like this:".yellow(),
self,
"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
.yellow(),
);
}
}
///Clears the current `chomp` value back to an empty string
pub fn chomp_clear(mut self: Parser) -> Parser {
self.chomp = "".to_string();
self
}
pub fn get_parser_function_by_name(name: String) -> ParserFunction {
match name.as_str() {
">" => Parser::lang_prim_next,
"\"" => Parser::lang_prim_quote,
//TODO handle prim_word
"@" => Parser::lang_prim_char,
"#" => Parser::lang_prim_digit,
"," => Parser::lang_prim_eols,
"." => Parser::lang_prim_eof,
";" => Parser::lang_prim_eols_or_eof,
//TODO handle combinators
//TODO handle elements
_ => Parser::lang_prim_eof,
}
}
}
///### Arena Helpers
///wrapping basic functions for indextree
impl Parser {
///Finds a variable by name if the parser created it already<br/>
///Option...<br/>
///Some(index of the found variable within the parser.output, and the variable[ParserElement](struct.ParserElement.html)<br/>
///None
pub fn output_arena_find_element_var(
mut self: Parser,
var_name: &str,
) -> Option<ParserElement> {
let arena = &mut self.output_arena;
//there should only be one or zero
let list_of_nodes_with_var_name: Vec<&indextree::Node<ParserElement>> = arena
.iter()
.filter(|x| x.get().var_name == Some(var_name.to_string()))
.collect();
if list_of_nodes_with_var_name.len() > 0 {
Some(list_of_nodes_with_var_name[0].get().clone())
} else {
None
}
}
pub fn output_arena_append_element(mut self: Parser, el: ParserElement) -> Parser {
let arena = &mut self.output_arena;
let new_node = arena.new_node(el);
self.output_arena_node_parent_id.append(new_node, arena);
self
}
pub fn language_arena_append_functionTypeAndParam(
mut self: Parser,
fp: ParserFunctionTypeAndParam,
) -> Parser {
let arena = &mut self.language_arena;
let new_node = arena.new_node(fp);
self.language_arena_node_parent_id.append(new_node, arena);
self
}
pub fn test_printing_functionTypeAndParam(mut self: Parser, s: &str) {
let test_language_arena = &mut self.language_arena;
let last_child = self
.clone()
.language_arena_get_last_child_functionTypeAndParam();
println!("####{} {:?}", s, last_child);
}
pub fn output_arena_get_current_parent_element(mut self: Parser) -> Option<ParserElement> {
let arena = &mut self.output_arena;
let output_arena_current_parent_node_id = self.output_arena_node_parent_id;
let parent_option = arena.get(output_arena_current_parent_node_id);
match parent_option {
Some(parent) => Some(parent.get().clone()),
_ => None,
}
//parent_option.get()
}
pub fn output_arena_get_last_child_element(mut self: Parser) -> Option<ParserElement> {
let arena = &mut self.output_arena;
let output_arena_current_parent_node_id = self.output_arena_node_parent_id;
//get parent node
let parent_option = arena.get(output_arena_current_parent_node_id);
match parent_option {
Some(parent) => {
//get last child id
let last_child_id_option = parent.last_child();
match last_child_id_option {
Some(last_child_id) => {
//get last child node
let child_option = arena.get(last_child_id);
match child_option {
Some(child) => Some(child.get().clone()),
_ => None,
}
}
_ => None,
}
}
_ => None,
}
//parent_option.get()
}
pub fn language_arena_get_last_child_functionTypeAndParam(
mut self: Parser,
) -> Option<ParserFunctionTypeAndParam> {
let arena = &mut self.language_arena;
let language_arena_current_parent_node_id = self.language_arena_node_parent_id;
//get parent node
let parent_option = arena.get(language_arena_current_parent_node_id);
match parent_option {
Some(parent) => {
//get last child id
let last_child_id_option = parent.last_child();
match last_child_id_option {
Some(last_child_id) => {
//get last child node
let child_option = arena.get(last_child_id);
match child_option {
Some(child) => Some(child.get().clone()),
_ => None,
}
}
_ => None,
}
}
_ => None,
}
//parent_option.get()
}
pub fn output_arena_get_nth_last_child_element(
mut self: Parser,
index: usize,
) -> Option<ParserElement> {
let arena = &mut self.output_arena;
let output_arena_current_parent_node_id = self.output_arena_node_parent_id;
//get node_id
let node_id_option = output_arena_current_parent_node_id
.reverse_children(arena)
.nth(index);
match node_id_option {
Some(node_id) => {
//get node
let node_option = arena.get(node_id);
match node_option {
Some(node) => Some(node.get().clone()),
_ => None,
}
}
_ => None,
}
}
pub fn output_arena_remove_nth_last_child_element(mut self: Parser, index: usize) -> Parser {
let arena = &mut self.output_arena;
let output_arena_current_parent_node_id = self.output_arena_node_parent_id;
//get node_id
let node_id_option = output_arena_current_parent_node_id
.reverse_children(arena)
.nth(index);
match node_id_option {
Some(node_id) => {
//remove node
node_id.remove(arena);
self.output_arena = arena.clone();
self
}
_ => self,
}
}
}
/// ## Language Aliases
///Functions to help decode a string of aliases of the parser functions of this module
impl Parser {
pub fn lang_one_of_all_lang_parsers(self: Parser) -> Parser {
self.combi_first_success_of(
&[
//combinators
//Parser::lang_combi_one_or_more,
//primitives
Parser::lang_prim_word,
Parser::lang_prim_eols_or_eof,
Parser::lang_prim_eof,
Parser::lang_prim_eols,
Parser::lang_prim_quote,
Parser::lang_prim_digit,
Parser::lang_prim_char,
Parser::lang_prim_next,
]
.to_vec(),
)
}
pub fn lang_factory_takes_parser(
mut self: Parser,
word: &str,
pf: ParserFunctionTypeAndParam,
error_text: &str,
) -> Parser {
if self.success {
self = self.prim_word(word);
if self.success {
self = self.language_arena_append_functionTypeAndParam(pf);
self
} else {
self.display_error(error_text);
self
}
} else {
self
}
}
//Primitives
pub fn lang_prim_next(self: Parser) -> Parser {
Parser::lang_factory_takes_parser(
self,
">",
(
ParserFunctionType::TakesParser(Parser::prim_next),
ParserFunctionParam::None,
),
"lang_prim_next",
)
}
pub fn lang_prim_quote(self: Parser) -> Parser {
Parser::lang_factory_takes_parser(
self,
"\"",
(
ParserFunctionType::TakesParser(Parser::prim_quote),
ParserFunctionParam::None,
),
"lang_prim_quote",
)
}
pub fn lang_prim_char(self: Parser) -> Parser {
Parser::lang_factory_takes_parser(
self,
"@",
(
ParserFunctionType::TakesParser(Parser::prim_char),
ParserFunctionParam::None,
),
"lang_prim_char",
)
}
pub fn lang_prim_digit(self: Parser) -> Parser {
Parser::lang_factory_takes_parser(
self,
"#",
(
ParserFunctionType::TakesParser(Parser::prim_digit),
ParserFunctionParam::None,
),
"lang_prim_digit",
)
}
pub fn lang_prim_eols(self: Parser) -> Parser {
Parser::lang_factory_takes_parser(
self,
",",
(
ParserFunctionType::TakesParser(Parser::prim_eols),
ParserFunctionParam::None,
),
"lang_prim_eols",
)
}
pub fn lang_prim_eof(self: Parser) -> Parser {
Parser::lang_factory_takes_parser(
self,
".",
(
ParserFunctionType::TakesParser(Parser::prim_eof),
ParserFunctionParam::None,
),
"lang_prim_eof",
)
}
pub fn lang_prim_eols_or_eof(self: Parser) -> Parser {
Parser::lang_factory_takes_parser(
self,
";",
(
ParserFunctionType::TakesParser(Parser::prim_eols_or_eof),
ParserFunctionParam::None,
),
"lang_prim_eols_or_eof",
)
}
pub fn lang_prim_word(mut self: Parser) -> Parser {
if self.success {
let display_errors_previous_flag_setting = self.display_errors;
self.display_errors = false;
self = self.prim_quote_single().combi_until_first_do_second(
[Parser::prim_quote_single, Parser::prim_next].to_vec(),
);
self.display_errors = display_errors_previous_flag_setting;
if self.success {
let fp = (
ParserFunctionType::TakesParserWord(Parser::prim_word),
ParserFunctionParam::String(self.clone().chomp),
);
self = self.language_arena_append_functionTypeAndParam(fp);
self = self.chomp_clear();
self
} else {
self.display_error("lang_prim_word");
self
}
} else {
self
}
}
//Combinators
pub fn lang_combi_one_or_more(mut self: Parser) -> Parser {
if self.success {
let display_errors_previous_flag_setting = self.display_errors;
self.display_errors = false;
self = self
.prim_word("1+")
.combi_zero_or_more_of(Parser::prim_space)
.combi_until_first_do_second([Parser::prim_space, Parser::prim_next].to_vec());
self.display_errors = display_errors_previous_flag_setting;
if self.success {
//TODO can't just do this because the chomp string, might be another nested combi...
//ParserFunctionParam::ParserFn(Parser::get_parser_function_by_name(
// self.clone().chomp,
//)),
//Have to call the parser on that string
//But it's getting a bit manual - need to look at a more nested AST approach?
//TODO replace with output_arena_append_element
/*self.language_arena.push((
ParserFunctionType::TakesParserFn(Parser::combi_one_or_more_of),
ParserFunctionParam::ParserFn(Parser::get_parser_function_by_name(
self.clone().chomp,
)),
));*/
self = self.chomp_clear();
self
} else {
self.display_error("lang_combi_one_or_more");
self
}
} else {
self
}
}
}
/// ## Parser primitives
/// they don't Panic at an error - but can return an error in case you need to capture that for parsing in a [Parser Combinator](#parser-combinators)
impl Parser {
///Matches whatever the next character is, fails if eof
pub fn prim_next(mut self: Parser) -> Parser {
if self.success {
self = self.prim_eof();
if self.success {
self.success = false;
self
} else {
match self.clone().input_remaining.graphemes(true).next() {
Some(next) => {
self.input_remaining = self.input_remaining[next.len()..].to_string();
if self.chomping {
self.chomp += next;
};
self.success = true;
self
}
_ => {
self.display_error("prim_next");
self.success = false;
self
}
}
}
} else {
self
}
}
pub fn prim_space(mut self: Parser) -> Parser {
let chomping_previous_flag_setting = self.chomping;
self.chomping = false;
self = self.prim_word(" ");
self.chomping = chomping_previous_flag_setting;
self
}
pub fn prim_quote(mut self: Parser) -> Parser {
let chomping_previous_flag_setting = self.chomping;
self.chomping = false;
self = self.prim_word("\"");
self.chomping = chomping_previous_flag_setting;
self
}
pub fn prim_quote_single(mut self: Parser) -> Parser {
let chomping_previous_flag_setting = self.chomping;
self.chomping = false;
self = self.prim_word("'");
self.chomping = chomping_previous_flag_setting;
self
}
/// Matches any series of [prim_car](#method.prim_char) in the supplied 'expected' string
/// Always succeeds
pub fn prim_word(mut self: Parser, expected: &str) -> Parser {
if self.success {
match self.clone().input_remaining.get(0..expected.len()) {
Some(next) if next == expected => {
self.input_remaining = self.input_remaining[expected.len()..].to_string();
if self.chomping {
self.chomp += next;
};
self.success = true;
self
}
_ => {
self.success = false;
self
}
}
} else {
self
}
}
/// Matches any unicode character except whitespace ' '
pub fn prim_char(mut self: Parser) -> Parser {
if self.success {
match self.clone().input_remaining.graphemes(true).next() {
Some(next) => {
if next == " " {
self.display_error("prim_char");
self.success = false;
self
} else {
self.input_remaining = self.input_remaining[next.len()..].to_string();
if self.chomping {
self.chomp += next;
};
self.success = true;
self
}
}
_ => {
self.success = false;
self.display_error("prim_char");
self
}
}
} else {
self.display_error("prim_char");
self
}
}
/// Matches a single digit 0,1,2,3,4,5,6,7,8,9
pub fn prim_digit(mut self: Parser) -> Parser {
if self.success {
match self.input_remaining.chars().next() {
Some(next) if next.is_digit(10) => {
self.input_remaining = self.input_remaining[next.len_utf8()..].to_string();
if self.chomping {
self.chomp += next.encode_utf8(&mut [0; 1]);
};
self.success = true;
self
}
_ => {
self.success = false;
self.display_error("prim_digit");
self
}
}
} else {
self.display_error("prim_digit");
self
}
}
/// Matches [a combination of one or more of](#method.combi_one_or_more_of) a single \r\n or \n
pub fn prim_eols(mut self: Parser) -> Parser {
if self.success {
let newline1 = self
.clone()
.combi_one_or_more_of(|s| Parser::prim_word(s, "\r\n"));
let newline2 = self
.clone()
.combi_one_or_more_of(|s| Parser::prim_word(s, "\n"));
if newline1.success {
newline1
} else if newline2.success {
newline2
} else {
self.success = false;
self.display_error("prim_eols");
self
}
} else {
self.display_error("prim_eols");
self
}
}
///Matches if you've reached the end of the parsed string, i.e. check for an empty string at this stage of the parser...
pub fn prim_eof(mut self: Parser) -> Parser {
if self.success && self.input_remaining.len() == 0 {
self
} else {
self.success = false;
self.display_error("prim_eof");
self
}
}
///Matches either (prim_eolss)[#method.prim_eolss] or (prim_eof)[#method.prim_eof]
pub fn prim_eols_or_eof(mut self: Parser) -> Parser {
if self.success {
let display_errors_previous_flag_setting = self.display_errors;
self.display_errors = false;
self = self.combi_first_success_of(&[Parser::prim_eols, Parser::prim_eof].to_vec());
if self.success {
self.display_errors = display_errors_previous_flag_setting;
self
} else {
self.display_error("prim_eols_or_eof");
self.display_errors = display_errors_previous_flag_setting;
self
}
} else {
self
}
}
}
/// ## Parser combinators
/// they will (TODO) Panic at an error - used to combine multiple [Parser primitives](#parser-primitives) or other [Parser combinators](#parser-combinators)
impl Parser {
///Matches either one, or multiple of any one parser or combinator of parsers
pub fn combi_one_or_more_of<F>(mut self: Parser, func: F) -> Parser
where
F: Fn(Parser) -> Parser,
{
if self.success {
let chomp = self.clone().chomp;
let display_errors_previous_flag_setting = self.display_errors;
self.display_errors = false;
while self.success {
self = func(self);
}
self.display_errors = display_errors_previous_flag_setting;
if self.chomp == chomp {
self.display_error("combi_one_or_more_of");
self.success = false;
self
} else {
self.success = true;
self
}
} else {
self
}
}
///Matches either zero, one or multiple of any [Parser primitives](#parser-primitives) or other [Parser combinators](#parser-combinators).<br />
///Beware, it will always succeed!
pub fn combi_zero_or_more_of<F>(mut self: Parser, func: F) -> Parser
where
F: Fn(Parser) -> Parser,
{
if self.success {
let display_errors_previous_flag_setting = self.display_errors;
self.display_errors = false;
while self.success {
self = func(self)
}
self.display_errors = display_errors_previous_flag_setting;
self.success = true;
self
} else {
self
}
}
///Matches either zero, one or multiple of any [Parser primitives](#parser-primitives) or other [Parser combinators](#parser-combinators)<br />
///until it reaches the second supplied [Parser primitives](#parser-primitives) or other [Parser combinators](#parser-combinators)
pub fn combi_until_first_do_second<F>(mut self: Parser, first_and_second: Vec<F>) -> Parser
where
F: Fn(Parser) -> Parser,
{
if self.success {
let display_errors_previous_flag_setting = self.display_errors;
self.display_errors = false;
while self.success {
self = Parser::combi_first_success_of(self, &first_and_second);
}
self.display_errors = display_errors_previous_flag_setting;
self.success = true;
self
} else {
self
}
}
///Matches either one or zero of any [Parser primitives](#parser-primitives) or other [Parser combinators](#parser-combinators).<br />
///Beware, it will always succeed!
pub fn combi_optional<F>(mut self: Parser, func: F) -> Parser
where
F: Fn(Parser) -> Parser,
{
if self.success {
self = func(self);
self.success = true;
self
} else {
self.display_error("combi_optional");
self
}
}
///Tries to match one of the parsers supplied in an array (vec) of [Parser primitives](#parser-primitives) or other [Parser combinators](#parser-combinators).
///
///It matches in the order supplied
pub fn combi_first_success_of<F>(mut self: Parser, funcs: &Vec<F>) -> Parser
where
F: Fn(Parser) -> Parser,
{
if self.success {
for func in funcs {
let mut new_self = self.clone();
let display_errors_previous_flag_setting = self.display_errors;
new_self.display_errors = false;
new_self = func(new_self);
new_self.display_errors = display_errors_previous_flag_setting;
if new_self.success {
return new_self;
}
}
self.display_error("combi_first_success_of");
self.success = false;
return self;
} else {
return self;
};
}
}
/// ## Parser Elements
impl Parser {
///string, e.g. "123" or "The quick brown fox jumps over the lazy dog"
pub fn el_str(mut self: Parser) -> Parser {
if self.success {
let display_errors_previous_flag_setting = self.display_errors;
self.display_errors = false;
self = self
.prim_quote()
.combi_until_first_do_second([Parser::prim_quote, Parser::prim_next].to_vec());
self.display_errors = display_errors_previous_flag_setting;
if self.success {
let mut el = ParserElement::new();
let val = self.clone().chomp;
el.el_type = Some(ParserElementType::Str);
el.string = Some(val);
self = self.output_arena_append_element(el);
self = self.chomp_clear();
self
} else {
self.display_error("el_str");
self
}
} else {
self
}
}
///integer number, e.g. 12 or -123456
pub fn el_int(mut self: Parser) -> Parser {
if self.success {
let display_errors_previous_flag_setting = self.display_errors;
self.display_errors = false;
self = self
.combi_optional(|s: Parser| Parser::prim_word(s, "-"))
.combi_one_or_more_of(Parser::prim_digit);
self.display_errors = display_errors_previous_flag_setting;
if self.success {
let mut el = ParserElement::new();
let val = self.clone().chomp.parse().unwrap();
el.el_type = Some(ParserElementType::Int64);
el.int64 = Some(val);
self = self.output_arena_append_element(el);
self = self.chomp_clear();
self
} else {
self.display_error("el_int");
self
}
} else {
self
}
}
///floating point number, e.g. 12.34 or -123.45
pub fn el_float(mut self: Parser) -> Parser {
if self.success {
let display_errors_previous_flag_setting = self.display_errors;
self.display_errors = false;
self = self
.combi_optional(|s: Parser| Parser::prim_word(s, "-"))
.combi_one_or_more_of(Parser::prim_digit)
.prim_word(".")
.combi_one_or_more_of(Parser::prim_digit);
self.display_errors = display_errors_previous_flag_setting;
if self.success {
let mut el = ParserElement::new();
let val = self.clone().chomp.parse().unwrap();
el.el_type = Some(ParserElementType::Float64);
el.float64 = Some(val);
self = self.output_arena_append_element(el);
self = self.chomp_clear();
self
} else {
self.display_error("el_float");
self
}
} else {
self
}
}
///el_var name of prim_chars followed by a space, e.g. "x" or "lö̲ng_variablé_name"
pub fn el_var(mut self: Parser) -> Parser {
self = self.combi_one_or_more_of(Parser::prim_char).prim_word(" ");
if self.success {
let display_errors_previous_flag_setting = self.display_errors;
self.display_errors = false;
let mut el = ParserElement::new();
let chomp = self.clone().chomp;
let el_var = chomp[..(chomp.len() - 1)].to_string();
el.el_type = Some(ParserElementType::Var);
el.var_name = Some(el_var);
self = self.output_arena_append_element(el);
//println!("{:?}", el);
self = self.chomp_clear();
self.display_errors = display_errors_previous_flag_setting;
self
} else {
self.display_error("el_var");
self
}
}
}
/// ## Parser Functions
impl Parser {
///equals sign, el_var name, value (test using el_int for now), e.g. "= x 1" (x equals 1)
pub fn fn_var_assign(self: Parser) -> Parser {
let mut temp_self = self
.clone()
.prim_word("= ")
.chomp_clear()
.el_var()
.combi_first_success_of(
&[
Parser::fn_var_sum,
//el_float first so the number before . is not thought of as an el_int
Parser::el_float,
Parser::el_int,
]
.to_vec(),
)
.prim_eols_or_eof();
if temp_self.success {
//get the previously parsed variable name, and variable value
let variable_el_option = temp_self.clone().output_arena_get_nth_last_child_element(1);
let value_el_option = temp_self.clone().output_arena_get_nth_last_child_element(0);
//combine them into one element
match (variable_el_option, value_el_option) {
(Some(variable_el), Some(mut value_el)) => {
value_el.el_type = Some(ParserElementType::Var);
value_el.var_name = variable_el.var_name;
//remove those two last elements, and replace them with the combined element
temp_self = temp_self.output_arena_remove_nth_last_child_element(0);
temp_self = temp_self.output_arena_remove_nth_last_child_element(0);
//add combined element back into arena
temp_self = temp_self.output_arena_append_element(value_el);
temp_self = temp_self.chomp_clear();
temp_self
}
_ => {
temp_self.display_error("fn_var_assign - no variable or value found to assign");
temp_self
}
}
} else {
temp_self.display_error("fn_var_assign");
temp_self
}
}
///plus sign, value, value (both ints or both floats), e.g. "+ 1 2" (1 + 2 = 3) or "+ 1.2 3.4" (1.2 + 3.4 = 4.6)
pub fn fn_var_sum(mut self: Parser) -> Parser {
let mut original_self = self.clone();
let without_brackets = self
.clone()
.prim_word("+ ")
.chomp_clear()
.combi_first_success_of(
&[Parser::fn_var_sum, Parser::el_float, Parser::el_int].to_vec(),
)
.prim_word(" ")
.chomp_clear()
.combi_first_success_of(
&[Parser::fn_var_sum, Parser::el_float, Parser::el_int].to_vec(),
);
let with_brackets = self
.clone()
.prim_word("(+ ")
.chomp_clear()
.combi_first_success_of(
&[Parser::fn_var_sum, Parser::el_float, Parser::el_int].to_vec(),
)
.prim_word(" ")
.chomp_clear()
.combi_first_success_of(
&[Parser::fn_var_sum, Parser::el_float, Parser::el_int].to_vec(),
)
.prim_word(")");
if without_brackets.success {
self = without_brackets;
} else if with_brackets.success {
self = with_brackets;
} else {
original_self.display_error("fn_var_sum");
original_self.success = false;
return original_self;
}
let mut el = ParserElement::new();
//check both values exist
let variable2_el_option = self.clone().output_arena_get_nth_last_child_element(0);
let variable1_el_option = self.clone().output_arena_get_nth_last_child_element(1);
match (variable1_el_option, variable2_el_option) {
(Some(variable1_el), Some(variable2_el)) => {
//check both values have the same element type
match (variable1_el.el_type, variable2_el.el_type) {
(Some(el1_type), Some(el2_type)) => {
if el1_type == el2_type {
match el1_type {
//if it's an el_int set the int64 of the first element to be the sum of the 2 ints
//(because we will remove the second element)
ParserElementType::Int64 => {
match (variable1_el.int64, variable2_el.int64) {
(Some(val1), Some(val2)) => {
el.el_type = Some(ParserElementType::Int64);
el.int64 = Some(val1 + val2);
}
(_, _) => {
original_self.success = false;
original_self //original_self
.display_error("fn_var_sum - can't find two Int64 values");
return original_self;
}
}
}
//can't sum strings
ParserElementType::Str => {
original_self.success = false;
original_self //original_self
.display_error("fn_var_sum - can't sum strings");
return original_self;
}
//if it's an el_float set the Float64 of the first element to be the sum of the 2 floats
//(because we will remove the second element)
_ => {
match (variable1_el.float64, variable2_el.float64) {
(Some(val1), Some(val2)) => {
el.el_type = Some(ParserElementType::Float64);
el.float64 = Some(val1 + val2);
}
(_, _) => {
original_self.success = false;
original_self //original_self
.display_error("fn_var_sum - can't find two Float64 values");
return original_self;
}
}
}
}
//remove the last 2 value elements
self = self.output_arena_remove_nth_last_child_element(0);
self = self.output_arena_remove_nth_last_child_element(0);
//add combined (sum) element back into arena
self = self.output_arena_append_element(el);
self = self.chomp_clear();
self
} else {
self
}
}
(_, _) => self,
}
}
_ => {
original_self.display_error("fn_var_sum - can't find either or both values");
original_self.success = false;
original_self
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
///TODO Need a way to test equlity of expected_result
fn test_lang_one_of_all_lang_parsers() {
let language_string = ">";
let _expected_result = (
ParserFunctionType::TakesParser(Parser::prim_next),
ParserFunctionParam::None,
);
let p = Parser::new(language_string);
let result = Parser::lang_one_of_all_lang_parsers(p);
assert_eq!(result.input_original, language_string);
}
#[test]
fn test_get_parser_function_by_name() {
assert_eq!(
Parser::get_parser_function_by_name(">".to_string()) == Parser::lang_prim_next,
true
);
}
//================================================================================
//Start Language Aliases Testing
//================================================================================
//lang_combinators
#[test]
fn test_lang_combi_one_or_more() {
//only combis of prims so far
let input_str = "aaaa";
let language_string = "1+a";
let result = Parser::new_and_parse_aliases(input_str, language_string);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "aaaa");
assert_eq!(result.success, true);
}
#[test]
fn test_lang_prim_word() {
let input_str = "test";
let language_string = "'test'";
let result = Parser::new_and_parse_aliases(input_str, language_string);
assert_eq!(result.input_original, input_str);
//assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "test");
assert_eq!(result.success, true);
}
#[test]
fn test_lang_prim_eols_or_eof() {
let mut input_str = "\r\n\r\n\r\n!\n";
let mut language_string = ",@,";
let mut result = Parser::new_and_parse_aliases(input_str, language_string);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "\r\n\r\n\r\n!\n");
assert_eq!(result.success, true);
input_str = "a";
language_string = "@.";
result = Parser::new_and_parse_aliases(input_str, language_string);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "a");
assert_eq!(result.success, true);
}
#[test]
fn test_lang_prim_eof() {
let input_str = "a";
let language_string = "@.";
let result = Parser::new_and_parse_aliases(input_str, language_string);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "a");
assert_eq!(result.success, true);
}
#[test]
fn test_lang_prim_eols() {
let input_str = "\r\n\r\n\r\n!\n";
let language_string = ",@,";
let result = Parser::new_and_parse_aliases(input_str, language_string);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "\r\n\r\n\r\n!\n");
assert_eq!(result.success, true);
}
#[test]
fn test_lang_prim_digit() {
let input_str = "0123456789";
let language_string = "##########";
let result = Parser::new_and_parse_aliases(input_str, language_string);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "0123456789");
assert_eq!(result.success, true);
}
#[test]
fn test_lang_prim_char() {
let input_str = "+%!";
let language_string = "@@@";
let result = Parser::new_and_parse_aliases(input_str, language_string);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "+%!");
assert_eq!(result.success, true);
}
#[test]
fn test_lang_prim_quote() {
let input_str = "\"\"\"";
let language_string = "\"\"\"";
let result = Parser::new_and_parse_aliases(input_str, language_string);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
}
#[test]
fn test_lang_prim_next() {
let input_str = "123";
let language_string = ">>>";
let result = Parser::new_and_parse_aliases(input_str, language_string);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "123");
assert_eq!(result.success, true);
}
//================================================================================
//End Language Aliases Testing
//================================================================================
#[test]
//A string
fn test_el_string() {
let input_str = "\"1234\"";
let result = Parser::new_and_parse(input_str, Parser::el_str);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "");
assert_eq!(result.output_arena.count(), 2);
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Str));
assert_eq!(el.string, Some("1234".to_string()));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
}
#[test]
//Next
fn test_prim_next() {
//Fails
let input_str = "";
let result = Parser::new_and_parse(input_str, Parser::prim_next);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "");
assert_eq!(result.success, false);
//character alpha
let input_str = "abc";
let result = Parser::new_and_parse(input_str, Parser::prim_next);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "bc");
assert_eq!(result.chomp, "a");
assert_eq!(result.success, true);
//character number
let input_str = "1bc";
let result = Parser::new_and_parse(input_str, Parser::prim_next);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "bc");
assert_eq!(result.chomp, "1");
assert_eq!(result.success, true);
//character special
let input_str = "~bc";
let result = Parser::new_and_parse(input_str, Parser::prim_next);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "bc");
assert_eq!(result.chomp, "~");
assert_eq!(result.success, true);
//character backslash
let input_str = "\\bc";
let result = Parser::new_and_parse(input_str, Parser::prim_next);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "bc");
assert_eq!(result.chomp, "\\");
assert_eq!(result.success, true);
//character unicode
let input_str = "ébc";
let result = Parser::new_and_parse(input_str, Parser::prim_next);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "bc");
assert_eq!(result.chomp, "é");
assert_eq!(result.success, true);
}
//= x + 1 2
//print x
//= y + 1.1 2.2
//print y
#[test]
fn test_run2() {
let func = |p| Parser::combi_first_success_of(p, &[Parser::fn_var_assign].to_vec());
let input_str = "= x 123";
let result = Parser::new_and_parse(input_str, func);
assert_eq!(result.input_original, input_str);
assert_eq!(result.input_remaining, "");
assert_eq!(
result
.output_arena
.iter()
.filter(|n| !n.is_removed())
.count(),
2
);
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.int64, Some(123));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
}
#[test]
fn test_variable_sum() {
//not a valid el_var sum
let mut parser = Parser::new(" + test 1");
parser.display_errors = false;
let result = parser.clone().fn_var_sum();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, " + test 1");
assert_eq!(result.chomp, "");
assert_eq!(result.success, false);
//short el_int plus short el_int, with combi_optional brackets
parser = Parser::new("(+ 1 2)");
parser.display_errors = false;
let result = parser.clone().fn_var_sum();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Int64));
assert_eq!(el.int64, Some(3));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//short el_int plus short el_int
parser = Parser::new("+ 1 2");
parser.display_errors = false;
let result = parser.clone().fn_var_sum();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Int64));
assert_eq!(el.int64, Some(3));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//long el_int plus long el_int
parser = Parser::new("+ 11111 22222");
parser.display_errors = false;
let result = parser.clone().fn_var_sum();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Int64));
assert_eq!(el.int64, Some(33333));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//long el_int plus negative long el_int
parser = Parser::new("+ 11111 -22222");
parser.display_errors = false;
let result = parser.clone().fn_var_sum();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Int64));
assert_eq!(el.int64, Some(-11111));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//short el_float plus short el_float
parser = Parser::new("+ 1.1 2.2");
parser.display_errors = false;
let result = parser.clone().fn_var_sum();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Float64));
assert_eq!(el.float64, Some(3.3000000000000003)); // yikes, floats
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//long el_float plus long el_float
parser = Parser::new("+ 11111.11111 22222.22222");
parser.display_errors = false;
let result = parser.clone().fn_var_sum();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Float64));
assert_eq!(el.float64, Some(33333.33333)); // yikes, floats
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//long el_float plus negative long el_float
parser = Parser::new("+ 11111.11111 -22222.22222");
parser.display_errors = false;
let result = parser.clone().fn_var_sum();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Float64));
assert_eq!(el.float64, Some(-11111.11111)); // yikes, floats
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
}
#[test]
fn test_multiple_variable_assign() {
let input_string = "= x + 1 2\r\n= y + 3 4\r\n= z + 5.0 6.0";
let mut parser = Parser::new(input_string);
//parser.display_errors = false;
let result = parser.parse();
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, "");
let mut el_option = result.clone().output_arena_get_nth_last_child_element(2);
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.int64, Some(3));
}
_ => assert!(true, false),
}
el_option = result.clone().output_arena_get_nth_last_child_element(1);
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("y".to_string()));
assert_eq!(el.int64, Some(7));
}
_ => assert!(true, false),
}
el_option = result.clone().output_arena_get_nth_last_child_element(0);
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("z".to_string()));
assert_eq!(el.float64, Some(11.0));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//don't create new var_name if already exists, update it
parser = Parser::new("= x + 1 2\r\n= x + 3 4");
parser.display_errors = false;
let result = parser.clone().parse();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.int64, Some(7));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
}
#[test]
fn test_variable_assign() {
//not a el_var assignment
let mut input_string = " = x 1";
let mut result = Parser::new_and_parse(input_string, Parser::fn_var_assign);
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, " = x 1");
assert_eq!(result.chomp, "");
assert_eq!(result.success, false);
//"= x (+ 1 (+ 2 (+ 3 4)))", i.e. x = 1 + (2 + (3 + 4))
//as below with brackets notation
input_string = "= x (+ 1 (+ 2 (+ 3 4)))";
result = Parser::new_and_parse(input_string, Parser::fn_var_assign);
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.int64, Some(10));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//"= x + 1 + 2 + 3 4", i.e. x = 1 + (2 + (3 + 4))
//short name el_var assignment to sum of 2 short ints, where the second is 2 nested sums of 2 short ints
input_string = "= x + 1 + 2 + 3 4";
result = Parser::new_and_parse(input_string, Parser::fn_var_assign);
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.int64, Some(10));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//"= x + + 1 2 + 3 4", i.e. x = (1 + 2) + (3 + 4))
//short name el_var assignment to sum of 2 short ints, where the second is 2 nested sums of 2 short ints, different format
input_string = "= x + + 1 2 + 3 4";
result = Parser::new_and_parse(input_string, Parser::fn_var_assign);
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.int64, Some(10));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//"= x + 1 + 2 3", i.e. x = 1 + (2 + 3)
//short name el_var assignment to sum of 2 short ints, where the second is a sum of 2 short ints
input_string = "= x + 1 + 2 3";
result = Parser::new_and_parse(input_string, Parser::fn_var_assign);
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.int64, Some(6));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//short name el_var assignment to sum of 2 short ints
input_string = "= x + 1 2";
result = Parser::new_and_parse(input_string, Parser::fn_var_assign);
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.int64, Some(3));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//short name el_var assignment to sum of 2 long floats
input_string = "= x + 11111.11111 22222.22222";
result = Parser::new_and_parse(input_string, Parser::fn_var_assign);
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.float64, Some(33333.33333));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//short name el_var assignment to short el_int
input_string = "= x 1";
result = Parser::new_and_parse(input_string, Parser::fn_var_assign);
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.int64, Some(1));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//short name el_var assignment to short el_int with newlines
input_string = "= x 1\r\n\r\n\r\n";
result = Parser::new_and_parse(input_string, Parser::fn_var_assign);
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.int64, Some(1));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//long name el_var with grapheme assignment to long negative el_int
input_string = "= éxample_long_variable_name -123456";
result = Parser::new_and_parse(input_string, Parser::fn_var_assign);
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("éxample_long_variable_name".to_string()));
assert_eq!(el.int64, Some(-123456));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//short name el_var assignment to short el_float
input_string = "= x 1.2";
result = Parser::new_and_parse(input_string, Parser::fn_var_assign);
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.float64, Some(1.2));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//short name el_var assignment to long negative el_float
input_string = "= x -11111.22222";
result = Parser::new_and_parse(input_string, Parser::fn_var_assign);
assert_eq!(result.input_original, input_string);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
assert_eq!(el.float64, Some(-11111.22222));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
}
#[test]
fn test_variable() {
//not a el_var
let mut parser = Parser::new(" x = 1");
parser.display_errors = false;
let result = parser.clone().el_var();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, " x = 1");
assert_eq!(result.chomp, "");
assert_eq!(result.success, false);
//short name el_var
parser = Parser::new("x = 1");
parser.display_errors = false;
let result = parser.clone().el_var();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "= 1");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("x".to_string()));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//long name el_var with grapheme
parser = Parser::new("éxample_long_variable_name = 123.45");
parser.display_errors = false;
let result = parser.clone().el_var();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "= 123.45");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Var));
assert_eq!(el.var_name, Some("éxample_long_variable_name".to_string()));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
}
#[test]
fn test_float() {
//not a el_float
let mut parser = Parser::new("a123.456");
parser.display_errors = false;
let result = parser.clone().el_float();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "a123.456");
assert_eq!(result.chomp, "");
assert_eq!(result.success, false);
//positive small el_float
parser = Parser::new("12.34");
parser.display_errors = false;
let result = parser.clone().el_float();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Float64));
assert_eq!(el.float64, Some(12.34));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//positive large el_float
parser = Parser::new("123456.78");
parser.display_errors = false;
let result = parser.clone().el_float();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Float64));
assert_eq!(el.float64, Some(123456.78));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//negative el_float
parser = Parser::new("-123456.78");
parser.display_errors = false;
let result = parser.clone().el_float();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Float64));
assert_eq!(el.float64, Some(-123456.78));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
}
#[test]
fn test_int() {
//not an el_int
let mut parser = Parser::new("a123");
parser.display_errors = false;
let result = parser.clone().el_int();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "a123");
assert_eq!(result.chomp, "");
assert_eq!(result.success, false);
//positive small el_int
parser = Parser::new("12");
parser.display_errors = false;
let result = parser.clone().el_int();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Int64));
assert_eq!(el.int64, Some(12));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//positive large el_int
parser = Parser::new("123456");
parser.display_errors = false;
let result = parser.clone().el_int();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Int64));
assert_eq!(el.int64, Some(123456));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//negative el_int
parser = Parser::new("-123456");
parser.display_errors = false;
let result = parser.clone().el_int();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
let el_option = result.clone().output_arena_get_last_child_element();
match el_option {
Some(el) => {
assert_eq!(el.el_type, Some(ParserElementType::Int64));
assert_eq!(el.int64, Some(-123456));
}
_ => assert!(true, false),
}
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
}
#[test]
fn test_combi_optional() {
let mut parser = Parser::new("a123Test");
parser.display_errors = false;
let result = parser.clone().combi_optional(Parser::prim_char);
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "123Test");
assert_eq!(result.chomp, "a");
assert_eq!(result.success, true);
parser = Parser::new("a123Test");
parser.display_errors = false;
let result = parser.clone().combi_zero_or_more_of(Parser::prim_digit);
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "a123Test");
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
}
#[test]
fn test_combi_zero_or_more_of() {
let mut parser = Parser::new("a123Test");
parser.display_errors = false;
let result = parser.clone().combi_zero_or_more_of(Parser::prim_digit);
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "a123Test");
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
parser = Parser::new("123Test");
parser.display_errors = false;
let result = parser.clone().combi_zero_or_more_of(Parser::prim_digit);
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "Test");
assert_eq!(result.chomp, "123");
assert_eq!(result.success, true);
}
#[test]
fn test_combi_one_or_more_of() {
let mut parser = Parser::new("a123Test");
parser.display_errors = false;
let result = parser.clone().combi_one_or_more_of(Parser::prim_digit);
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "a123Test");
assert_eq!(result.chomp, "");
assert_eq!(result.success, false);
parser = Parser::new("123Test");
parser.display_errors = false;
let result = parser.clone().combi_one_or_more_of(Parser::prim_digit);
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "Test");
assert_eq!(result.chomp, "123");
assert_eq!(result.success, true);
}
#[test]
fn test_multiple_parsers() {
let mut parser = Parser::new("1Test");
parser.display_errors = false;
let result = parser.clone().prim_digit().prim_word("Te");
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "st");
assert_eq!(result.chomp, "1Te");
assert_eq!(result.success, true);
}
#[test]
fn test_prim_eof_or_eol() {
//not eof or eol
let mut parser = Parser::new("1");
parser.display_errors = false;
let result = parser.clone().prim_eols_or_eof();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "1");
assert_eq!(result.chomp, "");
assert_eq!(result.success, false);
//eof
let mut parser = Parser::new("");
parser.display_errors = false;
let result = parser.clone().prim_eols_or_eof();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
//single eol1
let mut parser = Parser::new("\n");
parser.display_errors = false;
let result = parser.clone().prim_eols_or_eof();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "\n");
assert_eq!(result.success, true);
//single eol2
let mut parser = Parser::new("\r\n");
parser.display_errors = false;
let result = parser.clone().prim_eols_or_eof();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "\r\n");
assert_eq!(result.success, true);
//multiple eol1
let mut parser = Parser::new("\n\n\n\n");
parser.display_errors = false;
let result = parser.clone().prim_eols_or_eof();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "\n\n\n\n");
assert_eq!(result.success, true);
//multiple eol2
let mut parser = Parser::new("\r\n\r\n\r\n\r\n");
parser.display_errors = false;
let result = parser.clone().prim_eols_or_eof();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "\r\n\r\n\r\n\r\n");
assert_eq!(result.success, true);
}
#[test]
fn test_prim_eof() {
//not eof
let mut parser = Parser::new("1");
parser.display_errors = false;
let result = parser.clone().prim_eof();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "1");
assert_eq!(result.chomp, "");
assert_eq!(result.success, false);
//eof
let mut parser = Parser::new("");
parser.display_errors = false;
let result = parser.clone().prim_eof();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "");
assert_eq!(result.success, true);
}
#[test]
fn test_prim_eols() {
//not an eol
let mut parser = Parser::new("1");
parser.display_errors = false;
let result = parser.clone().prim_eols();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "1");
assert_eq!(result.chomp, "");
assert_eq!(result.success, false);
//single eol1
let mut parser = Parser::new("\n");
parser.display_errors = false;
let result = parser.clone().prim_eols();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "\n");
assert_eq!(result.success, true);
//single eol2
let mut parser = Parser::new("\r\n");
parser.display_errors = false;
let result = parser.clone().prim_eols();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "\r\n");
assert_eq!(result.success, true);
//multiple eol1
let mut parser = Parser::new("\n\n\n\n");
parser.display_errors = false;
let result = parser.clone().prim_eols();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "\n\n\n\n");
assert_eq!(result.success, true);
//multiple eol2
let mut parser = Parser::new("\r\n\r\n\r\n\r\n");
parser.display_errors = false;
let result = parser.clone().prim_eols();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "\r\n\r\n\r\n\r\n");
assert_eq!(result.success, true);
}
#[test]
fn test_prim_digit() {
let mut parser = Parser::new("123Test");
parser.display_errors = false;
let result = parser.clone().prim_digit().prim_digit().prim_digit();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "Test");
assert_eq!(result.chomp, "123");
assert_eq!(result.success, true);
}
#[test]
fn test_prim_char() {
//fail
let mut parser = Parser::new("Te sting 123");
parser.display_errors = false;
let result = parser
.clone()
.prim_char()
.prim_char()
.prim_char()
.prim_char();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, " sting 123");
assert_eq!(result.chomp, "Te");
assert_eq!(result.success, false);
//succeed
let mut parser = Parser::new("Testing 123");
parser.display_errors = false;
let result = parser
.clone()
.prim_char()
.prim_char()
.prim_char()
.prim_char();
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "ing 123");
assert_eq!(result.chomp, "Test");
assert_eq!(result.success, true);
}
#[test]
fn test_prim_word() {
let parser = Parser::new("Testing 123");
let result = parser
.clone()
.prim_word("Test")
.prim_word("ing")
.prim_word(" ")
.prim_word("123");
assert_eq!(result.input_original, parser.input_original);
assert_eq!(result.input_remaining, "");
assert_eq!(result.chomp, "Testing 123");
assert_eq!(result.success, true);
}
}
|
use crate::error::{GameError, GameResult};
use std::path::Path;
pub struct Filesystem {}
impl Filesystem {
pub(crate) fn new(_: FilesystemConfig) -> GameResult<Self> {
Ok(Self {})
}
pub fn read(&self, path: impl AsRef<Path>) -> GameResult<Vec<u8>> {
std::fs::read(path).map_err(|error| GameError::IoError(Box::new(error)))
}
pub fn read_to_string(&self, path: impl AsRef<Path>) -> GameResult<String> {
std::fs::read_to_string(path).map_err(|error| GameError::IoError(Box::new(error)))
}
}
#[derive(Debug, Clone)]
pub struct FilesystemConfig {}
impl FilesystemConfig {
pub fn new() -> Self {
Self {}
}
}
|
pub fn last<T>(li: &Vec<T>) -> Option<&T> {
li.last()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_last() {
let li = vec![1, 1, 2, 3, 5, 8];
assert_eq!(last(&li), Some(&8));
}
#[test]
fn test_last_empty_list() {
let li = Vec::<usize>::new();
assert_eq!(last(&li), None);
}
}
|
use std::collections::BTreeSet;
fn task1(linestring: &str) -> u32 {
let lines = linestring.lines();
let mut sum = 0;
'outer: for line in lines {
let mut words = BTreeSet::new();
for word in line.split_whitespace() {
if words.contains(word) {
continue 'outer;
}
words.insert(word);
}
sum += 1;
}
sum
}
fn task2(linestring: &str) -> u32 {
let lines = linestring.lines();
let mut sum = 0;
'outer: for line in lines {
let mut words = BTreeSet::new();
for word in line.split_whitespace() {
let mut chars: Vec<_> = word.chars().collect();
chars.sort_by(|a, b| b.cmp(a));
if words.contains(&chars) {
continue 'outer;
}
words.insert(chars);
}
sum += 1;
}
sum
}
fn main() {
let day4 = "vxjtwn vjnxtw sxibvv mmws wjvtxn icawnd rprh
fhaa qwy vqbq gsswej lxr yzl wakcige mwjrl
bhnlow huqa gtbjc gvj wrkyr jgvmhj bgs umo ikbpdto
drczdf bglmf gsx flcf ojpj kzrwrho owbkl dgrnv bggjevc
ndncqdl lncaugj mfa lncaugj skt pkssyen rsb npjzf
kdd itdyhe pvljizn cgi
jgy pyhuq eecb phwkyl oeftyu pyhuq hecxgti tpadffm jgy
zvc qdk mlmyj kybbh lgbb fvfzcer frmaxa yzgw podt dbycoii afj
zfr msn mns leqem frz
golnm ltizhd dvwv xrizqhd omegnez nan yqajse lgef
gbej rvek aehiz bgje
yej cphl jtp swe axhljo ddwk obwsq mnewiwu klddd
ipiev henods rpn qfpg gjfdgs zcpt sswab eosdhn teeil
gzje ydu oiu jzge udy sqjeoo olxej
mgn gox tcifta vzc lxry gox gox mvila qdl jipjnw dvu
hxk xhk unhdmdz yomze povrt nbww bxu qqsqc rvuk tgffy twddm
fyx fyx nzkm fyx
ymnoc zogudq yncom tqrob sidvy dfuu ccjpiej yidvs
bxebny akknwxw jeyxqvj syl cedps akknwxw akknwxw zpvnf kuoon pnkejn wqjgc
kcebrkj zmuf ueewxhi mgyepbr nleviqc dez
argavx fqguii gebohvw klnrq rkqnl goevhbw
ywqi abwi eswph nlplbl pswhe lnqx fpgk lllnpb
abpb mpkw ampey yapme xnuyj
tmuaq asd bhbs sqmbsnw wsbnqsm ydwdncn rpa vrllkh
dnltf cck djy ydj
wywwl scezo clowuz dkgqaj dohyzcp
diimshr vlmsnlj whqb dkicau ckdaiu terp kgcii npqc vvzrqzv nol
wfpxe sqf tbb ruqpcq zfgb
kajykuz tsxgtys vuz kglmgg ihnnn plyjxj rcrvo mij plyjxj jqiur
pxs hmet dwgvd mvhkvn cjxg yvid vmhnkv kwxz rfemsua wdgvd okixk
lzwxas ddtyeh ivyama crrhxdt hedytd jfw
vjfv oyd fvjv kfwlj mradbx mckseee xradmb
llga yytxyvj lstspek lstspek lstspek
fabgf wgop fabgf bvsfoaw
grqnbvo tntomdw hizg tmotdwn
mau ufkw cxfi rhehj ebe xyv rhehj acxngo arl qtl rhehj
kbkto stqjtm tpcwshj saerkrt pffj dthp pfjf axc gwmmfdw glnqtdy xmskw
veff zqm hzhxap lgwnwq twsdk mqz xbbarbv cdx fhnwt qjcji bbvbrxa
fjw eds hofskl nkbsv des hvx xyn
qzort qzort qesz rtq oonk vwzlw wapoj ifr cta
pja hvy nhjg paj smtfe fmtse
xvi tcjj xvkjtab nqftt aumijl xkd cmilegf hvsmodx uuo igmcelf mslkq
mdhezgv lelzy kzfvsqu hvmvaxw pxiqjc hvmvaxw kzfvsqu
hsicsav csshrhx znojm eapi lhmzq bbwnz seao gfk azk
pup xtgjyzy wqt ijeektl
ktwh qdegzs btj pfwzzho
xdkmdm izqtjrr iqbke vtp
fmrbpdr zpccv tmtwx tmtwx tmtwx bys
ehphfgq idd ehphfgq ehphfgq uphe hvrc jcscne nbnslqy
xzqucgj fcih fljk barz lvln hcfi azrb
cmfmclv mfgvifw rnxgn jpg bsnq wnduzj ymsdx smdxy pqomf
rlqsm qrsml emts qsmcowv scmvwqo
tshzkpa zwtpda ftsiwo nil tpawdz kjpa ptzashk
mnep sfc swjawtd vnwud gyulluw zpa kmwyvln evd btnmoi dnwe
jwq scepq redoxmw rbdzsa wlkzso kxpm bttg vxuc moxwdre ijtdd rzsabd
wpvo dsjox amuwjm pls lgwksva ctakgpl rmsjj lzwwpr zzm udg
bji obbn tmwyc afpmkxr glvrd kahhgpq rna qkxyntp vmd mloshc
ymq rtnr nxjzm pqiddrn qmy vgxw ull
mmzk ikge zhtzhs xyo qwe lll gjjm icetq qgrr mzwqa knec
kxomfck idlh xrbowo nyetbnl qskh xuwkkxe upmmmf zhvuyp
srcwyhl czgr xmhuws jueyh xcuib xhsuwm bxuic
crkueh beyxopz xpyozbe dxgadw qktmce rjropjg
lbktun imdpcp fkssp fhcpt fehho jqdnt aoewa
jmun pynzjo trs ijwcc pelf oft pcsqdxg zvql
mneaaq vjrg jidlrzz phd mvxpivd ldkhu
sao xqw nrukn gatkz quscpsx vmz oscoeb
goi wzxhb rrk aylqqcd mlcbvvf ororn heptid kdu byevr
qsj lsbieef deez vzwdx hez iwd
lmgfb keqt mqbsuis ogrr errbi xiqe xsszacp
ato hmk zfjaj kmh plxup cida dqd pfwh nkbxvpr buajw pxkrvnb
cli bdwu vrwott vowtrt grle
zisgks ciuaqr zvk tcb kvz ugmtv
oegrojm wofpwp gnaocx rweyull ellhwow dtefylf dqsz oiw varr bcirpf oxusz
oydkmib oydkmib yefts gbl gbl
sruwjk pgkrp kea gppkr zdcky cfljh
obpxbax jhpcrj slcsa lgd fborz vvpaus wsrpsws ifijuzo
rixz jwh uhdaf hoacv hdfua
kntk qprmfow kntk tbmcjx
vnqe ooyxtb ixl hdmnpn orpz ykspl xromvj kowtq wmho gquos
ynk xjjqw sut lmtub bmtlu zdo dztlk bpkuul smhpx rbczg
zals csdbe sbj dibicq kdfwwt
coyy pjddlfc lwvhyms ldjdcfp ryubz kfwst dqjrjja jtv jjjaqrd
jaexhms iqoiln ewgyr exmnrr fsr lgmyy fdofhn
pjgyn hfoz zbcnz nczbz
ovntivq vcey vdrkse giu ohyaxy ionyy fvpn yvwrgrv qta
yelpz htbk njgeyub tggh mdthzp fwyux rduqli twlhfp pnh gywif ttn
yxhsbil vplsmmx rgtq grsf lyibxhs hctnkfr awg lmloz jroy lpgb wga
kzytass szyksat tyskasz ehmhhu
jkus hwjv ymnnkk yffugg cvtnits gbl lywkn szihcn dbrbalf rxqpbqh
koyfcef wkom mwok qgjrytl
slmhry lcr slmhry lcr
mvoxbt cfkz purnsui xar ouhtc thbx
xcdifw kvvxyrj knac qmypw bou tmukqy eusgaoo bktiu
ablgnhb axumg bwpxnjp zqpc vtw ghhoxu zqpc znfpvl ghhoxu jlg ntdk
vmvc cdkhrx cvz rvxk mmcuo udpcayd lsmm gufduzt linj
mgyeqkv hqionh rgnqgz kkc qrgnzg egkmqyv topdp
koa dimwx gjxa atlfdy
uuez ueuz zeuu ezo daq
ofpaw bgomvmt mqa dexpy mbipd epyzcoa nuwrh vwly xppz qkjrleo rwhnu
wok grxk lchvtg plrzr lwaax cfeu ijapws dmkdwc cfeu
zkd hysxxip hlydw wicsvy gbwoaw dapre ktjn dzg uri
blzh hblz qgmjceg fyf
vkhpn xnc ogva pjrh cxn hkpnv
aja cldzta tdcazl lorr fwmxxh knilf ges tdhp gnlo vihrl
ucpr peair nlbmc msfg
trv ppq bmo xqd vbui yegsr xqxawu fvuz aclhspo wnan
loiq fvg kare rmgq hir rzo ossd ziw renh ygtkjys vda
xmans kio alexs ujekfl vvf ddghn
fcxvsf bjuytet zrzsobo uhn mlfzhlq bjefs
zys htlqvky plno pbcqfuf fjwc vshkxrl lonp lyzmy dqmui vyyc glad
tlc krhcter krhcter bolk tlc opryl
idcii dverl uswb wusb zgax zhbt gjsnlso yhs
cti npri rcbxjdw ollj nirp ghfvxzh
blyhug aflnrrz zudyw ccnstq cyoju jxtqoj ntuknjq gunjiwy ycuoj igac cqctns
bul yehpnw jifjrhc ifetu ufrodp hqzpeqf hdvpc qtvgxg ibb wcxsitx xztshb
xzct scetn eoaufyo jtudgkx xrpgxip lpubtq juezstc nuc hokswh obkf ipbu
nfq lwpmn qltal xnphsqs zlrgf iewtrtd mqzsob duokpy kfbqs icg
vil zjz xkqrvni uay ystq
terrrnt lnfg clm lbs ptpiy ybcuup ayzjm pqugx lmc yppit mbf
dtajh vqivg vnblt fmn qxkw stiwna pclrrr fro khu wbslnqp tjyosu
uqlehn tjuiy obt uedct bbwiq uxndqn
hiqfovy xiimca zwne ivunvjk cmctzi mxnnrx dclib xzaoq ieztkg
shpr xuorihj chuwq poadbo mhtvex gymsp iltgl sypjfua fmyh sgiv
alv nxjt txnj bhact
vjvtrex obmrxk fgigs meixbc fggsi awi rxdjpeg
ypwo oicmbdw xbpeeyj uabzj cjvutvc oicmbdw immtmks
exijri hogl epr gzdqyur xiiejr pre ihzlgzu
rlh qfhx lrh qmvrx
kogq okhd mivmivb mivmivb okhd
taekt nhjaa znbaahn iaospxy jawwf
ytdvq ghtqwud jkiig mre kzmmjxu jba nwpykc
ktyzr aczd exgadhb uinrgac izazxky yyfe
yrifb qgc lsiuapg teyelxn ugezu
wdzkc ltx fkhncb hwrecp kfbchn sfcpc hjvq
rjdjyt ahwxh nvggsmx lmz oshd xbcik powse ahhxw yhiq gxmgsnv
qdr qjnam gag qjamn kooek mqnaj
pza gml opf ilfbblu kjp luilbfb rhfrzgp ixagj ofp
yphz runy dhull bozcsgk wfxekrd akgkbz urcphc
tfyxwol lhcl npik beug
szatel yfkve yfkve lzqhs
yjzqon pcjibu bdncmcl kczuymm pbmg nyn
rerqvs aoxucwi pmstl sstawu joqu abvcchg mvgjn mslpt vhmfkr utusuh
gqbec jjpqdh yeaiavi nledfi jhzwc vyxjpf momnm vnknjs nvgjzik ipm
psirt rispt lrkgma irtsp
jbbaph xvunete gsvnr mjd ifxhpry cpsx hmuokkx vhcm yth shrrl zbhd
gfa bcmlxtf sqyanrp cugg qxfvftz pbl ujsgc jajxltm gugc oil
xjuhyg aht vmyvzhh oby oyb ybo xbybgmx
atfk qjudfzz mky tfy
nxk yzy jqgg qxgjt bevvvv efi xcbw bohc zaqlqjq
hdc qpnx ygmtqw acvoa udboxw dhc klh mwgpk xfpuri
cycgbkq skwhyf skwhyf veaqss skwhyf
jnezf jowjt vsdu uck scgxd fvopomz vfajslp
djvi epgkyqn apzd cpm owm kpwih fsr adlhqu jicp pmc
erxlmhj wqxvofi ugj ttrmtsb
omku vmrgoy tdicbje ewml dfnwbap
gpih pyt ptsmzc gmdbu rqxkqmz objm nurxjz oozbere ztxug koth
jpnl jpnl dmeh qed
intdwv ksgw qwlzhq zpd lrl mwjl dozrjwq aujbet bsnf vhqyg
eqs uot qyz xor aem kmrh mrhk jqx tsbrf
irytjab mdzm qbb kkjt gofiwo xgbovg kyeyxqn tcks tljhx
zgejy qodgah nqavvx xnigdvt
eqve bizrxq lkhz yzwxgt nwe zfe sxypkz xnssept
bxqn lkfg yfxbszo sphwifz wnj crhbq dvokzw
vzn afatwye ogzvnu vnz rfjba xtugnj kpbgly ocsjd
xrc cxr rahv yvhk khyv bed ctgbuq cmqwpqa jlbg hpj vmesvw
jbshkya dgqw lfl mzcch jxsg czcmh ifruvlw ufwrlvi xcczlol cqqchmr
rbk mhn tnmqdc sxnnn kvoa mhn sxnnn mgemob ieiyajs
cqi ghxg ghxg ghxg
uqwdxn qli gdtkngp gnptdgk udxqwn
dmcczr dnjaqc qwdta rhrbi hkdwe qdjcan peic iulaz xns
tcmppb nzq ecy sitdud nft ecy afrbf wvnc vmfpzx tcmppb cgb
plitv efnpq mjqav nrxxo izg lpitv rwbzdo rdbzwo
day dntga adtng agndt hhvtd
yrg iudsh gyr ryg
qttyeew tco flq bszw jkzftc wdh efcwnp mja rfmju
moch prkze uslzyv plhjuy kxczyq qlmm hgq
xtg ypz izy ixg bvs xlqgj xcy sepza abiylsg
wxvsxn bqag jnlzgxq ikxwa dfd plqxl xlgqnjz nuqvoyb emhodso gaqb
bzjdsm xmxkj fhuqn gauyw ntl kjxmx zcxdr vrds
ofjcc uxyzlk ofjcc ofjcc
zwosex kkvwobl cpudsmb kes zklf bayuojr otqnyr udbbs
iqpvzh ybds piovrh oivprh voprih pov sfl
upns cpeelht xboyk itb hsxdmt dnwgfbw upns fygf kwdpxzm mli dyy
djwutl sikh shki ikhs gecd jqkon trqyw
prbbdf vdp bvvfjcg ydqb muxygg
vhpurzn psemqe xwqfk hrvonxu nxkxacq
xicmhss tnpja qiad woipfy uvadcq usljh hzgs jntvfv wzikk
mmupc twntp upcmm pumcm
qnisuzy lppnfd uiqr eyqbain uxlp eyrfwjo olgkrps sbikam zin vckr
nmokl skfni jcdfot njzqeaj nqzjjea
slmaxx offfzqp wudicrf nfn rwfcdui cwirufd
paffi murnjd oyj lbtjdqe babuas dtqh qkt stapzl yrqlp
eedc rig zmnfmn edec ecde
bcfdf edovdj lacx nzvze sordvxj ybs ujh zvvvp rzstejg ueosuq
xrrfsd okuvem znzlvmb jwzcb bfg bmuxbc qzwfry
pqgxybd cvgra acgn ocd ancg fvfcx fbb bfb zfzv
tmmv mpywyg fwl bnvcv lcnv flw
xxnfbro papc ianru beuzx apcp rnt
wuyhycj nrnc cka ebg rncn rvo wcyhjuy
thh cmoog hwf imqfp okzpxd
rzxiqt rtaiy ytria tyria
cjkmro myif myif xyirn aqxlol wlhwibi dhzsen pzwgm bfbz bufjs qwffg
mxhiui umiihx zomyll vfieccs
yyntf rjk iivgj mwh rjk
dsshx wsmaxhc xcwuelh rdsgtr wsmaxhc rgtsfj
rdh nwlxiwu xsjzbpr bsgps
ufyo vqtzkg kpeohu mxzt fyuo gawgaq youf
hzbhut bxsnjwb zuhhbt zhhtbu
pdz sgntypg ragev hrrji goitft yphnebs xjzoo sqf jsuzijq dsocb hcxg
pptsq woomypc woomypc woomypc
axcg wfbnpql ejqb cmnn nncm csvlc wraludb pkmp whtht tfpicer
moom oomm ommo vfqeii
xvrgpp rofl yxyrkb oage nypzau pwfnkn jxnhkw cyxsi clzb adwpuh
mfbz vdtt muzhm wvwwfl ttdv
cpqgvbu byc pgfrlkr aftl tqm zcqxi juu gnf ppovxh huoa
konpcp lzordid jqng lwxs nqgj gghkxmf kyn ngqj
iorhccj xfygc cnfr tysqc xpcyf vmjpitf nut zmrk mgbrtb tcblxwf dkadwrm
kov jtmp xoatesx qxkilp rmggpfx ltpxzwf vko reqms mqq nps
hjigmk fyqy wpuwe mwmso thsimfs okcmeyh mzqkez duzaq vzhyrm uyvpkox cwivpls
ukoerf korufe zhs ntwfz hugem vriyk enfaib hrrcdgf zllsk vkiyr
shkx khxs wntpjv qdevaw noqyht nwpvjt egh hgok mukdjfi law bzbvjz
dquk kczxsq tdu trnkjs wqtdc ybvcb
hlrotxn cumcjkm qwufgle ylm nejh hnje pvaigrx myl sfvsd
szmvisn aywic vsnimsz iufmybr
zjozr zojzr qmn ffrggdh wam dafvok
nxkvlhr posmf posmf posmf zhlzb
ywis kpqpyb qae zqxpuz pcj hbsfz ejlwa lajew znuom
qxsl ussivur dstd avojo
yoeagao egpaqm ymzf kkauy ivm illir wsvchne skmamvn nqxc
cldo ixzzy vhk nra zhypgab
qjdd ecxud tbuqq mpotbdk tjdpczn knncm tyy
rbfc fhhjf innia tsjbbbv fmtcuup rapvhqz ebpzt whdbms gvjoy lykl fquvcby
bihhfwi lhal udxz uwjwp dmb
fekxamy uophet yzvv rqj zawlp ldrv mdymkzy taauf
rcwxvmh edueui ltdyo xfghz dgjig senm ifj
qcu fii axmgijj ifi oixjfsg jxagijm
sdtyr rbdh yvnvq czzuig wro
lot xkto cmpiena nht ozcg aotcw xiegl cyaouj und lsclep cexn
pgihljk cmgmv sajhi zfvbqij ogwoc ajsih zmppe
jexwkdp dwpexjk mzjydfu bff rubgdb
yshfhx emkl hshxyf mkle
dxgti jdo tkwprv pbxbrqd oiz gsbdphd qotu utfdnq tzvve bqc
ovdf bshfxyl xspjpd vljdsm mgkd djlsvm mlsjdv
etyia eytai sfq qafj xzgp ewhsn snwhe lhqp
zjz mwh dorxm ges gexo rckwsa dltoq mmntha
hqkuj ypsjcxo dixbe rmvnhjh ovnr
edc iffaxc lolu xwrvpb gva vti vit
ceuxq xbwejr lzyvm rozseit cwe mham fivpwj qtv omaktaw
alzdrk tsxbuld mdbq pgbdtoo xwf vzalric nqe jqwlxsy cbtylu dtubxsl lqm
rqjmjcs exjpn kpilcgu ihcm lfadjm mlri hpd vqs cxqwqhu twxrtk
aeuvlcp aubvnw riedvz arypagp uuvg kliehx cokt ogh xsdw cdsyywv
ddwrgvp bscaq bbfv qrbutp
jpdg uey eyu uyarl zgbk qyhqq fdvlql zmwkp
kbt bkt lebhpfu smrzt xalw mmwa zmtzfry tkb
fcvcv oewfzu fvvcc mldww lwdmw
ejrltsu sqoyx wfvsdbp bfdspvw bfir jqhgrmt ofdmrjg ysq
jzwucwn erqjd eikq knpf cvk xvqnscy eei wvfjzmj xujq cqaim boev
jqhkmr ipjpj zwno ybu krhqjm zqfyyzb dyciy
ugwsw rpwteje qtvwi pwyhrzt hfcdfmc qbovk ibws
ffy kdder qjookz bfvmvvq yjzuaj fvxllfb pjyz jcezhye fimyydt qjookz qjookz
loupd nwsc yytvuqo ltcqxnf
iho ulvxguz fxbf iqu ofjtmvq xhs ybbusd kxg mebdnah ucttcf zufb
wzdb wumuhtv kef aavv buu xmjtlur faaccl wospwff bjasr eapfsi
jau qzszci ciu inagax
kui tqig fyovsp fvwol fyovsp mzth tcp nhoq
ajdla wtpj amylu jly tvq wjqef
ofqc einz bdze tows bdze eew
avwavzt aesrsjv lbmpi hllv chdbul ezelxn
imcprs cafb clfg rsjo iylqu nvk vkrq izezlnu vkqr tyhnv
rwj zboui reh buzio wuhpvid cpzy jrw tsbuiby hmxwqr ute
ixq luwbi uoiwsjh souz ysoubw uilbw ffwjvw ewzswoh hci zmfdaov whowzse
xrhgqf xrhgqf giyv giyv
toiqgzv gakg udgdlb wvi carrn pjyha muqclu
wuxthi srtszr ourab hpds bakvy fnk yefe yfee doowxcx
ijdc ujhvls xmy hwg yetsda qelbe nang xgywo wgh
bhm icq cnam dec enksf qfctz pwxoo bdf cnma xoowp rbls
jguzh fextz yax kesaunn waljo jltcza tfzxe dezs syi ebwxnks
flvq bzgd clvqw ahtyvu xbdyv wssxx boscm grgl nqcg
caskpli hqctxxc nwpyo wjlqfqf ebti dva
wmsz fzpd ikgeq gti ejftoou ezs cqef mybojc rgwz
mdaay yfppa pavl fuuvfkh hpod tpb dhxmia emdecm rbqcwbk vecyt
neha rmvl ndp vlrm dpn debghi vyhvc
bnp zkxdu iqqkesd abtlx hmjasdq kyvekr krt srrjyd oxmfev oot
dumlcqd ccm hyir oritdz madjjw
oakqrs advfmu verrc zkfdcn btndsp
onlkinl rdtm bscfxre bnu oumyrvv kgc zkj
tfxfsgm uwmic agswclg uofezgc
wpfdyjn kjlihk etbot fbu scm gwccce xgownte wig cuaijbo
bzbdk etozk qracb oftfoo lkooe
xupzw vmxwu sis wzpxu
gbz oqbgh jwgrru bzg kwmxcfc jrurgw
agyjnyc tuec imxlult omwiyjg fiwnoqx nhmnro qtg kbr agyjnyc
koiq llreotu elrtoul dubfvgy whq
htm lll crzppb gdjaae nsmxzh gnfvn obiuy ymspzbo iuboy
thm xlfrr pbxdfo mht tygi sapxgbv mmngzf dej
eus seu qmstw ues
yvfsw esut biblze kbjcpk estu xih qzki ezlbbi blzv
ohq ugc tqqeo jygvpwm vfs ldnfibp ycbpa sml rmime
kuuow gbg nzwdaf wiimtg lam oqmm
wsbwkdd hda nqk ticz mvt
gqbljyh zqugqs cjod sxwlqy qkfs wwvwvt dsojb qbhjlgy riusoa uosari
jkphfx dbt les jsvoij rnuw mxmmchu dol vto swn
qqxe vwvephr twdqlyg cvdu xjiych clooq vkwavl whvverp yuz vkwval
txtbudi tiutdbx wqhx tws utgbf amh hmf izsez ooz
egdube nhsxjs nxjshs xoy sjsxnh
egdziod diodegz ejxn zogedid uhhkr rnm cyvvuc uqbl
rbn pinwag sidwdwv jqdbe jlbemk blkeaqq ipfqbtn zkrbp
bdryz sbh wxvn mhot wemsfm oemkff
vxyn xvdwwo xhd vyca zxjaw vfkz xhg ofsphks dyq mmzzd
yjrqsjf iiesdh envwyx rmtbmiv ggzsg ukx bprfym qmyqc vag ymho hjtoh
fuxxrd wbweptd vkoffr wbweptd
gfwcez smetli yjyh pslpz qyokpsm qsy cxjymg wqfkf obuq awz
eqhm ceest kayf heqm
rdi dti vntcf ewkmpvf jjwoihc
sfq qlb xrm ocy vtnj zdznbal zvon stln zwnj wsgalvq vhphap
pya jay mgnyo pya xmapdn
hrwbj xhr gvwl ktq ktq gvwl
rzgqi hjwtthl kxhggbl wepc hgavj ctmqug
tzfwkc xeqfath iiuwq iiuwq dhwuvy
gibagy smq getjofc lum msq ulm xuxu bilrus ily
xlv ndrkch hdcknr nqltoze xvl
wmc vuzlrj mwc atp cvpx atv ujatz
hxpafgl ymjltv nvvpy ahycdk jhpdcks ettm lvqyw ertpivm dnezwxx usi kdhcay
vrh hqyomv mcq ilwjbkz yprjxad
ugv szfitxg zeluib pfj ijm zmiigxx gltxzz jzljhgh otskue
mxp bilj jlbi tce yfted zxsqas ftyed
ykasqv ehye kirmnl upmi dojwmw wzj ykasqv ifixn vreoypz
kerbgub nnroqk onkqnr gbebkur tjhl knjo ccsem yozvrcg
ygq evkoj wkn ffljhds scxeibh egsybeg mwvi vgjblj qda ywqpp
hocvpl ozgkxp xgmj ejzyxm
gernu kks lxe nxzv sypg xle goz
xoatis fjp wzlbo dzkonz jtutyj vdonj swro tqclemv xhomap ymeqkua vaxcw
mxcyjs ywyxndk wng vpftv nsuvu
jmiyyhh gwser shgcu jmyg cjzegc hmhe eopg kmkan
smdd dmds mgqhtkh qtamih haqmit skkcy
dnj rmggy rgymg uburbao rymgg
klcpjgq ons ajyv sqryt son pjlcgkq xlobdt
piw shonk tzi mcdumz noskh tebolw yaypn
ozm mvmjgtg nxj weommiq asnmhzq xjn uobztuo cqgjh utfb oydt ommiewq
qlwgsc vvpe xgft ahpjc zjtx iyof scwqlg dxgcokx ltrefj xyzq rwto
ggqdd dqgdg ggdqd kjkmmfp
htzjam fjbg iagc xls iagc iydtf ihxl boa iydtf
vhe nqj bwgdoi hhaoa qtulz
axvyja hpdkwee hnryj prou rgadv oubjdqg knjbc
caz xibj wqkzwe peioeya vmz hesy ftb
dudwcr gupj sjrtzc xsqbb hiet nujv bebcvsj eks uuzlcx gex
kywozi tfzuc mflssw hnxxxqt zzc tzfuc hkokuv mnjg lwkavjp lvpwjak xez
izgh zfv cingjt dkf cknite qox vfz zvf
ojpu dzk tehpgnt gntpteh
glxfxa uxq ajtles ahgzn ajlste zwgc mrpu adz wuunwhc zda
hdgdtn hnoyz aromkb qujfv yjgmn tbf atw
uyvsv oaopjv uyvemxk ldpp tthe iisjk txr hebmd yxevukm rkziao znt
ypdr mnwuzvw acpg kzwz ywbn wcrr umrnlbe lkult ljify azyhu mgqoo
abmpl omsd xmyl mxyl mgoq kracrf ufm ppwi zpggh
uxfdpv jnm vvc vchunhl ubv ktj mxolsxz
fcja eci edzrb nlvksaw lhf ycohh tfztt xso ceub tyv
rkwtp tcmmvv kufg cxui hdamg suuaej fgku cvjlv
oldbgy riadoyo djsi wca zxoeq pmemqap aijxa
nyy ruxcosx xisqoz yny jvzfpbe tlfdiaj ybd jifatdl zuzv
kxwdz qvrvx svllp ergmme
swjfuv eronk favcxfm acptbh pnbjn ciqcrlt rgvdnlt icgahb
ddza xxfn use obqka bfzwjp gmf bld fyvde mxdfdl
ame bmxbyf ame bmxbyf
rdgby pyfog dybrg gdryb lpztd
sntg impd uxgxai naoalb ntnk xgix
oadpmqj oso criln izih oos
ouzjq gtl ito xefqt phnv ouzjq hoyjjj
mlp rboq lpm roqb whvp
tghcw ggshevw dzsgj ggshevw kec ggshevw
kmwhb kfcb mbhkw gemz fdh
euve veue kplrq evue
hikfiw bcdktj hcnawja gjasvwc vcht igrzly rkxijxe ikfwhi dvmp
hvksis kafs ktcs sfyqzyt etctrgt vodwr wff tskc juobnm
dpcsodn ehwc pglywfl yhdp mdiyzx
ibog umftejh cfm pnxhna wqwx yabnk ygws dqw
dezz tqw qism rarfe fpmlab xvbau irwtfs wwmoyss yvn xetqp xtqep
pchqwk npsmd jefec qok uuc ucnpz rlkakn
kudh rjysb xrdbx bkbmjfo xrdbx
rogu ssdwsus voa ncw obkxsr
tflf hlevus scq rrbpat tau wxsq wxoblt
rzr lex kqdy whtj ffnys xlgkkff msjhy dimaq hrc wyde qkwf
ghtwd wernjpn tdgwh olrfvmr edq gxvp
rjirvf skhdgln aauit bipu mubjiwp kowz gyjfbjx cmgdqs
aftfpbv agajyy aqjll vsf twh robpys lebt eav yribup
sby ymkla sxkbfwl awmd nhb vlp
kizvjj ycjswr jkzjiv vuy jijzkv jcs
cwvch xzqfal tephz lqfzax cnkbdcr mql zflaxq
jjxzwl himpra ssjf bibfiui seeaq pzse
jogrn jogrn sqew jogrn oixgwr
khonpyw iiyxir vybhc ndnxxv kzlt ipmncn
okqkqu svbemi nfn ovd xgwy edd ujet nrrbv dde vdo
jobvf dus asvio vaosi sovia
knmz qbz nkmz zmkn
isbmopr unduey impobrs hea zswciev sopbmri duuj
ocs ntgnrdu kbvtzp cvyieu fiyn znmh lhrz ixtnzrj vktbpz lbpqx vzkpbt
muduhc sabc dlyoisz kuaz ogpyepw yuog ictiiqt
xjflsf nfklvml thfh uajnmby cichyj xxoqi lpime bxpyx
riahifn bohbgd obhdgb jni qzvkf ybp hjkkwq ytutd cakcsh smfdoe tuytd
iddku nccp zgtl yne ppzpqcx lwm
refpcz uqt uqt uqt
mtn czxkagb nmt caqacrg bcakxgz
itxjii uethxbj vpds bsqod diqax inv zrwt doepe
bfyaj nbvhg zmi buf
dtre dkwdr nrapm qtfth odvt bbcnae vxuk gqm enlg
ybt qcfozrk yzrh bfp euuozuz pzsdkxx mhi nbkzprb
vpuhqn gyx caint antci vfep incat kqdakdx
ddhi chgnjk ibg xbemitr mjtdph eovw
ngbtuvq qdttlsg dbqhhwk bkrqze qdttlsg qdttlsg
evn smvhi dgcmn xjo ascc ahbpj uvzc pwn tung
ksu thr omg onvsqzz rllakar ysfjtfj grxwyx oawix gpk suk
qvb iouav yhtndkd vuoia ouaiv
kud kofcip hcczrgc cvvxxlk rvyamwe duthdzr dftun
rgv ynw gph tmxwfup nwy
dnc trawj kwzbx trawj zvp
ogqxijy tbqtsg tbo vqinnlq jbvgl sfafh rve mcxqs ubh
qccr lpv puuvdyb tydaflf uxic
tlon tbfwkxg tlon tlon
iytiz qjlqaqw uixb lnt zwro uzgxqfi gklgnqs zwgoidw iifk wkwdo
tmvhxw tmvhxw tmvhxw fhiqpjy ejk kvysd
cmphg xjjz groiccd dvetuk xbwa zhm lyi ohhd neg bxaw yil
kdmzopy lxx bvhach goxmxu qbqvzcm qbbrhvb nrfom aixmio grpxz hbrqbbv lkucih
bnqn phqr uycuxc mopyyfh bbpesqm stgigq stggqi cwtjm asqhpl imvlxj lbmloo
pws iuvbvjr cwccm qbr srqnstz cjebq
bfh jobkcy gtbroe lpagq icmax jobyck fbh
ounqdo qrrr pwi alho rrqr beao rsioepe
vrccqge qvcgrce cbslkjs qnclw rvmjkw
aaxjns deupjs wtgxtp penad depbho tbrdt depbho qxg zhjxpgd
drqfo kbp jfa jaf
izn oczcitj cpae quvzqo iwwk jck idjdpm
ecort zgcvxx bvh vrprsf
fhubfvy ndcfjo kol hyufbfv hvpka
kpt zgajpc rjvsxa gayznjd
xeoixk peq kfu lqa mjnv mzvh bicl hlfk
wyt imdx lksy twy
xeptp ilxs qbsqzwn rsy slxi xtpep dsdkekl
rotvbt fuirp elos ciu nhx bxej trmtx ixn xbpc vrxtma
skcprn yns sao ghlq vftezvc aaryahy telt
fkaov gexa xijv yiksa xega dhgw okfva gxxs edkecag mqbqvrm nrzcqub
ljc jujxeof fdj gdzjzr mabbktu pmyrfv uspven zxry snt hrah
nhujhdr jdhrnuh midm bbavhpp cpjk zmpbasz eptrpou znq zqn
ywzfq wuu lfflon uuw rke qzwyf hjbms gakx
yqrq zsk jzn uuuzrml kzs lseupsg waynfh blech
gwyqej weyjqg uwuje uujwe
lxud rnwkc bgygkh csq rfvtos ystqp keb gkakodj uthcce eqxifl
elvj evj rfwo vvgkosh aarcgjs utsbh orwf jxcqvmh uowmktl qtgf
bqszre oxntty ombwiz mbiwzo
ccp iilcc tacf czk giwv erqi jgdfah wip xtrzhv wosvbyb
gymyw rwsxeg gvydr izyk spsonkg knospsg
djj tbr tbr tbr ice
yyzh zkykapw puydtik ysxc hjumhsd cuhhw dnnhida yyzh lnklymg
nhbcxsu ccrbbyw scbxunh ghxrkqh brcwcyb
latdaav sexa ipzuzjl ayusb etb fshh
giz akqd vjmabii arfuzgv efrww jxkvolg efrww vrnzgbx
jmcc vqy adkzj fqrkdo tjrczp ccmj cfponk rptzjc
jsviu sraw imsj fujm cdf xwqhl lhz ojejzuy trtqblg
ibz dulm muoq quom etvjzxn tuhrpp jfukac jqctqn qhgbae msgmcit ludm
zgx bpfa elhp rnyqtq wyceube nkeuxz
lzxfo vygpecv jszacku zfxlo
cpmv ysaaj xnp wbvqg hrsiuj venjxna yeqvwmk ftaga dcqxc jgapb rqdixp
xpbbe tyn hfdlu fto wrgzkou sxylv cqto wdv xqc pnu rapk
pkrxypl wnu oipq tzbhnc gpug tgzf ofjb
mvaz bwcv gll itgcye dessw szt gzimgeu bvmohh wbywyhc kzerxbr anjsive
lhvnrzs qkmjwy pnyciwp mgp jfdz ghvtf yusfzg upab
xbscukx aubulj snbcmc uscxkbx ddpucyg
hgv ollh yzpjmpy fcicyae vhg gvh
prd onyd iux oik xui
zipadig nvewx cir lbpcusx dljqy
ifyxzsc btmy lsu tmyb lus ldyzx
egmyxbe ieasvek dylmj qahtatr uyqgbk
mejjczw spj vaekp kdud
vwan mgenld mnlged vpfuil euoxlr rclkpi dfknyoa rhthij kcyxl qaxab crlpik
pqm eihogk iwml nuauxi ngilkoh jmu mbdi cqxz nblb rmuj zczdgp
pswbe mtzch wbeps fxtnc psa aioff pas
prwrpvz oadpqvz tgzrt giom pjyihh rxdir dmya xjolzxv
khdybe obqkjn kdq jkvmgwo enpat wyw qjbnko waid msest wwkoyts
yep liv ofmtpod imdd qyw
afnrx jgn gxarpb myltj ggrsajy mdaobjo vbtn vbtn zlziz eds
hqr kqu oub skoeqk icnfm cqvld aay bto
rga odaf exoosh pwevx zpbd plaa xoseoh
mbr gqu oxvchrt nqa larxmjx pfozej
ozuo ywubjbg xcua eblwqp nfdvw hmhen zkjfu gmhgp bsyi ktprtf
src vrysby srybvy znwjm hmypwdl gdmau pqe
cldr crhi lbaq fbuduyn hygbz uhida
qrxukq dygkp oaks soka oask
vpido ajgfq pwlv hezt fmg epwrxo rqvjke iovpd hhkjm
anxf ydl xnfa hqph olorp
exydcg onxjm psqlbv ehz boar hze qsblpv
mnzrvc ipj swg ijp sgw gdkntsd fzz grqwly
erpq qghpj fay gci uglm afy
jwbq hbxaub jpdilyt yvalrlk topl qup
eczonk ftcc paltirb owz tihhe dglxory wthvqcb qdnxm lirejh alyxsr
ooruaby gboyeu lkv arrz jcqyzl uxlfk fhmeony fcmh
wzr xjb pwmf okqj adwcedy lkidve uwekxf asbdzr biub
dikhur pxgh urdinjh wednf ulzdxs
iplf byt tyt qnnlba pzt bednml ljjtkvo tjovlkj uwms xat
htzk ltmfha xikeze atfmhl fchxhyz
lqala bqwgcul vetaa xuxjau zcb wtdmomu wfqmpq sief uyblyz ahv
aytvvo awm ojaaigg awm dbfaokz
abq npcyld fzbfku oia qss jkxldm wgtmki pasgxi dieix rpqnuac tecnfy
nmr qzfj qjfz lsz vnahex
djxoo jzlkh svy xige
tjlkkg glcuvmh fwzlhi ecun qlgulj hrfhyql qgdlf ofakqdf zokkvm gelxkq oowgs
upfpk gfstjlv lxc rjd nhj sbq jpzsz zsjzp
favd nzqfdid nekfjsf mtjndu
sgdqx uvpuefv vhwrgd aivav gsqxd jdhfoq
llaf cthbgy njrpw fqgkx jzf xqkgf lnrfrm gkxqf
wzdwlc wisst alw kyjeur sjsqfcr tta bijnyn whfyoxl
dtjr baxkj lmnyrlg nrmyllg
mtgky xmwf zdko nnocxye gytkm ygp hixk xwmf
maudjy okgjga uadjmy dzfrk omd
azz ajdcqkd bcafn zaz dcjaqdk gylyzo
xzvfbf fopmfxu mvftgr mfupoxf coyhof talcc vpkslo";
println!("{} {}", task1(day4), task2(day4));
}
|
use convert_case::{Case, Casing};
use proc_macro2::{Ident, Span};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ECS<'a> {
/// The path of the output data structure
pub name: &'a str,
/// The error type, if none, default to `Box<dyn Error>`
pub error: Option<&'a str>,
/// List of stages in this ECS, a stage is a group
/// of system followed by a barrier and a flush.
/// The barrier means that all systems must be done executing
/// before reaching the barrier.
/// The flush means that all command buffers will be flushed
/// at that point.
pub stages: Vec<&'a str>,
}
impl<'a> ECS<'a> {
pub fn as_ident(&self) -> Ident {
Ident::new(&self.name.to_case(Case::UpperCamel), Span::call_site())
}
pub fn as_builder_ident(&self) -> Ident {
Ident::new(
&format!("{}Builder", self.name).to_case(Case::UpperCamel),
Span::call_site(),
)
}
pub fn as_component_store_ident(&self) -> Ident {
Ident::new(
&format!("{}ComponentStore", self.name).to_case(Case::UpperCamel),
Span::call_site(),
)
}
pub fn as_entity_builder_ident(&self) -> Ident {
Ident::new(
&format!("{}EntityBuilder", self.name).to_case(Case::UpperCamel),
Span::call_site(),
)
}
pub fn as_command_buffer_ident(&self) -> Ident {
Ident::new(
&format!("{}CommandBuffer", self.name).to_case(Case::UpperCamel),
Span::call_site(),
)
}
}
|
use std::fmt;
use crate::*;
/// Represents City tile of given team at position
///
/// # See also
///
/// Check <https://www.lux-ai.org/specs-2021#CityTiles>
#[derive(Clone, PartialEq, fmt::Debug)]
pub struct CityTile {
/// City id used as command arguments
pub cityid: EntityId,
/// Team id, whom this city belongs to
pub teamid: TeamId,
/// [`Position`] of city tile on map
///
/// # See also
///
/// Check <https://www.lux-ai.org/specs-2021#The%20Map>
pub pos: Position,
/// Amount of turns to next action
///
/// # See also
///
/// Check <https://www.lux-ai.org/specs-2021#Cooldown>
pub cooldown: Cooldown,
}
impl CityTile {
/// Creates new [`CityTile`]
///
/// # Parameters
///
/// - `teamid` - Team id, whom this city belongs to
/// - `cityid` - City id used as command arguments
/// - `position` - Where city tile is located
/// - `cooldown` - turns to next action
///
/// # Returns
///
/// A new created [`CityTile`]
///
/// # See also
///
/// Check <https://www.lux-ai.org/specs-2021#CityTiles>
pub fn new(teamid: TeamId, cityid: EntityId, position: Position, cooldown: Cooldown) -> Self {
Self {
teamid,
cityid,
pos: position,
cooldown,
}
}
/// Check if [`CityTile`] can perform action, i.e. cooldown is less than
/// `1.0`
///
/// # Parameters
///
/// - `self` - reference to Self
///
/// # Returns
///
/// `bool` value
///
/// # See also
///
/// Check <https://www.lux-ai.org/specs-2021#Cooldown>
pub fn can_act(&self) -> bool { self.cooldown < 1.0 }
/// Returns research action
///
/// # Parameters
///
/// - `self` - reference to Self
///
/// # Returns
///
/// Action to perform
///
/// # See also:
///
/// Check <https://www.lux-ai.org/specs-2021#CityTiles>
pub fn research(&self) -> Action {
format!("{} {}", Commands::RESEARCH, self.pos.to_argument())
}
/// Returns build worker action. When applied and requirements are met, a
/// worker will be built at the [`City`].
///
/// # Parameters
///
/// - `self` - reference to Self
///
/// # Returns
///
/// Action to perform
///
/// # See also:
///
/// Check <https://www.lux-ai.org/specs-2021#CityTiles>
pub fn build_worker(&self) -> Action {
format!("{} {}", Commands::BUILD_WORKER, self.pos.to_argument())
}
/// Returns the build cart action. When applied and requirements are met, a
/// cart will be built at the [`City`].
///
/// # Parameters
///
/// - `self` - reference to Self
///
/// # Returns
///
/// Action to perform
///
/// # See also:
///
/// Check <https://www.lux-ai.org/specs-2021#CityTiles>
pub fn build_cart(&self) -> Action {
format!("{} {}", Commands::BUILD_CART, self.pos.to_argument())
}
}
|
pub struct Solution;
impl Solution {
pub fn character_replacement(s: String, k: i32) -> i32 {
use std::collections::HashMap;
let bytes = s.as_bytes();
let n = bytes.len();
let k = k as usize;
let mut counts = HashMap::new();
for &b in bytes {
*counts.entry(b).or_insert(0) += 1;
}
let mut max = 0;
for (b, cnt) in counts {
if (cnt + k).min(n) <= max {
continue;
}
let mut i = 0;
let mut j = 0;
let mut r = 0;
loop {
if r <= k {
max = max.max(j - i);
if j == n {
break;
}
if bytes[j] != b {
r += 1;
}
j += 1;
} else {
if bytes[i] != b {
r -= 1;
}
i += 1;
}
}
}
max as i32
}
}
#[test]
fn test0424() {
fn case(s: &str, k: i32, want: i32) {
let got = Solution::character_replacement(s.to_string(), k);
assert_eq!(got, want);
}
case("ABAB", 2, 4);
case("AABABBA", 1, 4);
}
|
use std::{thread, time};
use futures::future::{ Future, FutureExt };
use tokio::time::{delay_for, Duration};
#[tokio::main]
async fn main() {
std::thread::spawn(|| {
match block_alarm::background_thread() {
Ok(_) => {},
Err(e) => {
println!("background thread had an error {:?}", e);
}
};
});
println!("Setting up the alarm");
// one hundred milliseconds in usec
let a = block_alarm::Alarm::new(1e5 as i64);
a.start();
println!("Alarm started.");
println!("Blocking");
let one_second = Duration::from_millis(1000);
thread::sleep(one_second);
println!("Blocked.");
println!("Cooperatively delaying");
delay_for(one_second).await;
println!("Delayed.");
println!("Blocking again");
thread::sleep(one_second);
println!("Done blocking.");
}
|
use std::any::Any;
use std::ops::{Range, RangeInclusive};
use fastrand::Rng;
use super::size_to_cplxity;
use crate::Mutator;
/// Mutator for a `char` within a list of ranges
#[derive(Debug)]
pub struct CharacterMutator {
ranges: Vec<RangeInclusive<char>>,
total_length: u32,
lengths: Vec<Range<u32>>,
search_space_complexity: f64,
max_cplx: f64,
min_cplx: f64,
rng: Rng,
}
impl CharacterMutator {
#[no_coverage]
pub fn new(ranges: Vec<RangeInclusive<char>>) -> Self {
let ranges = ranges.into_iter().filter(|r| !r.is_empty()).collect::<Vec<_>>();
assert!(!ranges.is_empty());
let total_length = ranges.iter().fold(
0,
#[no_coverage]
|x, y| x + y.clone().count(),
) as u32;
let lengths = ranges
.iter()
.scan(
0u32,
#[no_coverage]
|x, y| {
let start = *x;
let end = *x + y.clone().count() as u32;
*x = end;
Some(start..end)
},
)
.collect::<Vec<_>>();
let min_cplx = if total_length == 1 {
let c = *ranges[0].start();
Self::complexity_of_value(c)
} else {
8.0
};
let max_cplx = if total_length == 1 {
let c = *ranges[0].start();
Self::complexity_of_value(c)
} else {
32.0
};
let rng = Rng::new();
Self {
ranges,
total_length,
lengths,
search_space_complexity: size_to_cplxity(total_length as usize),
max_cplx,
min_cplx,
rng,
}
}
#[no_coverage]
pub fn get_char(&self, idx: u32) -> Option<char> {
for (len_range, range) in self.lengths.iter().zip(&self.ranges) {
if len_range.contains(&idx) {
return char::from_u32(*range.start() as u32 + (idx - len_range.start));
}
}
panic!()
}
}
impl CharacterMutator {
fn complexity_of_value(c: char) -> f64 {
(c.len_utf8() * 8) as f64
}
}
impl Mutator<char> for CharacterMutator {
#[doc(hidden)]
type Cache = ();
#[doc(hidden)]
type MutationStep = u64;
#[doc(hidden)]
type ArbitraryStep = u64;
#[doc(hidden)]
type UnmutateToken = char;
#[doc(hidden)]
#[no_coverage]
fn initialize(&self) {}
#[doc(hidden)]
#[no_coverage]
fn default_arbitrary_step(&self) -> Self::ArbitraryStep {
0
}
#[doc(hidden)]
#[no_coverage]
fn is_valid(&self, value: &char) -> bool {
self.ranges.iter().any(
#[no_coverage]
|range| range.contains(value),
)
}
#[doc(hidden)]
#[no_coverage]
fn validate_value(&self, value: &char) -> Option<Self::Cache> {
if self.ranges.iter().any(
#[no_coverage]
|range| range.contains(value),
) {
Some(())
} else {
None
}
}
#[doc(hidden)]
#[no_coverage]
fn default_mutation_step(&self, _value: &char, _cache: &Self::Cache) -> Self::MutationStep {
0
}
#[doc(hidden)]
#[no_coverage]
fn global_search_space_complexity(&self) -> f64 {
self.search_space_complexity
}
#[doc(hidden)]
#[no_coverage]
fn max_complexity(&self) -> f64 {
self.max_cplx
}
#[doc(hidden)]
#[no_coverage]
fn min_complexity(&self) -> f64 {
self.min_cplx
}
#[doc(hidden)]
#[no_coverage]
fn complexity(&self, value: &char, _cache: &Self::Cache) -> f64 {
Self::complexity_of_value(*value)
}
#[doc(hidden)]
#[no_coverage]
fn ordered_arbitrary(&self, step: &mut Self::ArbitraryStep, max_cplx: f64) -> Option<(char, f64)> {
if *step == self.total_length as u64 {
return None;
}
let idx = crate::mutators::integer::binary_search_arbitrary_u32(0, self.total_length - 1, *step);
*step += 1;
if let Some(c) = self.get_char(idx) {
Some((c, Self::complexity_of_value(c)))
} else {
self.ordered_arbitrary(step, max_cplx)
}
}
#[doc(hidden)]
#[no_coverage]
fn random_arbitrary(&self, max_cplx: f64) -> (char, f64) {
let idx = self.rng.u32(..self.total_length);
if let Some(c) = self.get_char(idx) {
(c, Self::complexity_of_value(c))
} else {
self.random_arbitrary(max_cplx)
}
}
#[doc(hidden)]
#[no_coverage]
fn ordered_mutate(
&self,
value: &mut char,
cache: &mut Self::Cache,
step: &mut Self::MutationStep,
subvalue_provider: &dyn crate::SubValueProvider,
max_cplx: f64,
) -> Option<(Self::UnmutateToken, f64)> {
if *step == self.total_length as u64 {
return None;
}
let idx = crate::mutators::integer::binary_search_arbitrary_u32(0, self.total_length - 1, *step);
*step += 1;
if let Some(mut c) = self.get_char(idx) {
std::mem::swap(value, &mut c);
Some((c, Self::complexity_of_value(*value)))
} else {
self.ordered_mutate(value, cache, step, subvalue_provider, max_cplx)
}
}
#[doc(hidden)]
#[no_coverage]
fn random_mutate(&self, value: &mut char, cache: &mut Self::Cache, max_cplx: f64) -> (Self::UnmutateToken, f64) {
let idx = self.rng.u32(..self.total_length);
if let Some(mut c) = self.get_char(idx) {
std::mem::swap(value, &mut c);
(c, Self::complexity_of_value(*value))
} else {
self.random_mutate(value, cache, max_cplx)
}
}
#[doc(hidden)]
#[no_coverage]
fn unmutate(&self, value: &mut char, _cache: &mut Self::Cache, t: Self::UnmutateToken) {
*value = t;
}
#[doc(hidden)]
#[no_coverage]
fn visit_subvalues<'a>(&self, _value: &'a char, _cache: &'a Self::Cache, _visit: &mut dyn FnMut(&'a dyn Any, f64)) {
}
}
#[cfg(test)]
mod tests {
use crate::mutators::character_classes::CharacterMutator;
use crate::Mutator;
#[test]
#[no_coverage]
fn char_classes_test() {
let chars = vec!['a'..='c', 'f'..='t', '0'..='9'];
let mutator = CharacterMutator::new(chars);
println!("{:?}", mutator);
let mut step = mutator.default_arbitrary_step();
for i in 0..30 {
if let Some((ch, _)) = mutator.ordered_arbitrary(&mut step, 10.0) {
println!("{}: {}", i, ch);
} else {
println!("{}: none", i);
}
}
}
}
|
use juniper::GraphQLInterface;
#[derive(GraphQLInterface)]
#[graphql(impl = Node2Value, for = Node2Value)]
struct Node1 {
id: String,
}
#[derive(GraphQLInterface)]
#[graphql(impl = Node1Value, for = Node1Value)]
struct Node2 {
id: String,
}
fn main() {}
|
mod window;
mod workspace;
mod screen;
mod layouts;
mod state;
mod stack;
mod keys;
mod command;
pub mod config;
pub mod manager;
pub mod displays;
|
extern crate slab;
use slab::Slab;
pub trait Drawer{
fn set_fill_style(&mut self, rgba:(f32, f32, f32, f32));
fn set_stroke_style(&mut self, rgba:(f32, f32, f32, f32));
fn set_font_style(&mut self, size: f32);
fn draw_rect(&mut self, xywh:(f32, f32, f32, f32));
fn draw_text(&mut self, text: &str, xy:(f32, f32));
fn rendered_text_wh(&mut self, text: &str) -> (f32, f32);
}
mod widget;
pub use self::widget::Widget;
pub use self::widget::Key;
pub struct Gui {
widgets: Slab<Widget>,
}
impl Gui {
pub fn new() -> Gui{
Gui {
widgets: Slab::new(),
}
}
pub fn put(&mut self, widget:Widget) -> usize{
self.widgets.insert(widget)
}
pub fn take(&mut self, widget_id: usize) -> Widget{
self.widgets.remove(widget_id)
}
pub fn get(&self, widget_id: usize) -> &Widget{
self.widgets.get(widget_id).unwrap()
}
pub fn get_mut(&mut self, widget_id: usize) -> &mut Widget{
self.widgets.get_mut(widget_id).unwrap()
}
pub fn draw(&mut self, drawer:&mut Drawer) {
for (_, widget) in self.widgets.iter() {
widget.draw(drawer);
}
}
pub fn update(&mut self){
for (_, mut widget) in self.widgets.iter_mut() {
widget.update();
}
}
pub fn mouse_move(&mut self, xy:(f32,f32)){
for (_, mut widget) in self.widgets.iter_mut() {
widget.mouse_move(xy);
}
}
pub fn mouse_down(&mut self, xy:(f32,f32)){
for (_, mut widget) in self.widgets.iter_mut() {
widget.mouse_down(xy);
}
}
pub fn mouse_up(&mut self, xy:(f32,f32)){
for (_, mut widget) in self.widgets.iter_mut() {
widget.mouse_up(xy);
}
}
pub fn key_down(&mut self, key: Key) {
for (_, mut widget) in self.widgets.iter_mut() {
widget.key_down(key);
}
}
pub fn key_input(&mut self, ch: char) {
for (_, mut widget) in self.widgets.iter_mut() {
widget.key_input(ch);
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
#![allow(dead_code)]
use rppal::gpio::Gpio;
use std::time::Duration;
use tokio::time::sleep;
// Gpio uses BCM pin numbering. BCM GPIO 23 is tied to physical pin 16.
const GPIO_PWM: u8 = 12;
// Servo configuration. Change these values based on your servo's verified safe
// minimum and maximum values.
//
// Period: 20 ms (50 Hz). Pulse width: min. 1200 µs, neutral 1500 µs, max. 1800 µs.
const PERIOD_MS: u64 = 20u64;
const PULSE_MIN_US: f32 = 1000.0f32;
const PULSE_NEUTRAL_US: f32 = 1500.00f32;
const PULSE_MAX_US: f32 = 2000.00f32;
fn get_pw(proc: f32) -> u64 {
let us = (PULSE_MAX_US - PULSE_MIN_US) * proc + PULSE_MIN_US;
us.floor() as u64
}
fn get_pw_duration(proc: f32) -> Duration {
Duration::from_micros(get_pw(proc))
}
pub async fn enable_drone() -> Result<(), anyhow::Error> {
let period_ms = Duration::from_millis(PERIOD_MS);
println!("switch on drone");
// Rotate the servo to the opposite side.
// Retrieve the GPIO pin and configure it as an output.
let mut pin = Gpio::new()?.get(GPIO_PWM)?.into_output();
// Enable software-based PWM with the specified period, and rotate the servo by
// setting the pulse width to its maximum value.
pin.set_pwm(period_ms.clone(), get_pw_duration(1.00f32))?;
// Sleep for 500 ms while the servo moves into position.
// Rotate the servo to the opposite side.
sleep(Duration::from_millis(1500)).await;
// Rotate the servo to the opposite side.
pin.set_pwm(period_ms.clone(), get_pw_duration(0.70f32))?;
sleep(Duration::from_millis(500)).await;
pin.set_pwm(period_ms.clone(), get_pw_duration(1.00f32))?;
sleep(Duration::from_millis(500)).await;
Ok(())
}
|
#[derive(PartialEq, Eq, Debug)]
pub enum GameRoundResult {
PlayerBusted,
DealerBusted,
PlayerWon,
DealerWon,
Draw,
}
#[derive(PartialEq, Eq)]
pub enum State {
GameStart,
GameEnd,
GameRoundStart,
GameRoundEnd,
PlayerTurn,
DealerTurn,
}
|
use crate::errors::*;
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;
use std::sync::RwLock;
type RegexCacheMap = HashMap<String, Regex>;
lazy_static! {
static ref REGEX_CACHE: RwLock<RegexCacheMap> = RwLock::new(HashMap::new());
}
pub struct RegexCache;
impl RegexCache {
pub fn build(pattern: &str) -> Result<Regex> {
if let Some(regex) = RegexCache::get(pattern) {
return Ok(regex);
}
let regex = Regex::new(&format!("(?i){}", pattern))?;
RegexCache::set(pattern, regex.clone());
Ok(regex)
}
fn get(pattern: &str) -> Option<Regex> {
match REGEX_CACHE.read() {
Ok(read_handle) => (*read_handle).get(pattern).cloned(),
Err(_) => None,
}
}
fn set(pattern: &str, regex: Regex) {
if let Ok(mut write_handle) = REGEX_CACHE.try_write() {
(*write_handle).insert(pattern.to_owned(), regex);
}
}
}
|
//! Describe decisions that must be specified.
use crate::ir::{self, Adaptable};
use fxhash::FxHashMap;
use itertools::{Either, Itertools};
use serde::Serialize;
use std;
use utils::*;
pub fn dummy_choice() -> Choice {
let def = ChoiceDef::Enum("Bool".into());
let args = ChoiceArguments::Plain { vars: vec![] };
Choice::new("DUMMY".into(), None, args, def)
}
/// A decision to specify.
#[derive(Clone, Debug)]
pub struct Choice {
name: RcStr,
doc: Option<RcStr>,
arguments: ChoiceArguments,
choice_def: ChoiceDef,
on_change: Vec<OnChangeAction>,
filter_actions: Vec<FilterAction>,
filters: Vec<ir::Filter>,
no_propagate_values: ir::ValueSet,
}
impl Choice {
/// Creates a new `Choice`.
pub fn new(
name: RcStr,
doc: Option<RcStr>,
arguments: ChoiceArguments,
def: ChoiceDef,
) -> Self {
let value_type = def.value_type();
Choice {
name,
doc,
arguments,
choice_def: def,
on_change: Vec::new(),
filter_actions: Vec::new(),
filters: Vec::new(),
no_propagate_values: ir::ValueSet::empty(&value_type),
}
}
/// Returns the name of the choice, in snake_case.
pub fn name(&self) -> &RcStr {
&self.name
}
/// Returns the documentation associated with the `Choice`.
pub fn doc(&self) -> Option<&str> {
self.doc.as_ref().map(|x| x as &str)
}
/// Returns the parameters for which the `Choice` is defined.
pub fn arguments(&self) -> &ChoiceArguments {
&self.arguments
}
/// Returns the type representing the values the `Choice` can take.
pub fn value_type(&self) -> ValueType {
self.choice_def.value_type()
}
/// Returns the definition of the `Choice.
pub fn choice_def(&self) -> &ChoiceDef {
&self.choice_def
}
/// Returns the actions to perform when the `Choice` is constrained.
pub fn on_change(&self) -> std::slice::Iter<OnChangeAction> {
self.on_change.iter()
}
/// Returns the actions to run to get the valid alternatives of the choice.
pub fn filter_actions(&self) -> std::slice::Iter<FilterAction> {
self.filter_actions.iter()
}
/// Returns the filters operating on the `Choice`.
pub fn filters(&self) -> std::slice::Iter<ir::Filter> {
self.filters.iter()
}
/// Adds a filter to run on initialization.
pub fn add_filter_action(&mut self, action: FilterAction) {
self.filter_actions.push(action)
}
/// Adds an action to perform when the `Choice` is constrained.
pub fn add_onchange(&mut self, action: OnChangeAction) {
// TODO(cc_perf): normalize and merge forall vars when possible
self.on_change.push(action);
}
/// Adds a filter to the `Choice`, returns an ID to indentify it.
pub fn add_filter(&mut self, filter: ir::Filter) -> usize {
self.filters.push(filter);
self.filters.len() - 1
}
/// Returns the values that should not be automatically restricted by filters.
pub fn fragile_values(&self) -> &ir::ValueSet {
&self.no_propagate_values
}
/// Extends the list of values that should not be automatically propagated by filters.
pub fn add_fragile_values(&mut self, values: ir::ValueSet) {
self.no_propagate_values.extend(values);
}
}
/// Defines the parameters for which the `Choice` is defined.
#[derive(Debug, Clone)]
pub enum ChoiceArguments {
/// The `Choice` is defined for all comibnation of variables of the given sets
/// Each variable can only appear once.
Plain { vars: Vec<(RcStr, ir::Set)> },
/// The `Choice` is defined on a triangular space. The rests is obtained by symmetry.
Symmetric {
names: [RcStr; 2],
t: ir::Set,
inverse: bool,
},
}
#[allow(clippy::len_without_is_empty)]
impl ChoiceArguments {
/// Creates a new `ChoiceArguments`.
pub fn new(mut vars: Vec<(RcStr, ir::Set)>, symmetric: bool, inverse: bool) -> Self {
if symmetric {
assert_eq!(vars.len(), 2);
let (rhs, t1) = vars.pop().unwrap();
let (lhs, t0) = vars.pop().unwrap();
assert_eq!(t0, t1);
ChoiceArguments::Symmetric {
names: [lhs, rhs],
t: t0,
inverse,
}
} else {
assert!(!inverse);
ChoiceArguments::Plain { vars }
}
}
/// Returns the name of the arguments.
pub fn names(&self) -> impl Iterator<Item = &RcStr> {
match *self {
ChoiceArguments::Plain { ref vars } => {
Either::Left(vars.iter().map(|x| &x.0))
}
ChoiceArguments::Symmetric { ref names, .. } => Either::Right(names.iter()),
}
}
/// Returns the sets of the arguments.
pub fn sets<'a>(&'a self) -> impl Iterator<Item = &'a ir::Set> + 'a {
match *self {
ChoiceArguments::Plain { ref vars } => {
Either::Left(vars.iter().map(|x| &x.1))
}
ChoiceArguments::Symmetric { ref t, .. } => {
Either::Right(vec![t, t].into_iter())
}
}
}
/// Returns the name and set of the argument at the given position.
pub fn get(&self, index: usize) -> (&RcStr, &ir::Set) {
match *self {
ChoiceArguments::Plain { ref vars } => (&vars[index].0, &vars[index].1),
ChoiceArguments::Symmetric {
ref names, ref t, ..
} => (&names[index], t),
}
}
/// Iterates over the arguments, with their sets and names.
pub fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a RcStr, &'a ir::Set)> + 'a {
self.names().zip_eq(self.sets())
}
/// Indicates if the arguments iteration domain is triangular.
pub fn is_symmetric(&self) -> bool {
if let ChoiceArguments::Symmetric { .. } = *self {
true
} else {
false
}
}
/// Returns the number of arguments.
pub fn len(&self) -> usize {
match *self {
ChoiceArguments::Plain { ref vars } => vars.len(),
ChoiceArguments::Symmetric { .. } => 2,
}
}
}
/// Specifies how the `Choice` is defined.
#[derive(Clone, Debug)]
#[allow(clippy::large_enum_variant)]
pub enum ChoiceDef {
/// The `Choice` can take a small set of predefined values.
Enum(RcStr),
/// An integer abstracted by an interval.
Counter {
kind: ir::CounterKind,
value: CounterVal,
incr_iter: Vec<ir::Set>,
incr: ir::ChoiceInstance,
incr_condition: ir::ValueSet,
visibility: CounterVisibility,
base: ir::Code,
},
/// The `Choice` can take a small set of dynamically defined numeric values.
Number { universe: ir::Code },
}
/// Indicates how a counter exposes how its maximum value. The variants are ordered by
/// increasing amount of information available.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[repr(C)]
pub enum CounterVisibility {
/// Only the minimal value is computed and stored.
NoMax,
/// Both the min and max are stored, but only the min is exposed.
HiddenMax,
/// Both the min and the max value are exposed.
Full,
}
impl ChoiceDef {
/// Returns the underlying value type.
pub fn value_type(&self) -> ValueType {
match *self {
ChoiceDef::Enum(ref name) => ValueType::Enum(name.clone()),
ChoiceDef::Counter { visibility, .. } => ValueType::Range {
is_half: visibility == CounterVisibility::NoMax,
},
ChoiceDef::Number { ref universe, .. } => {
ValueType::NumericSet(universe.clone())
}
}
}
/// Indicates if the choice is a counter.
pub fn is_counter(&self) -> bool {
if let ChoiceDef::Counter { .. } = *self {
true
} else {
false
}
}
/// Returns the name of the `Enum` the `Choice` is based on.
pub fn as_enum(&self) -> Option<&RcStr> {
if let ChoiceDef::Enum(ref name) = *self {
Some(name)
} else {
None
}
}
/// Indicates the comparison operators that can be applied to the decision.
pub fn is_valid_operator(&self, op: ir::CmpOp) -> bool {
match *self {
ChoiceDef::Enum(..) => op == ir::CmpOp::Eq || op == ir::CmpOp::Neq,
ChoiceDef::Counter {
visibility: CounterVisibility::Full,
..
} => true,
ChoiceDef::Counter { .. } => op == ir::CmpOp::Lt || op == ir::CmpOp::Leq,
ChoiceDef::Number { .. } => true,
}
}
}
/// The value of the increments of a counter.
#[derive(Clone, Debug)]
pub enum CounterVal {
Code(ir::Code),
Choice(ir::ChoiceInstance),
}
impl Adaptable for CounterVal {
fn adapt(&self, adaptator: &ir::Adaptator) -> Self {
match *self {
CounterVal::Code(ref code) => CounterVal::Code(code.adapt(adaptator)),
CounterVal::Choice(ref choice_instance) => {
CounterVal::Choice(choice_instance.adapt(adaptator))
}
}
}
}
impl ValueType {
/// Returns the full type, instead of a the trimmed one.
pub fn full_type(self) -> Self {
match self {
ValueType::Range { .. } => ValueType::Range { is_half: false },
t => t,
}
}
/// Returns the enum name, if applicable.
pub fn as_enum(&self) -> Option<&RcStr> {
if let ValueType::Enum(ref name) = *self {
Some(name)
} else {
None
}
}
}
/// Specifies the type of the values a choice can take.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ValueType {
/// Generated type that represents the values of an enum choice.
Enum(RcStr),
/// Represents a contiguous range of values.
Range { is_half: bool },
/// Represents a small set of integers.
NumericSet(ir::Code),
/// Represents an external constant, provided by the user. Its exact type is
/// unspecified.
Constant,
}
impl Adaptable for ValueType {
fn adapt(&self, adaptator: &ir::Adaptator) -> Self {
match self {
ValueType::NumericSet(ref uni) => ValueType::NumericSet(uni.adapt(adaptator)),
t => t.clone(),
}
}
}
/// A call to a filter in another choice.
#[derive(Clone, Debug)]
pub struct RemoteFilterCall {
pub choice: ir::ChoiceInstance,
pub filter: FilterCall,
}
impl Adaptable for RemoteFilterCall {
fn adapt(&self, adaptator: &ir::Adaptator) -> Self {
RemoteFilterCall {
choice: self.choice.adapt(adaptator),
filter: self.filter.adapt(adaptator),
}
}
}
/// A call to a filter.
#[derive(Clone, Debug)]
pub struct FilterCall {
pub forall_vars: Vec<ir::Set>,
pub filter_ref: FilterRef,
}
impl Adaptable for FilterCall {
fn adapt(&self, adaptator: &ir::Adaptator) -> Self {
FilterCall {
forall_vars: self.forall_vars.adapt(adaptator),
filter_ref: self.filter_ref.adapt(adaptator),
}
}
}
/// References a filter to call.
#[derive(Clone, Debug)]
pub enum FilterRef {
Inline(Vec<ir::Rule>),
Function {
choice: RcStr,
id: usize,
args: Vec<ir::Variable>,
},
}
impl Adaptable for FilterRef {
fn adapt(&self, adaptator: &ir::Adaptator) -> Self {
use self::FilterRef::*;
match self {
Inline(rules) => Inline(rules.adapt(adaptator)),
Function { choice, id, args } => Function {
choice: choice.clone(),
id: *id,
args: args.adapt(adaptator),
},
}
}
}
/// An action to perform when the choice is restricted.
#[derive(Clone, Debug)]
pub struct OnChangeAction {
pub forall_vars: Vec<ir::Set>,
pub set_constraints: ir::SetConstraints,
pub action: ChoiceAction,
}
impl OnChangeAction {
/// Indicates if the action sould also be registered for the symmetric of the choice,
/// if applicable.
pub fn applies_to_symmetric(&self) -> bool {
self.action.applies_to_symmetric()
}
/// Returns the action for the symmetric of the choice.
pub fn inverse(&self, ir_desc: &ir::IrDesc) -> Self {
let adaptator = &mut ir::Adaptator::default();
adaptator.set_variable(ir::Variable::Arg(0), ir::Variable::Arg(1));
adaptator.set_variable(ir::Variable::Arg(1), ir::Variable::Arg(0));
let mut out = self.adapt(adaptator);
out.action.inverse_self(ir_desc);
out
}
}
impl Adaptable for OnChangeAction {
fn adapt(&self, adaptator: &ir::Adaptator) -> Self {
OnChangeAction {
forall_vars: self.forall_vars.adapt(adaptator),
set_constraints: self.set_constraints.adapt(adaptator),
action: self.action.adapt(adaptator),
}
}
}
/// An action to perform,
#[derive(Clone, Debug)]
pub enum ChoiceAction {
/// The choice runs all its filters on itself.
FilterSelf,
/// The choice runs a filter on another choice.
RemoteFilter(RemoteFilterCall),
/// Increments a counter if the increment condition is statisfied.
IncrCounter {
counter: ir::ChoiceInstance,
value: ir::CounterVal,
incr_condition: ir::ValueSet,
},
/// Update a counter after the increment value is changed.
UpdateCounter {
counter: ir::ChoiceInstance,
incr: ir::ChoiceInstance,
incr_condition: ir::ValueSet,
},
/// Triggers a lowering.
Trigger {
id: usize,
condition: ir::ChoiceCondition,
code: ir::Code,
inverse_self_cond: bool,
},
}
impl ChoiceAction {
/// Indicates if the action sould also be registered for the symmetric of the choice,
/// if applicable.
fn applies_to_symmetric(&self) -> bool {
match *self {
// Filters for the symmetric are already produced by constraint translation.
ChoiceAction::FilterSelf | ChoiceAction::RemoteFilter { .. } => false,
_ => true,
}
}
/// Returns the list of variables to allocate.
pub fn variables<'a>(&'a self) -> Box<dyn Iterator<Item = &'a ir::Set> + 'a> {
match self {
ChoiceAction::RemoteFilter(remote_call) => {
Box::new(remote_call.filter.forall_vars.iter()) as Box<_>
}
ChoiceAction::Trigger { .. }
| ChoiceAction::IncrCounter { .. }
| ChoiceAction::UpdateCounter { .. }
| ChoiceAction::FilterSelf => Box::new(std::iter::empty()) as Box<_>,
}
}
/// Returns the list of inputs used by the action.
pub fn inputs(&self) -> &[ir::ChoiceInstance] {
match *self {
ChoiceAction::Trigger { ref condition, .. } => &condition.inputs,
_ => &[],
}
}
/// Inverse references to the value of the choice the action is registered in.
pub fn inverse_self(&mut self, ir_desc: &ir::IrDesc) {
match self {
ChoiceAction::Trigger {
inverse_self_cond, ..
} => *inverse_self_cond = !*inverse_self_cond,
ChoiceAction::IncrCounter { incr_condition, .. }
| ChoiceAction::UpdateCounter { incr_condition, .. } => {
incr_condition.inverse(ir_desc)
}
_ => (),
}
}
}
impl Adaptable for ChoiceAction {
fn adapt(&self, adaptator: &ir::Adaptator) -> Self {
use self::ChoiceAction::*;
match self {
FilterSelf => FilterSelf,
RemoteFilter(remote_call) => RemoteFilter(remote_call.adapt(adaptator)),
IncrCounter {
counter,
value,
incr_condition,
} => IncrCounter {
counter: counter.adapt(adaptator),
value: value.adapt(adaptator),
incr_condition: incr_condition.adapt(adaptator),
},
UpdateCounter {
counter,
incr,
incr_condition,
} => UpdateCounter {
counter: counter.adapt(adaptator),
incr: incr.adapt(adaptator),
incr_condition: incr_condition.adapt(adaptator),
},
Trigger {
id,
condition,
code,
inverse_self_cond,
} => Trigger {
condition: condition.adapt(adaptator),
code: code.adapt(adaptator),
id: *id,
inverse_self_cond: *inverse_self_cond,
},
}
}
}
/// A condition from the point of view of a choice.
#[derive(Clone, Debug)]
pub struct ChoiceCondition {
pub inputs: Vec<ir::ChoiceInstance>,
pub self_condition: ir::ValueSet,
pub others_conditions: Vec<ir::Condition>,
}
impl ChoiceCondition {
/// Adapt the list of conditions to be from the point of view of the given choice.
pub fn new(
ir_desc: &ir::IrDesc,
mut inputs: Vec<ir::ChoiceInstance>,
self_id: usize,
conditions: &[ir::Condition],
env: FxHashMap<ir::Variable, ir::Set>,
) -> (Vec<ir::Set>, ir::SetConstraints, Self, ir::Adaptator) {
// Create the new evironement.
let (foralls, set_constraints, mut adaptator) =
ir_desc.adapt_env(env, &inputs[self_id]);
let choice = inputs.swap_remove(self_id).choice;
adaptator.set_input(inputs.len(), self_id);
let inputs = inputs.into_iter().map(|i| i.adapt(&adaptator)).collect();
// Extract the constraints on the considered input.
let choice = ir_desc.get_choice(&choice);
let value_type = choice.value_type().adapt(&adaptator);
let mut self_condition = ir::ValueSet::empty(&value_type);
let others_conditions = conditions
.iter()
.flat_map(|condition| {
let alternatives =
condition.alternatives_of(self_id, &value_type, ir_desc);
if let Some(alternatives) = alternatives {
self_condition.extend(alternatives.adapt(&adaptator));
None
} else {
Some(condition.adapt(&adaptator))
}
})
.collect();
let condition = ChoiceCondition {
inputs,
self_condition,
others_conditions,
};
(foralls, set_constraints, condition, adaptator)
}
}
impl Adaptable for ChoiceCondition {
fn adapt(&self, adaptator: &ir::Adaptator) -> Self {
ChoiceCondition {
inputs: self.inputs.adapt(&adaptator),
self_condition: self.self_condition.adapt(&adaptator),
others_conditions: self.others_conditions.adapt(&adaptator),
}
}
}
/// Restricts the set of valid values.
#[derive(Clone, Debug)]
pub struct FilterAction {
pub set_constraints: ir::SetConstraints,
pub filter: FilterCall,
}
|
use std::collections::VecDeque;
use itertools::Itertools;
pub use crate::graph::Graph;
pub use crate::fasttw::Decomposition;
pub use crate::parser::Formula;
pub type Assignment = Vec<bool>;
pub type NiceDecomposition = Vec<(usize, Node)>;
// assignment (bit-map), score, true variables
pub type Configuration = (usize, usize, Vec<usize>);
#[derive(Clone, Copy, Debug)]
pub enum Node {
Leaf,
Introduce(usize),
Forget(usize),
Edge(usize, usize),
Join
}
pub use crate::solver::Node::*;
pub trait Solve {
fn solve(self, td: Decomposition, k: usize, formula: Formula) -> Option<(Assignment, usize)>;
}
pub fn duplicate_configs(configs: &mut Vec<Configuration>, var: usize, tree_index: &Vec<usize>) {
// clone configs and set bit for var to 1
let clones = configs.iter().cloned().map(|(mut a, s, mut v)| {
set_bit(&mut a, tree_index[var], true);
v.push(var);
(a, s, v)
}).collect_vec();
// append clones to config
configs.extend(clones);
}
pub fn deduplicate(config: &mut Vec<Configuration>) {
let max_fingerprint = config.iter().map(|(a, _, _)| a).max().unwrap();
// we should save every byte possible here, so we also use usize instead of Option<usize>
// for this we use 0 as None and i+1 as Some(i)
let mut indexes = vec![0; max_fingerprint+1];
for (i, &(a, s, _)) in config.iter().enumerate() {
if indexes[a] == 0 { // None
indexes[a] = i+1;
} else { // Some(i+1)
if config[indexes[a] - 1].1 < s {
// this one is better
indexes[a] = i+1
}
}
}
// deduplicate
for i in (0..config.len()).rev() {
let fingerprint = config[i].0;
if indexes[fingerprint] != i+1 {
// if an assignment does not find its own index, another assignment with the same
// fingerprint had a better score, so we can remove this assigmnent
config.swap_remove(i);
}
}
}
pub fn make_nice(graph: &impl Graph, td: Decomposition, very_nice: bool) -> NiceDecomposition {
enum Work<'a> {
// parent node, children
Join(usize, &'a [usize]),
// parent node, child
Stretch(usize, usize),
// parent node, leaf-bag
Empty(usize, usize)
}
let mut nice_decomposition = Vec::new();
let (root, children) = reverse(&td);
let mut work_queue = VecDeque::new();
work_queue.push_back(Work::Stretch(0, root));
while let Some(work) = work_queue.pop_front() {
match work {
Work::Join(parent, children) => {
// this is where the join node will be placed
let this_node = nice_decomposition.len();
if children.len() == 2 {
// join left and right
nice_decomposition.push((parent, Join));
// only two children remain, no further joins needed. stretch left and right from join-bag
work_queue.push_back(Work::Stretch(this_node, children[0]));
work_queue.push_back(Work::Stretch(this_node, children[1]));
} else {
// join the following join node and the following stretch
nice_decomposition.push((parent, Join));
// join children except for the last
work_queue.push_back(Work::Join(this_node, &children[0..children.len()-1]));
// stretch from Join-root to last child
work_queue.push_back(Work::Stretch(this_node, *children.last().unwrap()));
}
}
Work::Stretch(mut parent, child) => {
// while we stretch from the parent to its child, we actually add and remove from the child
let (parent_bag, src_bag) = &td[child];
let dest_bag = if child == root { &[] } else { td[*parent_bag].1.as_slice() };
// find out which nodes to introduce (add) or forget (remove) if moving from src_bag to dest_bag
let add = dest_bag.into_iter().filter(|v| !src_bag.contains(v)).collect_vec();
let remove = src_bag.into_iter().filter(|v| !dest_bag.contains(v)).collect_vec();
for &introduce in add {
nice_decomposition.push((parent, Introduce(introduce)));
parent = nice_decomposition.len() - 1;
}
for &forget in remove {
nice_decomposition.push((parent, Forget(forget)));
parent = nice_decomposition.len() - 1;
if very_nice {
// add all edges that are incident to forget
for &node in src_bag {
if graph.edge(node, forget) {
nice_decomposition.push((parent, Edge(node, forget)));
parent += 1;
} else if graph.edge(forget, node) {
nice_decomposition.push((parent, Edge(forget, node)));
parent += 1;
}
}
}
}
// next work item is whatever follows from child or final leaf node, if child has no children
if children[child].len() == 0 {
work_queue.push_back(Work::Empty(parent, child))
} else if children[child].len() > 1 {
work_queue.push_back(Work::Join(parent, &children[child]));
} else {
work_queue.push_back(Work::Stretch(parent, children[child][0]));
}
}
Work::Empty(mut parent, leaf_bag) => {
// introduce everything to start with empty bag
for &introduce in &td[leaf_bag].1 {
nice_decomposition.push((parent, Introduce(introduce)));
parent = nice_decomposition.len() - 1;
}
// add empty bag as leaf
nice_decomposition.push((parent, Leaf));
}
}
}
nice_decomposition
}
pub fn reverse<T>(tree: &Vec<(usize, T)>) -> (usize, Vec<Vec<usize>>) {
let (root, _) = tree.iter().enumerate().find(|(i, (p, _))| p == i).unwrap();
let mut children = vec![Vec::with_capacity(2); tree.len()];
for (i, &(parent, _)) in tree.iter().enumerate() {
// root should not be its own child
if parent != i {
children[parent].push(i);
}
}
(root, children)
}
fn post_order<T>(tree: &Vec<(usize, T)>) -> Vec<usize> {
let (root, children) = reverse(&tree);
let mut traverse_stack = vec![root];
let mut traversal = Vec::with_capacity(tree.len());
// do a preorder
while let Some(node) = traverse_stack.pop() {
traversal.push(node);
for &child in &children[node] {
traverse_stack.push(child);
}
}
// postorder is reversed preorder (with the exception of going right to left now)
traversal.reverse();
traversal
}
pub fn traverse_order(tree: &Vec<(usize, Node)>) -> Vec<usize> {
let mut optimized_subtrees = vec![];
for i in post_order(tree) {
let (_, node) = tree[i];
match node {
Leaf => {
optimized_subtrees.push((1, vec![i]))
},
Forget(_) | Introduce(_) | Edge(_, _) => {
let (stack_cost, mut traversal) = optimized_subtrees.pop().unwrap();
traversal.push(i);
optimized_subtrees.push((stack_cost, traversal));
},
Join => {
let (left_cost, left_traversal) = optimized_subtrees.pop().unwrap();
let (right_cost, right_traversal) = optimized_subtrees.pop().unwrap();
if left_cost < right_cost {
// go right first to reduce its cost to 1
let mut traversal: Vec<_> = right_traversal.into_iter().chain(left_traversal.into_iter()).collect();
traversal.push(i);
optimized_subtrees.push((1 + left_cost, traversal));
} else {
// go left first to reduce its cost to 1
let mut traversal: Vec<_> = left_traversal.into_iter().chain(right_traversal.into_iter()).collect();
traversal.push(i);
optimized_subtrees.push((1 + right_cost, traversal));
}
}
}
}
optimized_subtrees.pop().unwrap().1
}
pub fn tree_index(tree: &NiceDecomposition, k: usize, size: usize) -> Vec<usize> {
let (root, children) = reverse(tree);
let mut index = vec![0; size];
let mut free = vec![(0..k).collect_vec()];
let mut work_stack = vec![root];
while let Some(node) = work_stack.pop() {
match tree[node].1 {
Forget(node) => {
// claim first free index in current free list
let free_index = free.last_mut().unwrap().pop().unwrap();
index[node] = free_index;
},
Introduce(node) => {
// free own index again
free.last_mut().unwrap().push(index[node]);
},
Join => {
// we need to be able to undo all changes to the free list if we jump into the right sub-tree
free.push(free.last().unwrap().clone());
},
Leaf => {
// we are done with this path, so dispose all changes done to the free list since last join
free.pop();
},
// the rest is uninteresting
_ => {}
}
// traverse in preorder
for &child in &children[node] {
work_stack.push(child);
}
}
index
}
pub fn set_bit(bitmap: &mut usize, bit: usize, value: bool) {
if value {
*bitmap |= 1 << bit;
} else {
*bitmap &= !(1 << bit);
}
}
pub fn get_bit(bitmap: &usize, bit: usize) -> bool {
(bitmap & (1 << bit)) != 0
}
|
use cpp_data::{CppDataWithDeps, CppData, ParserCppData, ProcessedCppData, CppTypeAllocationPlace,
CppTypeKind, CppVisibility, CppTemplateInstantiations, CppTemplateInstantiation,
CppTypeData, CppBaseSpecifier};
use cpp_method::{CppMethod, CppMethodKind, CppMethodClassMembership};
use cpp_type::{CppType, CppTypeClassBase, CppTypeBase, CppTypeIndirection};
use common::log;
use common::errors::{Result, unexpected};
use std::collections::{HashMap, HashSet};
use std::iter::once;
use common::string_utils::JoinWithSeparator;
struct CppPostProcessor<'a> {
parser_data: ParserCppData,
dependencies: Vec<&'a CppData>,
}
/// Derives `ProcessedCppData` from `ParserCppData`.
pub fn cpp_post_process<'a>(parser_data: ParserCppData,
dependencies: Vec<&'a CppData>,
allocation_place_overrides: &HashMap<String, CppTypeAllocationPlace>)
-> Result<CppDataWithDeps<'a>> {
let processor = CppPostProcessor {
parser_data: parser_data,
dependencies: dependencies,
};
let inherited_methods = processor.detect_inherited_methods2()?;
let implicit_destructors = processor
.ensure_explicit_destructors(&inherited_methods)?;
let type_allocation_places =
processor
.choose_allocation_places(allocation_place_overrides, &inherited_methods)?;
let result = ProcessedCppData {
implicit_destructors: implicit_destructors,
template_instantiations: processor.find_template_instantiations(),
inherited_methods: inherited_methods,
signal_argument_types: processor.detect_signal_argument_types()?,
type_allocation_places: type_allocation_places,
};
Ok(CppDataWithDeps {
current: CppData {
parser: processor.parser_data,
processed: result,
},
dependencies: processor.dependencies,
})
}
impl<'a> CppPostProcessor<'a> {
/// Checks if specified class has virtual destructor (own or inherited).
pub fn has_virtual_destructor(&self, class_name: &str, inherited_methods: &[CppMethod]) -> bool {
for method in self
.parser_data
.methods
.iter()
.chain(inherited_methods.iter()) {
if let Some(ref info) = method.class_membership {
if info.kind == CppMethodKind::Destructor && &info.class_type.name == class_name {
return info.is_virtual;
}
}
}
false
}
/// Checks if specified class has any virtual methods (own or inherited).
pub fn has_virtual_methods(&self, class_name: &str, inherited_methods: &[CppMethod]) -> bool {
for method in self
.parser_data
.methods
.iter()
.chain(inherited_methods.iter()) {
if let Some(ref info) = method.class_membership {
if &info.class_type.name == class_name && info.is_virtual {
return true;
}
}
}
false
}
/// Adds destructors for every class that does not have explicitly
/// defined destructor, allowing to create wrappings for
/// destructors implicitly available in C++.
fn ensure_explicit_destructors(&self, inherited_methods: &[CppMethod]) -> Result<Vec<CppMethod>> {
let mut methods = Vec::new();
for type1 in &self.parser_data.types {
if let CppTypeKind::Class { .. } = type1.kind {
let class_name = &type1.name;
let found_destructor = self
.parser_data
.methods
.iter()
.any(|m| m.is_destructor() && m.class_name() == Some(class_name));
if !found_destructor {
let is_virtual = self.has_virtual_destructor(class_name, inherited_methods);
methods.push(CppMethod {
name: format!("~{}", class_name),
class_membership: Some(CppMethodClassMembership {
class_type: type1.default_class_type()?,
is_virtual: is_virtual,
is_pure_virtual: false,
is_const: false,
is_static: false,
visibility: CppVisibility::Public,
is_signal: false,
is_slot: false,
kind: CppMethodKind::Destructor,
}),
operator: None,
return_type: CppType::void(),
arguments: vec![],
allows_variadic_arguments: false,
include_file: type1.include_file.clone(),
origin_location: None,
template_arguments: None,
template_arguments_values: None,
declaration_code: None,
doc: None,
inheritance_chain: Vec::new(),
//is_fake_inherited_method: false,
is_ffi_whitelisted: false,
});
}
}
}
Ok(methods)
}
/// Searches for template instantiations in this library's API,
/// excluding results that were already processed in dependencies.
#[cfg_attr(feature="clippy", allow(block_in_if_condition_stmt))]
fn find_template_instantiations(&self) -> Vec<CppTemplateInstantiations> {
fn check_type(type1: &CppType,
deps: &[&CppData],
result: &mut Vec<CppTemplateInstantiations>) {
if let CppTypeBase::Class(CppTypeClassBase {
ref name,
ref template_arguments,
}) = type1.base {
if let Some(ref template_arguments) = *template_arguments {
if !template_arguments
.iter()
.any(|x| x.base.is_or_contains_template_parameter()) {
if !deps
.iter()
.any(|data| {
data
.processed
.template_instantiations
.iter()
.any(|i| {
&i.class_name == name &&
i.instantiations
.iter()
.any(|x| &x.template_arguments == template_arguments)
})
}) {
if !result.iter().any(|x| &x.class_name == name) {
log::llog(log::DebugParser, || {
format!("Found template instantiation: {}<{:?}>",
name,
template_arguments)
});
result.push(CppTemplateInstantiations {
class_name: name.clone(),
instantiations: vec![CppTemplateInstantiation {
template_arguments: template_arguments.clone(),
}],
});
} else {
let item = result
.iter_mut()
.find(|x| &x.class_name == name)
.expect("previously found");
if !item
.instantiations
.iter()
.any(|x| &x.template_arguments == template_arguments) {
log::llog(log::DebugParser, || {
format!("Found template instantiation: {}<{:?}>",
name,
template_arguments)
});
item
.instantiations
.push(CppTemplateInstantiation {
template_arguments: template_arguments.clone(),
});
}
}
}
}
for arg in template_arguments {
check_type(arg, deps, result);
}
}
}
}
let mut result = Vec::new();
for m in &self.parser_data.methods {
check_type(&m.return_type, &self.dependencies, &mut result);
for arg in &m.arguments {
check_type(&arg.argument_type, &self.dependencies, &mut result);
}
}
for t in &self.parser_data.types {
if let CppTypeKind::Class {
ref bases,
ref fields,
..
} = t.kind {
for base in bases {
check_type(&base.base_type, &self.dependencies, &mut result);
}
for field in fields {
check_type(&field.field_type, &self.dependencies, &mut result);
}
}
}
result
}
fn detect_inherited_methods2(&self) -> Result<Vec<CppMethod>> {
let mut remaining_classes: Vec<&CppTypeData> = self
.parser_data
.types
.iter()
.filter(|t| if let CppTypeKind::Class { ref bases, .. } = t.kind {
!bases.is_empty()
} else {
false
})
.collect();
let mut ordered_classes = Vec::new();
while !remaining_classes.is_empty() {
let mut any_added = false;
let mut remaining_classes2 = Vec::new();
for class in &remaining_classes {
if let CppTypeKind::Class { ref bases, .. } = class.kind {
if bases
.iter()
.any(|base| if base.visibility != CppVisibility::Private &&
base.base_type.indirection == CppTypeIndirection::None {
if let CppTypeBase::Class(ref base_info) = base.base_type.base {
remaining_classes
.iter()
.any(|c| c.name == base_info.name)
} else {
false
}
} else {
false
}) {
remaining_classes2.push(*class);
} else {
ordered_classes.push(*class);
any_added = true;
}
} else {
unreachable!()
}
}
remaining_classes = remaining_classes2;
if !any_added {
return Err("Cyclic dependency detected while detecting inherited methods".into());
}
}
let mut result = Vec::new();
for class in ordered_classes {
log::llog(log::DebugInheritance,
|| format!("Detecting inherited methods for {}\n", class.name));
let own_methods: Vec<&CppMethod> = self
.parser_data
.methods
.iter()
.filter(|m| m.class_name() == Some(&class.name))
.collect();
let bases = if let CppTypeKind::Class { ref bases, .. } = class.kind {
bases
} else {
unreachable!()
};
let bases_with_methods: Vec<(&CppBaseSpecifier, Vec<&CppMethod>)> = bases
.iter()
.filter(|base| {
base.visibility != CppVisibility::Private &&
base.base_type.indirection == CppTypeIndirection::None
})
.map(|base| {
let methods = if let CppTypeBase::Class(ref base_class_base) = base.base_type.base {
once(&self.parser_data)
.chain(self.dependencies.iter().map(|d| &d.parser))
.map(|p| &p.methods)
.flat_map(|m| m)
.filter(|m| if let Some(ref info) = m.class_membership {
&info.class_type == base_class_base
} else {
false
})
.collect()
} else {
Vec::new()
};
(base, methods)
})
.filter(|x| !x.1.is_empty())
.collect();
for &(ref base, ref methods) in &bases_with_methods {
if let CppTypeBase::Class(ref base_class_base) = base.base_type.base {
for method in methods {
if let CppTypeKind::Class { ref using_directives, .. } = class.kind {
let use_method = if using_directives
.iter()
.any(|dir| {
dir.class_name == base_class_base.name && dir.method_name == method.name
}) {
true // excplicitly inherited with a using directive
} else if own_methods.iter().any(|m| m.name == method.name) {
// not inherited because method with the same name exists in the derived class
false
} else if bases_with_methods
.iter()
.any(|&(ref base2, ref methods2)| {
base != base2 && methods2.iter().any(|m| m.name == method.name)
}) {
// not inherited because method with the same name exists in one of
// the other bases
false
} else {
// no aliased method found and no using directives
true
};
// TODO: detect diamond inheritance
if use_method {
let mut new_method = (*method).clone();
if let Some(ref mut info) = new_method.class_membership {
info.class_type = class.default_class_type()?;
} else {
return Err(unexpected("no class membership").into());
}
new_method.include_file = class.include_file.clone();
new_method.origin_location = None;
new_method.declaration_code = None;
new_method.inheritance_chain.push((*base).clone());
//new_method.is_fake_inherited_method = true;
log::llog(log::DebugInheritance,
|| format!("Method added: {}", new_method.short_text()));
log::llog(log::DebugInheritance, || {
format!("Base method: {} ({:?})\n",
method.short_text(),
method.origin_location)
});
result.push(new_method);
}
} else {
unreachable!()
}
}
} else {
unreachable!()
}
}
}
Ok(result)
}
fn detect_signal_argument_types(&self) -> Result<Vec<Vec<CppType>>> {
let mut all_types = HashSet::new();
for method in &self.parser_data.methods {
if let Some(ref method_info) = method.class_membership {
if method_info.is_signal {
let types: Vec<_> = method
.arguments
.iter()
.map(|x| x.argument_type.clone())
.collect();
if !all_types.contains(&types) &&
!self
.dependencies
.iter()
.any(|d| {
d.processed
.signal_argument_types
.iter()
.any(|t| t == &types)
}) {
all_types.insert(types);
}
}
}
}
let mut types_with_omitted_args = HashSet::new();
for t in &all_types {
let mut types = t.clone();
while let Some(_) = types.pop() {
if !types_with_omitted_args.contains(&types) && !all_types.contains(&types) &&
!self
.dependencies
.iter()
.any(|d| {
d.processed
.signal_argument_types
.iter()
.any(|t| t == &types)
}) {
types_with_omitted_args.insert(types.clone());
}
}
}
all_types.extend(types_with_omitted_args.into_iter());
log::llog(log::DebugSignals, || "Signal argument types:");
for t in &all_types {
log::llog(log::DebugSignals, || {
format!(" ({})",
t.iter().map(|x| x.to_cpp_pseudo_code()).join(", "))
});
}
Ok(all_types.into_iter().collect())
}
/// Detects the preferred type allocation place for each type based on
/// API of all known methods. Keys of `overrides` are C++ type names.
/// If `overrides` contains type allocation place for a type, it's used instead of
/// the place that would be automatically selected.
pub fn choose_allocation_places(&self,
overrides: &HashMap<String, CppTypeAllocationPlace>,
inherited_methods: &[CppMethod])
-> Result<HashMap<String, CppTypeAllocationPlace>> {
log::status("Detecting type allocation places");
#[derive(Default)]
struct TypeStats {
// has_derived_classes: bool,
has_virtual_methods: bool,
pointers_count: usize,
not_pointers_count: usize,
};
fn check_type(cpp_type: &CppType, data: &mut HashMap<String, TypeStats>) {
if let CppTypeBase::Class(CppTypeClassBase {
ref name,
ref template_arguments,
}) = cpp_type.base {
if !data.contains_key(name) {
data.insert(name.clone(), TypeStats::default());
}
match cpp_type.indirection {
CppTypeIndirection::None | CppTypeIndirection::Ref => {
data.get_mut(name).unwrap().not_pointers_count += 1
}
CppTypeIndirection::Ptr => data.get_mut(name).unwrap().pointers_count += 1,
_ => {}
}
if let Some(ref args) = *template_arguments {
for arg in args {
check_type(arg, data);
}
}
}
}
let mut data = HashMap::new();
for type1 in &self.parser_data.types {
if self.has_virtual_methods(&type1.name, inherited_methods) {
if !data.contains_key(&type1.name) {
data.insert(type1.name.clone(), TypeStats::default());
}
data.get_mut(&type1.name).unwrap().has_virtual_methods = true;
}
}
for method in &self.parser_data.methods {
check_type(&method.return_type, &mut data);
for arg in &method.arguments {
check_type(&arg.argument_type, &mut data);
}
}
let mut results = HashMap::new();
{
let mut logger = log::default_logger();
if logger.is_on(log::DebugAllocationPlace) {
for (name, stats) in &data {
logger.log(log::DebugAllocationPlace,
format!("{}\t{}\t{}\t{}",
name,
stats.has_virtual_methods,
stats.pointers_count,
stats.not_pointers_count));
}
}
}
for type1 in &self.parser_data.types {
if !type1.is_class() {
continue;
}
let name = &type1.name;
let result = if overrides.contains_key(name) {
overrides[name].clone()
} else if let Some(ref stats) = data.get(name) {
if stats.has_virtual_methods {
CppTypeAllocationPlace::Heap
} else if stats.pointers_count == 0 {
CppTypeAllocationPlace::Stack
} else {
let min_safe_data_count = 5;
let min_not_pointers_percent = 0.3;
if stats.pointers_count + stats.not_pointers_count < min_safe_data_count {
log::llog(log::DebugAllocationPlace,
|| format!("Can't determine type allocation place for '{}':", name));
log::llog(log::DebugAllocationPlace, || {
format!(" Not enough data (pointers={}, not pointers={})",
stats.pointers_count,
stats.not_pointers_count)
});
} else if stats.not_pointers_count as f32 /
(stats.pointers_count + stats.not_pointers_count) as f32 >
min_not_pointers_percent {
log::llog(log::DebugAllocationPlace,
|| format!("Can't determine type allocation place for '{}':", name));
log::llog(log::DebugAllocationPlace, || {
format!(" Many not pointers (pointers={}, not pointers={})",
stats.pointers_count,
stats.not_pointers_count)
});
}
CppTypeAllocationPlace::Heap
}
} else {
log::llog(log::DebugAllocationPlace, || {
format!("Can't determine type allocation place for '{}' (no data)",
name)
});
CppTypeAllocationPlace::Heap
};
results.insert(name.clone(), result);
}
log::llog(log::DebugAllocationPlace, || {
format!("Allocation place is heap for: {}",
results
.iter()
.filter(|&(_, v)| v == &CppTypeAllocationPlace::Heap)
.map(|(k, _)| k)
.join(", "))
});
log::llog(log::DebugAllocationPlace, || {
format!("Allocation place is stack for: {}",
results
.iter()
.filter(|&(_, v)| v == &CppTypeAllocationPlace::Stack)
.map(|(k, _)| k)
.join(", "))
});
Ok(results)
}
}
|
use super::utills::get_points;
use prelude::*;
use serenity::framework::standard::CreateGroup;
use store::UserInfo;
use store::UsersInfo;
use utills::success;
use PREFIX;
struct StartCommand;
impl Command for StartCommand {
fn execute(&self, ctx: &mut Context, msg: &Message, _args: Args) -> CommandResult {
let found_points = match get_points(ctx, msg.author.id) {
Some(points) => Some(points),
None => {
let mut data = ctx.data.lock();
let users = data.get_mut::<UsersInfo>().unwrap();
users.insert(msg.author.id.0, UserInfo::default());
None
}
};
match found_points {
Some(points) => {
let _ = success(
msg.channel_id,
&format!("You've already started. You have {} points", points),
None,
);
}
None => {
let _ = success(
msg.channel_id,
&format!(
"You are now collecting Boogie Points! You can type `{}bp info` to see how many Boogie Points you have",
PREFIX
),
None,
);
}
}
Ok(())
}
}
pub fn register_command(sf: CreateGroup) -> CreateGroup {
sf.cmd("start", StartCommand)
}
|
use std::iter::FromIterator;
use std::str::FromStr;
use toml_datetime::*;
use crate::key::Key;
use crate::parser;
use crate::repr::{Decor, Formatted};
use crate::{Array, InlineTable, InternalString, RawString};
/// Representation of a TOML Value (as part of a Key/Value Pair).
#[derive(Debug, Clone)]
pub enum Value {
/// A string value.
String(Formatted<String>),
/// A 64-bit integer value.
Integer(Formatted<i64>),
/// A 64-bit float value.
Float(Formatted<f64>),
/// A boolean value.
Boolean(Formatted<bool>),
/// An RFC 3339 formatted date-time with offset.
Datetime(Formatted<Datetime>),
/// An inline array of values.
Array(Array),
/// An inline table of key/value pairs.
InlineTable(InlineTable),
}
/// Downcasting
impl Value {
/// Text description of value type
pub fn type_name(&self) -> &'static str {
match self {
Value::String(..) => "string",
Value::Integer(..) => "integer",
Value::Float(..) => "float",
Value::Boolean(..) => "boolean",
Value::Datetime(..) => "datetime",
Value::Array(..) => "array",
Value::InlineTable(..) => "inline table",
}
}
/// Casts `self` to str.
pub fn as_str(&self) -> Option<&str> {
match *self {
Value::String(ref value) => Some(value.value()),
_ => None,
}
}
/// Returns true iff `self` is a string.
pub fn is_str(&self) -> bool {
self.as_str().is_some()
}
/// Casts `self` to integer.
pub fn as_integer(&self) -> Option<i64> {
match *self {
Value::Integer(ref value) => Some(*value.value()),
_ => None,
}
}
/// Returns true iff `self` is an integer.
pub fn is_integer(&self) -> bool {
self.as_integer().is_some()
}
/// Casts `self` to float.
pub fn as_float(&self) -> Option<f64> {
match *self {
Value::Float(ref value) => Some(*value.value()),
_ => None,
}
}
/// Returns true iff `self` is a float.
pub fn is_float(&self) -> bool {
self.as_float().is_some()
}
/// Casts `self` to boolean.
pub fn as_bool(&self) -> Option<bool> {
match *self {
Value::Boolean(ref value) => Some(*value.value()),
_ => None,
}
}
/// Returns true iff `self` is a boolean.
pub fn is_bool(&self) -> bool {
self.as_bool().is_some()
}
/// Casts `self` to date-time.
pub fn as_datetime(&self) -> Option<&Datetime> {
match *self {
Value::Datetime(ref value) => Some(value.value()),
_ => None,
}
}
/// Returns true iff `self` is a date-time.
pub fn is_datetime(&self) -> bool {
self.as_datetime().is_some()
}
/// Casts `self` to array.
pub fn as_array(&self) -> Option<&Array> {
match *self {
Value::Array(ref value) => Some(value),
_ => None,
}
}
/// Casts `self` to mutable array.
pub fn as_array_mut(&mut self) -> Option<&mut Array> {
match *self {
Value::Array(ref mut value) => Some(value),
_ => None,
}
}
/// Returns true iff `self` is an array.
pub fn is_array(&self) -> bool {
self.as_array().is_some()
}
/// Casts `self` to inline table.
pub fn as_inline_table(&self) -> Option<&InlineTable> {
match *self {
Value::InlineTable(ref value) => Some(value),
_ => None,
}
}
/// Casts `self` to mutable inline table.
pub fn as_inline_table_mut(&mut self) -> Option<&mut InlineTable> {
match *self {
Value::InlineTable(ref mut value) => Some(value),
_ => None,
}
}
/// Returns true iff `self` is an inline table.
pub fn is_inline_table(&self) -> bool {
self.as_inline_table().is_some()
}
}
impl Value {
/// Get the decoration of the value.
/// # Example
/// ```rust
/// let v = toml_edit::Value::from(true);
/// assert_eq!(v.decor().suffix(), None);
///```
pub fn decor_mut(&mut self) -> &mut Decor {
match self {
Value::String(f) => f.decor_mut(),
Value::Integer(f) => f.decor_mut(),
Value::Float(f) => f.decor_mut(),
Value::Boolean(f) => f.decor_mut(),
Value::Datetime(f) => f.decor_mut(),
Value::Array(a) => a.decor_mut(),
Value::InlineTable(t) => t.decor_mut(),
}
}
/// Get the decoration of the value.
/// # Example
/// ```rust
/// let v = toml_edit::Value::from(true);
/// assert_eq!(v.decor().suffix(), None);
///```
pub fn decor(&self) -> &Decor {
match *self {
Value::String(ref f) => f.decor(),
Value::Integer(ref f) => f.decor(),
Value::Float(ref f) => f.decor(),
Value::Boolean(ref f) => f.decor(),
Value::Datetime(ref f) => f.decor(),
Value::Array(ref a) => a.decor(),
Value::InlineTable(ref t) => t.decor(),
}
}
/// Sets the prefix and the suffix for value.
/// # Example
/// ```rust
/// let mut v = toml_edit::Value::from(42);
/// assert_eq!(&v.to_string(), "42");
/// let d = v.decorated(" ", " ");
/// assert_eq!(&d.to_string(), " 42 ");
/// ```
pub fn decorated(mut self, prefix: impl Into<RawString>, suffix: impl Into<RawString>) -> Self {
self.decorate(prefix, suffix);
self
}
pub(crate) fn decorate(&mut self, prefix: impl Into<RawString>, suffix: impl Into<RawString>) {
let decor = self.decor_mut();
*decor = Decor::new(prefix, suffix);
}
/// Returns the location within the original document
pub(crate) fn span(&self) -> Option<std::ops::Range<usize>> {
match self {
Value::String(f) => f.span(),
Value::Integer(f) => f.span(),
Value::Float(f) => f.span(),
Value::Boolean(f) => f.span(),
Value::Datetime(f) => f.span(),
Value::Array(a) => a.span(),
Value::InlineTable(t) => t.span(),
}
}
pub(crate) fn despan(&mut self, input: &str) {
match self {
Value::String(f) => f.despan(input),
Value::Integer(f) => f.despan(input),
Value::Float(f) => f.despan(input),
Value::Boolean(f) => f.despan(input),
Value::Datetime(f) => f.despan(input),
Value::Array(a) => a.despan(input),
Value::InlineTable(t) => t.despan(input),
}
}
}
impl FromStr for Value {
type Err = crate::TomlError;
/// Parses a value from a &str
fn from_str(s: &str) -> Result<Self, Self::Err> {
parser::parse_value(s)
}
}
impl<'b> From<&'b Value> for Value {
fn from(s: &'b Value) -> Self {
s.clone()
}
}
impl<'b> From<&'b str> for Value {
fn from(s: &'b str) -> Self {
s.to_owned().into()
}
}
impl<'b> From<&'b String> for Value {
fn from(s: &'b String) -> Self {
s.to_owned().into()
}
}
impl From<String> for Value {
fn from(s: String) -> Self {
Value::String(Formatted::new(s))
}
}
impl<'b> From<&'b InternalString> for Value {
fn from(s: &'b InternalString) -> Self {
s.as_str().into()
}
}
impl From<InternalString> for Value {
fn from(s: InternalString) -> Self {
s.as_str().into()
}
}
impl From<i64> for Value {
fn from(i: i64) -> Self {
Value::Integer(Formatted::new(i))
}
}
impl From<f64> for Value {
fn from(f: f64) -> Self {
Value::Float(Formatted::new(f))
}
}
impl From<bool> for Value {
fn from(b: bool) -> Self {
Value::Boolean(Formatted::new(b))
}
}
impl From<Datetime> for Value {
fn from(d: Datetime) -> Self {
Value::Datetime(Formatted::new(d))
}
}
impl From<Date> for Value {
fn from(d: Date) -> Self {
let d: Datetime = d.into();
d.into()
}
}
impl From<Time> for Value {
fn from(d: Time) -> Self {
let d: Datetime = d.into();
d.into()
}
}
impl From<Array> for Value {
fn from(array: Array) -> Self {
Value::Array(array)
}
}
impl From<InlineTable> for Value {
fn from(table: InlineTable) -> Self {
Value::InlineTable(table)
}
}
impl<V: Into<Value>> FromIterator<V> for Value {
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = V>,
{
let array: Array = iter.into_iter().collect();
Value::Array(array)
}
}
impl<K: Into<Key>, V: Into<Value>> FromIterator<(K, V)> for Value {
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
{
let table: InlineTable = iter.into_iter().collect();
Value::InlineTable(table)
}
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
crate::encode::Encode::encode(self, f, None, ("", ""))
}
}
// `key1 = value1`
pub(crate) const DEFAULT_VALUE_DECOR: (&str, &str) = (" ", "");
// `{ key = value }`
pub(crate) const DEFAULT_TRAILING_VALUE_DECOR: (&str, &str) = (" ", " ");
// `[value1, value2]`
pub(crate) const DEFAULT_LEADING_VALUE_DECOR: (&str, &str) = ("", "");
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_iter_formatting() {
let features = vec!["node".to_owned(), "mouth".to_owned()];
let features: Value = features.iter().cloned().collect();
assert_eq!(features.to_string(), r#"["node", "mouth"]"#);
}
}
|
// Copyright (C) 2019 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: MIT
use std::io::{self, Write};
use crate::{Choice, Input, Message, Password, Question, Result};
/// The fallback backend using standard input and output.
///
/// This backend is intended as a fallback backend to use if no other backend is available. The
/// dialogs are printed to the standard output and user input is read from the standard input.
#[derive(Debug)]
pub struct Stdio {}
impl Stdio {
/// Creates a new `Stdio` instance.
pub fn new() -> Stdio {
Stdio {}
}
}
impl AsRef<Stdio> for Stdio {
fn as_ref(&self) -> &Self {
self
}
}
fn print_title(title: &Option<String>) {
if let Some(ref title) = title {
println!("{}", title);
println!("{}", "=".repeat(title.len()));
}
}
fn read_input() -> Result<String> {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(input.trim_end_matches('\n').to_string())
}
fn parse_choice(input: &str) -> Choice {
match input.to_lowercase().as_ref() {
"y" => Choice::Yes,
"yes" => Choice::Yes,
"n" => Choice::No,
"no" => Choice::No,
_ => Choice::Cancel,
}
}
impl super::Backend for Stdio {
fn show_input(&self, input: &Input) -> Result<Option<String>> {
print_title(&input.title);
if let Some(ref default) = input.default {
print!("{} [default: {}]: ", input.text, default);
} else {
print!("{}: ", input.text);
}
io::stdout().flush()?;
let user_input = read_input()?;
if user_input.is_empty() {
if let Some(ref default) = input.default {
return Ok(Some(default.to_string()));
}
}
Ok(Some(user_input))
}
fn show_message(&self, message: &Message) -> Result<()> {
print_title(&message.title);
println!("{}", message.text);
Ok(())
}
fn show_password(&self, password: &Password) -> Result<Option<String>> {
print_title(&password.title);
print!("{}: ", password.text);
io::stdout().flush()?;
Ok(Some(rpassword::read_password()?))
}
fn show_question(&self, question: &Question) -> Result<Choice> {
print_title(&question.title);
print!("{} [y/n]: ", question.text);
io::stdout().flush()?;
Ok(parse_choice(&read_input()?))
}
}
|
fn main() {
#macro[[#m1[a], a*4]];
assert (#m1[2] == 8);
}
|
use super::component_prelude::*;
#[derive(Default)]
pub struct CanRun;
impl Component for CanRun {
type Storage = NullStorage<Self>;
}
|
use std::{cmp::Reverse, collections::BinaryHeap};
use proconio::input;
fn main() {
input! {
n: usize,
mut k: usize,
mut a: [usize; n],
};
let mut heap = BinaryHeap::new();
for i in 0..n {
heap.push((Reverse(a[i]), Reverse(i)));
}
let mut sub = 0;
while let Some((Reverse(x), Reverse(i))) = heap.pop() {
if (x - sub) * (heap.len() + 1) > k {
// もどす
heap.push((Reverse(x), Reverse(i)));
break;
}
k -= (x - sub) * (heap.len() + 1);
sub += x - sub;
a[i] = 0;
}
let l = heap.len();
let mut indicies = Vec::new();
for (_, Reverse(i)) in heap {
indicies.push(i);
}
indicies.sort();
for (t, &i) in indicies.iter().enumerate() {
a[i] -= sub;
a[i] -= k / l;
if t < k % l {
a[i] -= 1;
}
}
for i in 0..n {
print!("{}", a[i]);
if i + 1 < n {
print!(" ");
}
}
println!();
}
|
use std::{collections::HashMap, fmt::Display};
use async_trait::async_trait;
use data_types::{Namespace, NamespaceId, NamespaceSchema};
use super::NamespacesSource;
#[derive(Debug, Clone)]
/// contains [`Namespace`] and a [`NamespaceSchema`]
pub struct NamespaceWrapper {
/// namespace
pub ns: Namespace,
/// schema
pub schema: NamespaceSchema,
}
#[derive(Debug)]
pub struct MockNamespacesSource {
namespaces: HashMap<NamespaceId, NamespaceWrapper>,
}
impl MockNamespacesSource {
#[allow(dead_code)] // not used anywhere
pub fn new(namespaces: HashMap<NamespaceId, NamespaceWrapper>) -> Self {
Self { namespaces }
}
}
impl Display for MockNamespacesSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "mock")
}
}
#[async_trait]
impl NamespacesSource for MockNamespacesSource {
async fn fetch_by_id(&self, ns: NamespaceId) -> Option<Namespace> {
let wrapper = self.namespaces.get(&ns);
wrapper.map(|wrapper| wrapper.ns.clone())
}
async fn fetch_schema_by_id(&self, ns: NamespaceId) -> Option<NamespaceSchema> {
let wrapper = self.namespaces.get(&ns);
wrapper.map(|wrapper| wrapper.schema.clone())
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use data_types::{Column, ColumnId, ColumnType, ColumnsByName, TableId, TableSchema};
use super::*;
#[test]
fn test_display() {
assert_eq!(
MockNamespacesSource::new(HashMap::default()).to_string(),
"mock",
)
}
#[tokio::test]
async fn test_fetch_namespace() {
let ns_1 = NamespaceBuilder::new(1).build();
let ns_2 = NamespaceBuilder::new(2).build();
let namespaces = HashMap::from([
(NamespaceId::new(1), ns_1.clone()),
(NamespaceId::new(2), ns_2.clone()),
]);
let source = MockNamespacesSource::new(namespaces);
// different tables
assert_eq!(
source.fetch_by_id(NamespaceId::new(1)).await,
Some(ns_1.clone().ns),
);
assert_eq!(source.fetch_by_id(NamespaceId::new(2)).await, Some(ns_2.ns),);
// fetching does not drain
assert_eq!(source.fetch_by_id(NamespaceId::new(1)).await, Some(ns_1.ns),);
// unknown namespace => None result
assert_eq!(source.fetch_by_id(NamespaceId::new(3)).await, None,);
}
#[tokio::test]
async fn test_fetch_namespace_schema() {
let ns_1 = NamespaceBuilder::new(1).build();
let ns_2 = NamespaceBuilder::new(2).build();
let namespaces = HashMap::from([
(NamespaceId::new(1), ns_1.clone()),
(NamespaceId::new(2), ns_2.clone()),
]);
let source = MockNamespacesSource::new(namespaces);
// different tables
assert_eq!(
source.fetch_schema_by_id(NamespaceId::new(1)).await,
Some(ns_1.clone().schema),
);
assert_eq!(
source.fetch_schema_by_id(NamespaceId::new(2)).await,
Some(ns_2.schema),
);
// fetching does not drain
assert_eq!(
source.fetch_schema_by_id(NamespaceId::new(1)).await,
Some(ns_1.schema),
);
// unknown namespace => None result
assert_eq!(source.fetch_schema_by_id(NamespaceId::new(3)).await, None,);
}
#[derive(Debug)]
/// Build [`NamespaceWrapper`] for testing
pub struct NamespaceBuilder {
namespace: NamespaceWrapper,
}
impl NamespaceBuilder {
pub fn new(id: i64) -> Self {
let tables = BTreeMap::from([
(
"table1".to_string(),
TableSchema {
id: TableId::new(1),
partition_template: Default::default(),
columns: ColumnsByName::new([
Column {
name: "col1".to_string(),
id: ColumnId::new(1),
column_type: ColumnType::I64,
table_id: TableId::new(1),
},
Column {
name: "col2".to_string(),
id: ColumnId::new(2),
column_type: ColumnType::String,
table_id: TableId::new(1),
},
]),
},
),
(
"table2".to_string(),
TableSchema {
id: TableId::new(2),
partition_template: Default::default(),
columns: ColumnsByName::new([
Column {
name: "col1".to_string(),
id: ColumnId::new(3),
column_type: ColumnType::I64,
table_id: TableId::new(2),
},
Column {
name: "col2".to_string(),
id: ColumnId::new(4),
column_type: ColumnType::String,
table_id: TableId::new(2),
},
Column {
name: "col3".to_string(),
id: ColumnId::new(5),
column_type: ColumnType::F64,
table_id: TableId::new(2),
},
]),
},
),
]);
let id = NamespaceId::new(id);
Self {
namespace: NamespaceWrapper {
ns: Namespace {
id,
name: "ns".to_string(),
max_tables: 10,
max_columns_per_table: 10,
retention_period_ns: None,
deleted_at: None,
partition_template: Default::default(),
},
schema: NamespaceSchema {
id,
tables,
max_columns_per_table: 10,
max_tables: 42,
retention_period_ns: None,
partition_template: Default::default(),
},
},
}
}
pub fn build(self) -> NamespaceWrapper {
self.namespace
}
}
}
|
#[doc = "Reader of register IM"]
pub type R = crate::R<u32, super::IM>;
#[doc = "Writer for register IM"]
pub type W = crate::W<u32, super::IM>;
#[doc = "Register IM `reset()`'s with value 0"]
impl crate::ResetValue for super::IM {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `RTCALT0`"]
pub type RTCALT0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RTCALT0`"]
pub struct RTCALT0_W<'a> {
w: &'a mut W,
}
impl<'a> RTCALT0_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 `LOWBAT`"]
pub type LOWBAT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LOWBAT`"]
pub struct LOWBAT_W<'a> {
w: &'a mut W,
}
impl<'a> LOWBAT_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 `EXTW`"]
pub type EXTW_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EXTW`"]
pub struct EXTW_W<'a> {
w: &'a mut W,
}
impl<'a> EXTW_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 `WC`"]
pub type WC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `WC`"]
pub struct WC_W<'a> {
w: &'a mut W,
}
impl<'a> WC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `PADIOWK`"]
pub type PADIOWK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PADIOWK`"]
pub struct PADIOWK_W<'a> {
w: &'a mut W,
}
impl<'a> PADIOWK_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `RSTWK`"]
pub type RSTWK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RSTWK`"]
pub struct RSTWK_W<'a> {
w: &'a mut W,
}
impl<'a> RSTWK_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `VDDFAIL`"]
pub type VDDFAIL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `VDDFAIL`"]
pub struct VDDFAIL_W<'a> {
w: &'a mut W,
}
impl<'a> VDDFAIL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
impl R {
#[doc = "Bit 0 - RTC Alert 0 Interrupt Mask"]
#[inline(always)]
pub fn rtcalt0(&self) -> RTCALT0_R {
RTCALT0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 2 - Low Battery Voltage Interrupt Mask"]
#[inline(always)]
pub fn lowbat(&self) -> LOWBAT_R {
LOWBAT_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - External Wake-Up Interrupt Mask"]
#[inline(always)]
pub fn extw(&self) -> EXTW_R {
EXTW_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - External Write Complete/Capable Interrupt Mask"]
#[inline(always)]
pub fn wc(&self) -> WC_R {
WC_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Pad I/O Wake-Up Interrupt Mask"]
#[inline(always)]
pub fn padiowk(&self) -> PADIOWK_R {
PADIOWK_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Reset Pad I/O Wake-Up Interrupt Mask"]
#[inline(always)]
pub fn rstwk(&self) -> RSTWK_R {
RSTWK_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - VDD Fail Interrupt Mask"]
#[inline(always)]
pub fn vddfail(&self) -> VDDFAIL_R {
VDDFAIL_R::new(((self.bits >> 7) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - RTC Alert 0 Interrupt Mask"]
#[inline(always)]
pub fn rtcalt0(&mut self) -> RTCALT0_W {
RTCALT0_W { w: self }
}
#[doc = "Bit 2 - Low Battery Voltage Interrupt Mask"]
#[inline(always)]
pub fn lowbat(&mut self) -> LOWBAT_W {
LOWBAT_W { w: self }
}
#[doc = "Bit 3 - External Wake-Up Interrupt Mask"]
#[inline(always)]
pub fn extw(&mut self) -> EXTW_W {
EXTW_W { w: self }
}
#[doc = "Bit 4 - External Write Complete/Capable Interrupt Mask"]
#[inline(always)]
pub fn wc(&mut self) -> WC_W {
WC_W { w: self }
}
#[doc = "Bit 5 - Pad I/O Wake-Up Interrupt Mask"]
#[inline(always)]
pub fn padiowk(&mut self) -> PADIOWK_W {
PADIOWK_W { w: self }
}
#[doc = "Bit 6 - Reset Pad I/O Wake-Up Interrupt Mask"]
#[inline(always)]
pub fn rstwk(&mut self) -> RSTWK_W {
RSTWK_W { w: self }
}
#[doc = "Bit 7 - VDD Fail Interrupt Mask"]
#[inline(always)]
pub fn vddfail(&mut self) -> VDDFAIL_W {
VDDFAIL_W { w: self }
}
}
|
use std::marker::PhantomData;
use std::mem::size_of;
struct Something(i32, f32, String);
fn main() {
assert_eq!(0, size_of::<PhantomData<i32>>());
assert_eq!(0, size_of::<PhantomData<Something>>());
}
|
use crate::{
self as p2p, BootstrapConfig, Event, EventReceiver, Peers, PeriodicTaskConfig, TestEvent,
};
use anyhow::{Context, Result};
use core::panic;
use libp2p::identity::Keypair;
use libp2p::multiaddr::Protocol;
use libp2p::{Multiaddr, PeerId};
use std::collections::HashSet;
use std::fmt::Debug;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
use tokio::task::JoinHandle;
#[allow(dead_code)]
#[derive(Debug)]
struct TestPeer {
pub keypair: Keypair,
pub peer_id: PeerId,
pub peers: Arc<RwLock<Peers>>,
pub client: p2p::Client,
pub event_receiver: p2p::EventReceiver,
pub main_loop_jh: JoinHandle<()>,
}
impl TestPeer {
#[must_use]
pub fn new(periodic_cfg: PeriodicTaskConfig) -> Self {
let keypair = Keypair::generate_ed25519();
let peer_id = keypair.public().to_peer_id();
let peers: Arc<RwLock<Peers>> = Default::default();
let (client, event_receiver, main_loop) =
p2p::new(keypair.clone(), peers.clone(), periodic_cfg);
let main_loop_jh = tokio::spawn(main_loop.run());
Self {
keypair,
peer_id,
peers,
client,
event_receiver,
main_loop_jh,
}
}
/// Start listening on a specified address
pub async fn start_listening_on(&mut self, addr: Multiaddr) -> Result<Multiaddr> {
self.client
.start_listening(addr)
.await
.context("Start listening failed")?;
let event = tokio::time::timeout(Duration::from_secs(1), self.event_receiver.recv())
.await
.context("Timedout while waiting for new listen address")?
.context("Event channel closed")?;
let addr = match event {
Event::Test(TestEvent::NewListenAddress(addr)) => addr,
_ => anyhow::bail!("Unexpected event: {event:?}"),
};
Ok(addr)
}
/// Start listening on localhost with port automatically assigned
pub async fn start_listening(&mut self) -> Result<Multiaddr> {
self.start_listening_on(Multiaddr::from_str("/ip4/127.0.0.1/tcp/0").unwrap())
.await
}
/// Get peer IDs of the connected peers
pub async fn connected(&self) -> HashSet<PeerId> {
self.peers
.read()
.await
.connected()
.map(Clone::clone)
.collect()
}
}
impl Default for TestPeer {
fn default() -> Self {
Self::new(Default::default())
}
}
/// [`MainLoop`](p2p::MainLoop)'s event channel size is 1, so we need to consume
/// all events as soon as they're sent otherwise the main loop will stall.
/// `f` should return `Some(data)` where `data` is extracted from
/// the event type of interest. For other events that should be ignored
/// `f` should return `None`. This function returns a receiver to the filtered
/// events' data channel.
fn filter_events<T: Debug + Send + 'static>(
mut event_receiver: EventReceiver,
f: impl FnOnce(Event) -> Option<T> + Copy + Send + 'static,
) -> tokio::sync::mpsc::Receiver<T> {
let (tx, rx) = tokio::sync::mpsc::channel(100);
tokio::spawn(async move {
loop {
tokio::select! {
event = event_receiver.recv() => if let Some(event) = event {
if let Some(data) = f(event) {
tx.send(data).await.unwrap()
}
}
}
}
});
rx
}
/// [`MainLoop`](p2p::MainLoop)'s event channel size is 1, so we need to consume
/// all events as soon as they're sent otherwise the main loop will stall
fn consume_events(mut event_receiver: EventReceiver) {
tokio::spawn(async move {
loop {
tokio::select! {
_ = event_receiver.recv() => {}
}
}
});
}
#[test_log::test(tokio::test)]
async fn dial() {
let _ = env_logger::builder().is_test(true).try_init();
// tokio::time::pause() does not make a difference
let mut peer1 = TestPeer::default();
let mut peer2 = TestPeer::default();
let addr1 = peer1.start_listening().await.unwrap();
let addr2 = peer2.start_listening().await.unwrap();
tracing::info!(%peer1.peer_id, %addr1);
tracing::info!(%peer2.peer_id, %addr2);
peer1.client.dial(peer2.peer_id, addr2).await.unwrap();
let peers_of1 = peer1.connected().await;
let peers_of2 = peer2.connected().await;
assert_eq!(peers_of1, [peer2.peer_id].into());
assert_eq!(peers_of2, [peer1.peer_id].into());
}
#[test_log::test(tokio::test)]
async fn periodic_bootstrap() {
let _ = env_logger::builder().is_test(true).try_init();
// TODO figure out how to make this test run using tokio::time::pause()
// instead of arbitrary short delays
let periodic_cfg = PeriodicTaskConfig {
bootstrap: BootstrapConfig {
period: Duration::from_millis(500),
start_offset: Duration::from_secs(1),
},
status_period: Duration::from_secs(60 * 60),
};
let mut boot = TestPeer::new(periodic_cfg);
let mut peer1 = TestPeer::new(periodic_cfg);
let mut peer2 = TestPeer::new(periodic_cfg);
let mut boot_addr = boot.start_listening().await.unwrap();
boot_addr.push(Protocol::P2p(boot.peer_id.into()));
let addr1 = peer1.start_listening().await.unwrap();
let addr2 = peer2.start_listening().await.unwrap();
tracing::info!(%boot.peer_id, %boot_addr);
tracing::info!(%peer1.peer_id, %addr1);
tracing::info!(%peer2.peer_id, %addr2);
peer1
.client
.dial(boot.peer_id, boot_addr.clone())
.await
.unwrap();
peer2.client.dial(boot.peer_id, boot_addr).await.unwrap();
let filter_periodic_bootstrap = |event| match event {
Event::Test(TestEvent::PeriodicBootstrapCompleted(_)) => Some(()),
_ => None,
};
consume_events(boot.event_receiver);
let peer_id2 = peer2.peer_id;
let mut peer2_added_to_dht_of_peer1 =
filter_events(peer1.event_receiver, move |event| match event {
Event::Test(TestEvent::PeerAddedToDHT { remote }) if remote == peer_id2 => Some(()),
_ => None,
});
let mut peer2_bootstrap_done = filter_events(peer2.event_receiver, filter_periodic_bootstrap);
tokio::join!(peer2_added_to_dht_of_peer1.recv(), async {
peer2_bootstrap_done.recv().await;
peer2_bootstrap_done.recv().await;
});
let boot_dht = boot.client.for_test().get_peers_from_dht().await;
let dht1 = peer1.client.for_test().get_peers_from_dht().await;
let dht2 = peer2.client.for_test().get_peers_from_dht().await;
assert_eq!(boot_dht, [peer1.peer_id, peer2.peer_id].into());
assert_eq!(dht1, [boot.peer_id, peer2.peer_id].into());
assert_eq!(dht2, [boot.peer_id, peer1.peer_id].into());
}
#[test_log::test(tokio::test)]
async fn provide_capability() {
let _ = env_logger::builder().is_test(true).try_init();
let mut peer1 = TestPeer::default();
let mut peer2 = TestPeer::default();
let addr1 = peer1.start_listening().await.unwrap();
let addr2 = peer2.start_listening().await.unwrap();
tracing::info!(%peer1.peer_id, %addr1);
tracing::info!(%peer2.peer_id, %addr2);
let mut peer1_started_providing = filter_events(peer1.event_receiver, |event| match event {
Event::Test(TestEvent::StartProvidingCompleted(_)) => Some(()),
_ => None,
});
consume_events(peer2.event_receiver);
peer1.client.dial(peer2.peer_id, addr2).await.unwrap();
peer1.client.provide_capability("blah").await.unwrap();
peer1_started_providing.recv().await;
// Apparently sometimes still not yet providing at this point and there's
// no other event to rely on
tokio::time::sleep(Duration::from_millis(500)).await;
// sha256("blah")
let key =
hex::decode("8b7df143d91c716ecfa5fc1730022f6b421b05cedee8fd52b1fc65a96030ad52").unwrap();
let providers = peer2.client.for_test().get_providers(key).await.unwrap();
assert_eq!(providers, [peer1.peer_id].into());
}
#[test_log::test(tokio::test)]
async fn subscription_and_propagation() {
use fake::{Fake, Faker};
use p2p_proto::propagation::{Message, NewBlockBody, NewBlockHeader, NewBlockState};
let _ = env_logger::builder().is_test(true).try_init();
let mut peer1 = TestPeer::default();
let mut peer2 = TestPeer::default();
let addr1 = peer1.start_listening().await.unwrap();
let addr2 = peer2.start_listening().await.unwrap();
tracing::info!(%peer1.peer_id, %addr1);
tracing::info!(%peer2.peer_id, %addr2);
let mut peer2_subscribed_to_peer1 = filter_events(peer1.event_receiver, |event| match event {
Event::Test(TestEvent::Subscribed { .. }) => Some(()),
_ => None,
});
let mut propagated_to_peer2 = filter_events(peer2.event_receiver, |event| match event {
Event::BlockPropagation(message) => Some(message),
_ => None,
});
const TOPIC: &str = "TOPIC";
peer2.client.dial(peer1.peer_id, addr1).await.unwrap();
peer2.client.subscribe_topic(TOPIC).await.unwrap();
peer2_subscribed_to_peer1.recv().await;
let new_block_header = Message::NewBlockHeader(Faker.fake::<NewBlockHeader>());
let new_block_body = Message::NewBlockBody(Faker.fake::<NewBlockBody>());
let new_block_state = Message::NewBlockState(Faker.fake::<NewBlockState>());
for expected in [new_block_header, new_block_body, new_block_state] {
peer1
.client
.publish_propagation_message(TOPIC, expected.clone())
.await
.unwrap();
let msg = propagated_to_peer2.recv().await.unwrap();
assert_eq!(msg, expected);
}
}
#[test_log::test(tokio::test)]
async fn sync_request_response() {
use fake::{Fake, Faker};
use p2p_proto::sync::{Request, Response, Status};
let _ = env_logger::builder().is_test(true).try_init();
let mut peer1 = TestPeer::default();
let mut peer2 = TestPeer::default();
let addr1 = peer1.start_listening().await.unwrap();
let addr2 = peer2.start_listening().await.unwrap();
tracing::info!(%peer1.peer_id, %addr1);
tracing::info!(%peer2.peer_id, %addr2);
let mut peer1_inbound_sync_requests =
filter_events(peer1.event_receiver, move |event| match event {
Event::InboundSyncRequest {
from,
request,
channel,
} => {
assert_eq!(from, peer2.peer_id);
Some((request, channel))
}
_ => None,
});
consume_events(peer2.event_receiver);
// Dial so that the peers have each other in their DHTs, the direction doesn't matter
peer1.client.dial(peer2.peer_id, addr2).await.unwrap();
for _ in 0..10 {
let expected_request = Faker.fake::<Request>();
let expected_response = Faker.fake::<Response>();
let expected_request_cloned = expected_request.clone();
let expected_response_cloned = expected_response.clone();
let client2 = peer2.client.clone();
tokio::spawn(async move {
let resp = client2
.send_sync_request(peer1.peer_id, expected_request_cloned)
.await
.unwrap();
assert_eq!(resp, expected_response_cloned);
});
let (request, resp_channel) = peer1_inbound_sync_requests.recv().await.unwrap();
assert_eq!(request, expected_request);
peer1
.client
.send_sync_response(resp_channel, expected_response)
.await;
}
// Also test the client method used specifically to send status requests
let expected_sync_request = Faker.fake::<Status>();
peer2
.client
.send_sync_status_request(peer1.peer_id, expected_sync_request.clone())
.await;
let (request, _) = peer1_inbound_sync_requests.recv().await.unwrap();
assert_eq!(request, Request::Status(expected_sync_request));
}
#[test_log::test(tokio::test)]
async fn sync_status_events_and_periodic() {
use assert_matches::assert_matches;
let _ = env_logger::builder().is_test(true).try_init();
let periodic_cfg = PeriodicTaskConfig {
bootstrap: BootstrapConfig {
period: Duration::from_secs(60 * 60),
start_offset: Duration::from_secs(60 * 60),
},
status_period: Duration::from_millis(100),
};
let mut peer1 = TestPeer::new(periodic_cfg);
let mut peer2 = TestPeer::new(periodic_cfg);
let addr1 = peer1.start_listening().await.unwrap();
let addr2 = peer2.start_listening().await.unwrap();
tracing::info!(%peer1.peer_id, %addr1, "peer1");
tracing::info!(%peer2.peer_id, %addr2, "peer2");
tracing::info!("peer1 < peer2 = {}", peer1.peer_id < peer2.peer_id);
#[derive(Debug)]
enum FilteredEvent {
SyncPeerConnected { from: PeerId },
SyncPeerRequestStatus { from: PeerId },
}
let filter = move |event| match event {
Event::SyncPeerConnected { peer_id } => {
Some(FilteredEvent::SyncPeerConnected { from: peer_id })
}
Event::SyncPeerRequestStatus { peer_id } => {
Some(FilteredEvent::SyncPeerRequestStatus { from: peer_id })
}
_ => None,
};
let mut peer1_events = filter_events(peer1.event_receiver, filter);
let mut peer2_events = filter_events(peer2.event_receiver, filter);
// Dial so that the peers have each other in their DHTs, the direction doesn't matter
peer1
.client
.dial(peer2.peer_id, addr2.clone())
.await
.unwrap();
assert_matches!(peer1_events.recv().await.unwrap(), FilteredEvent::SyncPeerConnected { from } => { assert_eq!(from, peer2.peer_id)});
assert_matches!(peer2_events.recv().await.unwrap(), FilteredEvent::SyncPeerConnected { from } => { assert_eq!(from, peer1.peer_id)});
// Only one of the peers will trigger a periodic sync status request
// depending on which has the lower peer id
tokio::select! {
e = peer1_events.recv() => {
assert_matches!(e, Some(FilteredEvent::SyncPeerRequestStatus { from }) => { assert_eq!(from, peer2.peer_id)});
assert!(peer1.peer_id < peer2.peer_id);
}
e = peer2_events.recv() => {
assert_matches!(e, Some(FilteredEvent::SyncPeerRequestStatus { from }) => { assert_eq!(from, peer1.peer_id)});
assert!(peer2.peer_id < peer1.peer_id);
}
}
}
|
#[cfg(test)]
mod test;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::Term;
#[native_implemented::function(erlang:self/0)]
pub fn result(process: &Process) -> Term {
process.pid_term()
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - DSI Host version register"]
pub vr: VR,
#[doc = "0x04 - DSI Host control register"]
pub cr: CR,
#[doc = "0x08 - DSI Host clock control register"]
pub ccr: CCR,
#[doc = "0x0c - DSI Host LTDC VCID register"]
pub lvcidr: LVCIDR,
#[doc = "0x10 - DSI Host LTDC color coding register"]
pub lcolcr: LCOLCR,
#[doc = "0x14 - DSI Host LTDC polarity configuration register"]
pub lpcr: LPCR,
#[doc = "0x18 - DSI Host low-power mode configuration register"]
pub lpmcr: LPMCR,
_reserved7: [u8; 16usize],
#[doc = "0x2c - DSI Host protocol configuration register"]
pub pcr: PCR,
#[doc = "0x30 - DSI Host generic VCID register"]
pub gvcidr: GVCIDR,
#[doc = "0x34 - DSI Host mode configuration register"]
pub mcr: MCR,
#[doc = "0x38 - DSI Host video mode configuration register"]
pub vmcr: VMCR,
#[doc = "0x3c - DSI Host video packet configuration register"]
pub vpcr: VPCR,
#[doc = "0x40 - DSI Host video chunks configuration register"]
pub vccr: VCCR,
#[doc = "0x44 - DSI Host video null packet configuration register"]
pub vnpcr: VNPCR,
#[doc = "0x48 - DSI Host video HSA configuration register"]
pub vhsacr: VHSACR,
#[doc = "0x4c - DSI Host video HBP configuration register"]
pub vhbpcr: VHBPCR,
#[doc = "0x50 - DSI Host video line configuration register"]
pub vlcr: VLCR,
#[doc = "0x54 - DSI Host video VSA configuration register"]
pub vvsacr: VVSACR,
#[doc = "0x58 - DSI Host video VBP configuration register"]
pub vvbpcr: VVBPCR,
#[doc = "0x5c - DSI Host video VFP configuration register"]
pub vvfpcr: VVFPCR,
#[doc = "0x60 - DSI Host video VA configuration register"]
pub vvacr: VVACR,
#[doc = "0x64 - DSI Host LTDC command configuration register"]
pub lccr: LCCR,
#[doc = "0x68 - DSI Host command mode configuration register"]
pub cmcr: CMCR,
#[doc = "0x6c - DSI Host generic header configuration register"]
pub ghcr: GHCR,
#[doc = "0x70 - DSI Host generic payload data register"]
pub gpdr: GPDR,
#[doc = "0x74 - DSI Host generic packet status register"]
pub gpsr: GPSR,
#[doc = "0x78 - DSI Host timeout counter configuration register 0"]
pub tccr0: TCCR0,
#[doc = "0x7c - DSI Host timeout counter configuration register 1"]
pub tccr1: TCCR1,
#[doc = "0x80 - DSI Host timeout counter configuration register 2"]
pub tccr2: TCCR2,
#[doc = "0x84 - DSI Host timeout counter configuration register 3"]
pub tccr3: TCCR3,
#[doc = "0x88 - DSI Host timeout counter configuration register 4"]
pub tccr4: TCCR4,
#[doc = "0x8c - DSI Host timeout counter configuration register 5"]
pub tccr5: TCCR5,
_reserved32: [u8; 4usize],
#[doc = "0x94 - DSI Host clock lane configuration register"]
pub clcr: CLCR,
#[doc = "0x98 - DSI Host clock lane timer configuration register"]
pub cltcr: CLTCR,
#[doc = "0x9c - DSI Host data lane timer configuration register"]
pub dltcr: DLTCR,
#[doc = "0xa0 - DSI Host PHY control register"]
pub pctlr: PCTLR,
#[doc = "0xa4 - DSI Host PHY configuration register"]
pub pconfr: PCONFR,
#[doc = "0xa8 - DSI Host PHY ULPS control register"]
pub pucr: PUCR,
#[doc = "0xac - DSI Host PHY TX triggers configuration register"]
pub pttcr: PTTCR,
_reserved39: [u8; 12usize],
#[doc = "0xbc - DSI Host interrupt and status register 0"]
pub psr: PSR,
#[doc = "0xc0 - DSI Host interrupt and status register 1"]
pub isr1: ISR1,
#[doc = "0xc4 - DSI Host interrupt enable register 0"]
pub ier0: IER0,
#[doc = "0xc8 - DSI Host interrupt enable register 1"]
pub ier1: IER1,
_reserved43: [u8; 12usize],
#[doc = "0xd8 - DSI Host force interrupt register 0"]
pub fir0: FIR0,
#[doc = "0xdc - DSI Host force interrupt register 1"]
pub fir1: FIR1,
_reserved45: [u8; 32usize],
#[doc = "0x100 - DSI Host video shadow control register"]
pub vscr: VSCR,
_reserved46: [u8; 8usize],
#[doc = "0x10c - DSI Host LTDC current VCID register"]
pub lcvcidr: LCVCIDR,
#[doc = "0x110 - DSI Host LTDC current color coding register"]
pub lcccr: LCCCR,
_reserved48: [u8; 4usize],
#[doc = "0x118 - DSI Host low-power mode current configuration register"]
pub lpmccr: LPMCCR,
_reserved49: [u8; 28usize],
#[doc = "0x138 - DSI Host video mode current configuration register"]
pub vmccr: VMCCR,
#[doc = "0x13c - DSI Host video packet current configuration register"]
pub vpccr: VPCCR,
#[doc = "0x140 - DSI Host video chunks current configuration register"]
pub vcccr: VCCCR,
#[doc = "0x144 - DSI Host video null packet current configuration register"]
pub vnpccr: VNPCCR,
#[doc = "0x148 - DSI Host video HSA current configuration register"]
pub vhsaccr: VHSACCR,
#[doc = "0x14c - DSI Host video HBP current configuration register"]
pub vhbpccr: VHBPCCR,
#[doc = "0x150 - DSI Host video line current configuration register"]
pub vlccr: VLCCR,
#[doc = "0x154 - DSI Host video VSA current configuration register"]
pub vvsaccr: VVSACCR,
#[doc = "0x158 - DSI Host video VBP current configuration register"]
pub vvpbccr: VVPBCCR,
#[doc = "0x15c - DSI Host video VFP current configuration register"]
pub vvfpccr: VVFPCCR,
#[doc = "0x160 - DSI Host video VA current configuration register"]
pub vvaccr: VVACCR,
_reserved60: [u8; 668usize],
#[doc = "0x400 - DSI wrapper configuration register"]
pub wcfgr: WCFGR,
#[doc = "0x404 - DSI wrapper control register"]
pub wcr: WCR,
#[doc = "0x408 - DSI wrapper interrupt enable register"]
pub wier: WIER,
#[doc = "0x40c - DSI wrapper interrupt and status register"]
pub wisr: WISR,
#[doc = "0x410 - DSI wrapper interrupt flag clear register"]
pub wifcr: WIFCR,
_reserved65: [u8; 4usize],
#[doc = "0x418 - DSI wrapper PHY configuration register 0"]
pub wpcr0: WPCR0,
#[doc = "0x41c - DSI wrapper PHY configuration register 1"]
pub wpcr1: WPCR1,
_reserved67: [u8; 8usize],
#[doc = "0x428 - DSI wrapper PHY configuration register 4"]
pub wpcr2: WPCR2,
_reserved68: [u8; 4usize],
#[doc = "0x430 - DSI wrapper regulator and PLL control register"]
pub wrpcr: WRPCR,
}
#[doc = "DSI Host version register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vr](vr) module"]
pub type VR = crate::Reg<u32, _VR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VR;
#[doc = "`read()` method returns [vr::R](vr::R) reader structure"]
impl crate::Readable for VR {}
#[doc = "DSI Host version register"]
pub mod vr;
#[doc = "DSI Host control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr](cr) module"]
pub type CR = crate::Reg<u32, _CR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CR;
#[doc = "`read()` method returns [cr::R](cr::R) reader structure"]
impl crate::Readable for CR {}
#[doc = "`write(|w| ..)` method takes [cr::W](cr::W) writer structure"]
impl crate::Writable for CR {}
#[doc = "DSI Host control register"]
pub mod cr;
#[doc = "DSI Host clock control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ccr](ccr) module"]
pub type CCR = crate::Reg<u32, _CCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CCR;
#[doc = "`read()` method returns [ccr::R](ccr::R) reader structure"]
impl crate::Readable for CCR {}
#[doc = "`write(|w| ..)` method takes [ccr::W](ccr::W) writer structure"]
impl crate::Writable for CCR {}
#[doc = "DSI Host clock control register"]
pub mod ccr;
#[doc = "DSI Host LTDC VCID register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [lvcidr](lvcidr) module"]
pub type LVCIDR = crate::Reg<u32, _LVCIDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _LVCIDR;
#[doc = "`read()` method returns [lvcidr::R](lvcidr::R) reader structure"]
impl crate::Readable for LVCIDR {}
#[doc = "`write(|w| ..)` method takes [lvcidr::W](lvcidr::W) writer structure"]
impl crate::Writable for LVCIDR {}
#[doc = "DSI Host LTDC VCID register"]
pub mod lvcidr;
#[doc = "DSI Host LTDC color coding register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [lcolcr](lcolcr) module"]
pub type LCOLCR = crate::Reg<u32, _LCOLCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _LCOLCR;
#[doc = "`read()` method returns [lcolcr::R](lcolcr::R) reader structure"]
impl crate::Readable for LCOLCR {}
#[doc = "`write(|w| ..)` method takes [lcolcr::W](lcolcr::W) writer structure"]
impl crate::Writable for LCOLCR {}
#[doc = "DSI Host LTDC color coding register"]
pub mod lcolcr;
#[doc = "DSI Host LTDC polarity configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [lpcr](lpcr) module"]
pub type LPCR = crate::Reg<u32, _LPCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _LPCR;
#[doc = "`read()` method returns [lpcr::R](lpcr::R) reader structure"]
impl crate::Readable for LPCR {}
#[doc = "`write(|w| ..)` method takes [lpcr::W](lpcr::W) writer structure"]
impl crate::Writable for LPCR {}
#[doc = "DSI Host LTDC polarity configuration register"]
pub mod lpcr;
#[doc = "DSI Host low-power mode configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [lpmcr](lpmcr) module"]
pub type LPMCR = crate::Reg<u32, _LPMCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _LPMCR;
#[doc = "`read()` method returns [lpmcr::R](lpmcr::R) reader structure"]
impl crate::Readable for LPMCR {}
#[doc = "`write(|w| ..)` method takes [lpmcr::W](lpmcr::W) writer structure"]
impl crate::Writable for LPMCR {}
#[doc = "DSI Host low-power mode configuration register"]
pub mod lpmcr;
#[doc = "DSI Host protocol configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pcr](pcr) module"]
pub type PCR = crate::Reg<u32, _PCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PCR;
#[doc = "`read()` method returns [pcr::R](pcr::R) reader structure"]
impl crate::Readable for PCR {}
#[doc = "`write(|w| ..)` method takes [pcr::W](pcr::W) writer structure"]
impl crate::Writable for PCR {}
#[doc = "DSI Host protocol configuration register"]
pub mod pcr;
#[doc = "DSI Host generic VCID register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gvcidr](gvcidr) module"]
pub type GVCIDR = crate::Reg<u32, _GVCIDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GVCIDR;
#[doc = "`read()` method returns [gvcidr::R](gvcidr::R) reader structure"]
impl crate::Readable for GVCIDR {}
#[doc = "`write(|w| ..)` method takes [gvcidr::W](gvcidr::W) writer structure"]
impl crate::Writable for GVCIDR {}
#[doc = "DSI Host generic VCID register"]
pub mod gvcidr;
#[doc = "DSI Host mode configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mcr](mcr) module"]
pub type MCR = crate::Reg<u32, _MCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MCR;
#[doc = "`read()` method returns [mcr::R](mcr::R) reader structure"]
impl crate::Readable for MCR {}
#[doc = "`write(|w| ..)` method takes [mcr::W](mcr::W) writer structure"]
impl crate::Writable for MCR {}
#[doc = "DSI Host mode configuration register"]
pub mod mcr;
#[doc = "DSI Host video mode configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vmcr](vmcr) module"]
pub type VMCR = crate::Reg<u32, _VMCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VMCR;
#[doc = "`read()` method returns [vmcr::R](vmcr::R) reader structure"]
impl crate::Readable for VMCR {}
#[doc = "`write(|w| ..)` method takes [vmcr::W](vmcr::W) writer structure"]
impl crate::Writable for VMCR {}
#[doc = "DSI Host video mode configuration register"]
pub mod vmcr;
#[doc = "DSI Host video packet configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vpcr](vpcr) module"]
pub type VPCR = crate::Reg<u32, _VPCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VPCR;
#[doc = "`read()` method returns [vpcr::R](vpcr::R) reader structure"]
impl crate::Readable for VPCR {}
#[doc = "`write(|w| ..)` method takes [vpcr::W](vpcr::W) writer structure"]
impl crate::Writable for VPCR {}
#[doc = "DSI Host video packet configuration register"]
pub mod vpcr;
#[doc = "DSI Host video chunks configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vccr](vccr) module"]
pub type VCCR = crate::Reg<u32, _VCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VCCR;
#[doc = "`read()` method returns [vccr::R](vccr::R) reader structure"]
impl crate::Readable for VCCR {}
#[doc = "`write(|w| ..)` method takes [vccr::W](vccr::W) writer structure"]
impl crate::Writable for VCCR {}
#[doc = "DSI Host video chunks configuration register"]
pub mod vccr;
#[doc = "DSI Host video null packet configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vnpcr](vnpcr) module"]
pub type VNPCR = crate::Reg<u32, _VNPCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VNPCR;
#[doc = "`read()` method returns [vnpcr::R](vnpcr::R) reader structure"]
impl crate::Readable for VNPCR {}
#[doc = "`write(|w| ..)` method takes [vnpcr::W](vnpcr::W) writer structure"]
impl crate::Writable for VNPCR {}
#[doc = "DSI Host video null packet configuration register"]
pub mod vnpcr;
#[doc = "DSI Host video HSA configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vhsacr](vhsacr) module"]
pub type VHSACR = crate::Reg<u32, _VHSACR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VHSACR;
#[doc = "`read()` method returns [vhsacr::R](vhsacr::R) reader structure"]
impl crate::Readable for VHSACR {}
#[doc = "`write(|w| ..)` method takes [vhsacr::W](vhsacr::W) writer structure"]
impl crate::Writable for VHSACR {}
#[doc = "DSI Host video HSA configuration register"]
pub mod vhsacr;
#[doc = "DSI Host video HBP configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vhbpcr](vhbpcr) module"]
pub type VHBPCR = crate::Reg<u32, _VHBPCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VHBPCR;
#[doc = "`read()` method returns [vhbpcr::R](vhbpcr::R) reader structure"]
impl crate::Readable for VHBPCR {}
#[doc = "`write(|w| ..)` method takes [vhbpcr::W](vhbpcr::W) writer structure"]
impl crate::Writable for VHBPCR {}
#[doc = "DSI Host video HBP configuration register"]
pub mod vhbpcr;
#[doc = "DSI Host video line configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vlcr](vlcr) module"]
pub type VLCR = crate::Reg<u32, _VLCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VLCR;
#[doc = "`read()` method returns [vlcr::R](vlcr::R) reader structure"]
impl crate::Readable for VLCR {}
#[doc = "`write(|w| ..)` method takes [vlcr::W](vlcr::W) writer structure"]
impl crate::Writable for VLCR {}
#[doc = "DSI Host video line configuration register"]
pub mod vlcr;
#[doc = "DSI Host video VSA configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vvsacr](vvsacr) module"]
pub type VVSACR = crate::Reg<u32, _VVSACR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VVSACR;
#[doc = "`read()` method returns [vvsacr::R](vvsacr::R) reader structure"]
impl crate::Readable for VVSACR {}
#[doc = "`write(|w| ..)` method takes [vvsacr::W](vvsacr::W) writer structure"]
impl crate::Writable for VVSACR {}
#[doc = "DSI Host video VSA configuration register"]
pub mod vvsacr;
#[doc = "DSI Host video VBP configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vvbpcr](vvbpcr) module"]
pub type VVBPCR = crate::Reg<u32, _VVBPCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VVBPCR;
#[doc = "`read()` method returns [vvbpcr::R](vvbpcr::R) reader structure"]
impl crate::Readable for VVBPCR {}
#[doc = "`write(|w| ..)` method takes [vvbpcr::W](vvbpcr::W) writer structure"]
impl crate::Writable for VVBPCR {}
#[doc = "DSI Host video VBP configuration register"]
pub mod vvbpcr;
#[doc = "DSI Host video VFP configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vvfpcr](vvfpcr) module"]
pub type VVFPCR = crate::Reg<u32, _VVFPCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VVFPCR;
#[doc = "`read()` method returns [vvfpcr::R](vvfpcr::R) reader structure"]
impl crate::Readable for VVFPCR {}
#[doc = "`write(|w| ..)` method takes [vvfpcr::W](vvfpcr::W) writer structure"]
impl crate::Writable for VVFPCR {}
#[doc = "DSI Host video VFP configuration register"]
pub mod vvfpcr;
#[doc = "DSI Host video VA configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vvacr](vvacr) module"]
pub type VVACR = crate::Reg<u32, _VVACR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VVACR;
#[doc = "`read()` method returns [vvacr::R](vvacr::R) reader structure"]
impl crate::Readable for VVACR {}
#[doc = "`write(|w| ..)` method takes [vvacr::W](vvacr::W) writer structure"]
impl crate::Writable for VVACR {}
#[doc = "DSI Host video VA configuration register"]
pub mod vvacr;
#[doc = "DSI Host LTDC command configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [lccr](lccr) module"]
pub type LCCR = crate::Reg<u32, _LCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _LCCR;
#[doc = "`read()` method returns [lccr::R](lccr::R) reader structure"]
impl crate::Readable for LCCR {}
#[doc = "`write(|w| ..)` method takes [lccr::W](lccr::W) writer structure"]
impl crate::Writable for LCCR {}
#[doc = "DSI Host LTDC command configuration register"]
pub mod lccr;
#[doc = "DSI Host command mode configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cmcr](cmcr) module"]
pub type CMCR = crate::Reg<u32, _CMCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CMCR;
#[doc = "`read()` method returns [cmcr::R](cmcr::R) reader structure"]
impl crate::Readable for CMCR {}
#[doc = "`write(|w| ..)` method takes [cmcr::W](cmcr::W) writer structure"]
impl crate::Writable for CMCR {}
#[doc = "DSI Host command mode configuration register"]
pub mod cmcr;
#[doc = "DSI Host generic header configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ghcr](ghcr) module"]
pub type GHCR = crate::Reg<u32, _GHCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GHCR;
#[doc = "`read()` method returns [ghcr::R](ghcr::R) reader structure"]
impl crate::Readable for GHCR {}
#[doc = "`write(|w| ..)` method takes [ghcr::W](ghcr::W) writer structure"]
impl crate::Writable for GHCR {}
#[doc = "DSI Host generic header configuration register"]
pub mod ghcr;
#[doc = "DSI Host generic payload data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpdr](gpdr) module"]
pub type GPDR = crate::Reg<u32, _GPDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPDR;
#[doc = "`read()` method returns [gpdr::R](gpdr::R) reader structure"]
impl crate::Readable for GPDR {}
#[doc = "`write(|w| ..)` method takes [gpdr::W](gpdr::W) writer structure"]
impl crate::Writable for GPDR {}
#[doc = "DSI Host generic payload data register"]
pub mod gpdr;
#[doc = "DSI Host generic packet status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpsr](gpsr) module"]
pub type GPSR = crate::Reg<u32, _GPSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPSR;
#[doc = "`read()` method returns [gpsr::R](gpsr::R) reader structure"]
impl crate::Readable for GPSR {}
#[doc = "`write(|w| ..)` method takes [gpsr::W](gpsr::W) writer structure"]
impl crate::Writable for GPSR {}
#[doc = "DSI Host generic packet status register"]
pub mod gpsr;
#[doc = "DSI Host timeout counter configuration register 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [tccr0](tccr0) module"]
pub type TCCR0 = crate::Reg<u32, _TCCR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TCCR0;
#[doc = "`read()` method returns [tccr0::R](tccr0::R) reader structure"]
impl crate::Readable for TCCR0 {}
#[doc = "`write(|w| ..)` method takes [tccr0::W](tccr0::W) writer structure"]
impl crate::Writable for TCCR0 {}
#[doc = "DSI Host timeout counter configuration register 0"]
pub mod tccr0;
#[doc = "DSI Host timeout counter configuration register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [tccr1](tccr1) module"]
pub type TCCR1 = crate::Reg<u32, _TCCR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TCCR1;
#[doc = "`read()` method returns [tccr1::R](tccr1::R) reader structure"]
impl crate::Readable for TCCR1 {}
#[doc = "`write(|w| ..)` method takes [tccr1::W](tccr1::W) writer structure"]
impl crate::Writable for TCCR1 {}
#[doc = "DSI Host timeout counter configuration register 1"]
pub mod tccr1;
#[doc = "DSI Host timeout counter configuration register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [tccr2](tccr2) module"]
pub type TCCR2 = crate::Reg<u32, _TCCR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TCCR2;
#[doc = "`read()` method returns [tccr2::R](tccr2::R) reader structure"]
impl crate::Readable for TCCR2 {}
#[doc = "`write(|w| ..)` method takes [tccr2::W](tccr2::W) writer structure"]
impl crate::Writable for TCCR2 {}
#[doc = "DSI Host timeout counter configuration register 2"]
pub mod tccr2;
#[doc = "DSI Host timeout counter configuration register 3\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [tccr3](tccr3) module"]
pub type TCCR3 = crate::Reg<u32, _TCCR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TCCR3;
#[doc = "`read()` method returns [tccr3::R](tccr3::R) reader structure"]
impl crate::Readable for TCCR3 {}
#[doc = "`write(|w| ..)` method takes [tccr3::W](tccr3::W) writer structure"]
impl crate::Writable for TCCR3 {}
#[doc = "DSI Host timeout counter configuration register 3"]
pub mod tccr3;
#[doc = "DSI Host timeout counter configuration register 4\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [tccr4](tccr4) module"]
pub type TCCR4 = crate::Reg<u32, _TCCR4>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TCCR4;
#[doc = "`read()` method returns [tccr4::R](tccr4::R) reader structure"]
impl crate::Readable for TCCR4 {}
#[doc = "`write(|w| ..)` method takes [tccr4::W](tccr4::W) writer structure"]
impl crate::Writable for TCCR4 {}
#[doc = "DSI Host timeout counter configuration register 4"]
pub mod tccr4;
#[doc = "DSI Host timeout counter configuration register 5\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [tccr5](tccr5) module"]
pub type TCCR5 = crate::Reg<u32, _TCCR5>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TCCR5;
#[doc = "`read()` method returns [tccr5::R](tccr5::R) reader structure"]
impl crate::Readable for TCCR5 {}
#[doc = "`write(|w| ..)` method takes [tccr5::W](tccr5::W) writer structure"]
impl crate::Writable for TCCR5 {}
#[doc = "DSI Host timeout counter configuration register 5"]
pub mod tccr5;
#[doc = "DSI Host clock lane configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clcr](clcr) module"]
pub type CLCR = crate::Reg<u32, _CLCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLCR;
#[doc = "`read()` method returns [clcr::R](clcr::R) reader structure"]
impl crate::Readable for CLCR {}
#[doc = "`write(|w| ..)` method takes [clcr::W](clcr::W) writer structure"]
impl crate::Writable for CLCR {}
#[doc = "DSI Host clock lane configuration register"]
pub mod clcr;
#[doc = "DSI Host clock lane timer configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cltcr](cltcr) module"]
pub type CLTCR = crate::Reg<u32, _CLTCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLTCR;
#[doc = "`read()` method returns [cltcr::R](cltcr::R) reader structure"]
impl crate::Readable for CLTCR {}
#[doc = "`write(|w| ..)` method takes [cltcr::W](cltcr::W) writer structure"]
impl crate::Writable for CLTCR {}
#[doc = "DSI Host clock lane timer configuration register"]
pub mod cltcr;
#[doc = "DSI Host data lane timer configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dltcr](dltcr) module"]
pub type DLTCR = crate::Reg<u32, _DLTCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DLTCR;
#[doc = "`read()` method returns [dltcr::R](dltcr::R) reader structure"]
impl crate::Readable for DLTCR {}
#[doc = "`write(|w| ..)` method takes [dltcr::W](dltcr::W) writer structure"]
impl crate::Writable for DLTCR {}
#[doc = "DSI Host data lane timer configuration register"]
pub mod dltcr;
#[doc = "DSI Host PHY control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pctlr](pctlr) module"]
pub type PCTLR = crate::Reg<u32, _PCTLR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PCTLR;
#[doc = "`read()` method returns [pctlr::R](pctlr::R) reader structure"]
impl crate::Readable for PCTLR {}
#[doc = "`write(|w| ..)` method takes [pctlr::W](pctlr::W) writer structure"]
impl crate::Writable for PCTLR {}
#[doc = "DSI Host PHY control register"]
pub mod pctlr;
#[doc = "DSI Host PHY configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pconfr](pconfr) module"]
pub type PCONFR = crate::Reg<u32, _PCONFR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PCONFR;
#[doc = "`read()` method returns [pconfr::R](pconfr::R) reader structure"]
impl crate::Readable for PCONFR {}
#[doc = "`write(|w| ..)` method takes [pconfr::W](pconfr::W) writer structure"]
impl crate::Writable for PCONFR {}
#[doc = "DSI Host PHY configuration register"]
pub mod pconfr;
#[doc = "DSI Host PHY ULPS control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pucr](pucr) module"]
pub type PUCR = crate::Reg<u32, _PUCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PUCR;
#[doc = "`read()` method returns [pucr::R](pucr::R) reader structure"]
impl crate::Readable for PUCR {}
#[doc = "`write(|w| ..)` method takes [pucr::W](pucr::W) writer structure"]
impl crate::Writable for PUCR {}
#[doc = "DSI Host PHY ULPS control register"]
pub mod pucr;
#[doc = "DSI Host PHY TX triggers configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pttcr](pttcr) module"]
pub type PTTCR = crate::Reg<u32, _PTTCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PTTCR;
#[doc = "`read()` method returns [pttcr::R](pttcr::R) reader structure"]
impl crate::Readable for PTTCR {}
#[doc = "`write(|w| ..)` method takes [pttcr::W](pttcr::W) writer structure"]
impl crate::Writable for PTTCR {}
#[doc = "DSI Host PHY TX triggers configuration register"]
pub mod pttcr;
#[doc = "DSI Host interrupt and status register 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [psr](psr) module"]
pub type PSR = crate::Reg<u32, _PSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PSR;
#[doc = "`read()` method returns [psr::R](psr::R) reader structure"]
impl crate::Readable for PSR {}
#[doc = "`write(|w| ..)` method takes [psr::W](psr::W) writer structure"]
impl crate::Writable for PSR {}
#[doc = "DSI Host interrupt and status register 0"]
pub mod psr;
#[doc = "DSI Host interrupt and status register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [isr1](isr1) module"]
pub type ISR1 = crate::Reg<u32, _ISR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ISR1;
#[doc = "`read()` method returns [isr1::R](isr1::R) reader structure"]
impl crate::Readable for ISR1 {}
#[doc = "`write(|w| ..)` method takes [isr1::W](isr1::W) writer structure"]
impl crate::Writable for ISR1 {}
#[doc = "DSI Host interrupt and status register 1"]
pub mod isr1;
#[doc = "DSI Host interrupt enable register 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ier0](ier0) module"]
pub type IER0 = crate::Reg<u32, _IER0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IER0;
#[doc = "`read()` method returns [ier0::R](ier0::R) reader structure"]
impl crate::Readable for IER0 {}
#[doc = "`write(|w| ..)` method takes [ier0::W](ier0::W) writer structure"]
impl crate::Writable for IER0 {}
#[doc = "DSI Host interrupt enable register 0"]
pub mod ier0;
#[doc = "DSI Host interrupt enable register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ier1](ier1) module"]
pub type IER1 = crate::Reg<u32, _IER1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IER1;
#[doc = "`read()` method returns [ier1::R](ier1::R) reader structure"]
impl crate::Readable for IER1 {}
#[doc = "`write(|w| ..)` method takes [ier1::W](ier1::W) writer structure"]
impl crate::Writable for IER1 {}
#[doc = "DSI Host interrupt enable register 1"]
pub mod ier1;
#[doc = "DSI Host force interrupt register 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fir0](fir0) module"]
pub type FIR0 = crate::Reg<u32, _FIR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FIR0;
#[doc = "`read()` method returns [fir0::R](fir0::R) reader structure"]
impl crate::Readable for FIR0 {}
#[doc = "`write(|w| ..)` method takes [fir0::W](fir0::W) writer structure"]
impl crate::Writable for FIR0 {}
#[doc = "DSI Host force interrupt register 0"]
pub mod fir0;
#[doc = "DSI Host force interrupt register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fir1](fir1) module"]
pub type FIR1 = crate::Reg<u32, _FIR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FIR1;
#[doc = "`read()` method returns [fir1::R](fir1::R) reader structure"]
impl crate::Readable for FIR1 {}
#[doc = "`write(|w| ..)` method takes [fir1::W](fir1::W) writer structure"]
impl crate::Writable for FIR1 {}
#[doc = "DSI Host force interrupt register 1"]
pub mod fir1;
#[doc = "DSI Host video shadow control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vscr](vscr) module"]
pub type VSCR = crate::Reg<u32, _VSCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VSCR;
#[doc = "`read()` method returns [vscr::R](vscr::R) reader structure"]
impl crate::Readable for VSCR {}
#[doc = "`write(|w| ..)` method takes [vscr::W](vscr::W) writer structure"]
impl crate::Writable for VSCR {}
#[doc = "DSI Host video shadow control register"]
pub mod vscr;
#[doc = "DSI Host LTDC current VCID register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [lcvcidr](lcvcidr) module"]
pub type LCVCIDR = crate::Reg<u32, _LCVCIDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _LCVCIDR;
#[doc = "`read()` method returns [lcvcidr::R](lcvcidr::R) reader structure"]
impl crate::Readable for LCVCIDR {}
#[doc = "`write(|w| ..)` method takes [lcvcidr::W](lcvcidr::W) writer structure"]
impl crate::Writable for LCVCIDR {}
#[doc = "DSI Host LTDC current VCID register"]
pub mod lcvcidr;
#[doc = "DSI Host LTDC current color coding register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [lcccr](lcccr) module"]
pub type LCCCR = crate::Reg<u32, _LCCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _LCCCR;
#[doc = "`read()` method returns [lcccr::R](lcccr::R) reader structure"]
impl crate::Readable for LCCCR {}
#[doc = "`write(|w| ..)` method takes [lcccr::W](lcccr::W) writer structure"]
impl crate::Writable for LCCCR {}
#[doc = "DSI Host LTDC current color coding register"]
pub mod lcccr;
#[doc = "DSI Host low-power mode current configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [lpmccr](lpmccr) module"]
pub type LPMCCR = crate::Reg<u32, _LPMCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _LPMCCR;
#[doc = "`read()` method returns [lpmccr::R](lpmccr::R) reader structure"]
impl crate::Readable for LPMCCR {}
#[doc = "`write(|w| ..)` method takes [lpmccr::W](lpmccr::W) writer structure"]
impl crate::Writable for LPMCCR {}
#[doc = "DSI Host low-power mode current configuration register"]
pub mod lpmccr;
#[doc = "DSI Host video mode current configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vmccr](vmccr) module"]
pub type VMCCR = crate::Reg<u32, _VMCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VMCCR;
#[doc = "`read()` method returns [vmccr::R](vmccr::R) reader structure"]
impl crate::Readable for VMCCR {}
#[doc = "`write(|w| ..)` method takes [vmccr::W](vmccr::W) writer structure"]
impl crate::Writable for VMCCR {}
#[doc = "DSI Host video mode current configuration register"]
pub mod vmccr;
#[doc = "DSI Host video packet current configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vpccr](vpccr) module"]
pub type VPCCR = crate::Reg<u32, _VPCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VPCCR;
#[doc = "`read()` method returns [vpccr::R](vpccr::R) reader structure"]
impl crate::Readable for VPCCR {}
#[doc = "`write(|w| ..)` method takes [vpccr::W](vpccr::W) writer structure"]
impl crate::Writable for VPCCR {}
#[doc = "DSI Host video packet current configuration register"]
pub mod vpccr;
#[doc = "DSI Host video chunks current configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vcccr](vcccr) module"]
pub type VCCCR = crate::Reg<u32, _VCCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VCCCR;
#[doc = "`read()` method returns [vcccr::R](vcccr::R) reader structure"]
impl crate::Readable for VCCCR {}
#[doc = "`write(|w| ..)` method takes [vcccr::W](vcccr::W) writer structure"]
impl crate::Writable for VCCCR {}
#[doc = "DSI Host video chunks current configuration register"]
pub mod vcccr;
#[doc = "DSI Host video null packet current configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vnpccr](vnpccr) module"]
pub type VNPCCR = crate::Reg<u32, _VNPCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VNPCCR;
#[doc = "`read()` method returns [vnpccr::R](vnpccr::R) reader structure"]
impl crate::Readable for VNPCCR {}
#[doc = "`write(|w| ..)` method takes [vnpccr::W](vnpccr::W) writer structure"]
impl crate::Writable for VNPCCR {}
#[doc = "DSI Host video null packet current configuration register"]
pub mod vnpccr;
#[doc = "DSI Host video HSA current configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vhsaccr](vhsaccr) module"]
pub type VHSACCR = crate::Reg<u32, _VHSACCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VHSACCR;
#[doc = "`read()` method returns [vhsaccr::R](vhsaccr::R) reader structure"]
impl crate::Readable for VHSACCR {}
#[doc = "`write(|w| ..)` method takes [vhsaccr::W](vhsaccr::W) writer structure"]
impl crate::Writable for VHSACCR {}
#[doc = "DSI Host video HSA current configuration register"]
pub mod vhsaccr;
#[doc = "DSI Host video HBP current configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vhbpccr](vhbpccr) module"]
pub type VHBPCCR = crate::Reg<u32, _VHBPCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VHBPCCR;
#[doc = "`read()` method returns [vhbpccr::R](vhbpccr::R) reader structure"]
impl crate::Readable for VHBPCCR {}
#[doc = "`write(|w| ..)` method takes [vhbpccr::W](vhbpccr::W) writer structure"]
impl crate::Writable for VHBPCCR {}
#[doc = "DSI Host video HBP current configuration register"]
pub mod vhbpccr;
#[doc = "DSI Host video line current configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vlccr](vlccr) module"]
pub type VLCCR = crate::Reg<u32, _VLCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VLCCR;
#[doc = "`read()` method returns [vlccr::R](vlccr::R) reader structure"]
impl crate::Readable for VLCCR {}
#[doc = "`write(|w| ..)` method takes [vlccr::W](vlccr::W) writer structure"]
impl crate::Writable for VLCCR {}
#[doc = "DSI Host video line current configuration register"]
pub mod vlccr;
#[doc = "DSI Host video VSA current configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vvsaccr](vvsaccr) module"]
pub type VVSACCR = crate::Reg<u32, _VVSACCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VVSACCR;
#[doc = "`read()` method returns [vvsaccr::R](vvsaccr::R) reader structure"]
impl crate::Readable for VVSACCR {}
#[doc = "`write(|w| ..)` method takes [vvsaccr::W](vvsaccr::W) writer structure"]
impl crate::Writable for VVSACCR {}
#[doc = "DSI Host video VSA current configuration register"]
pub mod vvsaccr;
#[doc = "DSI Host video VBP current configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vvpbccr](vvpbccr) module"]
pub type VVPBCCR = crate::Reg<u32, _VVPBCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VVPBCCR;
#[doc = "`read()` method returns [vvpbccr::R](vvpbccr::R) reader structure"]
impl crate::Readable for VVPBCCR {}
#[doc = "`write(|w| ..)` method takes [vvpbccr::W](vvpbccr::W) writer structure"]
impl crate::Writable for VVPBCCR {}
#[doc = "DSI Host video VBP current configuration register"]
pub mod vvpbccr;
#[doc = "DSI Host video VFP current configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vvfpccr](vvfpccr) module"]
pub type VVFPCCR = crate::Reg<u32, _VVFPCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VVFPCCR;
#[doc = "`read()` method returns [vvfpccr::R](vvfpccr::R) reader structure"]
impl crate::Readable for VVFPCCR {}
#[doc = "`write(|w| ..)` method takes [vvfpccr::W](vvfpccr::W) writer structure"]
impl crate::Writable for VVFPCCR {}
#[doc = "DSI Host video VFP current configuration register"]
pub mod vvfpccr;
#[doc = "DSI Host video VA current configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [vvaccr](vvaccr) module"]
pub type VVACCR = crate::Reg<u32, _VVACCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VVACCR;
#[doc = "`read()` method returns [vvaccr::R](vvaccr::R) reader structure"]
impl crate::Readable for VVACCR {}
#[doc = "`write(|w| ..)` method takes [vvaccr::W](vvaccr::W) writer structure"]
impl crate::Writable for VVACCR {}
#[doc = "DSI Host video VA current configuration register"]
pub mod vvaccr;
#[doc = "DSI wrapper configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wcfgr](wcfgr) module"]
pub type WCFGR = crate::Reg<u32, _WCFGR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WCFGR;
#[doc = "`read()` method returns [wcfgr::R](wcfgr::R) reader structure"]
impl crate::Readable for WCFGR {}
#[doc = "`write(|w| ..)` method takes [wcfgr::W](wcfgr::W) writer structure"]
impl crate::Writable for WCFGR {}
#[doc = "DSI wrapper configuration register"]
pub mod wcfgr;
#[doc = "DSI wrapper control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wcr](wcr) module"]
pub type WCR = crate::Reg<u32, _WCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WCR;
#[doc = "`read()` method returns [wcr::R](wcr::R) reader structure"]
impl crate::Readable for WCR {}
#[doc = "`write(|w| ..)` method takes [wcr::W](wcr::W) writer structure"]
impl crate::Writable for WCR {}
#[doc = "DSI wrapper control register"]
pub mod wcr;
#[doc = "DSI wrapper interrupt enable register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wier](wier) module"]
pub type WIER = crate::Reg<u32, _WIER>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WIER;
#[doc = "`read()` method returns [wier::R](wier::R) reader structure"]
impl crate::Readable for WIER {}
#[doc = "`write(|w| ..)` method takes [wier::W](wier::W) writer structure"]
impl crate::Writable for WIER {}
#[doc = "DSI wrapper interrupt enable register"]
pub mod wier;
#[doc = "DSI wrapper interrupt and status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wisr](wisr) module"]
pub type WISR = crate::Reg<u32, _WISR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WISR;
#[doc = "`read()` method returns [wisr::R](wisr::R) reader structure"]
impl crate::Readable for WISR {}
#[doc = "`write(|w| ..)` method takes [wisr::W](wisr::W) writer structure"]
impl crate::Writable for WISR {}
#[doc = "DSI wrapper interrupt and status register"]
pub mod wisr;
#[doc = "DSI wrapper interrupt flag clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wifcr](wifcr) module"]
pub type WIFCR = crate::Reg<u32, _WIFCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WIFCR;
#[doc = "`read()` method returns [wifcr::R](wifcr::R) reader structure"]
impl crate::Readable for WIFCR {}
#[doc = "`write(|w| ..)` method takes [wifcr::W](wifcr::W) writer structure"]
impl crate::Writable for WIFCR {}
#[doc = "DSI wrapper interrupt flag clear register"]
pub mod wifcr;
#[doc = "DSI wrapper PHY configuration register 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wpcr0](wpcr0) module"]
pub type WPCR0 = crate::Reg<u32, _WPCR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WPCR0;
#[doc = "`read()` method returns [wpcr0::R](wpcr0::R) reader structure"]
impl crate::Readable for WPCR0 {}
#[doc = "`write(|w| ..)` method takes [wpcr0::W](wpcr0::W) writer structure"]
impl crate::Writable for WPCR0 {}
#[doc = "DSI wrapper PHY configuration register 0"]
pub mod wpcr0;
#[doc = "DSI wrapper PHY configuration register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wpcr1](wpcr1) module"]
pub type WPCR1 = crate::Reg<u32, _WPCR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WPCR1;
#[doc = "`read()` method returns [wpcr1::R](wpcr1::R) reader structure"]
impl crate::Readable for WPCR1 {}
#[doc = "`write(|w| ..)` method takes [wpcr1::W](wpcr1::W) writer structure"]
impl crate::Writable for WPCR1 {}
#[doc = "DSI wrapper PHY configuration register 1"]
pub mod wpcr1;
#[doc = "DSI wrapper PHY configuration register 4\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wpcr2](wpcr2) module"]
pub type WPCR2 = crate::Reg<u32, _WPCR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WPCR2;
#[doc = "`read()` method returns [wpcr2::R](wpcr2::R) reader structure"]
impl crate::Readable for WPCR2 {}
#[doc = "`write(|w| ..)` method takes [wpcr2::W](wpcr2::W) writer structure"]
impl crate::Writable for WPCR2 {}
#[doc = "DSI wrapper PHY configuration register 4"]
pub mod wpcr2;
#[doc = "DSI wrapper regulator and PLL control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wrpcr](wrpcr) module"]
pub type WRPCR = crate::Reg<u32, _WRPCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WRPCR;
#[doc = "`read()` method returns [wrpcr::R](wrpcr::R) reader structure"]
impl crate::Readable for WRPCR {}
#[doc = "`write(|w| ..)` method takes [wrpcr::W](wrpcr::W) writer structure"]
impl crate::Writable for WRPCR {}
#[doc = "DSI wrapper regulator and PLL control register"]
pub mod wrpcr;
|
// Compiler:
//
// Run-time:
// status: 0
#![feature(asm, global_asm)]
global_asm!("
.global add_asm
add_asm:
mov rax, rdi
add rax, rsi
ret"
);
extern "C" {
fn add_asm(a: i64, b: i64) -> i64;
}
fn main() {
unsafe {
asm!("nop");
}
let x: u64;
unsafe {
asm!("mov $5, {}",
out(reg) x,
options(att_syntax)
);
}
assert_eq!(x, 5);
let x: u64;
let input: u64 = 42;
unsafe {
asm!("mov {input}, {output}",
"add $1, {output}",
input = in(reg) input,
output = out(reg) x,
options(att_syntax)
);
}
assert_eq!(x, 43);
let x: u64;
unsafe {
asm!("mov {}, 6",
out(reg) x,
);
}
assert_eq!(x, 6);
let x: u64;
let input: u64 = 42;
unsafe {
asm!("mov {output}, {input}",
"add {output}, 1",
input = in(reg) input,
output = out(reg) x,
);
}
assert_eq!(x, 43);
assert_eq!(unsafe { add_asm(40, 2) }, 42);
}
|
//! This module implements common functionalities for OS's strings.
use crate::sys::{Error, OsStr, OsString};
use core::{fmt, ops::Deref};
#[cfg(feature = "std")]
use std::{
ffi,
path::{Path, PathBuf},
};
impl Clone for OsString {
fn clone(&self) -> Self {
self.to_os_str()
.and_then(|str| str.into_os_string())
.expect("Allocation error")
}
}
impl fmt::Debug for OsString {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{:?}", self.as_ref())
}
}
impl fmt::Display for OsString {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.as_ref())
}
}
impl Deref for OsString {
type Target = OsStr;
fn deref(&self) -> &OsStr {
self.as_ref()
}
}
/// Either borrowed or owned allocation of an OS-native string.
#[derive(Debug)]
pub enum EitherOsStr<'str> {
/// Borrowed allocation.
Borrowed(&'str OsStr),
/// Owned allocation.
Owned(OsString),
}
impl<'str> AsRef<OsStr> for EitherOsStr<'str> {
fn as_ref(&self) -> &OsStr {
match self {
Self::Borrowed(str) => str,
Self::Owned(string) => string.as_ref(),
}
}
}
impl<'str> Deref for EitherOsStr<'str> {
type Target = OsStr;
fn deref(&self) -> &OsStr {
self.as_ref()
}
}
/// Conversion of anything into an owned OS-native string. If allocation fails,
/// an error shall be returned.
pub trait IntoOsString {
/// Converts with possible allocation error.
fn into_os_string(self) -> Result<OsString, Error>;
}
impl IntoOsString for OsString {
fn into_os_string(self) -> Result<OsString, Error> {
Ok(self)
}
}
impl<'str> IntoOsString for EitherOsStr<'str> {
fn into_os_string(self) -> Result<OsString, Error> {
match self {
Self::Borrowed(str) => str.into_os_string(),
Self::Owned(string) => Ok(string),
}
}
}
#[cfg(feature = "std")]
impl<'str> IntoOsString for &'str ffi::OsStr {
fn into_os_string(self) -> Result<OsString, Error> {
self.to_os_str()?.into_os_string()
}
}
#[cfg(feature = "std")]
impl IntoOsString for PathBuf {
fn into_os_string(self) -> Result<OsString, Error> {
(*self).into_os_string()
}
}
#[cfg(feature = "std")]
impl<'str> IntoOsString for &'str Path {
fn into_os_string(self) -> Result<OsString, Error> {
AsRef::<ffi::OsStr>::as_ref(self).to_os_str()?.into_os_string()
}
}
#[cfg(feature = "std")]
impl IntoOsString for ffi::OsString {
fn into_os_string(self) -> Result<OsString, Error> {
(*self).into_os_string()
}
}
impl<'str> IntoOsString for &'str str {
fn into_os_string(self) -> Result<OsString, Error> {
self.to_os_str()?.into_os_string()
}
}
#[cfg(feature = "std")]
impl IntoOsString for String {
fn into_os_string(self) -> Result<OsString, Error> {
self.to_os_str()?.into_os_string()
}
}
#[cfg(feature = "std")]
impl ToOsStr for String {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
(**self).to_os_str()
}
}
/// Conversion of anything to an either borrowed or owned OS-native string. If
/// allocation fails, an error shall be returned.
pub trait ToOsStr {
/// Converts with possible allocation error.
fn to_os_str(&self) -> Result<EitherOsStr, Error>;
}
impl<'str> ToOsStr for EitherOsStr<'str> {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
Ok(match self {
EitherOsStr::Owned(string) => {
EitherOsStr::Owned(string.to_os_str()?.into_os_string()?)
},
EitherOsStr::Borrowed(str) => EitherOsStr::Borrowed(str),
})
}
}
impl ToOsStr for OsStr {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
Ok(EitherOsStr::Borrowed(self))
}
}
impl ToOsStr for OsString {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
Ok(EitherOsStr::Borrowed(self.as_ref()))
}
}
#[cfg(feature = "std")]
impl ToOsStr for ffi::OsString {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
(**self).to_os_str()
}
}
#[cfg(feature = "std")]
impl ToOsStr for PathBuf {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
(**self).to_os_str()
}
}
#[cfg(feature = "std")]
impl ToOsStr for Path {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
AsRef::<ffi::OsStr>::as_ref(self).to_os_str()
}
}
|
#[doc = "Reader of register CR"]
pub type R = crate::R<u32, super::CR>;
#[doc = "Writer for register CR"]
pub type W = crate::W<u32, super::CR>;
#[doc = "Register CR `reset()`'s with value 0x1000"]
impl crate::ResetValue for super::CR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x1000
}
}
#[doc = "Reader of field `LPDS`"]
pub type LPDS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LPDS`"]
pub struct LPDS_W<'a> {
w: &'a mut W,
}
impl<'a> LPDS_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 = "Power down deepsleep\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PDDS_A {
#[doc = "0: Enter Stop mode when the CPU enters deepsleep"]
STOP_MODE = 0,
#[doc = "1: Enter Standby mode when the CPU enters deepsleep"]
STANDBY_MODE = 1,
}
impl From<PDDS_A> for bool {
#[inline(always)]
fn from(variant: PDDS_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `PDDS`"]
pub type PDDS_R = crate::R<bool, PDDS_A>;
impl PDDS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PDDS_A {
match self.bits {
false => PDDS_A::STOP_MODE,
true => PDDS_A::STANDBY_MODE,
}
}
#[doc = "Checks if the value of the field is `STOP_MODE`"]
#[inline(always)]
pub fn is_stop_mode(&self) -> bool {
*self == PDDS_A::STOP_MODE
}
#[doc = "Checks if the value of the field is `STANDBY_MODE`"]
#[inline(always)]
pub fn is_standby_mode(&self) -> bool {
*self == PDDS_A::STANDBY_MODE
}
}
#[doc = "Write proxy for field `PDDS`"]
pub struct PDDS_W<'a> {
w: &'a mut W,
}
impl<'a> PDDS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PDDS_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Enter Stop mode when the CPU enters deepsleep"]
#[inline(always)]
pub fn stop_mode(self) -> &'a mut W {
self.variant(PDDS_A::STOP_MODE)
}
#[doc = "Enter Standby mode when the CPU enters deepsleep"]
#[inline(always)]
pub fn standby_mode(self) -> &'a mut W {
self.variant(PDDS_A::STANDBY_MODE)
}
#[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 = "Clear wakeup flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CWUF_A {
#[doc = "1: Clear the WUF Wakeup flag after 2 system clock cycles"]
CLEAR = 1,
}
impl From<CWUF_A> for bool {
#[inline(always)]
fn from(variant: CWUF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `CWUF`"]
pub type CWUF_R = crate::R<bool, CWUF_A>;
impl CWUF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<bool, CWUF_A> {
use crate::Variant::*;
match self.bits {
true => Val(CWUF_A::CLEAR),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `CLEAR`"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == CWUF_A::CLEAR
}
}
#[doc = "Write proxy for field `CWUF`"]
pub struct CWUF_W<'a> {
w: &'a mut W,
}
impl<'a> CWUF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CWUF_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clear the WUF Wakeup flag after 2 system clock cycles"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(CWUF_A::CLEAR)
}
#[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 = "Clear standby flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CSBF_A {
#[doc = "1: Clear the SBF Standby flag"]
CLEAR = 1,
}
impl From<CSBF_A> for bool {
#[inline(always)]
fn from(variant: CSBF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `CSBF`"]
pub type CSBF_R = crate::R<bool, CSBF_A>;
impl CSBF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<bool, CSBF_A> {
use crate::Variant::*;
match self.bits {
true => Val(CSBF_A::CLEAR),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `CLEAR`"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == CSBF_A::CLEAR
}
}
#[doc = "Write proxy for field `CSBF`"]
pub struct CSBF_W<'a> {
w: &'a mut W,
}
impl<'a> CSBF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CSBF_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clear the SBF Standby flag"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(CSBF_A::CLEAR)
}
#[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 = "Power voltage detector enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PVDE_A {
#[doc = "0: PVD Disabled"]
DISABLED = 0,
#[doc = "1: PVD Enabled"]
ENABLED = 1,
}
impl From<PVDE_A> for bool {
#[inline(always)]
fn from(variant: PVDE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `PVDE`"]
pub type PVDE_R = crate::R<bool, PVDE_A>;
impl PVDE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PVDE_A {
match self.bits {
false => PVDE_A::DISABLED,
true => PVDE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == PVDE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == PVDE_A::ENABLED
}
}
#[doc = "Write proxy for field `PVDE`"]
pub struct PVDE_W<'a> {
w: &'a mut W,
}
impl<'a> PVDE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PVDE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "PVD Disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(PVDE_A::DISABLED)
}
#[doc = "PVD Enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(PVDE_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "PVD level selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum PLS_A {
#[doc = "0: 1.9 V"]
V1_9 = 0,
#[doc = "1: 2.1 V"]
V2_1 = 1,
#[doc = "2: 2.3 V"]
V2_3 = 2,
#[doc = "3: 2.5 V"]
V2_5 = 3,
#[doc = "4: 2.7 V"]
V2_7 = 4,
#[doc = "5: 2.9 V"]
V2_9 = 5,
#[doc = "6: 3.1 V"]
V3_1 = 6,
#[doc = "7: External input analog voltage (Compare internally to VREFINT)"]
EXTERNAL = 7,
}
impl From<PLS_A> for u8 {
#[inline(always)]
fn from(variant: PLS_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `PLS`"]
pub type PLS_R = crate::R<u8, PLS_A>;
impl PLS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PLS_A {
match self.bits {
0 => PLS_A::V1_9,
1 => PLS_A::V2_1,
2 => PLS_A::V2_3,
3 => PLS_A::V2_5,
4 => PLS_A::V2_7,
5 => PLS_A::V2_9,
6 => PLS_A::V3_1,
7 => PLS_A::EXTERNAL,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `V1_9`"]
#[inline(always)]
pub fn is_v1_9(&self) -> bool {
*self == PLS_A::V1_9
}
#[doc = "Checks if the value of the field is `V2_1`"]
#[inline(always)]
pub fn is_v2_1(&self) -> bool {
*self == PLS_A::V2_1
}
#[doc = "Checks if the value of the field is `V2_3`"]
#[inline(always)]
pub fn is_v2_3(&self) -> bool {
*self == PLS_A::V2_3
}
#[doc = "Checks if the value of the field is `V2_5`"]
#[inline(always)]
pub fn is_v2_5(&self) -> bool {
*self == PLS_A::V2_5
}
#[doc = "Checks if the value of the field is `V2_7`"]
#[inline(always)]
pub fn is_v2_7(&self) -> bool {
*self == PLS_A::V2_7
}
#[doc = "Checks if the value of the field is `V2_9`"]
#[inline(always)]
pub fn is_v2_9(&self) -> bool {
*self == PLS_A::V2_9
}
#[doc = "Checks if the value of the field is `V3_1`"]
#[inline(always)]
pub fn is_v3_1(&self) -> bool {
*self == PLS_A::V3_1
}
#[doc = "Checks if the value of the field is `EXTERNAL`"]
#[inline(always)]
pub fn is_external(&self) -> bool {
*self == PLS_A::EXTERNAL
}
}
#[doc = "Write proxy for field `PLS`"]
pub struct PLS_W<'a> {
w: &'a mut W,
}
impl<'a> PLS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PLS_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "1.9 V"]
#[inline(always)]
pub fn v1_9(self) -> &'a mut W {
self.variant(PLS_A::V1_9)
}
#[doc = "2.1 V"]
#[inline(always)]
pub fn v2_1(self) -> &'a mut W {
self.variant(PLS_A::V2_1)
}
#[doc = "2.3 V"]
#[inline(always)]
pub fn v2_3(self) -> &'a mut W {
self.variant(PLS_A::V2_3)
}
#[doc = "2.5 V"]
#[inline(always)]
pub fn v2_5(self) -> &'a mut W {
self.variant(PLS_A::V2_5)
}
#[doc = "2.7 V"]
#[inline(always)]
pub fn v2_7(self) -> &'a mut W {
self.variant(PLS_A::V2_7)
}
#[doc = "2.9 V"]
#[inline(always)]
pub fn v2_9(self) -> &'a mut W {
self.variant(PLS_A::V2_9)
}
#[doc = "3.1 V"]
#[inline(always)]
pub fn v3_1(self) -> &'a mut W {
self.variant(PLS_A::V3_1)
}
#[doc = "External input analog voltage (Compare internally to VREFINT)"]
#[inline(always)]
pub fn external(self) -> &'a mut W {
self.variant(PLS_A::EXTERNAL)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 5)) | (((value as u32) & 0x07) << 5);
self.w
}
}
#[doc = "Disable backup domain write protection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DBP_A {
#[doc = "0: Access to RTC, RTC Backup and RCC CSR registers disabled"]
DISABLED = 0,
#[doc = "1: Access to RTC, RTC Backup and RCC CSR registers enabled"]
ENABLED = 1,
}
impl From<DBP_A> for bool {
#[inline(always)]
fn from(variant: DBP_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `DBP`"]
pub type DBP_R = crate::R<bool, DBP_A>;
impl DBP_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DBP_A {
match self.bits {
false => DBP_A::DISABLED,
true => DBP_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == DBP_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == DBP_A::ENABLED
}
}
#[doc = "Write proxy for field `DBP`"]
pub struct DBP_W<'a> {
w: &'a mut W,
}
impl<'a> DBP_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DBP_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Access to RTC, RTC Backup and RCC CSR registers disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(DBP_A::DISABLED)
}
#[doc = "Access to RTC, RTC Backup and RCC CSR registers enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(DBP_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Ultra-low-power mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ULP_A {
#[doc = "0: VREFINT is on in low-power mode"]
ENABLED = 0,
#[doc = "1: VREFINT is off in low-power mode"]
DISABLED = 1,
}
impl From<ULP_A> for bool {
#[inline(always)]
fn from(variant: ULP_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `ULP`"]
pub type ULP_R = crate::R<bool, ULP_A>;
impl ULP_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ULP_A {
match self.bits {
false => ULP_A::ENABLED,
true => ULP_A::DISABLED,
}
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == ULP_A::ENABLED
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == ULP_A::DISABLED
}
}
#[doc = "Write proxy for field `ULP`"]
pub struct ULP_W<'a> {
w: &'a mut W,
}
impl<'a> ULP_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ULP_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "VREFINT is on in low-power mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(ULP_A::ENABLED)
}
#[doc = "VREFINT is off in low-power mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(ULP_A::DISABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Fast wakeup\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FWU_A {
#[doc = "0: Low-power modes exit occurs only when VREFINT is ready"]
DISABLED = 0,
#[doc = "1: VREFINT start up time is ignored when exiting low-power modes"]
ENABLED = 1,
}
impl From<FWU_A> for bool {
#[inline(always)]
fn from(variant: FWU_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `FWU`"]
pub type FWU_R = crate::R<bool, FWU_A>;
impl FWU_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FWU_A {
match self.bits {
false => FWU_A::DISABLED,
true => FWU_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == FWU_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == FWU_A::ENABLED
}
}
#[doc = "Write proxy for field `FWU`"]
pub struct FWU_W<'a> {
w: &'a mut W,
}
impl<'a> FWU_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FWU_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Low-power modes exit occurs only when VREFINT is ready"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(FWU_A::DISABLED)
}
#[doc = "VREFINT start up time is ignored when exiting low-power modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(FWU_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Voltage scaling range selection\n\nValue on reset: 2"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum VOS_A {
#[doc = "1: 1.8 V (range 1)"]
V1_8 = 1,
#[doc = "2: 1.5 V (range 2)"]
V1_5 = 2,
#[doc = "3: 1.2 V (range 3)"]
V1_2 = 3,
}
impl From<VOS_A> for u8 {
#[inline(always)]
fn from(variant: VOS_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `VOS`"]
pub type VOS_R = crate::R<u8, VOS_A>;
impl VOS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, VOS_A> {
use crate::Variant::*;
match self.bits {
1 => Val(VOS_A::V1_8),
2 => Val(VOS_A::V1_5),
3 => Val(VOS_A::V1_2),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `V1_8`"]
#[inline(always)]
pub fn is_v1_8(&self) -> bool {
*self == VOS_A::V1_8
}
#[doc = "Checks if the value of the field is `V1_5`"]
#[inline(always)]
pub fn is_v1_5(&self) -> bool {
*self == VOS_A::V1_5
}
#[doc = "Checks if the value of the field is `V1_2`"]
#[inline(always)]
pub fn is_v1_2(&self) -> bool {
*self == VOS_A::V1_2
}
}
#[doc = "Write proxy for field `VOS`"]
pub struct VOS_W<'a> {
w: &'a mut W,
}
impl<'a> VOS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: VOS_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "1.8 V (range 1)"]
#[inline(always)]
pub fn v1_8(self) -> &'a mut W {
self.variant(VOS_A::V1_8)
}
#[doc = "1.5 V (range 2)"]
#[inline(always)]
pub fn v1_5(self) -> &'a mut W {
self.variant(VOS_A::V1_5)
}
#[doc = "1.2 V (range 3)"]
#[inline(always)]
pub fn v1_2(self) -> &'a mut W {
self.variant(VOS_A::V1_2)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 11)) | (((value as u32) & 0x03) << 11);
self.w
}
}
#[doc = "Deep sleep mode with Flash memory kept off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DS_EE_KOFF_A {
#[doc = "0: NVM woken up when exiting from Deepsleep mode even if the bit RUN_PD is set"]
NVMWAKEUP = 0,
#[doc = "1: NVM not woken up when exiting from low-power mode (if the bit RUN_PD is set)"]
NVMSLEEP = 1,
}
impl From<DS_EE_KOFF_A> for bool {
#[inline(always)]
fn from(variant: DS_EE_KOFF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `DS_EE_KOFF`"]
pub type DS_EE_KOFF_R = crate::R<bool, DS_EE_KOFF_A>;
impl DS_EE_KOFF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DS_EE_KOFF_A {
match self.bits {
false => DS_EE_KOFF_A::NVMWAKEUP,
true => DS_EE_KOFF_A::NVMSLEEP,
}
}
#[doc = "Checks if the value of the field is `NVMWAKEUP`"]
#[inline(always)]
pub fn is_nvmwake_up(&self) -> bool {
*self == DS_EE_KOFF_A::NVMWAKEUP
}
#[doc = "Checks if the value of the field is `NVMSLEEP`"]
#[inline(always)]
pub fn is_nvmsleep(&self) -> bool {
*self == DS_EE_KOFF_A::NVMSLEEP
}
}
#[doc = "Write proxy for field `DS_EE_KOFF`"]
pub struct DS_EE_KOFF_W<'a> {
w: &'a mut W,
}
impl<'a> DS_EE_KOFF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DS_EE_KOFF_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "NVM woken up when exiting from Deepsleep mode even if the bit RUN_PD is set"]
#[inline(always)]
pub fn nvmwake_up(self) -> &'a mut W {
self.variant(DS_EE_KOFF_A::NVMWAKEUP)
}
#[doc = "NVM not woken up when exiting from low-power mode (if the bit RUN_PD is set)"]
#[inline(always)]
pub fn nvmsleep(self) -> &'a mut W {
self.variant(DS_EE_KOFF_A::NVMSLEEP)
}
#[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 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Low power run mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LPRUN_A {
#[doc = "0: Voltage regulator in Main mode in Low-power run mode"]
MAIN_MODE = 0,
#[doc = "1: Voltage regulator in low-power mode in Low-power run mode"]
LOW_POWER_MODE = 1,
}
impl From<LPRUN_A> for bool {
#[inline(always)]
fn from(variant: LPRUN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LPRUN`"]
pub type LPRUN_R = crate::R<bool, LPRUN_A>;
impl LPRUN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LPRUN_A {
match self.bits {
false => LPRUN_A::MAIN_MODE,
true => LPRUN_A::LOW_POWER_MODE,
}
}
#[doc = "Checks if the value of the field is `MAIN_MODE`"]
#[inline(always)]
pub fn is_main_mode(&self) -> bool {
*self == LPRUN_A::MAIN_MODE
}
#[doc = "Checks if the value of the field is `LOW_POWER_MODE`"]
#[inline(always)]
pub fn is_low_power_mode(&self) -> bool {
*self == LPRUN_A::LOW_POWER_MODE
}
}
#[doc = "Write proxy for field `LPRUN`"]
pub struct LPRUN_W<'a> {
w: &'a mut W,
}
impl<'a> LPRUN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPRUN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Voltage regulator in Main mode in Low-power run mode"]
#[inline(always)]
pub fn main_mode(self) -> &'a mut W {
self.variant(LPRUN_A::MAIN_MODE)
}
#[doc = "Voltage regulator in low-power mode in Low-power run mode"]
#[inline(always)]
pub fn low_power_mode(self) -> &'a mut W {
self.variant(LPRUN_A::LOW_POWER_MODE)
}
#[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 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Low-power deepsleep/Sleep/Low-power run\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LPSDSR_A {
#[doc = "0: Voltage regulator on during Deepsleep/Sleep/Low-power run mode"]
MAIN_MODE = 0,
#[doc = "1: Voltage regulator in low-power mode during Deepsleep/Sleep/Low-power run mode"]
LOW_POWER_MODE = 1,
}
impl From<LPSDSR_A> for bool {
#[inline(always)]
fn from(variant: LPSDSR_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LPSDSR`"]
pub type LPSDSR_R = crate::R<bool, LPSDSR_A>;
impl LPSDSR_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LPSDSR_A {
match self.bits {
false => LPSDSR_A::MAIN_MODE,
true => LPSDSR_A::LOW_POWER_MODE,
}
}
#[doc = "Checks if the value of the field is `MAIN_MODE`"]
#[inline(always)]
pub fn is_main_mode(&self) -> bool {
*self == LPSDSR_A::MAIN_MODE
}
#[doc = "Checks if the value of the field is `LOW_POWER_MODE`"]
#[inline(always)]
pub fn is_low_power_mode(&self) -> bool {
*self == LPSDSR_A::LOW_POWER_MODE
}
}
#[doc = "Write proxy for field `LPSDSR`"]
pub struct LPSDSR_W<'a> {
w: &'a mut W,
}
impl<'a> LPSDSR_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPSDSR_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Voltage regulator on during Deepsleep/Sleep/Low-power run mode"]
#[inline(always)]
pub fn main_mode(self) -> &'a mut W {
self.variant(LPSDSR_A::MAIN_MODE)
}
#[doc = "Voltage regulator in low-power mode during Deepsleep/Sleep/Low-power run mode"]
#[inline(always)]
pub fn low_power_mode(self) -> &'a mut W {
self.variant(LPSDSR_A::LOW_POWER_MODE)
}
#[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
}
}
impl R {
#[doc = "Bit 0 - Low-power deep sleep"]
#[inline(always)]
pub fn lpds(&self) -> LPDS_R {
LPDS_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Power down deepsleep"]
#[inline(always)]
pub fn pdds(&self) -> PDDS_R {
PDDS_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Clear wakeup flag"]
#[inline(always)]
pub fn cwuf(&self) -> CWUF_R {
CWUF_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Clear standby flag"]
#[inline(always)]
pub fn csbf(&self) -> CSBF_R {
CSBF_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Power voltage detector enable"]
#[inline(always)]
pub fn pvde(&self) -> PVDE_R {
PVDE_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bits 5:7 - PVD level selection"]
#[inline(always)]
pub fn pls(&self) -> PLS_R {
PLS_R::new(((self.bits >> 5) & 0x07) as u8)
}
#[doc = "Bit 8 - Disable backup domain write protection"]
#[inline(always)]
pub fn dbp(&self) -> DBP_R {
DBP_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - Ultra-low-power mode"]
#[inline(always)]
pub fn ulp(&self) -> ULP_R {
ULP_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - Fast wakeup"]
#[inline(always)]
pub fn fwu(&self) -> FWU_R {
FWU_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bits 11:12 - Voltage scaling range selection"]
#[inline(always)]
pub fn vos(&self) -> VOS_R {
VOS_R::new(((self.bits >> 11) & 0x03) as u8)
}
#[doc = "Bit 13 - Deep sleep mode with Flash memory kept off"]
#[inline(always)]
pub fn ds_ee_koff(&self) -> DS_EE_KOFF_R {
DS_EE_KOFF_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - Low power run mode"]
#[inline(always)]
pub fn lprun(&self) -> LPRUN_R {
LPRUN_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 0 - Low-power deepsleep/Sleep/Low-power run"]
#[inline(always)]
pub fn lpsdsr(&self) -> LPSDSR_R {
LPSDSR_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Low-power deep sleep"]
#[inline(always)]
pub fn lpds(&mut self) -> LPDS_W {
LPDS_W { w: self }
}
#[doc = "Bit 1 - Power down deepsleep"]
#[inline(always)]
pub fn pdds(&mut self) -> PDDS_W {
PDDS_W { w: self }
}
#[doc = "Bit 2 - Clear wakeup flag"]
#[inline(always)]
pub fn cwuf(&mut self) -> CWUF_W {
CWUF_W { w: self }
}
#[doc = "Bit 3 - Clear standby flag"]
#[inline(always)]
pub fn csbf(&mut self) -> CSBF_W {
CSBF_W { w: self }
}
#[doc = "Bit 4 - Power voltage detector enable"]
#[inline(always)]
pub fn pvde(&mut self) -> PVDE_W {
PVDE_W { w: self }
}
#[doc = "Bits 5:7 - PVD level selection"]
#[inline(always)]
pub fn pls(&mut self) -> PLS_W {
PLS_W { w: self }
}
#[doc = "Bit 8 - Disable backup domain write protection"]
#[inline(always)]
pub fn dbp(&mut self) -> DBP_W {
DBP_W { w: self }
}
#[doc = "Bit 9 - Ultra-low-power mode"]
#[inline(always)]
pub fn ulp(&mut self) -> ULP_W {
ULP_W { w: self }
}
#[doc = "Bit 10 - Fast wakeup"]
#[inline(always)]
pub fn fwu(&mut self) -> FWU_W {
FWU_W { w: self }
}
#[doc = "Bits 11:12 - Voltage scaling range selection"]
#[inline(always)]
pub fn vos(&mut self) -> VOS_W {
VOS_W { w: self }
}
#[doc = "Bit 13 - Deep sleep mode with Flash memory kept off"]
#[inline(always)]
pub fn ds_ee_koff(&mut self) -> DS_EE_KOFF_W {
DS_EE_KOFF_W { w: self }
}
#[doc = "Bit 14 - Low power run mode"]
#[inline(always)]
pub fn lprun(&mut self) -> LPRUN_W {
LPRUN_W { w: self }
}
#[doc = "Bit 0 - Low-power deepsleep/Sleep/Low-power run"]
#[inline(always)]
pub fn lpsdsr(&mut self) -> LPSDSR_W {
LPSDSR_W { w: self }
}
}
|
use openexr_sys as sys;
use std::ffi::CString;
use std::path::Path;
use crate::core::{
error::Error,
header::{HeaderRef, HeaderSlice},
};
type Result<T, E = Error> = std::result::Result<T, E>;
/// Manages writing multi-part images.
///
/// Multi-part files are essentially just containers around multiple
/// [`OutputFile`](crate::core::output_file::OutputFile)s
///
/// Certain attributes are shared between all parts:
/// * `displayWindow`
/// * `pixelAspectRatio`
/// * `timeCode`
/// * `chromaticities`
///
#[repr(transparent)]
pub struct MultiPartOutputFile(pub(crate) *mut sys::Imf_MultiPartOutputFile_t);
impl MultiPartOutputFile {
/// Creates a new multi-part output file from a slice of slice of headers
/// with the given filename. If `override_shared_attributes` is `true`, then
/// mismatching attributes between headers will be overriden with the value
/// from the first header. If `false` then [`Error::InvalidArgument`] is
/// returned instead.
///
/// # Errors
/// * [`Error::InvalidArgument`] - if `override_shared_attributes` is `false`
/// and there is a mismatch between headers' common attributes, or if each
/// header does not have a unique name.
/// * [`Error::Base`] - if the file cannot be opened.
///
pub fn new<P: AsRef<Path>>(
filename: P,
headers: &HeaderSlice,
override_shared_attributes: bool,
num_threads: i32,
) -> Result<MultiPartOutputFile> {
let c_filename = CString::new(
filename
.as_ref()
.to_str()
.expect("Invalid bytes in filename"),
)
.expect("Internal null bytes in filename");
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_MultiPartOutputFile_ctor(
&mut ptr,
c_filename.as_ptr(),
headers.0.as_ptr(),
headers.0.len() as i32,
override_shared_attributes,
num_threads,
)
.into_result()?;
}
Ok(MultiPartOutputFile(ptr))
}
/// The number of parts in the file
///
pub fn parts(&self) -> i32 {
let mut v = 0;
unsafe {
sys::Imf_MultiPartOutputFile_parts(self.0, &mut v);
}
v
}
/// Return a [`Header`](crate::core::header::Header) for part `n`.
///
/// Due to enforcing attribute sharing, the attributes of the returned
/// [`Header`](crate::core::header::Header) may be different from the matching one passed in to the
/// constructor.
///
/// # Errors
/// * [`Error::InvalidArgument`] - if `n` does not correspond to a part in
/// the file.
///
pub fn header(&self, n: i32) -> Result<HeaderRef> {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_MultiPartOutputFile_header(self.0, &mut ptr, n)
.into_result()?;
}
Ok(HeaderRef::new(ptr))
}
}
impl Drop for MultiPartOutputFile {
fn drop(&mut self) {
unsafe {
sys::Imf_MultiPartOutputFile_dtor(self.0);
}
}
}
#[cfg(test)]
#[test]
fn write_multipartoutputfile1() {
use crate::{
core::{
channel_list::Channel,
frame_buffer::{FrameBuffer, Slice},
header::{Header, ImageType},
output_part::OutputPart,
Compression, PixelType,
},
rgba::rgba::Rgba,
};
let (pixels, width, height) = crate::tests::load_ferris();
let channel = Channel {
type_: PixelType::Half.into(),
x_sampling: 1,
y_sampling: 1,
p_linear: true,
};
let mut header_array = Header::new_array(2);
let mut i = 0;
for mut header in header_array.iter_mut() {
header.set_compression(Compression::Zip);
header.channels_mut().insert("R", &channel);
header.channels_mut().insert("G", &channel);
header.channels_mut().insert("B", &channel);
header.channels_mut().insert("A", &channel);
header.set_image_type(ImageType::Scanline);
header.set_dimensions(width, height);
if i == 0 {
header.set_name("left");
i += 1;
} else {
header.set_name("right");
}
}
let mut frame_buffer_left = FrameBuffer::new();
frame_buffer_left
.insert(
"R",
&Slice::builder(
PixelType::Half,
&pixels[0].r as *const _ as *const u8,
width as i64,
height as i64,
)
.x_stride(std::mem::size_of::<Rgba>())
.build()
.unwrap(),
)
.unwrap();
frame_buffer_left
.insert(
"G",
&Slice::builder(
PixelType::Half,
&pixels[0].g as *const _ as *const u8,
width as i64,
height as i64,
)
.x_stride(std::mem::size_of::<Rgba>())
.build()
.unwrap(),
)
.unwrap();
frame_buffer_left
.insert(
"B",
&Slice::builder(
PixelType::Half,
&pixels[0].b as *const _ as *const u8,
width as i64,
height as i64,
)
.x_stride(std::mem::size_of::<Rgba>())
.build()
.unwrap(),
)
.unwrap();
frame_buffer_left
.insert(
"A",
&Slice::builder(
PixelType::Half,
&pixels[0].a as *const _ as *const u8,
width as i64,
height as i64,
)
.x_stride(std::mem::size_of::<Rgba>())
.build()
.unwrap(),
)
.unwrap();
let mut frame_buffer_right = FrameBuffer::new();
frame_buffer_right
.insert(
"B",
&Slice::builder(
PixelType::Half,
&pixels[0].r as *const _ as *const u8,
width as i64,
height as i64,
)
.x_stride(std::mem::size_of::<Rgba>())
.build()
.unwrap(),
)
.unwrap();
frame_buffer_right
.insert(
"G",
&Slice::builder(
PixelType::Half,
&pixels[0].g as *const _ as *const u8,
width as i64,
height as i64,
)
.x_stride(std::mem::size_of::<Rgba>())
.build()
.unwrap(),
)
.unwrap();
frame_buffer_right
.insert(
"R",
&Slice::builder(
PixelType::Half,
&pixels[0].b as *const _ as *const u8,
width as i64,
height as i64,
)
.x_stride(std::mem::size_of::<Rgba>())
.build()
.unwrap(),
)
.unwrap();
frame_buffer_right
.insert(
"A",
&Slice::builder(
PixelType::Half,
&pixels[0].a as *const _ as *const u8,
width as i64,
height as i64,
)
.x_stride(std::mem::size_of::<Rgba>())
.build()
.unwrap(),
)
.unwrap();
let file = MultiPartOutputFile::new(
"write_multipartoutputfile1.exr",
&header_array,
true,
4,
)
.unwrap();
let mut part_left = OutputPart::new(&file, 0).unwrap();
let mut part_right = OutputPart::new(&file, 1).unwrap();
part_left.set_frame_buffer(&frame_buffer_left).unwrap();
part_right.set_frame_buffer(&frame_buffer_right).unwrap();
unsafe {
part_left.write_pixels(height).unwrap();
part_right.write_pixels(height).unwrap();
}
}
|
#[doc = "Reader of register CRL"]
pub type R = crate::R<u32, super::CRL>;
#[doc = "Writer for register CRL"]
pub type W = crate::W<u32, super::CRL>;
#[doc = "Register CRL `reset()`'s with value 0x20"]
impl crate::ResetValue for super::CRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x20
}
}
#[doc = "Reader of field `SECF`"]
pub type SECF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SECF`"]
pub struct SECF_W<'a> {
w: &'a mut W,
}
impl<'a> SECF_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 `ALRF`"]
pub type ALRF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ALRF`"]
pub struct ALRF_W<'a> {
w: &'a mut W,
}
impl<'a> ALRF_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 `OWF`"]
pub type OWF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OWF`"]
pub struct OWF_W<'a> {
w: &'a mut W,
}
impl<'a> OWF_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 `RSF`"]
pub type RSF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RSF`"]
pub struct RSF_W<'a> {
w: &'a mut W,
}
impl<'a> RSF_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 `CNF`"]
pub type CNF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CNF`"]
pub struct CNF_W<'a> {
w: &'a mut W,
}
impl<'a> CNF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `RTOFF`"]
pub type RTOFF_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Second Flag"]
#[inline(always)]
pub fn secf(&self) -> SECF_R {
SECF_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Alarm Flag"]
#[inline(always)]
pub fn alrf(&self) -> ALRF_R {
ALRF_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Overflow Flag"]
#[inline(always)]
pub fn owf(&self) -> OWF_R {
OWF_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Registers Synchronized Flag"]
#[inline(always)]
pub fn rsf(&self) -> RSF_R {
RSF_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Configuration Flag"]
#[inline(always)]
pub fn cnf(&self) -> CNF_R {
CNF_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - RTC operation OFF"]
#[inline(always)]
pub fn rtoff(&self) -> RTOFF_R {
RTOFF_R::new(((self.bits >> 5) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Second Flag"]
#[inline(always)]
pub fn secf(&mut self) -> SECF_W {
SECF_W { w: self }
}
#[doc = "Bit 1 - Alarm Flag"]
#[inline(always)]
pub fn alrf(&mut self) -> ALRF_W {
ALRF_W { w: self }
}
#[doc = "Bit 2 - Overflow Flag"]
#[inline(always)]
pub fn owf(&mut self) -> OWF_W {
OWF_W { w: self }
}
#[doc = "Bit 3 - Registers Synchronized Flag"]
#[inline(always)]
pub fn rsf(&mut self) -> RSF_W {
RSF_W { w: self }
}
#[doc = "Bit 4 - Configuration Flag"]
#[inline(always)]
pub fn cnf(&mut self) -> CNF_W {
CNF_W { w: self }
}
}
|
#![cfg_attr(not(feature = "std"), no_std)]
use ink_lang as ink;
use schnorrkel::{PublicKey,Signature,signing_context};
#[ink::contract]
mod dependcydemo {
use super::*;
use ink_prelude::{string::String};
use scale::Encode;
const SIGNING_CTX: &[u8] = b"substrate";
/// Defines the storage of your contract.
/// Add new fields to the below struct in order
/// to add new static storage fields to your contract.
#[ink(storage)]
pub struct Dependcydemo {
/// Stores a single `bool` value on the storage.
manager:AccountId,
}
impl Dependcydemo {
#[ink(constructor)]
pub fn new(init_account_id: AccountId)->Self {
Self{
manager:init_account_id
}
}
#[ink(message)]
pub fn authorization(&mut self,signature:[u8;64],new_manager:AccountId)->Result<(),String>{
//just for test
let caller = self.env().caller();
let context = signing_context(b"this signature does this thing");
let signature = Signature::from_bytes(&signature).unwrap();
match PublicKey::from_bytes(&caller.encode()) {
Ok(pk) => {
if pk.verify(context.bytes(&new_manager.encode()), &signature).is_ok(){
self.manager = new_manager;
Ok(())
}else{
Err(String::from("Signature content does not match verification content!"))
}
},
Err(_err) => Err(String::from("PublicKey convert")),
}
}
}
}
|
extern crate itertools_num;
#[macro_use]
extern crate lazy_static;
mod controllers;
mod game_state;
mod geometry;
mod models;
use std::os::raw::{c_double, c_int};
use std::sync::Mutex;
use self::game_state::GameState;
use self::geometry::Size;
use self::controllers::{Actions, TimeController};
lazy_static! {
static ref DATA: Mutex<GameData> = Mutex::new(new_game_data(1024.0, 600.0));
}
struct GameData {
state: GameState,
actions: Actions,
time_controller: TimeController,
}
fn new_game_data(width: f64, height: f64) -> GameData {
GameData {
state: GameState::new(Size::new(width, height)),
actions: Actions::default(),
time_controller: TimeController::new(),
}
}
// These functions are provided by the runtime
extern "C" {
fn clear_screen();
fn draw_enemy(_: c_double, _: c_double);
fn draw_particle(_: c_double, _: c_double, _: c_double);
fn draw_score(_: c_int, _: c_int);
fn draw_line_a(_: c_double, _: c_double, _: c_double, _: c_double);
fn draw_line_b(_: c_double, _: c_double, _: c_double, _: c_double);
fn rust_log(_: c_int);
}
#[no_mangle]
pub extern "C" fn resize(width: c_double, height: c_double) {
*DATA.lock().unwrap() = new_game_data(width, height);
}
#[no_mangle]
pub unsafe extern "C" fn draw() {
let data = &mut DATA.lock().unwrap();
clear_screen();
draw_score(data.state.world.score_a as i32, data.state.world.score_b as i32);
if data.state.current_line_active {
let a = &data.state.start_dot;
let b = &data.state.mouse;
if data.state.world.active_player.is_a() {
draw_line_a(a.point.x, a.point.y, b.point.x, b.point.y);
} else {
draw_line_b(a.point.x, a.point.y, b.point.x, b.point.y);
}
}
for row in &data.state.world.dots {
for dot in row {
draw_enemy(dot.point.x, dot.point.y);
}
}
for line in data.state.world.lines_a.iter() {
draw_line_a(line.a.point.x, line.a.point.y, line.b.point.x, line.b.point.y);
}
for line in data.state.world.lines_b.iter() {
draw_line_b(line.a.point.x, line.a.point.y, line.b.point.x, line.b.point.y);
}
/*
if data.actions.click != (0, 0) {
rust_log(1);
}
if data.state.current_line_active && data.actions.mouse_position != (0, 0) {
rust_log(2);
}
if data.actions.mouseup {
rust_log(3);
}*/
}
#[no_mangle]
pub extern "C" fn update(time: c_double) {
let data: &mut GameData = &mut DATA.lock().unwrap();
data.time_controller.update_seconds(time, &data.actions, &mut data.state);
data.actions.mouseup = false;
data.actions.click = (0.0, 0.0);
}
fn int_to_bool(i: c_int) -> bool {
i != 0
}
#[no_mangle]
pub extern "C" fn toggle_shoot(b: c_int) {
let data = &mut DATA.lock().unwrap();
data.actions.shoot = int_to_bool(b);
}
#[no_mangle]
pub extern "C" fn toggle_boost(b: c_int) {
let data = &mut DATA.lock().unwrap();
data.actions.boost = int_to_bool(b);
}
#[no_mangle]
pub extern "C" fn toggle_turn_left(b: c_int) {
let data = &mut DATA.lock().unwrap();
data.actions.rotate_left = int_to_bool(b);
}
#[no_mangle]
pub extern "C" fn toggle_turn_right(b: c_int) {
let data = &mut DATA.lock().unwrap();
data.actions.rotate_right = int_to_bool(b);
}
#[no_mangle]
pub extern "C" fn handle_mousedown(x: c_double, y: c_double) {
let data = &mut DATA.lock().unwrap();
data.actions.click = (x, y);
}
#[no_mangle]
pub extern "C" fn handle_mousemove(x: c_double, y: c_double) {
let data = &mut DATA.lock().unwrap();
data.actions.mouse_position = (x, y);
}
#[no_mangle]
pub extern "C" fn handle_mouseup() {
let data = &mut DATA.lock().unwrap();
data.actions.mouseup = true
}
|
use crate::{
lexer::{Lexer, Token, TokenType},
Comment, Span,
};
use core::fmt::{self, Display, Formatter};
/// A [`char`]-[`f32`] pair, used for things like arguments (`X3.14`), command
/// numbers (`G90`) and line numbers (`N10`).
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(
feature = "serde-1",
derive(serde_derive::Serialize, serde_derive::Deserialize)
)]
#[repr(C)]
pub struct Word {
/// The letter part of this [`Word`].
pub letter: char,
/// The value part.
pub value: f32,
/// Where the [`Word`] lies in the original string.
pub span: Span,
}
impl Word {
/// Create a new [`Word`].
pub fn new(letter: char, value: f32, span: Span) -> Self {
Word {
letter,
value,
span,
}
}
}
impl Display for Word {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}{}", self.letter, self.value)
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) enum Atom<'input> {
Word(Word),
Comment(Comment<'input>),
/// Incomplete parts of a [`Word`].
BrokenWord(Token<'input>),
/// Garbage from the tokenizer (see [`TokenType::Unknown`]).
Unknown(Token<'input>),
}
impl<'input> Atom<'input> {
pub(crate) fn span(&self) -> Span {
match self {
Atom::Word(word) => word.span,
Atom::Comment(comment) => comment.span,
Atom::Unknown(token) | Atom::BrokenWord(token) => token.span,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct WordsOrComments<'input, I> {
tokens: I,
/// keep track of the last letter so we can deal with a trailing letter
/// that has no number
last_letter: Option<Token<'input>>,
}
impl<'input, I> WordsOrComments<'input, I>
where
I: Iterator<Item = Token<'input>>,
{
pub(crate) fn new(tokens: I) -> Self {
WordsOrComments {
tokens,
last_letter: None,
}
}
}
impl<'input, I> Iterator for WordsOrComments<'input, I>
where
I: Iterator<Item = Token<'input>>,
{
type Item = Atom<'input>;
fn next(&mut self) -> Option<Self::Item> {
while let Some(token) = self.tokens.next() {
let Token { kind, value, span } = token;
match kind {
TokenType::Unknown => return Some(Atom::Unknown(token)),
TokenType::Comment => {
return Some(Atom::Comment(Comment { value, span }))
},
TokenType::Letter if self.last_letter.is_none() => {
self.last_letter = Some(token);
},
TokenType::Number if self.last_letter.is_some() => {
let letter_token = self.last_letter.take().unwrap();
let span = letter_token.span.merge(span);
debug_assert_eq!(letter_token.value.len(), 1);
let letter = letter_token.value.chars().next().unwrap();
let value = value.parse().expect("");
return Some(Atom::Word(Word {
letter,
value,
span,
}));
},
_ => return Some(Atom::BrokenWord(token)),
}
}
self.last_letter.take().map(Atom::BrokenWord)
}
}
impl<'input> From<&'input str> for WordsOrComments<'input, Lexer<'input>> {
fn from(other: &'input str) -> WordsOrComments<'input, Lexer<'input>> {
WordsOrComments::new(Lexer::new(other))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lexer::Lexer;
#[test]
fn pass_comments_through() {
let mut words =
WordsOrComments::new(Lexer::new("(this is a comment) 3.14"));
let got = words.next().unwrap();
let comment = "(this is a comment)";
let expected = Atom::Comment(Comment {
value: comment,
span: Span {
start: 0,
end: comment.len(),
line: 0,
},
});
assert_eq!(got, expected);
}
#[test]
fn pass_garbage_through() {
let text = "!@#$ *";
let mut words = WordsOrComments::new(Lexer::new(text));
let got = words.next().unwrap();
let expected = Atom::Unknown(Token {
value: text,
kind: TokenType::Unknown,
span: Span {
start: 0,
end: text.len(),
line: 0,
},
});
assert_eq!(got, expected);
}
#[test]
fn numbers_are_garbage_if_they_dont_have_a_letter_in_front() {
let text = "3.14 ()";
let mut words = WordsOrComments::new(Lexer::new(text));
let got = words.next().unwrap();
let expected = Atom::BrokenWord(Token {
value: "3.14",
kind: TokenType::Number,
span: Span {
start: 0,
end: 4,
line: 0,
},
});
assert_eq!(got, expected);
}
#[test]
fn recognise_a_valid_word() {
let text = "G90";
let mut words = WordsOrComments::new(Lexer::new(text));
let got = words.next().unwrap();
let expected = Atom::Word(Word {
letter: 'G',
value: 90.0,
span: Span {
start: 0,
end: text.len(),
line: 0,
},
});
assert_eq!(got, expected);
}
}
|
pub mod minimax;
pub mod alphabeta;
pub mod heuristics;
pub mod turn;
pub mod types; |
extern crate allegro;
extern crate allegro_font;
extern crate allegro_image;
extern crate tiled;
mod states;
use allegro::{Bitmap, Color, Core, SharedBitmap, SubBitmap};
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::fs::File;
use std::mem;
use std::rc::Rc;
use std::path::{Path, PathBuf};
#[no_mangle]
pub fn update(p: &Platform, s: State) -> State {
s.update(p)
}
#[no_mangle]
#[allow(unused_variables)]
pub fn render(p: &Platform, s: &State) {
p.core.clear_to_color(Color::from_rgb(0, 0, 0));
s.render(p);
}
#[no_mangle]
#[allow(unused_variables)]
pub fn handle_event(p: &Platform, s: State, e: allegro::Event) -> State {
s.handle_event(p, e)
}
#[no_mangle]
pub fn clean_up(mut s: State) {
s.clean_up();
mem::forget(s);
}
#[allow(dead_code)]
pub struct Platform {
pub core: allegro::Core,
pub font_addon: allegro_font::FontAddon,
pub image_addon: allegro_image::ImageAddon,
}
pub enum State {
Loading(states::loading::Loading),
Game(states::game::Game),
}
impl State {
pub fn new(p: &Platform) -> State {
State::Loading(states::loading::Loading::new(p))
}
fn update(self, p: &Platform) -> State {
match self {
State::Loading(x) => x.update(p),
State::Game(x) => x.update(p),
}
}
fn render(&self, p: &Platform) {
match *self {
State::Loading(ref x) => x.render(p),
State::Game(ref x) => x.render(p),
}
}
fn handle_event(self, p: &Platform, e: allegro::Event) -> State {
match self {
State::Loading(x) => State::Loading(x),
State::Game(x) => x.handle_event(p, e),
}
}
fn clean_up(&mut self) {
match *self {
State::Loading(_) => (),
State::Game(ref mut x) => { x.clean_up(); mem::forget(x) },
}
}
}
pub struct TiledMap {
pub m: tiled::Map,
pub bitmaps: HashMap<String, Rc<Bitmap>>,
pub tiles: HashMap<u32, SubBitmap>,
}
impl TiledMap {
pub fn load<P: AsRef<Path>>(core: &Core, filename: P) -> TiledMap {
let f = match File::open(filename.as_ref()) {
Ok(f) => f,
Err(e) => panic!("failed to open map file: {}", e),
};
let m = match tiled::parse(f) {
Ok(m) => m,
Err(e) => panic!("failed to parse map: {}", e),
};
let dir = filename.as_ref().parent().unwrap();
// Load all of the backing tilesheet images as Allegro memory bitmaps.
let mut bitmaps = HashMap::new();
for tileset in &m.tilesets {
for image in &tileset.images {
let mut path = PathBuf::from(dir); path.push(&image.source[..]);
let bmp = match Bitmap::load(core, &path.to_string_lossy()) {
Ok(x) => x,
Err(e) => panic!("failed to load bitmap: {:?}", e),
};
bitmaps.insert(image.source.clone(), Rc::new(bmp));
}
}
let mut tiles = HashMap::new();
for layer in &m.layers {
for y in 0..layer.tiles.len() {
for x in 0..layer.tiles[y].len() {
let gid = layer.tiles[y][x];
if let Entry::Vacant(entry) = tiles.entry(gid) {
if let Some(tileset) = m.get_tileset_by_gid(gid) {
let image = &tileset.images[0];
let relative_gid = gid - tileset.first_gid;
let tiles_per_row = ((image.width as u32) + tileset.spacing) / (tileset.tile_width + tileset.spacing);
let ty = relative_gid / tiles_per_row;
let tx = relative_gid - (ty * tiles_per_row);
entry.insert(bitmaps.get(&image.source).unwrap()
.create_sub_bitmap(
((tx * (tileset.tile_width + tileset.spacing)) + tileset.margin) as i32,
((ty * (tileset.tile_height + tileset.spacing)) + tileset.margin) as i32,
tileset.tile_width as i32,
tileset.tile_height as i32,
).unwrap());
}
}
}
}
}
TiledMap{ m: m, bitmaps: bitmaps, tiles: tiles }
}
pub fn render(&self, p: &Platform, dx: i32, dy: i32) {
for layer in &self.m.layers {
if !layer.visible {
continue;
}
for ty in 0..layer.tiles.len() {
for tx in 0..layer.tiles[ty].len() {
let gid = layer.tiles[ty][tx];
if let Some(tileset) = self.m.get_tileset_by_gid(gid) {
if let Some(bmp) = self.tiles.get(&gid) {
let x = ((tx as i32 * tileset.tile_width as i32) - dx) as f32;
let y = ((ty as i32 * tileset.tile_height as i32) - dy) as f32;
if layer.opacity == 1.00 {
p.core.draw_bitmap(bmp, x, y, allegro::FLIP_NONE);
} else {
p.core.draw_tinted_bitmap(bmp, Color::from_rgba_f(layer.opacity, layer.opacity, layer.opacity, layer.opacity), x, y, allegro::FLIP_NONE);
}
}
}
}
}
}
}
}
impl Drop for TiledMap {
fn drop(&mut self) {
println!("Dropping a map");
}
}
|
use convert_case::{Case, Casing};
use proc_macro2::{Ident, Span, TokenStream};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ComponentStorage {
/// Backed by a vector: this means that data is reserved
/// for every entity, including ones that don't have it, this
/// trades memory for faster iteration and search.
Vec,
/// Backed by a HashMap: efficient memory use and fairly fast
/// iteration and search.
/// /!\ **NOTE**: this uses a fast but **non-secure** hashing algorithm.
HashMap,
/// Backed by a BTreeMap
BTreeMap,
/// Uses a table to map entities and components allowing better memory efficiency.
DenseVec,
/// Used for component that do not contain any data (**must implement [`Default`]**)
Null,
/// A storage that is flagged for writes: allows detection that the storage has been written to.
Flagged(Box<ComponentStorage>),
}
impl ComponentStorage {
pub fn storage_type(&self, path: TokenStream) -> TokenStream {
match self {
ComponentStorage::Vec => quote::quote! { ::std::vec::Vec<#path> },
ComponentStorage::HashMap => {
quote::quote! { ::secs::fxhash::FxHashMap<::secs::Entity, #path> }
}
ComponentStorage::BTreeMap => {
quote::quote! { ::std::collections::BTreeMap<::secs::Entity, #path> }
}
ComponentStorage::DenseVec => todo!(),
ComponentStorage::Null => quote::quote! { () },
ComponentStorage::Flagged(_) => todo!(),
}
}
pub fn storage_init(&self) -> TokenStream {
match self {
ComponentStorage::Vec => quote::quote! { Vec::new() },
ComponentStorage::HashMap => quote::quote! { ::secs::fxhash::FxHashMap::new() },
ComponentStorage::BTreeMap => quote::quote! { ::std::collections::BTreeMap::new() },
ComponentStorage::DenseVec => todo!(),
ComponentStorage::Null => quote::quote! { () },
ComponentStorage::Flagged(_) => todo!(),
}
}
pub fn storage_init_with_capacity(&self, capacity: TokenStream) -> TokenStream {
match self {
ComponentStorage::Vec => quote::quote! { Vec::with_capacity(#capacity) },
ComponentStorage::HashMap => {
quote::quote! { ::secs::fxhash::FxHashMap::with_capacity(#capacity) }
}
ComponentStorage::BTreeMap => {
quote::quote! { ::std::collections::BTreeMap::new() }
}
ComponentStorage::DenseVec => todo!(),
ComponentStorage::Null => quote::quote! { () },
ComponentStorage::Flagged(_) => todo!(),
}
}
pub fn as_kind(&self) -> TokenStream {
match self {
ComponentStorage::Vec => quote::quote! { Vec },
ComponentStorage::HashMap => quote::quote! { HashMap },
ComponentStorage::BTreeMap => quote::quote! { BTreeMap },
ComponentStorage::DenseVec => todo!(),
ComponentStorage::Null => todo!("Null storage"),
ComponentStorage::Flagged(_) => todo!("Flagged storage"),
}
}
pub fn read_function(
&self,
component: &Component,
id: TokenStream,
store: TokenStream,
value: TokenStream,
mutable: bool,
optional: bool,
) -> TokenStream {
let out = match self {
ComponentStorage::Vec => {
if mutable {
quote::quote! { #value.get_mut(#id.index() as usize).unwrap().as_mut() }
} else {
quote::quote! { #value.get(#id.index() as usize).unwrap().as_ref() }
}
}
ComponentStorage::HashMap | ComponentStorage::BTreeMap => {
if mutable {
quote::quote! { #value.get_mut(&#id) }
} else {
quote::quote! { #value.get(&#id) }
}
}
ComponentStorage::DenseVec => todo!(),
ComponentStorage::Null => {
let bitset = component.as_bitset();
quote::quote! { if #store.#bitset.contains(#id.index()) { Some(Default::default()) } else { None } }
}
ComponentStorage::Flagged(_) => todo!(),
};
if optional {
out
} else {
quote::quote! { #out.unwrap() }
}
}
pub fn write_function(
&self,
path: TokenStream,
id: TokenStream,
value: TokenStream,
) -> TokenStream {
match self {
ComponentStorage::Vec => quote::quote! {
if #path.len() <= #id.index() as usize {
#path.resize(#id.index() as usize + 1, None);
}
#path[#id.index() as usize] = Some(#value);
},
ComponentStorage::HashMap | ComponentStorage::BTreeMap => {
quote::quote! { #path.insert(#id, #value); }
}
ComponentStorage::Null => quote::quote! {},
ComponentStorage::DenseVec => todo!(),
ComponentStorage::Flagged(_) => todo!(),
}
}
pub fn remove_function(
&self,
component: &Component,
path: TokenStream,
id: TokenStream,
exists: TokenStream,
) -> TokenStream {
match self {
ComponentStorage::Vec => quote::quote! { #path[#id.index() as usize].take() },
ComponentStorage::HashMap | ComponentStorage::BTreeMap => {
quote::quote! { #path.remove(&#id) }
}
ComponentStorage::Null => {
let ty = component.as_ty();
quote::quote! {
if #exists {
Some(<#ty>::default())
} else {
None
}
}
}
ComponentStorage::Flagged(flagged_inner) => {
flagged_inner.remove_function(component, path, id, exists)
}
_ => quote::quote! {},
}
}
pub fn clear_function(
&self,
caller: TokenStream,
bitset: TokenStream,
id: TokenStream,
) -> TokenStream {
match self {
ComponentStorage::Vec => quote::quote! {
if (#id.index() as usize) <= #caller.len() {
#caller[#id.index() as usize] = None;
#bitset.remove(#id.index());
} else {
#caller.resize(#id.index() as usize + 1, None)
}
},
ComponentStorage::BTreeMap | ComponentStorage::HashMap => quote::quote! {
#caller.remove(&#id);
#bitset.remove(#id.index());
},
ComponentStorage::Null => quote::quote! {
#bitset.remove(#id.index());
},
ComponentStorage::Flagged(flagged_inner) => {
flagged_inner.clear_function(caller, bitset, id)
}
ComponentStorage::DenseVec => todo!(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Component<'a> {
/// The path to the component
pub path: &'a str,
/// The name of the component (allows multiple components with the same type but different names)
pub name: &'a str,
/// The type of storage used by this component
pub storage: ComponentStorage,
/// List of lifetimes the `path` contains
pub lifetimes: Option<Vec<&'a str>>,
}
impl ComponentStorage {
pub fn as_type(&self, comp: &Component, ty: TokenStream) -> TokenStream {
match self {
ComponentStorage::Vec => quote::quote! { Vec<Option<#ty>> },
ComponentStorage::HashMap => {
quote::quote! { ::fxhash::FxHashMap<::secs::Entity, #ty> }
}
ComponentStorage::BTreeMap => {
quote::quote! { ::std::collections::BTreeMap<::secs::Entity, #ty> }
}
ComponentStorage::DenseVec => quote::quote! { ::secs::DenseVec<#ty> },
ComponentStorage::Null => {
if let Some(lifetimes) = &comp.lifetimes {
if !lifetimes.is_empty() {
panic!(
"Null components cannot have lifetimes, found for: {}",
comp.name
);
}
}
quote::quote! { () }
}
ComponentStorage::Flagged(flagged) => {
let flagged_ty = flagged.as_type(comp, ty);
quote::quote! { ::secs::Flagged<#flagged_ty> }
}
}
}
}
impl<'a> Component<'a> {
pub fn as_field_name(&self) -> String {
self.name.to_case(Case::Snake)
}
pub fn as_mut_name(&self) -> String {
format!("{}_mut", self.name).to_case(Case::Snake)
}
pub fn as_bitset_name(&self) -> String {
format!("bitset_{}_", self.name).to_case(Case::Snake)
}
pub fn as_del_name(&self) -> String {
format!("del_{}", self.name).to_case(Case::Snake)
}
pub fn as_add_name(&self) -> String {
format!("add_{}", self.name).to_case(Case::Snake)
}
pub fn as_ident(&self) -> Ident {
Ident::new(&self.as_field_name(), Span::call_site())
}
pub fn as_mut(&self) -> Ident {
Ident::new(&self.as_mut_name(), Span::call_site())
}
pub fn as_add_ident(&self) -> Ident {
Ident::new(&self.as_add_name(), Span::call_site())
}
pub fn as_del_ident(&self) -> Ident {
Ident::new(&self.as_del_name(), Span::call_site())
}
pub fn as_bitset(&self) -> Ident {
Ident::new(&self.as_bitset_name(), Span::call_site())
}
pub fn as_ty(&self) -> TokenStream {
syn::parse_str(&self.path).expect("Failed to parse path")
}
pub fn as_storage(&self) -> TokenStream {
let ty = self.as_ty();
self.storage.as_type(self, ty)
}
pub fn as_struct_field(&self) -> TokenStream {
let name = self.as_ident();
let storage = self.as_storage();
quote::quote! {
#name: #storage
}
}
pub fn as_struct_bitset(&self) -> TokenStream {
let name = self.as_bitset();
quote::quote! {
#name: ::secs::hibitset::BitSet
}
}
pub fn as_field_ref(&self, mutable: bool) -> TokenStream {
let name = self.as_ident();
if mutable {
quote::quote! {
&#name
}
} else {
quote::quote! {
&mut #name
}
}
}
}
|
///! dag-pb support operations. Placing this module inside unixfs module is a bit unfortunate but
///! follows from the inseparability of dag-pb and UnixFS.
use crate::pb::PBNode;
use alloc::borrow::Cow;
use core::convert::TryFrom;
use core::fmt;
use core::ops::Range;
/// Extracts the PBNode::Data field from the block as it appears on the block.
pub fn node_data(block: &[u8]) -> Result<Option<&[u8]>, quick_protobuf::Error> {
let doc = PBNode::try_from(block)?;
Ok(match doc.Data {
Some(Cow::Borrowed(slice)) => Some(slice),
Some(Cow::Owned(_)) => unreachable!("never converted to owned"),
None => None,
})
}
/// Creates a wrapper around the given block representation which does not consume the block
/// representation but allows accessing the dag-pb node Data.
pub fn wrap_node_data<T>(block: T) -> Result<NodeData<T>, quick_protobuf::Error>
where
T: AsRef<[u8]>,
{
let full = block.as_ref();
let range = node_data(full)?
.map(|data| subslice_to_range(full, data).expect("this has to be in range"));
Ok(NodeData {
inner: block,
range,
})
}
fn subslice_to_range(full: &[u8], sub: &[u8]) -> Option<Range<usize>> {
// note this doesn't work for all types, for example () or similar ZSTs.
let max = full.len();
let amt = sub.len();
if max < amt {
// if the latter slice is larger than the first one, surely it isn't a subslice.
return None;
}
let full = full.as_ptr() as usize;
let sub = sub.as_ptr() as usize;
sub.checked_sub(full)
// not needed as it would divide by one: .map(|diff| diff / mem::size_of::<T>())
//
// if there are two slices of a continuous chunk, [A|B] we need to make sure B will not be
// calculated as subslice of A
.and_then(|start| if start >= max { None } else { Some(start) })
.map(|start| start..(start + amt))
}
/// The wrapper returned from [`wrap_node_data`], allows accessing dag-pb nodes Data.
#[derive(PartialEq)]
pub struct NodeData<T> {
inner: T,
range: Option<Range<usize>>,
}
impl<T: AsRef<[u8]>> fmt::Debug for NodeData<T> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
fmt,
"NodeData<{}> {{ inner.len: {}, range: {:?} }}",
std::any::type_name::<T>(),
self.inner.as_ref().len(),
self.range
)
}
}
impl<T: AsRef<[u8]>> NodeData<T> {
/// Returns the dag-pb nodes Data field as slice
pub fn node_data(&self) -> &[u8] {
if let Some(range) = self.range.as_ref() {
&self.inner.as_ref()[range.clone()]
} else {
&[][..]
}
}
/// Returns access to the wrapped block representation
pub fn get_ref(&self) -> &T {
&self.inner
}
/// Consumes self and returns the block representation
pub fn into_inner(self) -> T {
self.inner
}
}
impl<T: AsRef<[u8]>, B: AsRef<[u8]>> PartialEq<B> for NodeData<T> {
fn eq(&self, other: &B) -> bool {
self.node_data() == other.as_ref()
}
}
#[cfg(test)]
mod tests {
use super::subslice_to_range;
#[test]
fn subslice_ranges() {
let full = &b"01234"[..];
for start in 0..(full.len() - 1) {
for end in start..(full.len() - 1) {
let sub = &full[start..end];
assert_eq!(subslice_to_range(full, sub), Some(start..end));
}
}
}
#[test]
fn not_in_following_subslice() {
// this could be done with two distinct/disjoint 'static slices but there might not be any
// guarantees it working in all rust released and unreleased versions, and with different
// linkers.
let full = &b"0123456789"[..];
let a = &full[0..4];
let b = &full[4..];
let a_sub = &a[1..3];
let b_sub = &b[0..2];
assert_eq!(subslice_to_range(a, a_sub), Some(1..3));
assert_eq!(subslice_to_range(b, b_sub), Some(0..2));
assert_eq!(subslice_to_range(a, b_sub), None);
assert_eq!(subslice_to_range(b, a_sub), None);
}
}
|
#[doc = "Reader of register SSFIFO0"]
pub type R = crate::R<u32, super::SSFIFO0>;
#[doc = "Reader of field `DATA`"]
pub type DATA_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:11 - Conversion Result Data"]
#[inline(always)]
pub fn data(&self) -> DATA_R {
DATA_R::new((self.bits & 0x0fff) as u16)
}
}
|
use rpc_client::*;
use utils::hex_to_vec;
use bitcoin;
use serde_json;
use tokio;
use bitcoin_hashes::sha256d::Hash as Sha256dHash;
use bitcoin_hashes::hex::ToHex;
use futures::future;
use futures::future::Future;
use futures::{Stream, Sink};
use futures::sync::mpsc;
use lightning::chain::chaininterface;
use lightning::chain::chaininterface::{BlockNotifier, ChainError};
use lightning::util::logger::Logger;
use bitcoin::blockdata::block::Block;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::consensus::encode;
use bitcoin::network::constants::Network;
use bitcoin::util::hash::BitcoinHash;
use std::collections::HashMap;
use std::cmp;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::vec::Vec;
use std::time::{Instant, Duration};
pub struct FeeEstimator {
background_est: AtomicUsize,
normal_est: AtomicUsize,
high_prio_est: AtomicUsize,
}
impl FeeEstimator {
pub fn new() -> Self {
FeeEstimator {
background_est: AtomicUsize::new(0),
normal_est: AtomicUsize::new(0),
high_prio_est: AtomicUsize::new(0),
}
}
fn update_values(us: Arc<Self>, rpc_client: &RPCClient) -> impl Future<Item=(), Error=()> {
let mut reqs: Vec<Box<dyn Future<Item=(), Error=()> + Send>> = Vec::with_capacity(3);
{
let us = us.clone();
reqs.push(Box::new(rpc_client.make_rpc_call("estimatesmartfee", &vec!["6", "\"CONSERVATIVE\""], false).and_then(move |v| {
if let Some(serde_json::Value::Number(hp_btc_per_kb)) = v.get("feerate") {
us.high_prio_est.store((hp_btc_per_kb.as_f64().unwrap() * 100_000_000.0 / 250.0) as usize + 3, Ordering::Release);
}
Ok(())
})));
}
{
let us = us.clone();
reqs.push(Box::new(rpc_client.make_rpc_call("estimatesmartfee", &vec!["18", "\"ECONOMICAL\""], false).and_then(move |v| {
if let Some(serde_json::Value::Number(np_btc_per_kb)) = v.get("feerate") {
us.normal_est.store((np_btc_per_kb.as_f64().unwrap() * 100_000_000.0 / 250.0) as usize + 3, Ordering::Release);
}
Ok(())
})));
}
{
let us = us.clone();
reqs.push(Box::new(rpc_client.make_rpc_call("estimatesmartfee", &vec!["144", "\"ECONOMICAL\""], false).and_then(move |v| {
if let Some(serde_json::Value::Number(bp_btc_per_kb)) = v.get("feerate") {
us.background_est.store((bp_btc_per_kb.as_f64().unwrap() * 100_000_000.0 / 250.0) as usize + 3, Ordering::Release);
}
Ok(())
})));
}
future::join_all(reqs).then(|_| { Ok(()) })
}
}
impl chaininterface::FeeEstimator for FeeEstimator {
fn get_est_sat_per_1000_weight(&self, conf_target: chaininterface::ConfirmationTarget) -> u64 {
cmp::max(match conf_target {
chaininterface::ConfirmationTarget::Background => self.background_est.load(Ordering::Acquire) as u64,
chaininterface::ConfirmationTarget::Normal => self.normal_est.load(Ordering::Acquire) as u64,
chaininterface::ConfirmationTarget::HighPriority => self.high_prio_est.load(Ordering::Acquire) as u64,
}, 253)
}
}
pub struct ChainInterface {
util: chaininterface::ChainWatchInterfaceUtil,
txn_to_broadcast: Mutex<HashMap<Sha256dHash, bitcoin::blockdata::transaction::Transaction>>,
rpc_client: Arc<RPCClient>,
}
impl ChainInterface {
pub fn new(rpc_client: Arc<RPCClient>, network: Network, logger: Arc<dyn Logger>) -> Self {
ChainInterface {
util: chaininterface::ChainWatchInterfaceUtil::new(network, logger),
txn_to_broadcast: Mutex::new(HashMap::new()),
rpc_client,
}
}
fn rebroadcast_txn(&self) -> impl Future {
let mut send_futures = Vec::new();
{
let txn = self.txn_to_broadcast.lock().unwrap();
for (_, tx) in txn.iter() {
let tx_ser = "\"".to_string() + &encode::serialize_hex(tx) + "\"";
send_futures.push(self.rpc_client.make_rpc_call("sendrawtransaction", &[&tx_ser], true).then(|_| -> Result<(), ()> { Ok(()) }));
}
}
future::join_all(send_futures).then(|_| -> Result<(), ()> { Ok(()) })
}
}
impl chaininterface::ChainWatchInterface for ChainInterface {
fn install_watch_tx(&self, txid: &bitcoin_hashes::sha256d::Hash, script: &bitcoin::blockdata::script::Script) {
self.util.install_watch_tx(txid, script);
}
fn install_watch_outpoint(&self, outpoint: (bitcoin_hashes::sha256d::Hash, u32), script_pubkey: &bitcoin::blockdata::script::Script) {
self.util.install_watch_outpoint(outpoint, script_pubkey);
}
fn watch_all_txn(&self) {
self.util.watch_all_txn();
}
fn get_chain_utxo(&self, genesis_hash: bitcoin_hashes::sha256d::Hash, unspent_tx_output_identifier: u64) -> Result<(bitcoin::blockdata::script::Script, u64), ChainError> {
self.util.get_chain_utxo(genesis_hash, unspent_tx_output_identifier)
}
fn filter_block<'a>(&self, block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>) {
self.util.filter_block(block)
}
fn reentered(&self) -> usize {
self.util.reentered()
}
}
impl chaininterface::BroadcasterInterface for ChainInterface {
fn broadcast_transaction (&self, tx: &bitcoin::blockdata::transaction::Transaction) {
self.txn_to_broadcast.lock().unwrap().insert(tx.txid(), tx.clone());
let tx_ser = "\"".to_string() + &encode::serialize_hex(tx) + "\"";
tokio::spawn(self.rpc_client.make_rpc_call("sendrawtransaction", &[&tx_ser], true).then(|_| { Ok(()) }));
}
}
enum ForkStep {
DisconnectBlock((bitcoin::blockdata::block::BlockHeader, u32)),
ConnectBlock((String, u32)),
}
fn find_fork_step(steps_tx: mpsc::Sender<ForkStep>, current_header: GetHeaderResponse, target_header_opt: Option<(String, GetHeaderResponse)>, rpc_client: Arc<RPCClient>) {
if target_header_opt.is_some() && target_header_opt.as_ref().unwrap().0 == current_header.previousblockhash {
// Target is the parent of current, we're done!
return;
} else if current_header.height == 1 {
return;
} else if target_header_opt.is_none() || target_header_opt.as_ref().unwrap().1.height < current_header.height {
tokio::spawn(steps_tx.send(ForkStep::ConnectBlock((current_header.previousblockhash.clone(), current_header.height - 1))).then(move |send_res| {
if let Ok(steps_tx) = send_res {
future::Either::A(rpc_client.get_header(¤t_header.previousblockhash).then(move |new_cur_header| {
find_fork_step(steps_tx, new_cur_header.unwrap(), target_header_opt, rpc_client);
Ok(())
}))
} else {
// Caller droped the receiver, we should give up now
future::Either::B(future::result(Ok(())))
}
}));
} else {
let target_header = target_header_opt.unwrap().1;
// Everything below needs to disconnect target, so go ahead and do that now
tokio::spawn(steps_tx.send(ForkStep::DisconnectBlock((target_header.to_block_header(), target_header.height))).then(move |send_res| {
if let Ok(steps_tx) = send_res {
future::Either::A(if target_header.previousblockhash == current_header.previousblockhash {
// Found the fork, also connect current and finish!
future::Either::A(future::Either::A(
steps_tx.send(ForkStep::ConnectBlock((current_header.previousblockhash.clone(), current_header.height - 1))).then(|_| { Ok(()) })))
} else if target_header.height > current_header.height {
// Target is higher, walk it back and recurse
future::Either::B(rpc_client.get_header(&target_header.previousblockhash).then(move |new_target_header| {
find_fork_step(steps_tx, current_header, Some((target_header.previousblockhash, new_target_header.unwrap())), rpc_client);
Ok(())
}))
} else {
// Target and current are at the same height, but we're not at fork yet, walk
// both back and recurse
future::Either::A(future::Either::B(
steps_tx.send(ForkStep::ConnectBlock((current_header.previousblockhash.clone(), current_header.height - 1))).then(move |send_res| {
if let Ok(steps_tx) = send_res {
future::Either::A(rpc_client.get_header(¤t_header.previousblockhash).then(move |new_cur_header| {
rpc_client.get_header(&target_header.previousblockhash).then(move |new_target_header| {
find_fork_step(steps_tx, new_cur_header.unwrap(), Some((target_header.previousblockhash, new_target_header.unwrap())), rpc_client);
Ok(())
})
}))
} else {
// Caller droped the receiver, we should give up now
future::Either::B(future::result(Ok(())))
}
})
))
})
} else {
// Caller droped the receiver, we should give up now
future::Either::B(future::result(Ok(())))
}
}));
}
}
/// Walks backwards from current_hash and target_hash finding the fork and sending ForkStep events
/// into the steps_tx Sender. There is no ordering guarantee between different ForkStep types, but
/// DisconnectBlock and ConnectBlock events are each in reverse, height-descending order.
fn find_fork(mut steps_tx: mpsc::Sender<ForkStep>, current_hash: String, target_hash: String, rpc_client: Arc<RPCClient>) {
if current_hash == target_hash { return; }
tokio::spawn(rpc_client.get_header(¤t_hash).then(move |current_resp| {
let current_header = current_resp.unwrap();
assert!(steps_tx.start_send(ForkStep::ConnectBlock((current_hash, current_header.height))).unwrap().is_ready());
if current_header.previousblockhash == target_hash || current_header.height == 1 {
// Fastpath one-new-block-connected or reached block 1
future::Either::A(future::result(Ok(())))
} else {
future::Either::B(rpc_client.get_header(&target_hash).then(move |target_resp| {
match target_resp {
Ok(target_header) => find_fork_step(steps_tx, current_header, Some((target_hash, target_header)), rpc_client),
Err(_) => {
assert_eq!(target_hash, "");
find_fork_step(steps_tx, current_header, None, rpc_client)
},
}
Ok(())
}))
}
}));
}
pub fn spawn_chain_monitor(fee_estimator: Arc<FeeEstimator>, rpc_client: Arc<RPCClient>, chain_interface: Arc<ChainInterface>, chain_notifier: Arc<BlockNotifier>, event_notify: mpsc::Sender<()>) {
tokio::spawn(FeeEstimator::update_values(fee_estimator.clone(), &rpc_client));
let cur_block = Arc::new(Mutex::new(String::from("")));
tokio::spawn(tokio::timer::Interval::new(Instant::now(), Duration::from_secs(1)).for_each(move |_| {
let cur_block = cur_block.clone();
let fee_estimator = fee_estimator.clone();
let rpc_client = rpc_client.clone();
let chain_interface = chain_interface.clone();
let chain_notifier = chain_notifier.clone();
let mut event_notify = event_notify.clone();
rpc_client.make_rpc_call("getblockchaininfo", &[], false).and_then(move |v| {
let new_block = v["bestblockhash"].as_str().unwrap().to_string();
let old_block = cur_block.lock().unwrap().clone();
if new_block == old_block { return future::Either::A(future::result(Ok(()))); }
*cur_block.lock().unwrap() = new_block.clone();
if old_block == "" { return future::Either::A(future::result(Ok(()))); }
let (events_tx, events_rx) = mpsc::channel(1);
find_fork(events_tx, new_block, old_block, rpc_client.clone());
println!("NEW BEST BLOCK!");
future::Either::B(events_rx.collect().then(move |events_res| {
let events = events_res.unwrap();
for event in events.iter().rev() {
if let &ForkStep::DisconnectBlock((ref header, ref height)) = &event {
println!("Disconnecting block {}", header.bitcoin_hash().to_hex());
chain_notifier.block_disconnected(header, *height);
}
}
let mut connect_futures = Vec::with_capacity(events.len());
for event in events.iter().rev() {
if let &ForkStep::ConnectBlock((ref hash, height)) = &event {
let block_height = *height;
let chain_notifier = chain_notifier.clone();
connect_futures.push(rpc_client.make_rpc_call("getblock", &[&("\"".to_string() + hash + "\""), "0"], false).then(move |blockhex| {
let block: Block = encode::deserialize(&hex_to_vec(blockhex.unwrap().as_str().unwrap()).unwrap()).unwrap();
println!("Connecting block {}", block.bitcoin_hash().to_hex());
chain_notifier.block_connected(&block, block_height);
Ok(())
}));
}
}
future::join_all(connect_futures)
.then(move |_: Result<Vec<()>, ()>| { FeeEstimator::update_values(fee_estimator, &rpc_client) })
.then(move |_| { let _ = event_notify.try_send(()); Ok(()) })
.then(move |_: Result<(), ()>| { chain_interface.rebroadcast_txn() })
.then(|_| { Ok(()) })
}))
}).then(|_| { Ok(()) })
}).then(|_| { Ok(()) }));
}
|
pub enum Button {
A,
B,
Start,
Select,
L,
R,
LeftDPadUp,
LeftDPadDown,
LeftDPadLeft,
LeftDPadRight,
RightDPadUp,
RightDPadDown,
RightDPadLeft,
RightDPadRight,
}
pub struct GamePad {
a_pressed: bool,
b_pressed: bool,
start_pressed: bool,
select_pressed: bool,
l_pressed: bool,
r_pressed: bool,
left_d_pad_up_pressed: bool,
left_d_pad_down_pressed: bool,
left_d_pad_left_pressed: bool,
left_d_pad_right_pressed: bool,
right_d_pad_up_pressed: bool,
right_d_pad_down_pressed: bool,
right_d_pad_left_pressed: bool,
right_d_pad_right_pressed: bool,
}
impl GamePad {
pub fn new() -> GamePad {
GamePad {
a_pressed: false,
b_pressed: false,
start_pressed: false,
select_pressed: false,
l_pressed: false,
r_pressed: false,
left_d_pad_up_pressed: false,
left_d_pad_down_pressed: false,
left_d_pad_left_pressed: false,
left_d_pad_right_pressed: false,
right_d_pad_up_pressed: false,
right_d_pad_down_pressed: false,
right_d_pad_left_pressed: false,
right_d_pad_right_pressed: false,
}
}
pub fn read_input_control_reg(&self) -> u8 {
logln!(Log::GamePad, "WARNING: Read Game Pad Input Control Register not yet implemented");
0
}
pub fn write_input_control_reg(&mut self, value: u8) {
logln!(Log::GamePad, "WARNING: Write Game Pad Input Control Register not yet implemented (value: 0x{:02x})", value);
}
pub fn read_input_low_reg(&self) -> u8 {
let version = 1;
// TODO: Would be cool to be able to toggle this at startup/runtime :)
let low_battery = false;
(if self.right_d_pad_right_pressed { 1 } else { 0 } << 7) |
(if self.right_d_pad_up_pressed { 1 } else { 0 } << 6) |
(if self.l_pressed { 1 } else { 0 } << 5) |
(if self.r_pressed { 1 } else { 0 } << 4) |
(if self.b_pressed { 1 } else { 0 } << 3) |
(if self.a_pressed { 1 } else { 0 } << 2) |
(version << 1) |
if low_battery { 1 } else { 0 }
}
pub fn read_input_high_reg(&self) -> u8 {
(if self.right_d_pad_down_pressed { 1 } else { 0 } << 7) |
(if self.right_d_pad_left_pressed { 1 } else { 0 } << 6) |
(if self.select_pressed { 1 } else { 0 } << 5) |
(if self.start_pressed { 1 } else { 0 } << 4) |
(if self.left_d_pad_up_pressed { 1 } else { 0 } << 3) |
(if self.left_d_pad_down_pressed { 1 } else { 0 } << 2) |
(if self.left_d_pad_left_pressed { 1 } else { 0 } << 1) |
if self.left_d_pad_right_pressed { 1 } else { 0 }
}
pub fn set_button_pressed(&mut self, button: Button, pressed: bool) {
match button {
Button::A => self.a_pressed = pressed,
Button::B => self.b_pressed = pressed,
Button::Start => self.start_pressed = pressed,
Button::Select => self.select_pressed = pressed,
Button::L => self.l_pressed = pressed,
Button::R => self.r_pressed = pressed,
Button::LeftDPadUp => self.left_d_pad_up_pressed = pressed,
Button::LeftDPadDown => self.left_d_pad_down_pressed = pressed,
Button::LeftDPadLeft => self.left_d_pad_left_pressed = pressed,
Button::LeftDPadRight => self.left_d_pad_right_pressed = pressed,
Button::RightDPadUp => self.right_d_pad_up_pressed = pressed,
Button::RightDPadDown => self.right_d_pad_down_pressed = pressed,
Button::RightDPadLeft => self.right_d_pad_left_pressed = pressed,
Button::RightDPadRight => self.right_d_pad_right_pressed = pressed,
}
}
}
|
#![allow(clippy::all)]
const NUM_BINARY_DIGITS: usize = 12;
fn calc_gamma_rate<'a>(input: impl Iterator<Item = u16> + 'a) -> u16 {
let most_common_acc = input.fold([0i64; NUM_BINARY_DIGITS], |mut most_common_acc, number| {
for i in 0..NUM_BINARY_DIGITS {
match (number & (1 << i)) >> i {
1 => most_common_acc[i] += 1,
0 => most_common_acc[i] -= 1,
_ => unreachable!(),
}
}
most_common_acc
});
most_common_acc
.iter()
.enumerate()
.fold(0, |mut gamma_rate, (i, d)| {
if *d > 0 {
gamma_rate |= 1 << i;
}
gamma_rate
})
}
fn calc_epsilon_rate(gamma_rate: u16) -> u16 {
!gamma_rate & !(u16::MAX << NUM_BINARY_DIGITS)
}
fn split_whitespace_and_convert_binary<'a>(input: &'a String) -> impl Iterator<Item = u16> + 'a {
input
.split_whitespace()
.map(|s| u16::from_str_radix(s, 2).expect("Could not convert binary to i64."))
}
pub fn part1(input: String) {
let input = split_whitespace_and_convert_binary(&input);
let gamma_rate = calc_gamma_rate(input);
let epsilon_rate = calc_epsilon_rate(gamma_rate);
println!("Epsilon Rate: {:012b}", epsilon_rate);
println!("Gamma Rate: {:012b}", gamma_rate);
println!(
"Puzzle Answer: {}",
(epsilon_rate as u64) * (gamma_rate as u64)
);
}
fn filter_by_preferred<F>(input: &String, preferred_fn: F) -> u16
where
F: Fn(i64) -> u16,
{
let mut remaining: Vec<u16> = split_whitespace_and_convert_binary(&input).collect();
for i in 0..NUM_BINARY_DIGITS {
let shift = NUM_BINARY_DIGITS - 1 - i;
let preferred = preferred_fn(remaining.iter().fold(0, |acc, n| {
if *n & (1 << shift) > 0 {
acc + 1
} else {
acc - 1
}
}));
assert!(preferred == 0 || preferred == 1);
remaining = remaining
.into_iter()
.filter(|n| (*n & (1 << shift)) >> shift == preferred)
.collect();
if remaining.len() == 1 {
break;
}
}
remaining[0]
}
pub fn part2(input: String) {
let oxygen_generator_rating = filter_by_preferred(&input, |acc| if acc >= 0 { 1 } else { 0 });
let co2_scrubber_rating = filter_by_preferred(&input, |acc| if acc >= 0 { 0 } else { 1 });
println!("Oxygen Generator Rating: {}", oxygen_generator_rating);
println!("CO2 Scrubber Rating: {}", co2_scrubber_rating);
println!(
"Life Support Rating: {}",
(oxygen_generator_rating as u64) * (co2_scrubber_rating as u64)
);
}
|
use actix::prelude::*;
use actix::{
Recipient
};
use crate::WorkerClient;
use crate::messages::{
Connect,
ControllerState,
WorkerCommand,
StatusUpdate,
CreateWorker
};
use crate::uuid;
// This is following the pattern here:
// https://github.com/actix/examples/blob/master/websocket-chat/src/server.rs
pub struct Coordinator {
listeners: Vec<Recipient<StatusUpdate>>,
workers: Vec<Recipient<WorkerCommand>>,
state: ControllerState
}
impl Default for Coordinator {
fn default() -> Coordinator {
Coordinator {
listeners: Vec::new(),
workers: Vec::new(),
state: ControllerState {
jobs: Vec::new()
},
}
}
}
impl Actor for Coordinator {
/// We are going to use simple Context, we just need ability to communicate
/// with other actors.
type Context = Context<Self>;
fn started(&mut self, _ctx: &mut Self::Context) {
println!("[Coordinator] Started");
// ctx.run_later(Duration::from_millis(1000), move |act, _| {
// act.status.jobs.push(JobStatus {
// frame_start: 0,
// frame_end: 1000,
// render_times: Vec::new(),
// // time_start: None,
// // time_end: None
// });
// });
// TODO: get rid of this debugging
// ctx.notify(CreateWorker {});
}
}
impl Handler<Connect> for Coordinator {
type Result = ();
fn handle(&mut self, msg: Connect, _ctx: &mut Context<Self>) {
println!("[Coordinator] Someone joined");
self.listeners.push(msg.addr);
self.send_state_update();
}
}
impl Handler<CreateWorker> for Coordinator {
type Result = ();
fn handle(&mut self, _msg: CreateWorker, ctx: &mut Context<Self>) {
println!("[Coordinator] Creating worker...");
self.create_worker(ctx);
}
}
impl Coordinator {
fn create_worker(&mut self, ctx: &mut Context<Self>) {
let job_id = uuid::generate_uuid();
let coordinator_address = ctx.address();
let worker_arbiter = Arbiter::new();
let worker_client = WorkerClient::start_in_arbiter(&worker_arbiter, |_ctx: &mut Context<WorkerClient>| {
WorkerClient::new(job_id, coordinator_address)
});
self.workers.push(worker_client.clone().recipient());
worker_client.do_send(WorkerCommand::Create);
}
fn send_state_update(&mut self) {
println!("[Coordinator] Sending state update to everyone");
for listener in self.listeners.iter() {
println!("[Coordinator] Sending to recipient");
listener
.do_send(StatusUpdate {
status: self.state.clone()
})
.unwrap();
}
}
}
|
use crate::database::Database;
use candy_frontend::{
cst::CstDb,
error::CompilerError,
module::{Module, ModuleDb, ModuleKind, Package, PackagesPath},
position::{line_start_offsets_raw, Offset, PositionConversionDb},
};
use extension_trait::extension_trait;
use itertools::Itertools;
use lsp_types::{Diagnostic, DiagnosticSeverity, Position, Url};
use std::ops::Range;
pub fn error_to_diagnostic(db: &Database, module: Module, error: &CompilerError) -> Diagnostic {
let related_information = error
.to_related_information()
.into_iter()
.filter_map(|(module, cst_id, message)| {
let uri = module_to_url(&module, &db.packages_path)?;
let span = db.find_cst(module.clone(), cst_id).display_span();
let range = db.range_to_lsp_range(module, span);
Some(lsp_types::DiagnosticRelatedInformation {
location: lsp_types::Location { uri, range },
message,
})
})
.collect();
Diagnostic {
range: db.range_to_lsp_range(module, error.span.clone()),
severity: Some(DiagnosticSeverity::ERROR),
code: None,
code_description: None,
source: Some("🍭 Candy".to_owned()),
message: error.payload.to_string(),
related_information: Some(related_information),
tags: None,
data: None,
}
}
pub fn module_from_url(
url: &Url,
kind: ModuleKind,
packages_path: &PackagesPath,
) -> Result<Module, String> {
match url.scheme() {
"file" => Module::from_path(packages_path, &url.to_file_path().unwrap(), kind)
.map_err(|it| it.to_string()),
"untitled" => Ok(Module {
package: Package::Anonymous {
url: url
.to_string()
.strip_prefix("untitled:")
.unwrap()
.to_string(),
},
path: vec![],
kind,
}),
_ => Err(format!("Unsupported URI scheme: {}", url.scheme())),
}
}
pub fn module_to_url(module: &Module, packages_path: &PackagesPath) -> Option<Url> {
match &module.package {
Package::User(_) | Package::Managed(_) => Some(
Url::from_file_path(
module
.to_possible_paths(packages_path)
.unwrap()
.into_iter()
.find_or_first(|path| path.exists())
.unwrap(),
)
.unwrap(),
),
Package::Anonymous { url } => Some(Url::parse(&format!("untitled:{url}")).unwrap()),
Package::Tooling(_) => None,
}
}
// UTF-8 Byte Offset ↔ LSP Position/Range
#[extension_trait]
pub impl<DB: ModuleDb + PositionConversionDb + ?Sized> LspPositionConversion for DB {
fn lsp_position_to_offset(&self, module: Module, position: Position) -> Offset {
let text = self.get_module_content_as_string(module.clone()).unwrap();
let line_start_offsets = self.line_start_offsets(module);
lsp_position_to_offset_raw(&text, &line_start_offsets, position)
}
fn range_to_lsp_range(&self, module: Module, range: Range<Offset>) -> lsp_types::Range {
lsp_types::Range {
start: self.offset_to_lsp_position(module.clone(), range.start),
end: self.offset_to_lsp_position(module, range.end),
}
}
fn offset_to_lsp_position(&self, module: Module, offset: Offset) -> Position {
let text = self.get_module_content_as_string(module.clone()).unwrap();
let line_start_offsets = self.line_start_offsets(module);
offset_to_lsp_position_raw(&*text, &*line_start_offsets, offset)
}
}
pub fn lsp_range_to_range_raw(text: &str, range: lsp_types::Range) -> Range<Offset> {
let line_start_offsets = line_start_offsets_raw(text);
let start = lsp_position_to_offset_raw(text, &line_start_offsets, range.start);
let end = lsp_position_to_offset_raw(text, &line_start_offsets, range.end);
start..end
}
pub fn lsp_position_to_offset_raw(
text: &str,
line_start_offsets: &[Offset],
position: Position,
) -> Offset {
let line_offset = line_start_offsets[position.line as usize];
let line_length = if position.line as usize == line_start_offsets.len() - 1 {
text.len() - *line_offset
} else {
*line_start_offsets[(position.line + 1) as usize] - *line_offset
};
let line = &text[*line_offset..*line_offset + line_length];
let words = line.encode_utf16().collect::<Vec<_>>();
let char_offset = if position.character as usize >= words.len() {
line_length
} else {
String::from_utf16(&words[0..position.character as usize])
.unwrap()
.len()
};
Offset(*line_offset + char_offset)
}
pub fn range_to_lsp_range_raw<S, L>(
text: S,
line_start_offsets: L,
range: &Range<Offset>,
) -> lsp_types::Range
where
S: AsRef<str>,
L: AsRef<[Offset]>,
{
let text = text.as_ref();
let line_start_offsets = line_start_offsets.as_ref();
lsp_types::Range {
start: offset_to_lsp_position_raw(text, line_start_offsets, range.start),
end: offset_to_lsp_position_raw(text, line_start_offsets, range.end),
}
}
pub fn offset_to_lsp_position_raw<S, L>(
text: S,
line_start_offsets: L,
mut offset: Offset,
) -> Position
where
S: AsRef<str>,
L: AsRef<[Offset]>,
{
let text = text.as_ref();
let line_start_offsets = line_start_offsets.as_ref();
if *offset > text.len() {
*offset = text.len();
}
let line = line_start_offsets
.binary_search(&offset)
.unwrap_or_else(|i| i - 1);
let line_start = line_start_offsets[line];
let character_utf16_offset = text[*line_start..*offset].encode_utf16().count();
Position {
line: line as u32,
character: character_utf16_offset as u32,
}
}
pub trait JoinWithCommasAndAnd {
fn join_with_commas_and_and(&self) -> String;
}
impl<S: AsRef<str>> JoinWithCommasAndAnd for [S] {
fn join_with_commas_and_and(&self) -> String {
match self {
[] => panic!("Joining no parts."),
[part] => part.as_ref().to_string(),
[first, second] => format!("{} and {}", first.as_ref(), second.as_ref()),
[rest @ .., last] => format!(
"{}, and {}",
rest.iter().map(|it| it.as_ref()).join(", "),
last.as_ref(),
),
}
}
}
|
fn main() {
let mut x = 5;
println!("The value of x is : {}", x);
x = 6;
println!("The value of x is : {}", x);
const MAX_POINTS: u32 = 100000;
println!("The value of c is : {}", MAX_POINTS);
let y = 10;
let y = y*2;
let y = y/3;
println!("The value of y is : {}", y);
let space = " ";
let space = space.len(); // fine, cause immutable vars can change type
println!("The number of spaces is {}", space);
// let mut space1 = " ";
// space1 = space1.len(); // not fine, mutable vars cannot change type
}
|
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn parse_http_generic_error(
response: &http::Response<bytes::Bytes>,
) -> Result<smithy_types::Error, smithy_json::deserialize::Error> {
crate::json_errors::parse_generic_error(response.body(), response.headers())
}
pub fn deser_structure_duplicate_requestjson_err(
input: &[u8],
mut builder: crate::error::duplicate_request::Builder,
) -> Result<crate::error::duplicate_request::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"DuplicateOperationId" => {
builder = builder.set_duplicate_operation_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_invalid_inputjson_err(
input: &[u8],
mut builder: crate::error::invalid_input::Builder,
) -> Result<crate::error::invalid_input::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_namespace_already_existsjson_err(
input: &[u8],
mut builder: crate::error::namespace_already_exists::Builder,
) -> Result<crate::error::namespace_already_exists::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"CreatorRequestId" => {
builder = builder.set_creator_request_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"NamespaceId" => {
builder = builder.set_namespace_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_resource_limit_exceededjson_err(
input: &[u8],
mut builder: crate::error::resource_limit_exceeded::Builder,
) -> Result<crate::error::resource_limit_exceeded::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_too_many_tags_exceptionjson_err(
input: &[u8],
mut builder: crate::error::too_many_tags_exception::Builder,
) -> Result<crate::error::too_many_tags_exception::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"ResourceName" => {
builder = builder.set_resource_name(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_create_http_namespace(
input: &[u8],
mut builder: crate::output::create_http_namespace_output::Builder,
) -> Result<crate::output::create_http_namespace_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"OperationId" => {
builder = builder.set_operation_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_create_private_dns_namespace(
input: &[u8],
mut builder: crate::output::create_private_dns_namespace_output::Builder,
) -> Result<
crate::output::create_private_dns_namespace_output::Builder,
smithy_json::deserialize::Error,
> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"OperationId" => {
builder = builder.set_operation_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_create_public_dns_namespace(
input: &[u8],
mut builder: crate::output::create_public_dns_namespace_output::Builder,
) -> Result<
crate::output::create_public_dns_namespace_output::Builder,
smithy_json::deserialize::Error,
> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"OperationId" => {
builder = builder.set_operation_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_namespace_not_foundjson_err(
input: &[u8],
mut builder: crate::error::namespace_not_found::Builder,
) -> Result<crate::error::namespace_not_found::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_service_already_existsjson_err(
input: &[u8],
mut builder: crate::error::service_already_exists::Builder,
) -> Result<crate::error::service_already_exists::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"CreatorRequestId" => {
builder = builder.set_creator_request_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"ServiceId" => {
builder = builder.set_service_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_create_service(
input: &[u8],
mut builder: crate::output::create_service_output::Builder,
) -> Result<crate::output::create_service_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Service" => {
builder = builder
.set_service(crate::json_deser::deser_structure_service(tokens)?);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_resource_in_usejson_err(
input: &[u8],
mut builder: crate::error::resource_in_use::Builder,
) -> Result<crate::error::resource_in_use::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_delete_namespace(
input: &[u8],
mut builder: crate::output::delete_namespace_output::Builder,
) -> Result<crate::output::delete_namespace_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"OperationId" => {
builder = builder.set_operation_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_service_not_foundjson_err(
input: &[u8],
mut builder: crate::error::service_not_found::Builder,
) -> Result<crate::error::service_not_found::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_instance_not_foundjson_err(
input: &[u8],
mut builder: crate::error::instance_not_found::Builder,
) -> Result<crate::error::instance_not_found::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_deregister_instance(
input: &[u8],
mut builder: crate::output::deregister_instance_output::Builder,
) -> Result<crate::output::deregister_instance_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"OperationId" => {
builder = builder.set_operation_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_request_limit_exceededjson_err(
input: &[u8],
mut builder: crate::error::request_limit_exceeded::Builder,
) -> Result<crate::error::request_limit_exceeded::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_discover_instances(
input: &[u8],
mut builder: crate::output::discover_instances_output::Builder,
) -> Result<crate::output::discover_instances_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Instances" => {
builder = builder.set_instances(
crate::json_deser::deser_list_http_instance_summary_list(tokens)?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_get_instance(
input: &[u8],
mut builder: crate::output::get_instance_output::Builder,
) -> Result<crate::output::get_instance_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Instance" => {
builder = builder
.set_instance(crate::json_deser::deser_structure_instance(tokens)?);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_get_instances_health_status(
input: &[u8],
mut builder: crate::output::get_instances_health_status_output::Builder,
) -> Result<
crate::output::get_instances_health_status_output::Builder,
smithy_json::deserialize::Error,
> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Status" => {
builder = builder.set_status(
crate::json_deser::deser_map_instance_health_status_map(tokens)?,
);
}
"NextToken" => {
builder = builder.set_next_token(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_get_namespace(
input: &[u8],
mut builder: crate::output::get_namespace_output::Builder,
) -> Result<crate::output::get_namespace_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Namespace" => {
builder = builder
.set_namespace(crate::json_deser::deser_structure_namespace(tokens)?);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_operation_not_foundjson_err(
input: &[u8],
mut builder: crate::error::operation_not_found::Builder,
) -> Result<crate::error::operation_not_found::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_get_operation(
input: &[u8],
mut builder: crate::output::get_operation_output::Builder,
) -> Result<crate::output::get_operation_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Operation" => {
builder = builder
.set_operation(crate::json_deser::deser_structure_operation(tokens)?);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_get_service(
input: &[u8],
mut builder: crate::output::get_service_output::Builder,
) -> Result<crate::output::get_service_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Service" => {
builder = builder
.set_service(crate::json_deser::deser_structure_service(tokens)?);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_list_instances(
input: &[u8],
mut builder: crate::output::list_instances_output::Builder,
) -> Result<crate::output::list_instances_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Instances" => {
builder = builder.set_instances(
crate::json_deser::deser_list_instance_summary_list(tokens)?,
);
}
"NextToken" => {
builder = builder.set_next_token(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_list_namespaces(
input: &[u8],
mut builder: crate::output::list_namespaces_output::Builder,
) -> Result<crate::output::list_namespaces_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Namespaces" => {
builder = builder.set_namespaces(
crate::json_deser::deser_list_namespace_summaries_list(tokens)?,
);
}
"NextToken" => {
builder = builder.set_next_token(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_list_operations(
input: &[u8],
mut builder: crate::output::list_operations_output::Builder,
) -> Result<crate::output::list_operations_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Operations" => {
builder = builder.set_operations(
crate::json_deser::deser_list_operation_summary_list(tokens)?,
);
}
"NextToken" => {
builder = builder.set_next_token(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_list_services(
input: &[u8],
mut builder: crate::output::list_services_output::Builder,
) -> Result<crate::output::list_services_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Services" => {
builder = builder.set_services(
crate::json_deser::deser_list_service_summaries_list(tokens)?,
);
}
"NextToken" => {
builder = builder.set_next_token(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_resource_not_found_exceptionjson_err(
input: &[u8],
mut builder: crate::error::resource_not_found_exception::Builder,
) -> Result<crate::error::resource_not_found_exception::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_list_tags_for_resource(
input: &[u8],
mut builder: crate::output::list_tags_for_resource_output::Builder,
) -> Result<crate::output::list_tags_for_resource_output::Builder, smithy_json::deserialize::Error>
{
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Tags" => {
builder = builder.set_tags(crate::json_deser::deser_list_tag_list(tokens)?);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_register_instance(
input: &[u8],
mut builder: crate::output::register_instance_output::Builder,
) -> Result<crate::output::register_instance_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"OperationId" => {
builder = builder.set_operation_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_update_http_namespace(
input: &[u8],
mut builder: crate::output::update_http_namespace_output::Builder,
) -> Result<crate::output::update_http_namespace_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"OperationId" => {
builder = builder.set_operation_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_structure_custom_health_not_foundjson_err(
input: &[u8],
mut builder: crate::error::custom_health_not_found::Builder,
) -> Result<crate::error::custom_health_not_found::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Message" => {
builder = builder.set_message(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_update_private_dns_namespace(
input: &[u8],
mut builder: crate::output::update_private_dns_namespace_output::Builder,
) -> Result<
crate::output::update_private_dns_namespace_output::Builder,
smithy_json::deserialize::Error,
> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"OperationId" => {
builder = builder.set_operation_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_update_public_dns_namespace(
input: &[u8],
mut builder: crate::output::update_public_dns_namespace_output::Builder,
) -> Result<
crate::output::update_public_dns_namespace_output::Builder,
smithy_json::deserialize::Error,
> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"OperationId" => {
builder = builder.set_operation_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn deser_operation_update_service(
input: &[u8],
mut builder: crate::output::update_service_output::Builder,
) -> Result<crate::output::update_service_output::Builder, smithy_json::deserialize::Error> {
let mut tokens_owned =
smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input))
.peekable();
let tokens = &mut tokens_owned;
smithy_json::deserialize::token::expect_start_object(tokens.next())?;
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"OperationId" => {
builder = builder.set_operation_id(
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
if tokens.next().is_some() {
return Err(smithy_json::deserialize::Error::custom(
"found more JSON tokens after completing parsing",
));
}
Ok(builder)
}
pub fn or_empty_doc(data: &[u8]) -> &[u8] {
if data.is_empty() {
b"{}"
} else {
data
}
}
pub fn deser_structure_service<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::Service>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::Service::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Id" => {
builder = builder.set_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Arn" => {
builder = builder.set_arn(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Name" => {
builder = builder.set_name(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"NamespaceId" => {
builder = builder.set_namespace_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Description" => {
builder = builder.set_description(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"InstanceCount" => {
builder = builder.set_instance_count(
smithy_json::deserialize::token::expect_number_or_null(
tokens.next(),
)?
.map(|v| v.to_i32()),
);
}
"DnsConfig" => {
builder = builder.set_dns_config(
crate::json_deser::deser_structure_dns_config(tokens)?,
);
}
"Type" => {
builder = builder.set_type(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| {
s.to_unescaped()
.map(|u| crate::model::ServiceType::from(u.as_ref()))
})
.transpose()?,
);
}
"HealthCheckConfig" => {
builder = builder.set_health_check_config(
crate::json_deser::deser_structure_health_check_config(tokens)?,
);
}
"HealthCheckCustomConfig" => {
builder = builder.set_health_check_custom_config(
crate::json_deser::deser_structure_health_check_custom_config(
tokens,
)?,
);
}
"CreateDate" => {
builder = builder.set_create_date(
smithy_json::deserialize::token::expect_timestamp_or_null(
tokens.next(),
smithy_types::instant::Format::EpochSeconds,
)?,
);
}
"CreatorRequestId" => {
builder = builder.set_creator_request_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
#[allow(clippy::type_complexity, non_snake_case)]
pub fn deser_list_http_instance_summary_list<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<std::vec::Vec<crate::model::HttpInstanceSummary>>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartArray { .. }) => {
let mut items = Vec::new();
loop {
match tokens.peek() {
Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => {
tokens.next().transpose().unwrap();
break;
}
_ => {
let value =
crate::json_deser::deser_structure_http_instance_summary(tokens)?;
if let Some(value) = value {
items.push(value);
}
}
}
}
Ok(Some(items))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start array or null",
)),
}
}
pub fn deser_structure_instance<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::Instance>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::Instance::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Id" => {
builder = builder.set_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"CreatorRequestId" => {
builder = builder.set_creator_request_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Attributes" => {
builder = builder.set_attributes(
crate::json_deser::deser_map_attributes(tokens)?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
#[allow(clippy::type_complexity, non_snake_case)]
pub fn deser_map_instance_health_status_map<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<
Option<std::collections::HashMap<std::string::String, crate::model::HealthStatus>>,
smithy_json::deserialize::Error,
>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
let mut map = std::collections::HashMap::new();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
let key = key.to_unescaped().map(|u| u.into_owned())?;
let value =
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| {
s.to_unescaped()
.map(|u| crate::model::HealthStatus::from(u.as_ref()))
})
.transpose()?;
if let Some(value) = value {
map.insert(key, value);
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(map))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_namespace<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::Namespace>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::Namespace::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Id" => {
builder = builder.set_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Arn" => {
builder = builder.set_arn(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Name" => {
builder = builder.set_name(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Type" => {
builder = builder.set_type(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| {
s.to_unescaped()
.map(|u| crate::model::NamespaceType::from(u.as_ref()))
})
.transpose()?,
);
}
"Description" => {
builder = builder.set_description(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"ServiceCount" => {
builder = builder.set_service_count(
smithy_json::deserialize::token::expect_number_or_null(
tokens.next(),
)?
.map(|v| v.to_i32()),
);
}
"Properties" => {
builder = builder.set_properties(
crate::json_deser::deser_structure_namespace_properties(
tokens,
)?,
);
}
"CreateDate" => {
builder = builder.set_create_date(
smithy_json::deserialize::token::expect_timestamp_or_null(
tokens.next(),
smithy_types::instant::Format::EpochSeconds,
)?,
);
}
"CreatorRequestId" => {
builder = builder.set_creator_request_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_operation<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::Operation>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::Operation::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Id" => {
builder = builder.set_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Type" => {
builder = builder.set_type(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| {
s.to_unescaped()
.map(|u| crate::model::OperationType::from(u.as_ref()))
})
.transpose()?,
);
}
"Status" => {
builder = builder.set_status(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| {
s.to_unescaped().map(|u| {
crate::model::OperationStatus::from(u.as_ref())
})
})
.transpose()?,
);
}
"ErrorMessage" => {
builder = builder.set_error_message(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"ErrorCode" => {
builder = builder.set_error_code(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"CreateDate" => {
builder = builder.set_create_date(
smithy_json::deserialize::token::expect_timestamp_or_null(
tokens.next(),
smithy_types::instant::Format::EpochSeconds,
)?,
);
}
"UpdateDate" => {
builder = builder.set_update_date(
smithy_json::deserialize::token::expect_timestamp_or_null(
tokens.next(),
smithy_types::instant::Format::EpochSeconds,
)?,
);
}
"Targets" => {
builder = builder.set_targets(
crate::json_deser::deser_map_operation_targets_map(tokens)?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
#[allow(clippy::type_complexity, non_snake_case)]
pub fn deser_list_instance_summary_list<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<std::vec::Vec<crate::model::InstanceSummary>>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartArray { .. }) => {
let mut items = Vec::new();
loop {
match tokens.peek() {
Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => {
tokens.next().transpose().unwrap();
break;
}
_ => {
let value = crate::json_deser::deser_structure_instance_summary(tokens)?;
if let Some(value) = value {
items.push(value);
}
}
}
}
Ok(Some(items))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start array or null",
)),
}
}
#[allow(clippy::type_complexity, non_snake_case)]
pub fn deser_list_namespace_summaries_list<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<std::vec::Vec<crate::model::NamespaceSummary>>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartArray { .. }) => {
let mut items = Vec::new();
loop {
match tokens.peek() {
Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => {
tokens.next().transpose().unwrap();
break;
}
_ => {
let value = crate::json_deser::deser_structure_namespace_summary(tokens)?;
if let Some(value) = value {
items.push(value);
}
}
}
}
Ok(Some(items))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start array or null",
)),
}
}
#[allow(clippy::type_complexity, non_snake_case)]
pub fn deser_list_operation_summary_list<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<std::vec::Vec<crate::model::OperationSummary>>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartArray { .. }) => {
let mut items = Vec::new();
loop {
match tokens.peek() {
Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => {
tokens.next().transpose().unwrap();
break;
}
_ => {
let value = crate::json_deser::deser_structure_operation_summary(tokens)?;
if let Some(value) = value {
items.push(value);
}
}
}
}
Ok(Some(items))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start array or null",
)),
}
}
#[allow(clippy::type_complexity, non_snake_case)]
pub fn deser_list_service_summaries_list<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<std::vec::Vec<crate::model::ServiceSummary>>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartArray { .. }) => {
let mut items = Vec::new();
loop {
match tokens.peek() {
Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => {
tokens.next().transpose().unwrap();
break;
}
_ => {
let value = crate::json_deser::deser_structure_service_summary(tokens)?;
if let Some(value) = value {
items.push(value);
}
}
}
}
Ok(Some(items))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start array or null",
)),
}
}
#[allow(clippy::type_complexity, non_snake_case)]
pub fn deser_list_tag_list<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<std::vec::Vec<crate::model::Tag>>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartArray { .. }) => {
let mut items = Vec::new();
loop {
match tokens.peek() {
Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => {
tokens.next().transpose().unwrap();
break;
}
_ => {
let value = crate::json_deser::deser_structure_tag(tokens)?;
if let Some(value) = value {
items.push(value);
}
}
}
}
Ok(Some(items))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start array or null",
)),
}
}
pub fn deser_structure_dns_config<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::DnsConfig>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::DnsConfig::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"NamespaceId" => {
builder = builder.set_namespace_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"RoutingPolicy" => {
builder = builder.set_routing_policy(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| {
s.to_unescaped()
.map(|u| crate::model::RoutingPolicy::from(u.as_ref()))
})
.transpose()?,
);
}
"DnsRecords" => {
builder = builder.set_dns_records(
crate::json_deser::deser_list_dns_record_list(tokens)?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_health_check_config<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::HealthCheckConfig>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::HealthCheckConfig::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Type" => {
builder = builder.set_type(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| {
s.to_unescaped().map(|u| {
crate::model::HealthCheckType::from(u.as_ref())
})
})
.transpose()?,
);
}
"ResourcePath" => {
builder = builder.set_resource_path(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"FailureThreshold" => {
builder = builder.set_failure_threshold(
smithy_json::deserialize::token::expect_number_or_null(
tokens.next(),
)?
.map(|v| v.to_i32()),
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_health_check_custom_config<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::HealthCheckCustomConfig>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::HealthCheckCustomConfig::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"FailureThreshold" => {
builder = builder.set_failure_threshold(
smithy_json::deserialize::token::expect_number_or_null(
tokens.next(),
)?
.map(|v| v.to_i32()),
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_http_instance_summary<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::HttpInstanceSummary>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::HttpInstanceSummary::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"InstanceId" => {
builder = builder.set_instance_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"NamespaceName" => {
builder = builder.set_namespace_name(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"ServiceName" => {
builder = builder.set_service_name(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"HealthStatus" => {
builder = builder.set_health_status(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| {
s.to_unescaped()
.map(|u| crate::model::HealthStatus::from(u.as_ref()))
})
.transpose()?,
);
}
"Attributes" => {
builder = builder.set_attributes(
crate::json_deser::deser_map_attributes(tokens)?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
#[allow(clippy::type_complexity, non_snake_case)]
pub fn deser_map_attributes<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<
Option<std::collections::HashMap<std::string::String, std::string::String>>,
smithy_json::deserialize::Error,
>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
let mut map = std::collections::HashMap::new();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
let key = key.to_unescaped().map(|u| u.into_owned())?;
let value =
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?;
if let Some(value) = value {
map.insert(key, value);
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(map))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_namespace_properties<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::NamespaceProperties>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::NamespaceProperties::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"DnsProperties" => {
builder = builder.set_dns_properties(
crate::json_deser::deser_structure_dns_properties(tokens)?,
);
}
"HttpProperties" => {
builder = builder.set_http_properties(
crate::json_deser::deser_structure_http_properties(tokens)?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
#[allow(clippy::type_complexity, non_snake_case)]
pub fn deser_map_operation_targets_map<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<
Option<std::collections::HashMap<crate::model::OperationTargetType, std::string::String>>,
smithy_json::deserialize::Error,
>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
let mut map = std::collections::HashMap::new();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
let key = key
.to_unescaped()
.map(|u| crate::model::OperationTargetType::from(u.as_ref()))?;
let value =
smithy_json::deserialize::token::expect_string_or_null(tokens.next())?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?;
if let Some(value) = value {
map.insert(key, value);
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(map))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_instance_summary<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::InstanceSummary>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::InstanceSummary::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Id" => {
builder = builder.set_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Attributes" => {
builder = builder.set_attributes(
crate::json_deser::deser_map_attributes(tokens)?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_namespace_summary<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::NamespaceSummary>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::NamespaceSummary::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Id" => {
builder = builder.set_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Arn" => {
builder = builder.set_arn(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Name" => {
builder = builder.set_name(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Type" => {
builder = builder.set_type(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| {
s.to_unescaped()
.map(|u| crate::model::NamespaceType::from(u.as_ref()))
})
.transpose()?,
);
}
"Description" => {
builder = builder.set_description(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"ServiceCount" => {
builder = builder.set_service_count(
smithy_json::deserialize::token::expect_number_or_null(
tokens.next(),
)?
.map(|v| v.to_i32()),
);
}
"Properties" => {
builder = builder.set_properties(
crate::json_deser::deser_structure_namespace_properties(
tokens,
)?,
);
}
"CreateDate" => {
builder = builder.set_create_date(
smithy_json::deserialize::token::expect_timestamp_or_null(
tokens.next(),
smithy_types::instant::Format::EpochSeconds,
)?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_operation_summary<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::OperationSummary>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::OperationSummary::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Id" => {
builder = builder.set_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Status" => {
builder = builder.set_status(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| {
s.to_unescaped().map(|u| {
crate::model::OperationStatus::from(u.as_ref())
})
})
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_service_summary<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::ServiceSummary>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::ServiceSummary::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Id" => {
builder = builder.set_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Arn" => {
builder = builder.set_arn(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Name" => {
builder = builder.set_name(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Type" => {
builder = builder.set_type(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| {
s.to_unescaped()
.map(|u| crate::model::ServiceType::from(u.as_ref()))
})
.transpose()?,
);
}
"Description" => {
builder = builder.set_description(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"InstanceCount" => {
builder = builder.set_instance_count(
smithy_json::deserialize::token::expect_number_or_null(
tokens.next(),
)?
.map(|v| v.to_i32()),
);
}
"DnsConfig" => {
builder = builder.set_dns_config(
crate::json_deser::deser_structure_dns_config(tokens)?,
);
}
"HealthCheckConfig" => {
builder = builder.set_health_check_config(
crate::json_deser::deser_structure_health_check_config(tokens)?,
);
}
"HealthCheckCustomConfig" => {
builder = builder.set_health_check_custom_config(
crate::json_deser::deser_structure_health_check_custom_config(
tokens,
)?,
);
}
"CreateDate" => {
builder = builder.set_create_date(
smithy_json::deserialize::token::expect_timestamp_or_null(
tokens.next(),
smithy_types::instant::Format::EpochSeconds,
)?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_tag<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::Tag>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::Tag::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Key" => {
builder = builder.set_key(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"Value" => {
builder = builder.set_value(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
#[allow(clippy::type_complexity, non_snake_case)]
pub fn deser_list_dns_record_list<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<std::vec::Vec<crate::model::DnsRecord>>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartArray { .. }) => {
let mut items = Vec::new();
loop {
match tokens.peek() {
Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => {
tokens.next().transpose().unwrap();
break;
}
_ => {
let value = crate::json_deser::deser_structure_dns_record(tokens)?;
if let Some(value) = value {
items.push(value);
}
}
}
}
Ok(Some(items))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start array or null",
)),
}
}
pub fn deser_structure_dns_properties<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::DnsProperties>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::DnsProperties::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"HostedZoneId" => {
builder = builder.set_hosted_zone_id(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
"SOA" => {
builder = builder
.set_soa(crate::json_deser::deser_structure_soa(tokens)?);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_http_properties<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::HttpProperties>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::HttpProperties::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"HttpName" => {
builder = builder.set_http_name(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| s.to_unescaped().map(|u| u.into_owned()))
.transpose()?,
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_dns_record<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::DnsRecord>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::DnsRecord::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"Type" => {
builder = builder.set_type(
smithy_json::deserialize::token::expect_string_or_null(
tokens.next(),
)?
.map(|s| {
s.to_unescaped()
.map(|u| crate::model::RecordType::from(u.as_ref()))
})
.transpose()?,
);
}
"TTL" => {
builder = builder.set_ttl(
smithy_json::deserialize::token::expect_number_or_null(
tokens.next(),
)?
.map(|v| v.to_i64()),
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
pub fn deser_structure_soa<'a, I>(
tokens: &mut std::iter::Peekable<I>,
) -> Result<Option<crate::model::Soa>, smithy_json::deserialize::Error>
where
I: Iterator<
Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>,
>,
{
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None),
Some(smithy_json::deserialize::Token::StartObject { .. }) => {
#[allow(unused_mut)]
let mut builder = crate::model::Soa::builder();
loop {
match tokens.next().transpose()? {
Some(smithy_json::deserialize::Token::EndObject { .. }) => break,
Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => {
match key.to_unescaped()?.as_ref() {
"TTL" => {
builder = builder.set_ttl(
smithy_json::deserialize::token::expect_number_or_null(
tokens.next(),
)?
.map(|v| v.to_i64()),
);
}
_ => smithy_json::deserialize::token::skip_value(tokens)?,
}
}
_ => {
return Err(smithy_json::deserialize::Error::custom(
"expected object key or end object",
))
}
}
}
Ok(Some(builder.build()))
}
_ => Err(smithy_json::deserialize::Error::custom(
"expected start object or null",
)),
}
}
|
use tera_crate::{Tera, TesterFn, FilterFn, GlobalFn};
use serde::Serialize;
use ::traits::{RenderEngine, RenderEngineBase, AdditionalCIds};
use ::spec::{TemplateSpec, SubTemplateSpec, TemplateSource};
use self::error::TeraError;
pub mod error;
pub struct TeraRenderEngine {
tera: Tera
}
impl TeraRenderEngine {
/// create a new TeraRenderEngine given a base_templates_dir
///
/// The `base_templates_glob` contains a number of tera templates which can be used to
/// inherit (or include) from e.g. a `base_mail.html` which is then used in all
/// `mail.html` templates through `{% extends "base_mail.html" %}`.
///
/// The `base_templates_glob` _is separate from template dirs used by
/// the `RenderTemplateEngine`_. It contains only tera templates to be reused at
/// other places.
///
pub fn new(base_templats_glob: &str) -> Result<Self, TeraError> {
let tera = Tera::new(base_templats_glob)?;
Ok(TeraRenderEngine { tera })
}
/// expose `Tera::register_filter`
pub fn register_filter(&mut self, name: &str, filter: FilterFn) {
self.tera.register_filter(name, filter);
}
/// exposes `Tera::register_tester`
pub fn register_tester(&mut self, name: &str, tester: TesterFn) {
self.tera.register_tester(name, tester);
}
/// exposes `Tera::register_global_function`
pub fn register_global_function(&mut self, name: &str, function: GlobalFn) {
self.tera.register_global_function(name, function)
}
/// exposes `Tera::autoescape_on`
pub fn set_autoescape_file_suffixes(&mut self, suffixes: Vec<&'static str>) {
self.tera.autoescape_on(suffixes)
}
}
impl RenderEngineBase for TeraRenderEngine {
// nothing gurantees that the templates use \r\n, so by default fix newlines
// but it can be disabled
const PRODUCES_VALID_NEWLINES: bool = false;
type RenderError = TeraError;
type LoadingError = TeraError;
fn load_templates(&mut self, spec: &TemplateSpec) -> Result<(), Self::LoadingError> {
implement_load_helper! {
input::<Tera>(spec, &mut self.tera);
error(TeraError);
collision_error_fn(|id| { TeraError::TemplateIdCollision { id } });
has_template_fn(|tera, id| { tera.templates.contains_key(id) });
remove_fn(|tera, id| { tera.templates.remove(*id) });
add_file_fn(|tera, path| { Ok(tera.add_template_file(path, None)?) });
add_content_fn(|tera, id, content| { Ok(tera.add_raw_template(id, content)?) });
}
}
/// This can be used to reload a templates.
fn unload_templates(&mut self, spec: &TemplateSpec) {
for sub_spec in spec.sub_specs() {
let id = sub_spec.source().id();
self.tera.templates.remove(id);
}
}
fn unknown_template_id_error(id: &str) -> Self::RenderError {
TeraError::UnknowTemplateId { id: id.to_owned() }
}
}
#[derive(Serialize)]
struct DataWrapper<'a,D: Serialize + 'a> {
data: &'a D,
cids: AdditionalCIds<'a>
}
impl<D> RenderEngine<D> for TeraRenderEngine
where D: Serialize
{
fn render(
&self,
spec: &SubTemplateSpec,
data: &D,
cids: AdditionalCIds
) -> Result<String, Self::RenderError> {
let data = &DataWrapper { data, cids };
let id = spec.source().id();
Ok(self.tera.render(id, data)?)
}
}
|
use std::borrow::{Borrow, BorrowMut};
pub struct Post {
state: Option<Box<dyn State>>,
content: String,
}
impl Post {
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
pub fn add_text(&mut self, text: &str) {
self.state
.as_ref()
.unwrap()
.add_text(self.content.borrow_mut(), text);
}
pub fn content(&self) -> &str {
// 此处使用 as_ref 是希望获得引用而不是获取其所有权,
// 如果获取所有权则会因为不能将 state 从 immutable self 中 move
// 此处使用 unwrap 而不考虑 None 是因为我们在上下文中比编译器知道的更多,
// 这里 Post 所有的方法都保证了返回的实例中 state 有一个 Some(s) 值
self.state.as_ref().unwrap().content(&self)
}
// pub fn state(&self) -> &Box<dyn State> {
// self.state.unwrap().borrow()
// }
pub fn request_review(&mut self) {
// 调用 Option.take 方法将值取出并留下一个 None,这使得这里是 move 而不是 borrow
if let Some(s) = self.state.take() {
self.state = Some(s.request_review())
}
}
pub fn approve(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.approve())
}
}
pub fn reject(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.reject());
}
}
}
// 发布博文的工作流的规则实现了状态模式,
// 围绕这些规则的逻辑都存在于转态对象中而不是分散在 Post 之中
trait State {
// self: Box<Self> 该参数不同于 self, &self, &mut self,意味着这个方法调用只对这个类型的 Box 有效
// 这个语法获取了 Box<Self> 的所有权,使老状态无效化以便 Post 的状态值可以将自身转换为新状态
fn request_review(self: Box<Self>) -> Box<dyn State>;
fn approve(self: Box<Self>) -> Box<dyn State>;
fn reject(self: Box<Self>) -> Box<dyn State>;
// 根据状态来觉得返回内容,默认返回空字符串,然后在 Publish 中覆盖这个方法返回内容
// 因为该函数返回参数是形参的引用,所以需要声明生命周期参数
fn content<'a>(&self, post: &'a Post) -> &'a str {
""
}
fn add_text(&self, content: &mut String, text: &str) {}
}
struct Draft {}
impl State for Draft {
fn request_review(self: Box<Self>) -> Box<dyn State> {
Box::new(PendingReview {
publish_ensure_count: 0,
})
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
fn reject(self: Box<Self>) -> Box<dyn State> {
self
}
fn add_text(&self, content: &mut String, text: &str) {
content.push_str(text);
}
}
struct PendingReview {
publish_ensure_count: i32,
}
impl State for PendingReview {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
if let 2 = self.publish_ensure_count + 1 {
Box::new(Published {})
} else {
Box::new(PendingReview {
publish_ensure_count: self.publish_ensure_count + 1,
})
}
}
fn reject(self: Box<Self>) -> Box<dyn State> {
Box::new(Draft {})
}
}
struct Published {}
impl State for Published {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
fn reject(self: Box<Self>) -> Box<dyn State> {
self
}
fn content<'a>(&self, post: &'a Post) -> &'a str {
&post.content
}
}
|
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0.
pub mod trait_impl;
use std::cell::RefCell;
use std::collections::BTreeMap;
use bigint::U256;
use cid::Cid;
use ipld_cbor::{cbor_value_to_struct, struct_to_cbor_value};
use serde::{de::DeserializeOwned, Serialize};
use serde_cbor::Value;
use crate::error::*;
use crate::hash::{hash, HashBits};
use crate::ipld::CborIpldStore;
const ARRAY_WIDTH: usize = 3;
pub const DEFAULT_BIT_WIDTH: u32 = 8;
/// Hamt struct, hold root node. for public, we use `Hamt`, not `Node`
/// current `Hamt` is not thread safe, if want to use `Hamt` is multi thread, must use
/// lock to wrap `Hamt`
pub struct Hamt<B>
where
B: CborIpldStore,
{
/// root node of `Hamt`
root: Node,
/// database to store the relationship of cid and node
bs: B,
bit_width: u32,
}
pub type KV = BTreeMap<String, Value>;
pub type KVT = (String, Value);
/// Item would be `Link` `Ptr` and `Leaf`, but in factor, `Ptr` is the cache of `Link`.
/// when call `load_item`, the `Link` would convert to `Ptr`.
/// when call `flush`, the `Ptr` would refresh the `Link`
/// when serialize/deserialize, should not serialize `Ptr`, otherwise would panic.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(test, derive(Clone))]
pub enum Item {
Link(Cid),
Ptr(Box<Node>),
Leaf(KV),
}
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(test, derive(Clone))]
pub struct Node {
/// bitmap, we use U256 replace bigint, for we think the bit_width and HashBits couldn't
/// more then 256bit
bitfield: U256,
/// `Item` is wrapped by `Refcell` due to items would load in immutable `get` call.
items: RefCell<Vec<Item>>,
}
#[inline]
pub fn set_bit(input: &mut U256, n: u32) {
let one: U256 = 1.into();
*input = *input | (one << n as usize)
}
#[inline]
pub fn unset_bit(input: &mut U256, n: u32) {
let one: U256 = 1.into();
*input = *input & !(one << n as usize)
}
/// index for bit position in this bitmap
#[inline]
pub fn bit_to_index(bitmap: &U256, bit_pos: u32) -> usize {
let one: U256 = 1.into();
let mask: U256 = (one << bit_pos as usize) - one;
let r: U256 = mask & *bitmap;
r.0.iter().fold(0, |a, b| a + b.count_ones() as usize)
}
impl<B> Hamt<B>
where
B: CborIpldStore,
{
/// create a new empty Hamt with bit_width
pub fn new_with_bitwidth(store: B, bit_width: u32) -> Self {
Hamt {
root: Node::new(),
bs: store,
bit_width,
}
}
/// create a new empty Hamt
pub fn new(store: B) -> Self {
Self::new_with_bitwidth(store, DEFAULT_BIT_WIDTH)
}
/// load Hamt from cid with bitwidth
pub fn load_with_bitwidth(store: B, cid: &Cid, bit_width: u32) -> Result<Self> {
let root: Node = store.get(cid)?;
Ok(Hamt {
root,
bs: store,
bit_width,
})
}
/// load Hamt from cid
pub fn load(store: B, cid: &Cid) -> Result<Self> {
Self::load_with_bitwidth(store, cid, DEFAULT_BIT_WIDTH)
}
pub fn bit_width(&self) -> u32 {
self.bit_width
}
pub fn root(&self) -> &Node {
&self.root
}
/// get a value for k, if not find, would return Error::NotFound
pub fn find<Output: DeserializeOwned>(&self, k: &str) -> Result<Output> {
let hash = hash(k);
let mut hash_bits = HashBits::new(hash.as_ref(), self.bit_width);
let v = self.root.get(&self.bs, &mut hash_bits, k, |v| {
cbor_value_to_struct(v.clone()).map_err(Error::IpldCbor)
})?;
Ok(v)
}
/// set a value for k, if the value is already exist, override it.
pub fn set<V: Serialize>(&mut self, k: &str, v: V) -> Result<()> {
let hash = hash(k);
let mut hash_bits = HashBits::new(hash.as_ref(), self.bit_width);
let b = struct_to_cbor_value(&v).map_err(Error::IpldCbor)?;
self.root.set(&self.bs, &mut hash_bits, k, b)
}
/// delete for k, if the k is not exist, return Error::NotFound
pub fn delete(&mut self, k: &str) -> Result<()> {
let hash = hash(k);
let mut hash_bits = HashBits::new(hash.as_ref(), self.bit_width);
self.root.remove(&self.bs, &mut hash_bits, k)
}
/// flush all `Ptr` into `Link`, every flush should treat as `Commit`,
/// means commit current all changes into database, and generate changed cids.
/// the operation equals to persistence. if store the root cid, then the Hamt is immutable,
/// could recover all child status from any root cid.
pub fn flush(&mut self) -> Result<Cid> {
self.root.flush(&mut self.bs)?;
self.bs.put(&self.root)
}
/// just for test
#[cfg(test)]
pub fn check_size(&mut self) -> Result<u64> {
self.flush()?;
self.root.check_size(&mut self.bs)
}
}
impl Item {
pub fn from_kvs(kvs: Vec<KVT>) -> Self {
Item::Leaf(kvs.into_iter().collect())
}
pub fn from_link(cid: Cid) -> Self {
Item::Link(cid)
}
fn load_item<B>(&mut self, bs: &B) -> Result<()>
where
B: CborIpldStore,
{
if let Item::Link(cid) = self {
let node: Node = bs.get(cid)?;
*self = Item::Ptr(Box::new(node));
}
Ok(())
}
fn clean_child(&mut self) -> Result<()> {
match self {
Item::Ptr(node) => {
let len = node.items.borrow().len();
match len {
0 => Err(Error::InvalidFormatHAMT),
1 => {
// this branch means that if current node's child only have one child,
// and this child first sub-child is a leaf, then use sub-child replace
// current child directly.
// due to rust mutable check, when we hold `self` ref, we can't
// call mem::swap(self, node.items[0]), so that we just use a `tmp` item to
// swap first, and then move the `tmp` item replace `self`
let should_move_leaf = {
let mut items = node.items.borrow_mut();
let leaf = &mut items[0];
if let Item::Leaf(_) = leaf {
// it's safe, for current child would be release after `*self = leaf`
// so that we use a `tmp` Item to replace current sub-child,
// and now `tmp` is `sub-child`
let mut tmp = Item::Leaf(Default::default());
std::mem::swap(&mut tmp, leaf);
Some(tmp)
} else {
// if sub-child is not a leaf, do nothing.
None
}
};
// if sub-child is not leaf, this if branch would not hit
if let Some(leaf) = should_move_leaf {
*self = leaf
}
Ok(())
}
x if x <= ARRAY_WIDTH => {
// should use clone instead of mem::swap, for this part may be return directly
let mut child_vals = KV::default();
for child_item in node.items.borrow().iter() {
match child_item {
Item::Leaf(kvs) => {
for (k, v) in kvs.iter() {
if child_vals.len() == ARRAY_WIDTH {
return Ok(());
}
child_vals.insert(k.clone(), v.clone());
}
}
_ => return Ok(()),
}
}
*self = Item::Leaf(child_vals);
Ok(())
}
_ => Ok(()),
}
}
_ => unreachable!("`clean_child` param must be `Item::Ptr`"),
}
}
}
#[cfg(test)]
pub fn test_node(bitfield: &str, items: Vec<Item>) -> Node {
Node::from_raw(U256::from_dec_str(bitfield).unwrap(), items)
}
impl Node {
fn new() -> Self {
Node {
bitfield: U256::zero(),
items: Default::default(),
}
}
fn from_raw(bitfield: U256, items: Vec<Item>) -> Self {
Node {
bitfield,
items: RefCell::new(items),
}
}
fn get<'hash, B, F, Output>(
&self,
bs: &B,
hv: &mut HashBits<'hash>,
k: &str,
f: F,
) -> Result<Output>
where
B: CborIpldStore,
F: Fn(&Value) -> Result<Output>,
{
let idx = hv.next().ok_or(Error::MaxDepth)?;
if self.bitfield.bit(idx as usize) == false {
return Err(Error::NotFound(k.to_string()));
}
let child_index = bit_to_index(&self.bitfield, idx);
// load_item first
self.items.borrow_mut()[child_index].load_item(bs)?;
let items = self.items.borrow();
let child = &items[child_index];
match child {
Item::Link(_) => unreachable!("after `load_item`, should not be Link now"),
Item::Ptr(node) => node.get(bs, hv, k, f),
Item::Leaf(kvs) => kvs
.get(k)
.ok_or(Error::NotFound(k.to_string()))
.and_then(|v| f(v)),
}
}
fn set<'hash, B>(&mut self, bs: &B, hv: &mut HashBits<'hash>, k: &str, v: Value) -> Result<()>
where
B: CborIpldStore,
{
let idx = hv.next().ok_or(Error::MaxDepth)?;
if self.bitfield.bit(idx as usize) == false {
return self.insert_child(idx, k, v);
}
let item_index = bit_to_index(&self.bitfield, idx);
let mut items = self.items.borrow_mut();
let item = &mut items[item_index];
// try load node from cid
item.load_item(bs)?;
match item {
Item::Link(_) => unreachable!("after `load_item`, should not be Link now"),
Item::Ptr(node) => {
// it's branch, recurse to fetch child
node.set(bs, hv, k, v)
}
Item::Leaf(kvs) => {
let leaf_item = kvs.get_mut(k);
if let Some(old_v) = leaf_item {
// find item for this key, reset to new value
*old_v = v;
return Ok(());
}
// a new key/value, if not beyond leaf capacity, insert it directly
if kvs.len() < ARRAY_WIDTH {
kvs.insert(k.to_string(), v);
return Ok(());
}
// current leaf is full, create a new branch and move leaf
// notice the HashBits use different instance
let mut child = Box::new(Node::new());
let mut hash_copy = hv.clone();
child.set(bs, &mut hash_copy, k, v)?;
for (old_k, old_v) in kvs.iter() {
let new_hash = hash(old_k.as_bytes());
let mut ch_hv =
HashBits::new_with_consumed(new_hash.as_ref(), hv.consumed(), hv.bit_width);
// must use clone, not mem::swap, for this `set` function may be failed(e.g. MaxDepth)
// if failed, should not change the tree current struct
child.set(bs, &mut ch_hv, old_k, old_v.clone())?;
}
let child_item = Item::Ptr(child);
*item = child_item;
Ok(())
}
}
}
pub fn remove<'hash, B>(&mut self, bs: &B, hv: &mut HashBits<'hash>, k: &str) -> Result<()>
where
B: CborIpldStore,
{
let idx = hv.next().ok_or(Error::MaxDepth)?;
if self.bitfield.bit(idx as usize) == false {
return Err(Error::NotFound(k.to_string()));
}
let item_index = bit_to_index(&self.bitfield, idx);
let mut items = self.items.borrow_mut();
let item = &mut items[item_index];
// try load node from cid
item.load_item(bs)?;
match item {
Item::Link(_) => unreachable!("after `load_item`, should not be Link now"),
Item::Ptr(node) => {
// it's branch, recurse to fetch child
node.remove(bs, hv, k)?;
// return directly
item.clean_child()
}
Item::Leaf(kvs) => {
let _ = kvs.remove(k).ok_or(Error::NotFound(k.to_string()))?;
if kvs.is_empty() {
items.remove(item_index);
// set idx pos bit is zero
unset_bit(&mut self.bitfield, idx);
}
Ok(())
}
}
}
fn flush<B>(&mut self, bs: &mut B) -> Result<()>
where
B: CborIpldStore,
{
let mut items = self.items.borrow_mut();
for item in &mut items[..].iter_mut() {
if let Item::Ptr(node) = item {
node.flush(bs)?;
let cid = bs.put(&node)?;
// flush current item
*item = Item::Link(cid);
}
}
Ok(())
}
#[cfg(test)]
fn check_size<B>(&self, bs: &mut B) -> Result<u64>
where
B: CborIpldStore,
{
let cid = bs.put(&self)?;
let node: Node = bs.get(&cid)?;
let mut total_size = ipld_core::dump_object(&node)?.len() as u64;
for item in self.items.borrow_mut().iter_mut() {
item.load_item(bs)?;
if let Item::Ptr(node) = item {
let child_size = node.check_size(bs)?;
total_size += child_size;
}
}
Ok(total_size)
}
/// insert k,v to this bit position.
fn insert_child(&mut self, idx: u32, k: &str, v: Value) -> Result<()> {
let i = bit_to_index(&self.bitfield, idx);
// set bit for index i
set_bit(&mut self.bitfield, idx);
let leaf = Item::from_kvs(vec![(k.to_string(), v)]);
self.items.borrow_mut().insert(i as usize, leaf);
Ok(())
}
}
#[cfg(test)]
#[derive(Debug, Default)]
pub struct HamtStats {
total_nodes: usize,
total_kvs: usize,
counts: BTreeMap<usize, usize>,
}
#[cfg(test)]
pub fn stats<B>(hamt: &Hamt<B>) -> HamtStats
where
B: CborIpldStore,
{
let mut st = HamtStats::default();
stats_rec(&hamt.bs, &hamt.root, &mut st);
st
}
#[cfg(test)]
fn stats_rec<B>(bs: &B, node: &Node, st: &mut HamtStats)
where
B: CborIpldStore,
{
st.total_nodes += 1;
let mut items = node.items.borrow_mut();
for p in items.iter_mut() {
p.load_item(bs).unwrap();
match p {
Item::Link(_) => unreachable!(""),
Item::Ptr(node) => stats_rec(bs, node, st),
Item::Leaf(kvs) => {
st.total_kvs += kvs.len();
*(st.counts.entry(kvs.len()).or_insert(0)) += 1;
}
}
}
}
|
use proconio::{input, marker::Bytes};
fn main() {
input! {
s: Bytes,
};
for i in 0..s.len() {
if b'A' <= s[i] && s[i] <= b'Z' {
println!("{}", i + 1);
return;
}
}
unreachable!();
}
|
//! HTTP authorisation helpers.
use http::HeaderValue;
/// We strip off the "authorization" header from the request, to prevent it from being accidentally logged
/// and we put it in an extension of the request. Extensions are typed and this is the typed wrapper that
/// holds an (optional) authorization header value.
pub struct AuthorizationHeaderExtension(Option<HeaderValue>);
impl AuthorizationHeaderExtension {
/// Construct new extension wrapper for a possible header value
pub fn new(header: Option<HeaderValue>) -> Self {
Self(header)
}
}
impl std::fmt::Debug for AuthorizationHeaderExtension {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("AuthorizationHeaderExtension(...)")
}
}
impl std::ops::Deref for AuthorizationHeaderExtension {
type Target = Option<HeaderValue>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
|
pub mod de;
mod ser;
pub mod shared;
|
//! Alacritty socket IPC.
use std::ffi::OsStr;
use std::io::{BufRead, BufReader, Error as IoError, ErrorKind, Result as IoResult, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::{env, fs, process};
use log::warn;
use winit::event_loop::EventLoopProxy;
use winit::window::WindowId;
use alacritty_terminal::thread;
use crate::cli::{Options, SocketMessage};
use crate::event::{Event, EventType};
/// Environment variable name for the IPC socket path.
const ALACRITTY_SOCKET_ENV: &str = "ALACRITTY_SOCKET";
/// Create an IPC socket.
pub fn spawn_ipc_socket(options: &Options, event_proxy: EventLoopProxy<Event>) -> Option<PathBuf> {
// Create the IPC socket and export its path as env variable if necessary.
let socket_path = options.socket.clone().unwrap_or_else(|| {
let mut path = socket_dir();
path.push(format!("{}-{}.sock", socket_prefix(), process::id()));
path
});
env::set_var(ALACRITTY_SOCKET_ENV, socket_path.as_os_str());
let listener = match UnixListener::bind(&socket_path) {
Ok(listener) => listener,
Err(err) => {
warn!("Unable to create socket: {:?}", err);
return None;
},
};
// Spawn a thread to listen on the IPC socket.
thread::spawn_named("socket listener", move || {
let mut data = String::new();
for stream in listener.incoming().filter_map(Result::ok) {
data.clear();
let mut stream = BufReader::new(stream);
match stream.read_line(&mut data) {
Ok(0) | Err(_) => continue,
Ok(_) => (),
};
// Read pending events on socket.
let message: SocketMessage = match serde_json::from_str(&data) {
Ok(message) => message,
Err(err) => {
warn!("Failed to convert data from socket: {}", err);
continue;
},
};
// Handle IPC events.
match message {
SocketMessage::CreateWindow(options) => {
let event = Event::new(EventType::CreateWindow(options), None);
let _ = event_proxy.send_event(event);
},
SocketMessage::Config(ipc_config) => {
let window_id = ipc_config
.window_id
.and_then(|id| u64::try_from(id).ok())
.map(WindowId::from);
let event = Event::new(EventType::IpcConfig(ipc_config), window_id);
let _ = event_proxy.send_event(event);
},
}
}
});
Some(socket_path)
}
/// Send a message to the active Alacritty socket.
pub fn send_message(socket: Option<PathBuf>, message: SocketMessage) -> IoResult<()> {
let mut socket = find_socket(socket)?;
let message = serde_json::to_string(&message)?;
socket.write_all(message[..].as_bytes())?;
let _ = socket.flush();
Ok(())
}
/// Directory for the IPC socket file.
#[cfg(not(target_os = "macos"))]
fn socket_dir() -> PathBuf {
xdg::BaseDirectories::with_prefix("alacritty")
.ok()
.and_then(|xdg| xdg.get_runtime_directory().map(ToOwned::to_owned).ok())
.and_then(|path| fs::create_dir_all(&path).map(|_| path).ok())
.unwrap_or_else(env::temp_dir)
}
/// Directory for the IPC socket file.
#[cfg(target_os = "macos")]
fn socket_dir() -> PathBuf {
env::temp_dir()
}
/// Find the IPC socket path.
fn find_socket(socket_path: Option<PathBuf>) -> IoResult<UnixStream> {
// Handle --socket CLI override.
if let Some(socket_path) = socket_path {
// Ensure we inform the user about an invalid path.
return UnixStream::connect(&socket_path).map_err(|err| {
let message = format!("invalid socket path {:?}", socket_path);
IoError::new(err.kind(), message)
});
}
// Handle environment variable.
if let Ok(path) = env::var(ALACRITTY_SOCKET_ENV) {
let socket_path = PathBuf::from(path);
if let Ok(socket) = UnixStream::connect(socket_path) {
return Ok(socket);
}
}
// Search for sockets files.
for entry in fs::read_dir(socket_dir())?.filter_map(|entry| entry.ok()) {
let path = entry.path();
// Skip files that aren't Alacritty sockets.
let socket_prefix = socket_prefix();
if path
.file_name()
.and_then(OsStr::to_str)
.filter(|file| file.starts_with(&socket_prefix) && file.ends_with(".sock"))
.is_none()
{
continue;
}
// Attempt to connect to the socket.
match UnixStream::connect(&path) {
Ok(socket) => return Ok(socket),
// Delete orphan sockets.
Err(error) if error.kind() == ErrorKind::ConnectionRefused => {
let _ = fs::remove_file(&path);
},
// Ignore other errors like permission issues.
Err(_) => (),
}
}
Err(IoError::new(ErrorKind::NotFound, "no socket found"))
}
/// File prefix matching all available sockets.
///
/// This prefix will include display server information to allow for environments with multiple
/// display servers running for the same user.
#[cfg(not(target_os = "macos"))]
fn socket_prefix() -> String {
let display = env::var("WAYLAND_DISPLAY").or_else(|_| env::var("DISPLAY")).unwrap_or_default();
format!("Alacritty-{}", display.replace('/', "-"))
}
/// File prefix matching all available sockets.
#[cfg(target_os = "macos")]
fn socket_prefix() -> String {
String::from("Alacritty")
}
|
pub struct Solution;
impl Solution {
pub fn lexical_order(n: i32) -> Vec<i32> {
Solver::new(n).solve()
}
}
struct Solver {
n: i32,
nums: Vec<i32>,
}
impl Solver {
fn new(n: i32) -> Self {
Self {
n,
nums: Vec::with_capacity(n as usize),
}
}
fn solve(mut self) -> Vec<i32> {
for i in 1..=9 {
if !self.add(i) {
break;
}
}
self.nums
}
fn add(&mut self, i: i32) -> bool {
if i <= self.n {
self.nums.push(i);
for j in 0..=9 {
if !self.add(i * 10 + j) {
break;
}
}
true
} else {
false
}
}
}
#[test]
fn test0386() {
fn case(n: i32, want: Vec<i32>) {
let got = Solution::lexical_order(n);
assert_eq!(got, want);
}
case(13, vec![1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]);
}
|
mod encapsulation;
mod trait_object;
mod state_pattern;
mod state_pattern_redef;
pub use self::trait_object::gui;
pub use self::encapsulation::avg;
pub use self::state_pattern::blog;
pub use self::state_pattern_redef::blog2;
use self::gui::Draw;
pub struct TextBlock {
pub width: u32,
pub height: u32,
pub text: String,
}
impl Draw for TextBlock {
fn draw(&self) {
println!("Drawing a TextBlock");
}
}
|
extern crate prisoners_dilemma;
use prisoners_dilemma::*;
// use prisoners_dilemma::history::*;
// use prisoners_dilemma::choice::*;
use prisoners_dilemma::strategy::*;
const ROUNDS: usize = 10;
fn main() {
println!("Starting Game");
// put all the strategies into a list so we can try all the combinations.
let strategies: Vec<&Strategy> =
vec![
&Never,
&Always,
&AlternateTrueFalse,
&AlternateFalseTrue,
&TitForTat
];
for oppo in &strategies {
for item in &strategies {
let mut game = Game::new(ROUNDS);
let score = game.play(*item, *oppo);
println!("{} v {} {:?}", item.id(), oppo.id(), score);
}
}
}
|
//! A module for Reading/Writing ROSE data types to/from disk
mod file;
mod path;
mod reader;
mod writer;
pub use self::file::RoseFile;
pub use self::path::PathRoseExt;
pub use self::reader::ReadRoseExt;
pub use self::writer::WriteRoseExt;
|
use actix_web::{
web::{block, Data, Json},
Result,
};
use serde::{Deserialize, Serialize};
use validator::Validate;
use db::{
get_conn,
models::{Game, User},
PgPool,
};
use errors::Error;
use crate::validate::validate;
#[derive(Clone, Deserialize, Serialize, Validate)]
pub struct JoinRequest {
#[validate(length(min = "3"))]
name: String,
#[validate(length(equal = "6"))]
slug: String,
}
pub async fn join(pool: Data<PgPool>, params: Json<JoinRequest>) -> Result<Json<User>, Error> {
validate(¶ms)?;
let connection = get_conn(&pool).unwrap();
let res = block(move || {
let game = Game::find_by_slug(&connection, ¶ms.slug)?;
if User::find_by_game_id_and_name(&connection, game.id, ¶ms.name).is_ok() {
return Err(Error::UnprocessableEntity("Username is taken".to_string()));
}
let new_user = User::create(&connection, params.name.clone(), game.id)?;
Ok(new_user)
})
.await?;
let new_user = res?;
Ok(Json(new_user))
}
#[cfg(test)]
mod tests {
use diesel::RunQueryDsl;
use db::{
get_conn,
models::{Game, User},
new_pool,
schema::{games, users},
};
use errors::ErrorResponse;
use super::JoinRequest;
use crate::tests::helpers::tests::test_post;
#[derive(Insertable)]
#[table_name = "games"]
struct NewGame {
slug: String,
}
#[derive(Insertable)]
#[table_name = "users"]
struct NewUser {
user_name: String,
game_id: i32,
}
#[actix_rt::test]
async fn test_join_game() {
let pool = new_pool();
let conn = get_conn(&pool).unwrap();
let game: Game = diesel::insert_into(games::table)
.values(NewGame {
slug: "abc123".to_string(),
})
.get_result(&conn)
.unwrap();
let res: (u16, User) = test_post(
"/api/games/join",
JoinRequest {
name: "agmcleod".to_string(),
slug: game.slug.unwrap(),
},
None,
)
.await;
assert_eq!(res.0, 200);
assert_eq!(res.1.user_name, "agmcleod");
diesel::delete(users::table).execute(&conn).unwrap();
diesel::delete(games::table).execute(&conn).unwrap();
}
#[actix_rt::test]
async fn test_game_not_found() {
let res: (u16, ErrorResponse) = test_post(
"/api/games/join",
JoinRequest {
name: "agmcleod".to_string(),
slug: "-fake-".to_string(),
},
None,
)
.await;
assert_eq!(res.0, 404);
}
#[actix_rt::test]
async fn test_join_game_with_duplicate_name() {
let pool = new_pool();
let conn = get_conn(&pool).unwrap();
let game: Game = diesel::insert_into(games::table)
.values(NewGame {
slug: "newgam".to_string(),
})
.get_result(&conn)
.unwrap();
diesel::insert_into(users::table)
.values(NewUser {
user_name: "agmcleod".to_string(),
game_id: game.id,
})
.execute(&conn)
.unwrap();
let res: (u16, ErrorResponse) = test_post(
"/api/games/join",
JoinRequest {
slug: "newgam".to_string(),
name: "agmcleod".to_string(),
},
None,
)
.await;
assert_eq!(res.0, 422);
assert_eq!(res.1.errors[0], "Username is taken");
diesel::delete(users::table).execute(&conn).unwrap();
diesel::delete(games::table).execute(&conn).unwrap();
}
}
|
//! Тесты
//!
//! Реализован комплексный тест на расборку/сборку всех фалов из директории test_cases
#[cfg(test)]
mod complex_tests {
use crate::read_write::*;
use crate::sig::*;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn write_test<T: HasWrite>(sig: &T) -> Vec<u8> {
sig.write()
}
#[test]
fn complex_read_write_raw() {
let test_path = Path::new("test_cases");
for entry in test_path
.read_dir()
.expect("read_dir call failed")
.flatten()
{
let input = entry.path();
let display = input.display();
let mut file = match File::open(&input) {
Err(why) => panic!("couldn't open {}: {}", display, why),
Ok(file) => file,
};
let mut original_in: Vec<u8> = vec![];
if let Err(why) = file.read_to_end(&mut original_in) {
panic!("couldn't read {}: {}", display, why)
};
assert_eq!(original_in, write_test(&read_file_raw(&input)));
}
}
#[test]
fn complex_read_write() {
let test_path = Path::new("test_cases");
for entry in test_path
.read_dir()
.expect("read_dir call failed")
.flatten()
{
let input = entry.path();
let display = input.display();
let mut file = match File::open(&input) {
Err(why) => panic!("couldn't open {}: {}", display, why),
Ok(file) => file,
};
let mut original_in: Vec<u8> = vec![];
if let Err(why) = file.read_to_end(&mut original_in) {
panic!("couldn't read {}: {}", display, why)
};
assert_eq!(original_in, write_test(&read_file_raw(&input)));
}
}
}
#[cfg(test)]
pub mod rab_e_sig_test {
pub fn read_test_sig(path_str: &str) -> Vec<u8> {
use std::io::Read;
let path = std::path::Path::new(path_str);
let display = path.display();
let mut file = match std::fs::File::open(path) {
Err(why) => panic!("couldn't open {}: {}", display, why),
Ok(file) => file,
};
let mut original_in: Vec<u8> = vec![];
if let Err(why) = file.read_to_end(&mut original_in) {
panic!("couldn't read {}: {}", display, why)
};
original_in
}
}
|
use std::rc::Rc;
use scheme::LispResult;
use scheme::value::Sexp;
use scheme::value::Sexp::*;
use scheme::env::Environment;
use scheme::error::LispError::*;
use scheme::value::HostFunction2;
use scheme::value::Transformer;
use std::collections::HashMap;
use std::collections::vec_deque::VecDeque;
use scheme::ELLIPSIS;
use scheme::UNDERSCORE;
pub struct LispMachine {
pub exp: Option<Sexp>,
pub env: Environment,
pub val: Option<Sexp>,
pub argl: Vec<Sexp>,
pub unev: Option<Sexp>,
}
impl LispMachine {
pub fn new(env: Environment) -> Self {
LispMachine {
exp: None,
env,
val: None,
argl: vec![],
unev: None,
}
}
pub fn eval(&mut self, expr: &Sexp) -> LispResult<Sexp> {
match expr {
Nil => return Err(ApplyError("missing procedure expression".to_owned())),
Symbol(name) => if let Some(val) = self.env.lookup(&name) {
let val = val.borrow().clone();
match &val {
// 语法关键字如果不位于列表头部是无效的
Syntax { name, .. } => syntax_error!(name, "bad syntax"),
DefineSyntax { keyword, .. } => syntax_error!(keyword, "bad syntax"),
_ => Ok(val)
}
} else {
Err(Undefined(name.to_string()))
}
List(xs) => self.eval_list(&*xs),
_ => Ok(expr.clone()),
}
}
// 对列表中的第一个元素求值
fn eval_head(&mut self, expr: &Sexp) -> LispResult<Sexp> {
use self::Sexp::*;
match expr {
Symbol(name) => if let Some(val) = self.env.lookup(&name) {
Ok(val.borrow().clone())
} else {
Err(Undefined(name.to_string()))
}
_ => self.eval(expr),
}
}
// 对列表求值
fn eval_list(&mut self, exprs: &[Sexp]) -> LispResult<Sexp> {
use self::Sexp::*;
let (head, tail) = exprs.split_first().unwrap();
let proc = self.eval_head(head)?;
match proc {
DefineSyntax { keyword, transformer } => {
let expr = List(Box::new(exprs.to_vec()));
self.apply_transformer(&keyword, transformer, &expr)
}
Syntax { func, .. } => self.apply_keyword(func, tail),
_ => {
let (last, init) = tail.split_last().unwrap();
if *last != Nil {
syntax_error!("apply", "bad syntax")
}
let args: Result<Vec<_>, _> = init.iter().map(|e| self.eval(e)).collect();
if args.is_err() {
return Err(args.unwrap_err());
}
self.apply(&proc, &args.unwrap())
}
}
}
pub fn apply(&mut self, proc: &Sexp, exprs: &[Sexp]) -> LispResult<Sexp> {
use self::Sexp::*;
match proc {
Function { func, .. } => func(exprs),
Procedure { func, .. } => func(self, exprs),
Closure { name, params, vararg, body, env } => {
let func_name = if name.is_empty() {
"#<procedure>"
} else {
name
};
let args = exprs;
let nparams = params.len();
let nargs = args.len();
let mut ctx = Environment::new(Some(Rc::new(env.clone())));
match vararg {
Some(ref name) => {
if nargs < nparams {
// FIXME expected least nparams...
return Err(ArityMismatch(func_name.to_string(), nparams, nargs));
}
let (pos, rest) = args.split_at(nparams);
ctx.insert_many(params, pos);
let varg = if nargs == nparams {
Nil
} else {
let mut xs = rest.to_vec();
xs.push(Nil);
List(Box::new(xs))
};
ctx.insert(name, &varg);
}
_ => {
if nargs != nparams {
return Err(ArityMismatch(func_name.to_string(), nparams, nargs));
}
ctx.insert_many(params, &args);
}
}
let old_ctx = self.env.clone();
self.env = ctx;
// FIXME tail call optimization
let (last, init) = body.split_last().unwrap();
for expr in init {
self.eval(expr)?;
}
let res = self.eval(last);
self.env = old_ctx;
res
}
_ => Err(ApplyError(format!("not a procedure: {}", proc))),
}
}
fn apply_transformer(&mut self, keyword: &str, transformer: Transformer, form: &Sexp) -> LispResult<Sexp> {
let mut rules = transformer.rules.clone();
for rule in &mut rules {
println!("{}", rule.pattern);
if let Some(bindings) = Self::match_syntax_rule(&rule.pattern, form) {
// dbg!(&bindings);
let expr = self.render_template(&bindings, &rule.template);
println!("{}", expr);
return self.eval(&expr);
}
}
syntax_error!(keyword, "bad syntax")
}
fn apply_keyword(&mut self, func: HostFunction2, exprs: &[Sexp]) -> LispResult<Sexp> {
use self::Sexp::*;
let (last, init) = exprs.split_last().unwrap();
let args = if *last == Nil {
init
} else {
exprs
};
func(self, args)
}
fn render_template(&mut self, bindings: &HashMap<String, Sexp>, template: &Sexp) -> Sexp {
use self::Sexp::*;
let mut q = VecDeque::new();
let mut r: Sexp = Nil;
q.push_back(template);
loop {
let list: &Sexp = if let Some(list) = q.pop_front() {
list
} else {
return r;
};
for (index, item) in list.into_iter().enumerate() {
if let Symbol(ident) = &item {
if let Some(val) = bindings.get(ident) {
r = list.clone();
r.set_nth(index, val);
}
} else if item.is_pair() {
q.push_back(item)
}
}
r = list.clone();
}
}
fn match_syntax_rule(pat: &Sexp, form: &Sexp) -> Option<HashMap<String, Sexp>> {
use self::Sexp::*;
let mut q: VecDeque<(&Sexp, &Sexp)> = VecDeque::new();
let mut bindings = HashMap::new();
q.push_back((pat, form));
loop {
let (p, f): (&Sexp, &Sexp) = if let Some((a, b)) = q.pop_front() {
(a, b)
} else {
return Some(bindings);
};
if p.is_list() != f.is_list() {
return None;
}
let mut index_b = 0;
for (index, a) in p.as_slice().unwrap().iter().enumerate() {
if let Symbol(ident) = a {
if ident == ELLIPSIS {
if f.list_count() < p.list_count() - 2 {
return None;
}
} else if ident != UNDERSCORE {
if let Some(b) = f.nth(index) {
index_b += 1;
bindings.insert(ident.clone(), b.clone());
continue;
}
return None;
}
} else if a.is_pair() {
if let Some(b) = f.nth(index) {
index_b += 1;
if b.is_pair() {
q.push_back((a, b));
continue;
}
}
return None;
} else {
if let Some(b) = f.nth(index) {
index_b += 1;
if a == b {
continue;
}
}
return None;
}
}
if index_b + 1 != f.list_count() {
return None;
}
}
}
}
|
/// The keeper monitors the chain for underwater accounts on Hifi and sends a liquidation
/// transaction when it discovers one.
#[allow(unused)]
pub struct Keeper {
last_block: u64,
}
|
/*
* @lc app=leetcode id=64 lang=rust
*
* [64] Minimum Path Sum
*/
// @lc code=start
use std::cmp::min;
impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 {
let m = grid.len();
let n = grid[0].len();
let mut best = vec![vec![0; n]; m];
best[0][0] = grid[0][0];
for i in 1..m { best[i][0] = best[i-1][0] + grid[i][0]; }
for j in 1..n { best[0][j] = best[0][j-1] + grid[0][j]; }
for i in 1..m {
for j in 1..n {
best[i][j] = min(best[i-1][j], best[i][j-1]) + grid[i][j];
}
}
best[m-1][n-1]
}
}
// @lc code=end
|
use actix_multipart::Multipart;
use actix_web::Error;
use bytes::{Buf, BufMut, Bytes, BytesMut};
use futures::{StreamExt, TryStreamExt};
pub async fn split_payload(payload: &mut Multipart) -> Result<(Option<String>, Bytes), Error> {
let mut file_data = BytesMut::with_capacity(10 * 1024 * 1024);
let mut filename: Option<String> = None;
while let Some(mut field) = payload.try_next().await? {
let content_type = field.content_disposition().unwrap();
filename = Some(content_type.get_name().unwrap().clone().to_owned());
while let Some(chunk) = field.next().await {
let data: Bytes = chunk.unwrap();
file_data.put(data);
}
}
Ok((filename, file_data.to_bytes()))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.