text stringlengths 8 4.13M |
|---|
use std::io::Read;
fn main() -> Result<(), Box<dyn std::error::Error>> {
if std::env::args().count() != 1 {
println!("compute_class_hash -- reads from stdin, outputs a class hash");
println!(
"the input read from stdin is expected to be a class definition, which is a json blob."
);
std::process::exit(1);
}
let mut s = Vec::new();
std::io::stdin().read_to_end(&mut s).unwrap();
let s = s;
let class_hash = match starknet_gateway_types::class_hash::compute_class_hash(&s)? {
starknet_gateway_types::class_hash::ComputedClassHash::Cairo(h) => h.0,
starknet_gateway_types::class_hash::ComputedClassHash::Sierra(h) => h.0,
};
println!("{class_hash:x}");
Ok(())
}
|
//! Ideas for what a generated API might look like.
#[drive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct Key<T> {
index: usize,
phantom: PhantomData<T>,
}
#[drive(Clone, PartialEq, Eq, Hash)]
pub struct KeySet<T> {
set: SetUsize,
phantom: PhantomData<Key<T>>,
}
polygraph!{
struct Person {
/// Biological father
father: Option<Key<Person>>,
/// Biological mother
mother: Option<Key<Person>>,
godparents: Set<Person>,
surname: Surname,
givenname: String,
}
struct Surname(String);
}
/// The above generates:
struct Person {
/// Biological father
father: Option<Key<Person>>,
#[serde(ignore)]
father_of: Set<Person>,
/// Biological mother
mother: Option<Key<Person>>,
#[serde(ignore)]
mother_of: Set<Person>,
godparents: Set<Person>,
#[serde(ignore)]
godparent_of: Set<Person>,
surname: Surname,
givenname: String,
}
struct Surname {
value: String,
#[serde(ignore)]
persons: Set<Person>,
}
#[drive(Clone, PartialEq, Eq, Hash, Serializes, Deserialize)]
pub struct Graphs {
person: Vec<PersonDatum>,
surname: Vec<SurnameDatum>,
}
#[drive(Clone, PartialEq, Eq, Hash)]
pub struct RefSet<'a, T> {
graphs: &'a Graphs,
set: &'a KeySet<T>,
}
#[drive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct Ref<'a, T> {
graphs: &'a Graphs,
key: Key<T>,
}
impl<'a> Deref Ref<'a, Person> {
type Target = Person;
fn deref(& self) -> & Person {
&self.graphs.person[self.key.index]
}
}
impl<'a> Ref<'a, Person> {
fn father_of(&self) -> SetRef<Person> {
RefSet {
graphs: self.graphs,
set: &self.graphs.person[self.key.index].father_of,
}
}
fn father(&self) -> Option<Ref<Person>> {
self.graphs.person[self.key.index].father.map(|key|
Ref {
graphs: self.graphs,
key,
})
}
}
|
pub mod accounts;
pub mod deal;
|
use base64;
use std::io::Read;
use std::str::FromStr;
use xml_rs::reader::{EventReader as XmlEventReader, ParserConfig, XmlEvent};
use {Date, Error, Result, PlistEvent};
pub struct EventReader<R: Read> {
xml_reader: XmlEventReader<R>,
queued_event: Option<XmlEvent>,
element_stack: Vec<String>,
finished: bool,
}
impl<R: Read> EventReader<R> {
pub fn new(reader: R) -> EventReader<R> {
let config = ParserConfig::new()
.trim_whitespace(false)
.whitespace_to_characters(true)
.cdata_to_characters(true)
.ignore_comments(true)
.coalesce_characters(true);
EventReader {
xml_reader: XmlEventReader::new_with_config(reader, config),
queued_event: None,
element_stack: Vec::new(),
finished: false,
}
}
fn read_content<F>(&mut self, f: F) -> Result<PlistEvent>
where F: FnOnce(String) -> Result<PlistEvent>
{
match self.xml_reader.next() {
Ok(XmlEvent::Characters(s)) => f(s),
Ok(event @ XmlEvent::EndElement { .. }) => {
self.queued_event = Some(event);
f("".to_owned())
}
_ => Err(Error::InvalidData),
}
}
fn next_event(&mut self) -> ::std::result::Result<XmlEvent, ()> {
if let Some(event) = self.queued_event.take() {
Ok(event)
} else {
self.xml_reader.next().map_err(|_| ())
}
}
fn read_next(&mut self) -> Option<Result<PlistEvent>> {
loop {
match self.next_event() {
Ok(XmlEvent::StartElement { name, .. }) => {
// Add the current element to the element stack
self.element_stack.push(name.local_name.clone());
match &name.local_name[..] {
"plist" => (),
"array" => return Some(Ok(PlistEvent::StartArray(None))),
"dict" => return Some(Ok(PlistEvent::StartDictionary(None))),
"key" => return Some(self.read_content(|s| Ok(PlistEvent::StringValue(s)))),
"true" => return Some(Ok(PlistEvent::BooleanValue(true))),
"false" => return Some(Ok(PlistEvent::BooleanValue(false))),
"data" => {
return Some(self.read_content(|s| {
let data = base64::decode_config(&s, base64::MIME).map_err(|_| Error::InvalidData)?;
Ok(PlistEvent::DataValue(data))
}))
}
"date" => {
return Some(self.read_content(|s| {
Ok(PlistEvent::DateValue(Date::from_str(&s).map_err(|_| Error::InvalidData)?))
}))
}
"integer" => {
return Some(self.read_content(|s| match FromStr::from_str(&s) {
Ok(i) => Ok(PlistEvent::IntegerValue(i)),
Err(_) => Err(Error::InvalidData),
}))
}
"real" => {
return Some(self.read_content(|s| match FromStr::from_str(&s) {
Ok(f) => Ok(PlistEvent::RealValue(f)),
Err(_) => Err(Error::InvalidData),
}))
}
"string" => {
return Some(self.read_content(|s| Ok(PlistEvent::StringValue(s))))
}
_ => return Some(Err(Error::InvalidData)),
}
}
Ok(XmlEvent::EndElement { name, .. }) => {
// Check the corrent element is being closed
match self.element_stack.pop() {
Some(ref open_name) if &name.local_name == open_name => (),
Some(ref _open_name) => return Some(Err(Error::InvalidData)),
None => return Some(Err(Error::InvalidData)),
}
match &name.local_name[..] {
"array" => return Some(Ok(PlistEvent::EndArray)),
"dict" => return Some(Ok(PlistEvent::EndDictionary)),
"plist" => (),
_ => (),
}
}
Ok(XmlEvent::EndDocument) => {
if self.element_stack.is_empty() {
return None;
} else {
return Some(Err(Error::UnexpectedEof));
}
}
Err(_) => return Some(Err(Error::InvalidData)),
_ => (),
}
}
}
}
impl<R: Read> Iterator for EventReader<R> {
type Item = Result<PlistEvent>;
fn next(&mut self) -> Option<Result<PlistEvent>> {
if self.finished {
None
} else {
match self.read_next() {
Some(Ok(event)) => Some(Ok(event)),
Some(Err(err)) => {
self.finished = true;
Some(Err(err))
}
None => {
self.finished = true;
None
}
}
}
}
}
#[cfg(test)]
mod tests {
use chrono::{TimeZone, Utc};
use std::fs::File;
use std::path::Path;
use super::*;
use PlistEvent;
#[test]
fn streaming_parser() {
use PlistEvent::*;
let reader = File::open(&Path::new("./tests/data/xml.plist")).unwrap();
let streaming_parser = EventReader::new(reader);
let events: Vec<PlistEvent> = streaming_parser.map(|e| e.unwrap()).collect();
let comparison = &[StartDictionary(None),
StringValue("Author".to_owned()),
StringValue("William Shakespeare".to_owned()),
StringValue("Lines".to_owned()),
StartArray(None),
StringValue("It is a tale told by an idiot,".to_owned()),
StringValue("Full of sound and fury, signifying nothing.".to_owned()),
EndArray,
StringValue("Death".to_owned()),
IntegerValue(1564),
StringValue("Height".to_owned()),
RealValue(1.60),
StringValue("Data".to_owned()),
DataValue(vec![0, 0, 0, 190, 0, 0, 0, 3, 0, 0, 0, 30, 0, 0, 0]),
StringValue("Birthdate".to_owned()),
DateValue(Utc.ymd(1981, 05, 16).and_hms(11, 32, 06).into()),
StringValue("Blank".to_owned()),
StringValue("".to_owned()),
EndDictionary];
assert_eq!(events, comparison);
}
#[test]
fn bad_data() {
let reader = File::open(&Path::new("./tests/data/xml_error.plist")).unwrap();
let streaming_parser = EventReader::new(reader);
let events: Vec<_> = streaming_parser.collect();
assert!(events.last().unwrap().is_err());
}
}
|
// =========
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet};
use std::process::exit;
const MOD: usize = 1000000007;
macro_rules! input {
(source = $s:expr, $($r:tt)*) => {
let mut iter = $s.split_whitespace();
let mut next = || { iter.next().unwrap() };
input_inner!{next, $($r)*}
};
($($r:tt)*) => {
let mut stdin = std::io::stdin();
let mut next = move || {
use std::io::Read;
let buf = stdin.by_ref().bytes()
.map(|r|r.unwrap())
.skip_while(|&r|r== b' ' || r == b'\n' || r == b'\r' || r == b'\t')
.take_while(|&r|r != b' ' && r != b'\n' && r != b'\r' && r != b'\t')
.collect::<Vec<_>>();
unsafe { std::str::from_utf8_unchecked(&buf) }.parse().ok().expect("Parse error.")
};
input_inner!{next, $($r)*}
};
}
macro_rules! input_inner {
($next:expr) => {};
($next:expr, ) => {};
($next:expr, $var:ident : $t:tt $($r:tt)*) => {
let $var : $t = read_value!($next, $t);
input_inner!{$next $($r)*}
};
}
macro_rules! read_value {
($next:expr, ( $($t:tt),* )) => {
( $(read_value!($next, $t)),* )
};
($next:expr, [ $t:tt ; $len:expr ]) => {
(0..$len).map(|_| $next()).collect()
};
($next:expr, chars) => {
read_value!($next, String).chars().collect::<Vec<char>>()
};
($next:expr, usize1) => {
read_value!($next, usize) - 1
};
($next:expr, $t:ty) => {
$next()
};
}
// =========
fn main() {
loop {
input! {
n: usize,
b: usize,
}
if n == 0 {
break;
}
}
}
pub struct IO<R, W: std::io::Write>(R, std::io::BufWriter<W>);
impl<R: std::io::Read, W: std::io::Write> IO<R, W> {
pub fn new(r: R, w: W) -> IO<R, W> {
IO(r, std::io::BufWriter::new(w))
}
pub fn read<T: std::str::FromStr>(&mut self) -> T {
use std::io::Read;
let buf = self
.0
.by_ref()
.bytes()
.map(|b| b.unwrap())
.skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t')
.take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t')
.collect::<Vec<_>>();
unsafe { std::str::from_utf8_unchecked(&buf) }
.parse()
.ok()
.expect("Parse error.")
}
pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
(0..n).map(|_| self.read()).collect()
}
pub fn chars(&mut self) -> Vec<char> {
self.read::<String>().chars().collect()
}
}
macro_rules! input {
(source = $s:expr, $($r:tt)*) => {
let mut iter = $s.split_whitespace();
input_inner!{iter, $($r)*}
};
($($r:tt)*) => {
let s = {
use std::io::Read;
let mut s = String::new();
std::io::stdin().read_to_string(&mut s).unwrap();
s
};
let mut iter = s.split_whitespace();
input_inner!{iter, $($r)*}
};
}
macro_rules! input_inner {
($iter:expr) => {};
($iter:expr, ) => {};
// var... 変数の識別子, $t...型を一つよむ
($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
let $var = read_value!($iter, $t);
//ここで繰り返し
input_inner!{$iter $($r)*}
};
}
macro_rules! read_value {
($iter:expr, ( $($t:tt),* )) => {
( $(read_value!($iter, $t)),* )
};
//
($iter:expr, [ $t:tt ; $len:expr ]) => {
(0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
};
($iter:expr, chars) => {
read_value!($iter, String).chars().collect::<Vec<char>>()
};
($iter:expr, usize1) => {
read_value!($iter, usize) - 1
};
// 配列の最後のNestではここで型が指定されてparseされる
($iter:expr, $t:ty) => {
$iter.next().unwrap().parse::<$t>().expect("Parse error")
};
} |
//! Compile-time reflection of Rust types into GraphQL types.
use std::{rc::Rc, sync::Arc};
use futures::future::BoxFuture;
use crate::{
Arguments as FieldArguments, ExecutionResult, Executor, GraphQLValue, Nullable, ScalarValue,
};
/// Alias for a [GraphQL object][1], [scalar][2] or [interface][3] type's name
/// in a GraphQL schema.
///
/// See [`BaseType`] for more info.
///
/// [1]: https://spec.graphql.org/October2021#sec-Objects
/// [2]: https://spec.graphql.org/October2021#sec-Scalars
/// [3]: https://spec.graphql.org/October2021#sec-Interfaces
pub type Type = &'static str;
/// Alias for a slice of [`Type`]s.
///
/// See [`BaseSubTypes`] for more info.
pub type Types = &'static [Type];
/// Naming of a [GraphQL object][1], [scalar][2] or [interface][3] [`Type`].
///
/// This trait is transparent to [`Option`], [`Vec`] and other containers, so to
/// fully represent a [GraphQL object][1] we additionally use [`WrappedType`].
///
/// Different Rust types may have the same [`NAME`]. For example, [`String`] and
/// `&`[`str`](prim@str) share `String!` GraphQL type.
///
/// [`NAME`]: Self::NAME
/// [1]: https://spec.graphql.org/October2021#sec-Objects
/// [2]: https://spec.graphql.org/October2021#sec-Scalars
/// [3]: https://spec.graphql.org/October2021#sec-Interfaces
pub trait BaseType<S> {
/// [`Type`] of the [GraphQL object][1], [scalar][2] or [interface][3].
///
/// [1]: https://spec.graphql.org/October2021#sec-Objects
/// [2]: https://spec.graphql.org/October2021#sec-Scalars
/// [3]: https://spec.graphql.org/October2021#sec-Interfaces
const NAME: Type;
}
impl<'a, S, T: BaseType<S> + ?Sized> BaseType<S> for &'a T {
const NAME: Type = T::NAME;
}
impl<'ctx, S, T> BaseType<S> for (&'ctx T::Context, T)
where
S: ScalarValue,
T: BaseType<S> + GraphQLValue<S>,
{
const NAME: Type = T::NAME;
}
impl<S, T: BaseType<S>> BaseType<S> for Option<T> {
const NAME: Type = T::NAME;
}
impl<S, T: BaseType<S>> BaseType<S> for Nullable<T> {
const NAME: Type = T::NAME;
}
impl<S, T: BaseType<S>, E> BaseType<S> for Result<T, E> {
const NAME: Type = T::NAME;
}
impl<S, T: BaseType<S>> BaseType<S> for Vec<T> {
const NAME: Type = T::NAME;
}
impl<S, T: BaseType<S>> BaseType<S> for [T] {
const NAME: Type = T::NAME;
}
impl<S, T: BaseType<S>, const N: usize> BaseType<S> for [T; N] {
const NAME: Type = T::NAME;
}
impl<S, T: BaseType<S> + ?Sized> BaseType<S> for Box<T> {
const NAME: Type = T::NAME;
}
impl<S, T: BaseType<S> + ?Sized> BaseType<S> for Arc<T> {
const NAME: Type = T::NAME;
}
impl<S, T: BaseType<S> + ?Sized> BaseType<S> for Rc<T> {
const NAME: Type = T::NAME;
}
/// [Sub-types][2] of a [GraphQL object][1].
///
/// This trait is transparent to [`Option`], [`Vec`] and other containers.
///
/// [1]: https://spec.graphql.org/October2021#sec-Objects
/// [2]: https://spec.graphql.org/October2021#sel-JAHZhCHCDEJDAAAEEFDBtzC
pub trait BaseSubTypes<S> {
/// Sub-[`Types`] of the [GraphQL object][1].
///
/// [1]: https://spec.graphql.org/October2021#sec-Objects
const NAMES: Types;
}
impl<'a, S, T: BaseSubTypes<S> + ?Sized> BaseSubTypes<S> for &'a T {
const NAMES: Types = T::NAMES;
}
impl<'ctx, S, T> BaseSubTypes<S> for (&'ctx T::Context, T)
where
S: ScalarValue,
T: BaseSubTypes<S> + GraphQLValue<S>,
{
const NAMES: Types = T::NAMES;
}
impl<S, T: BaseSubTypes<S>> BaseSubTypes<S> for Option<T> {
const NAMES: Types = T::NAMES;
}
impl<S, T: BaseSubTypes<S>> BaseSubTypes<S> for Nullable<T> {
const NAMES: Types = T::NAMES;
}
impl<S, T: BaseSubTypes<S>, E> BaseSubTypes<S> for Result<T, E> {
const NAMES: Types = T::NAMES;
}
impl<S, T: BaseSubTypes<S>> BaseSubTypes<S> for Vec<T> {
const NAMES: Types = T::NAMES;
}
impl<S, T: BaseSubTypes<S>> BaseSubTypes<S> for [T] {
const NAMES: Types = T::NAMES;
}
impl<S, T: BaseSubTypes<S>, const N: usize> BaseSubTypes<S> for [T; N] {
const NAMES: Types = T::NAMES;
}
impl<S, T: BaseSubTypes<S> + ?Sized> BaseSubTypes<S> for Box<T> {
const NAMES: Types = T::NAMES;
}
impl<S, T: BaseSubTypes<S> + ?Sized> BaseSubTypes<S> for Arc<T> {
const NAMES: Types = T::NAMES;
}
impl<S, T: BaseSubTypes<S> + ?Sized> BaseSubTypes<S> for Rc<T> {
const NAMES: Types = T::NAMES;
}
/// Alias for a value of a [`WrappedType`] (composed GraphQL type).
pub type WrappedValue = u128;
// TODO: Just use `&str`s once they're allowed in `const` generics.
/// Encoding of a composed GraphQL type in numbers.
///
/// To fully represent a [GraphQL object][1] it's not enough to use [`Type`],
/// because of the [wrapping types][2]. To work around this we use a
/// [`WrappedValue`] which is represented via [`u128`] number in the following
/// encoding:
/// - In base case of non-nullable [object][1] [`VALUE`] is `1`.
/// - To represent nullability we "append" `2` to the [`VALUE`], so
/// [`Option`]`<`[object][1]`>` has [`VALUE`] of `12`.
/// - To represent list we "append" `3` to the [`VALUE`], so
/// [`Vec`]`<`[object][1]`>` has [`VALUE`] of `13`.
///
/// This approach allows us to uniquely represent any [GraphQL object][1] with a
/// combination of [`Type`] and [`WrappedValue`] and even format it via
/// [`format_type!`] macro in a `const` context.
///
/// # Examples
///
/// ```rust
/// # use juniper::{
/// # format_type,
/// # macros::reflect::{WrappedType, BaseType, WrappedValue, Type},
/// # DefaultScalarValue,
/// # };
/// #
/// assert_eq!(<Option<i32> as WrappedType<DefaultScalarValue>>::VALUE, 12);
/// assert_eq!(<Vec<i32> as WrappedType<DefaultScalarValue>>::VALUE, 13);
/// assert_eq!(<Vec<Option<i32>> as WrappedType<DefaultScalarValue>>::VALUE, 123);
/// assert_eq!(<Option<Vec<i32>> as WrappedType<DefaultScalarValue>>::VALUE, 132);
/// assert_eq!(<Option<Vec<Option<i32>>> as WrappedType<DefaultScalarValue>>::VALUE, 1232);
///
/// const TYPE_STRING: Type = <Option<Vec<Option<String>>> as BaseType<DefaultScalarValue>>::NAME;
/// const WRAP_VAL_STRING: WrappedValue = <Option<Vec<Option<String>>> as WrappedType<DefaultScalarValue>>::VALUE;
/// assert_eq!(format_type!(TYPE_STRING, WRAP_VAL_STRING), "[String]");
///
/// const TYPE_STR: Type = <Option<Vec<Option<&str>>> as BaseType<DefaultScalarValue>>::NAME;
/// const WRAP_VAL_STR: WrappedValue = <Option<Vec<Option<&str>>> as WrappedType<DefaultScalarValue>>::VALUE;
/// assert_eq!(format_type!(TYPE_STR, WRAP_VAL_STR), "[String]");
/// ```
///
/// [`VALUE`]: Self::VALUE
/// [1]: https://spec.graphql.org/October2021#sec-Objects
/// [2]: https://spec.graphql.org/October2021#sec-Wrapping-Types
pub trait WrappedType<S> {
/// [`WrappedValue`] of this type.
const VALUE: WrappedValue;
}
impl<'ctx, S, T: WrappedType<S>> WrappedType<S> for (&'ctx T::Context, T)
where
S: ScalarValue,
T: GraphQLValue<S>,
{
const VALUE: u128 = T::VALUE;
}
impl<S, T: WrappedType<S>> WrappedType<S> for Option<T> {
const VALUE: u128 = T::VALUE * 10 + 2;
}
impl<S, T: WrappedType<S>> WrappedType<S> for Nullable<T> {
const VALUE: u128 = T::VALUE * 10 + 2;
}
impl<S, T: WrappedType<S>, E> WrappedType<S> for Result<T, E> {
const VALUE: u128 = T::VALUE;
}
impl<S, T: WrappedType<S>> WrappedType<S> for Vec<T> {
const VALUE: u128 = T::VALUE * 10 + 3;
}
impl<S, T: WrappedType<S>> WrappedType<S> for [T] {
const VALUE: u128 = T::VALUE * 10 + 3;
}
impl<S, T: WrappedType<S>, const N: usize> WrappedType<S> for [T; N] {
const VALUE: u128 = T::VALUE * 10 + 3;
}
impl<'a, S, T: WrappedType<S> + ?Sized> WrappedType<S> for &'a T {
const VALUE: u128 = T::VALUE;
}
impl<S, T: WrappedType<S> + ?Sized> WrappedType<S> for Box<T> {
const VALUE: u128 = T::VALUE;
}
impl<S, T: WrappedType<S> + ?Sized> WrappedType<S> for Arc<T> {
const VALUE: u128 = T::VALUE;
}
impl<S, T: WrappedType<S> + ?Sized> WrappedType<S> for Rc<T> {
const VALUE: u128 = T::VALUE;
}
/// Alias for a [GraphQL object][1] or [interface][2] [field argument][3] name.
///
/// See [`Fields`] for more info.
///
/// [1]: https://spec.graphql.org/October2021#sec-Objects
/// [2]: https://spec.graphql.org/October2021#sec-Interfaces
/// [3]: https://spec.graphql.org/October2021#sec-Language.Arguments
pub type Name = &'static str;
/// Alias for a slice of [`Name`]s.
///
/// See [`Fields`] for more info.
pub type Names = &'static [Name];
/// Alias for [field argument][1]s [`Name`], [`Type`] and [`WrappedValue`].
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
pub type Argument = (Name, Type, WrappedValue);
/// Alias for a slice of [field argument][1]s [`Name`], [`Type`] and
/// [`WrappedValue`].
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
pub type Arguments = &'static [(Name, Type, WrappedValue)];
/// Alias for a `const`-hashed [`Name`] used in a `const` context.
pub type FieldName = u128;
/// [GraphQL object][1] or [interface][2] [field arguments][3] [`Names`].
///
/// [1]: https://spec.graphql.org/October2021#sec-Objects
/// [2]: https://spec.graphql.org/October2021#sec-Interfaces
/// [3]: https://spec.graphql.org/October2021#sec-Language.Arguments
pub trait Fields<S> {
/// [`Names`] of the [GraphQL object][1] or [interface][2]
/// [field arguments][3].
///
/// [1]: https://spec.graphql.org/October2021#sec-Objects
/// [2]: https://spec.graphql.org/October2021#sec-Interfaces
/// [3]: https://spec.graphql.org/October2021#sec-Language.Arguments
const NAMES: Names;
}
/// [`Types`] of the [GraphQL interfaces][1] implemented by this type.
///
/// [1]: https://spec.graphql.org/October2021#sec-Interfaces
pub trait Implements<S> {
/// [`Types`] of the [GraphQL interfaces][1] implemented by this type.
///
/// [1]: https://spec.graphql.org/October2021#sec-Interfaces
const NAMES: Types;
}
/// Stores meta information of a [GraphQL field][1]:
/// - [`Context`] and [`TypeInfo`].
/// - Return type's [`TYPE`], [`SUB_TYPES`] and [`WRAPPED_VALUE`].
/// - [`ARGUMENTS`].
///
/// [`ARGUMENTS`]: Self::ARGUMENTS
/// [`Context`]: Self::Context
/// [`SUB_TYPES`]: Self::SUB_TYPES
/// [`TYPE`]: Self::TYPE
/// [`TypeInfo`]: Self::TypeInfo
/// [`WRAPPED_VALUE`]: Self::WRAPPED_VALUE
/// [1]: https://spec.graphql.org/October2021#sec-Language.Fields
pub trait FieldMeta<S, const N: FieldName> {
/// [`GraphQLValue::Context`] of this [field][1].
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Fields
type Context;
/// [`GraphQLValue::TypeInfo`] of this [GraphQL field][1].
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Fields
type TypeInfo;
/// [`Types`] of [GraphQL field's][1] return type.
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Fields
const TYPE: Type;
/// [Sub-types][1] of [GraphQL field's][2] return type.
///
/// [1]: BaseSubTypes
/// [2]: https://spec.graphql.org/October2021#sec-Language.Fields
const SUB_TYPES: Types;
/// [`WrappedValue`] of [GraphQL field's][1] return type.
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Fields
const WRAPPED_VALUE: WrappedValue;
/// [GraphQL field's][1] [`Arguments`].
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Fields
const ARGUMENTS: Arguments;
}
/// Synchronous field of a [GraphQL object][1] or [interface][2].
///
/// [1]: https://spec.graphql.org/October2021#sec-Objects
/// [2]: https://spec.graphql.org/October2021#sec-Interfaces
pub trait Field<S, const N: FieldName>: FieldMeta<S, N> {
/// Resolves the [`Value`] of this synchronous [`Field`].
///
/// The `arguments` object contains all the specified arguments, with the
/// default values being substituted for the ones not provided by the query.
///
/// The `executor` can be used to drive selections into sub-[objects][1].
///
/// [`Value`]: crate::Value
/// [1]: https://spec.graphql.org/October2021#sec-Objects
fn call(
&self,
info: &Self::TypeInfo,
args: &FieldArguments<S>,
executor: &Executor<Self::Context, S>,
) -> ExecutionResult<S>;
}
/// Asynchronous field of a GraphQL [object][1] or [interface][2].
///
/// [1]: https://spec.graphql.org/October2021#sec-Objects
/// [2]: https://spec.graphql.org/October2021#sec-Interfaces
pub trait AsyncField<S, const N: FieldName>: FieldMeta<S, N> {
/// Resolves the [`Value`] of this asynchronous [`AsyncField`].
///
/// The `arguments` object contains all the specified arguments, with the
/// default values being substituted for the ones not provided by the query.
///
/// The `executor` can be used to drive selections into sub-[objects][1].
///
/// [1]: https://spec.graphql.org/October2021#sec-Objects
fn call<'b>(
&'b self,
info: &'b Self::TypeInfo,
args: &'b FieldArguments<S>,
executor: &'b Executor<Self::Context, S>,
) -> BoxFuture<'b, ExecutionResult<S>>;
}
/// Non-cryptographic hash with good dispersion to use as a [`str`](prim@str) in
/// `const` generics. See [spec] for more info.
///
/// [spec]: https://datatracker.ietf.org/doc/html/draft-eastlake-fnv-17.html
#[must_use]
pub const fn fnv1a128(str: Name) -> u128 {
const FNV_OFFSET_BASIS: u128 = 0x6c62272e07bb014262b821756295c58d;
const FNV_PRIME: u128 = 0x0000000001000000000000000000013b;
let bytes = str.as_bytes();
let mut hash = FNV_OFFSET_BASIS;
let mut i = 0;
while i < bytes.len() {
hash ^= bytes[i] as u128;
hash = hash.wrapping_mul(FNV_PRIME);
i += 1;
}
hash
}
/// Length __in bytes__ of the [`format_type!`] macro result.
#[must_use]
pub const fn type_len_with_wrapped_val(ty: Type, val: WrappedValue) -> usize {
let mut len = ty.as_bytes().len() + "!".as_bytes().len(); // Type!
let mut curr = val;
while curr % 10 != 0 {
match curr % 10 {
2 => len -= "!".as_bytes().len(), // remove !
3 => len += "[]!".as_bytes().len(), // [Type]!
_ => {}
}
curr /= 10;
}
len
}
/// Checks whether the given GraphQL [object][1] represents a `subtype` of the
/// given GraphQL `ty`pe, basing on the [`WrappedType`] encoding.
///
/// To fully determine the sub-typing relation the [`Type`] should be one of the
/// [`BaseSubTypes::NAMES`].
///
/// [1]: https://spec.graphql.org/October2021#sec-Objects
#[must_use]
pub const fn can_be_subtype(ty: WrappedValue, subtype: WrappedValue) -> bool {
let ty_curr = ty % 10;
let sub_curr = subtype % 10;
if ty_curr == sub_curr {
if ty_curr == 1 {
true
} else {
can_be_subtype(ty / 10, subtype / 10)
}
} else if ty_curr == 2 {
can_be_subtype(ty / 10, subtype)
} else {
false
}
}
/// Checks whether the given `val` exists in the given `arr`.
#[must_use]
pub const fn str_exists_in_arr(val: &str, arr: &[&str]) -> bool {
let mut i = 0;
while i < arr.len() {
if str_eq(val, arr[i]) {
return true;
}
i += 1;
}
false
}
/// Compares strings in a `const` context.
///
/// As there is no `const impl Trait` and `l == r` calls [`Eq`], we have to
/// write custom comparison function.
///
/// [`Eq`]: std::cmp::Eq
// TODO: Remove once `Eq` trait is allowed in `const` context.
pub const fn str_eq(l: &str, r: &str) -> bool {
let (l, r) = (l.as_bytes(), r.as_bytes());
if l.len() != r.len() {
return false;
}
let mut i = 0;
while i < l.len() {
if l[i] != r[i] {
return false;
}
i += 1;
}
true
}
/// Asserts that `#[graphql_interface(for = ...)]` has all the types referencing
/// this interface in the `impl = ...` attribute argument.
///
/// Symmetrical to [`assert_interfaces_impls!`].
#[macro_export]
macro_rules! assert_implemented_for {
($scalar: ty, $implementor: ty $(, $interfaces: ty)* $(,)?) => {
const _: () = {
$({
let is_present = $crate::macros::reflect::str_exists_in_arr(
<$implementor as ::juniper::macros::reflect::BaseType<$scalar>>::NAME,
<$interfaces as ::juniper::macros::reflect::BaseSubTypes<$scalar>>::NAMES,
);
if !is_present {
const MSG: &str = $crate::const_concat!(
"Failed to implement interface `",
<$interfaces as $crate::macros::reflect::BaseType<$scalar>>::NAME,
"` on `",
<$implementor as $crate::macros::reflect::BaseType<$scalar>>::NAME,
"`: missing implementer reference in interface's `for` attribute.",
);
::std::panic!("{}", MSG);
}
})*
};
};
}
/// Asserts that `impl = ...` attribute argument has all the types referencing
/// this GraphQL type in `#[graphql_interface(for = ...)]`.
///
/// Symmetrical to [`assert_implemented_for!`].
#[macro_export]
macro_rules! assert_interfaces_impls {
($scalar: ty, $interface: ty $(, $implementers: ty)* $(,)?) => {
const _: () = {
$({
let is_present = $crate::macros::reflect::str_exists_in_arr(
<$interface as ::juniper::macros::reflect::BaseType<$scalar>>::NAME,
<$implementers as ::juniper::macros::reflect::Implements<$scalar>>::NAMES,
);
if !is_present {
const MSG: &str = $crate::const_concat!(
"Failed to implement interface `",
<$interface as $crate::macros::reflect::BaseType<$scalar>>::NAME,
"` on `",
<$implementers as $crate::macros::reflect::BaseType<$scalar>>::NAME,
"`: missing interface reference in implementer's `impl` attribute.",
);
::std::panic!("{}", MSG);
}
})*
};
};
}
/// Asserts that all [transitive interfaces][0] (the ones implemented by the
/// `$interface`) are also implemented by the `$implementor`.
///
/// [0]: https://spec.graphql.org/October2021#sel-FAHbhBHCAACGB35P
#[macro_export]
macro_rules! assert_transitive_impls {
($scalar: ty, $interface: ty, $implementor: ty $(, $transitive: ty)* $(,)?) => {
const _: () = {
$({
let is_present = $crate::macros::reflect::str_exists_in_arr(
<$implementor as ::juniper::macros::reflect::BaseType<$scalar>>::NAME,
<$transitive as ::juniper::macros::reflect::BaseSubTypes<$scalar>>::NAMES,
);
if !is_present {
const MSG: &str = $crate::const_concat!(
"Failed to implement interface `",
<$interface as $crate::macros::reflect::BaseType<$scalar>>::NAME,
"` on `",
<$implementor as $crate::macros::reflect::BaseType<$scalar>>::NAME,
"`: missing `impl = ` for transitive interface `",
<$transitive as $crate::macros::reflect::BaseType<$scalar>>::NAME,
"` on `",
<$implementor as $crate::macros::reflect::BaseType<$scalar>>::NAME,
"`."
);
::std::panic!("{}", MSG);
}
})*
};
};
}
/// Asserts validness of [`Field`] [`Arguments`] and returned [`Type`].
///
/// This assertion is a combination of [`assert_subtype`] and
/// [`assert_field_args`].
///
/// See [spec][1] for more info.
///
/// [1]: https://spec.graphql.org/October2021#IsValidImplementation()
#[macro_export]
macro_rules! assert_field {
(
$base_ty: ty,
$impl_ty: ty,
$scalar: ty,
$field_name: expr $(,)?
) => {
$crate::assert_field_args!($base_ty, $impl_ty, $scalar, $field_name);
$crate::assert_subtype!($base_ty, $impl_ty, $scalar, $field_name);
};
}
/// Asserts validness of a [`Field`] return type.
///
/// See [spec][1] for more info.
///
/// [1]: https://spec.graphql.org/October2021#IsValidImplementationFieldType()
#[macro_export]
macro_rules! assert_subtype {
(
$base_ty: ty,
$impl_ty: ty,
$scalar: ty,
$field_name: expr $(,)?
) => {
const _: () = {
const BASE_TY: $crate::macros::reflect::Type =
<$base_ty as $crate::macros::reflect::BaseType<$scalar>>::NAME;
const IMPL_TY: $crate::macros::reflect::Type =
<$impl_ty as $crate::macros::reflect::BaseType<$scalar>>::NAME;
const ERR_PREFIX: &str = $crate::const_concat!(
"Failed to implement interface `",
BASE_TY,
"` on `",
IMPL_TY,
"`: ",
);
const FIELD_NAME: $crate::macros::reflect::Name =
$field_name;
const BASE_RETURN_WRAPPED_VAL: $crate::macros::reflect::WrappedValue =
<$base_ty as $crate::macros::reflect::FieldMeta<
$scalar,
{ $crate::checked_hash!(FIELD_NAME, $base_ty, $scalar, ERR_PREFIX) },
>>::WRAPPED_VALUE;
const IMPL_RETURN_WRAPPED_VAL: $crate::macros::reflect::WrappedValue =
<$impl_ty as $crate::macros::reflect::FieldMeta<
$scalar,
{ $crate::checked_hash!(FIELD_NAME, $impl_ty, $scalar, ERR_PREFIX) },
>>::WRAPPED_VALUE;
const BASE_RETURN_TY: $crate::macros::reflect::Type =
<$base_ty as $crate::macros::reflect::FieldMeta<
$scalar,
{ $crate::checked_hash!(FIELD_NAME, $base_ty, $scalar, ERR_PREFIX) },
>>::TYPE;
const IMPL_RETURN_TY: $crate::macros::reflect::Type =
<$impl_ty as $crate::macros::reflect::FieldMeta<
$scalar,
{ $crate::checked_hash!(FIELD_NAME, $impl_ty, $scalar, ERR_PREFIX) },
>>::TYPE;
const BASE_RETURN_SUB_TYPES: $crate::macros::reflect::Types =
<$base_ty as $crate::macros::reflect::FieldMeta<
$scalar,
{ $crate::checked_hash!(FIELD_NAME, $base_ty, $scalar, ERR_PREFIX) },
>>::SUB_TYPES;
let is_subtype = $crate::macros::reflect::str_exists_in_arr(IMPL_RETURN_TY, BASE_RETURN_SUB_TYPES)
&& $crate::macros::reflect::can_be_subtype(BASE_RETURN_WRAPPED_VAL, IMPL_RETURN_WRAPPED_VAL);
if !is_subtype {
const MSG: &str = $crate::const_concat!(
ERR_PREFIX,
"Field `",
FIELD_NAME,
"`: implementor is expected to return a subtype of interface's return object: `",
$crate::format_type!(IMPL_RETURN_TY, IMPL_RETURN_WRAPPED_VAL),
"` is not a subtype of `",
$crate::format_type!(BASE_RETURN_TY, BASE_RETURN_WRAPPED_VAL),
"`.",
);
::std::panic!("{}", MSG);
}
};
};
}
/// Asserts validness of the [`Field`]s arguments. See [spec][1] for more
/// info.
///
/// [1]: https://spec.graphql.org/October2021#sel-IAHZhCHCDEEFAAADHD8Cxob
#[macro_export]
macro_rules! assert_field_args {
(
$base_ty: ty,
$impl_ty: ty,
$scalar: ty,
$field_name: expr $(,)?
) => {
const _: () = {
const BASE_NAME: &str = <$base_ty as $crate::macros::reflect::BaseType<$scalar>>::NAME;
const IMPL_NAME: &str = <$impl_ty as $crate::macros::reflect::BaseType<$scalar>>::NAME;
const ERR_PREFIX: &str = $crate::const_concat!(
"Failed to implement interface `",
BASE_NAME,
"` on `",
IMPL_NAME,
"`: ",
);
const FIELD_NAME: &str = $field_name;
const BASE_ARGS: ::juniper::macros::reflect::Arguments =
<$base_ty as $crate::macros::reflect::FieldMeta<
$scalar,
{ $crate::checked_hash!(FIELD_NAME, $base_ty, $scalar, ERR_PREFIX) },
>>::ARGUMENTS;
const IMPL_ARGS: ::juniper::macros::reflect::Arguments =
<$impl_ty as $crate::macros::reflect::FieldMeta<
$scalar,
{ $crate::checked_hash!(FIELD_NAME, $impl_ty, $scalar, ERR_PREFIX) },
>>::ARGUMENTS;
struct Error {
cause: Cause,
base: ::juniper::macros::reflect::Argument,
implementation: ::juniper::macros::reflect::Argument,
}
enum Cause {
RequiredField,
AdditionalNonNullableField,
TypeMismatch,
}
const fn unwrap_error(v: ::std::result::Result<(), Error>) -> Error {
match v {
// Unfortunately we can't use `unreachable!()` here, as this
// branch will be executed either way.
Ok(()) => Error {
cause: Cause::RequiredField,
base: ("unreachable", "unreachable", 1),
implementation: ("unreachable", "unreachable", 1),
},
Err(err) => err,
}
}
const fn check() -> Result<(), Error> {
let mut base_i = 0;
while base_i < BASE_ARGS.len() {
let (base_name, base_type, base_wrap_val) = BASE_ARGS[base_i];
let mut impl_i = 0;
let mut was_found = false;
while impl_i < IMPL_ARGS.len() {
let (impl_name, impl_type, impl_wrap_val) = IMPL_ARGS[impl_i];
if $crate::macros::reflect::str_eq(base_name, impl_name) {
if $crate::macros::reflect::str_eq(base_type, impl_type)
&& base_wrap_val == impl_wrap_val
{
was_found = true;
break;
} else {
return Err(Error {
cause: Cause::TypeMismatch,
base: (base_name, base_type, base_wrap_val),
implementation: (impl_name, impl_type, impl_wrap_val),
});
}
}
impl_i += 1;
}
if !was_found {
return Err(Error {
cause: Cause::RequiredField,
base: (base_name, base_type, base_wrap_val),
implementation: (base_name, base_type, base_wrap_val),
});
}
base_i += 1;
}
let mut impl_i = 0;
while impl_i < IMPL_ARGS.len() {
let (impl_name, impl_type, impl_wrapped_val) = IMPL_ARGS[impl_i];
impl_i += 1;
if impl_wrapped_val % 10 == 2 {
continue;
}
let mut base_i = 0;
let mut was_found = false;
while base_i < BASE_ARGS.len() {
let (base_name, _, _) = BASE_ARGS[base_i];
if $crate::macros::reflect::str_eq(base_name, impl_name) {
was_found = true;
break;
}
base_i += 1;
}
if !was_found {
return Err(Error {
cause: Cause::AdditionalNonNullableField,
base: (impl_name, impl_type, impl_wrapped_val),
implementation: (impl_name, impl_type, impl_wrapped_val),
});
}
}
Ok(())
}
const RES: ::std::result::Result<(), Error> = check();
if RES.is_err() {
const ERROR: Error = unwrap_error(RES);
const BASE_ARG_NAME: &str = ERROR.base.0;
const IMPL_ARG_NAME: &str = ERROR.implementation.0;
const BASE_TYPE_FORMATTED: &str = $crate::format_type!(ERROR.base.1, ERROR.base.2);
const IMPL_TYPE_FORMATTED: &str =
$crate::format_type!(ERROR.implementation.1, ERROR.implementation.2);
const MSG: &str = match ERROR.cause {
Cause::TypeMismatch => {
$crate::const_concat!(
"Argument `",
BASE_ARG_NAME,
"`: expected type `",
BASE_TYPE_FORMATTED,
"`, found: `",
IMPL_TYPE_FORMATTED,
"`.",
)
}
Cause::RequiredField => {
$crate::const_concat!(
"Argument `",
BASE_ARG_NAME,
"` of type `",
BASE_TYPE_FORMATTED,
"` was expected, but not found."
)
}
Cause::AdditionalNonNullableField => {
$crate::const_concat!(
"Argument `",
IMPL_ARG_NAME,
"` of type `",
IMPL_TYPE_FORMATTED,
"` isn't present on the interface and so has to be nullable."
)
}
};
const ERROR_MSG: &str =
$crate::const_concat!(ERR_PREFIX, "Field `", FIELD_NAME, "`: ", MSG);
::std::panic!("{}", ERROR_MSG);
}
};
};
}
/// Concatenates `const` [`str`](prim@str)s in a `const` context.
#[macro_export]
macro_rules! const_concat {
($($s:expr),* $(,)?) => {{
const LEN: usize = 0 $(+ $s.as_bytes().len())*;
const CNT: usize = [$($s),*].len();
const fn concat(input: [&str; CNT]) -> [u8; LEN] {
let mut bytes = [0; LEN];
let (mut i, mut byte) = (0, 0);
while i < CNT {
let mut b = 0;
while b < input[i].len() {
bytes[byte] = input[i].as_bytes()[b];
byte += 1;
b += 1;
}
i += 1;
}
bytes
}
const CON: [u8; LEN] = concat([$($s),*]);
// TODO: Use `.unwrap()` once it becomes `const`.
match ::std::str::from_utf8(&CON) {
::std::result::Result::Ok(s) => s,
_ => unreachable!(),
}
}};
}
/// Ensures that the given `$impl_ty` implements [`Field`] and returns a
/// [`fnv1a128`] hash for it, otherwise panics with understandable message.
#[macro_export]
macro_rules! checked_hash {
($field_name: expr, $impl_ty: ty, $scalar: ty $(, $prefix: expr)? $(,)?) => {{
let exists = $crate::macros::reflect::str_exists_in_arr(
$field_name,
<$impl_ty as $crate::macros::reflect::Fields<$scalar>>::NAMES,
);
if exists {
$crate::macros::reflect::fnv1a128(FIELD_NAME)
} else {
const MSG: &str = $crate::const_concat!(
$($prefix,)?
"Field `",
$field_name,
"` isn't implemented on `",
<$impl_ty as $crate::macros::reflect::BaseType<$scalar>>::NAME,
"`."
);
::std::panic!("{}", MSG)
}
}};
}
/// Formats the given [`Type`] and [`WrappedValue`] into a readable GraphQL type
/// name.
///
/// # Examples
///
/// ```rust
/// # use juniper::format_type;
/// #
/// assert_eq!(format_type!("String", 123), "[String]!");
/// assert_eq!(format_type!("🦀", 123), "[🦀]!");
/// ```
#[macro_export]
macro_rules! format_type {
($ty: expr, $wrapped_value: expr $(,)?) => {{
const TYPE: (
$crate::macros::reflect::Type,
$crate::macros::reflect::WrappedValue,
) = ($ty, $wrapped_value);
const RES_LEN: usize = $crate::macros::reflect::type_len_with_wrapped_val(TYPE.0, TYPE.1);
const OPENING_BRACKET: &str = "[";
const CLOSING_BRACKET: &str = "]";
const BANG: &str = "!";
const fn format_type_arr() -> [u8; RES_LEN] {
let (ty, wrap_val) = TYPE;
let mut type_arr: [u8; RES_LEN] = [0; RES_LEN];
let mut current_start = 0;
let mut current_end = RES_LEN - 1;
let mut current_wrap_val = wrap_val;
let mut is_null = false;
while current_wrap_val % 10 != 0 {
match current_wrap_val % 10 {
2 => is_null = true, // Skips writing `BANG` later.
3 => {
// Write `OPENING_BRACKET` at `current_start`.
let mut i = 0;
while i < OPENING_BRACKET.as_bytes().len() {
type_arr[current_start + i] = OPENING_BRACKET.as_bytes()[i];
i += 1;
}
current_start += i;
if !is_null {
// Write `BANG` at `current_end`.
i = 0;
while i < BANG.as_bytes().len() {
type_arr[current_end - BANG.as_bytes().len() + i + 1] =
BANG.as_bytes()[i];
i += 1;
}
current_end -= i;
}
// Write `CLOSING_BRACKET` at `current_end`.
i = 0;
while i < CLOSING_BRACKET.as_bytes().len() {
type_arr[current_end - CLOSING_BRACKET.as_bytes().len() + i + 1] =
CLOSING_BRACKET.as_bytes()[i];
i += 1;
}
current_end -= i;
is_null = false;
}
_ => {}
}
current_wrap_val /= 10;
}
// Writes `Type` at `current_start`.
let mut i = 0;
while i < ty.as_bytes().len() {
type_arr[current_start + i] = ty.as_bytes()[i];
i += 1;
}
i = 0;
if !is_null {
// Writes `BANG` at `current_end`.
while i < BANG.as_bytes().len() {
type_arr[current_end - BANG.as_bytes().len() + i + 1] = BANG.as_bytes()[i];
i += 1;
}
}
type_arr
}
const TYPE_ARR: [u8; RES_LEN] = format_type_arr();
// TODO: Use `.unwrap()` once it becomes `const`.
const TYPE_FORMATTED: &str = match ::std::str::from_utf8(TYPE_ARR.as_slice()) {
::std::result::Result::Ok(s) => s,
_ => unreachable!(),
};
TYPE_FORMATTED
}};
}
|
use std::ffi::{CString, CStr};
use std::os::raw::{c_char};
pub mod console;
pub mod dom;
pub mod timing;
#[macro_export]
macro_rules! wasmblock_setup {
() => {
#[no_mangle]
pub extern fn alloc(size: usize) -> *mut c_void {
let mut buf = Vec::with_capacity(size);
let ptr = buf.as_mut_ptr();
mem::forget(buf);
return ptr as *mut c_void;
}
#[no_mangle]
pub extern fn dealloc_str(ptr: *mut c_char) {
unsafe {
let _ = CString::from_raw(ptr);
}
}
};
}
pub fn import_string(data: *mut c_char) -> String{
unsafe {
CStr::from_ptr(data).to_string_lossy().into_owned()
}
}
pub fn export_string<T:Into<std::vec::Vec<u8>>>(s:T) -> *const c_char{
let s = CString::new(s).unwrap();
let p = s.as_ptr();
std::mem::forget(s);
return p;
}
|
use super::*;
#[derive(Debug, PartialEq)]
pub enum Interpolated {
Command(Vec<Node>),
String(Vec<Node>),
Symbol(Vec<Node>),
}
|
use super::*;
#[test]
fn simple_test() {
let query = "dog";
let contents = "\
The quick brown fox
jumped over the lazy dog
and the dog wasn't pleased.";
assert_eq!(search(query, contents),
vec!["1: jumped over the lazy dog",
"2: and the dog wasn't pleased."]
);
} |
use std::collections::HashMap;
fn main() {
let s = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.";
let res = atom(s);
println!("{:?}", res);
}
fn atom(s: &str) -> HashMap<String, usize> {
let mut res = HashMap::new();
s.replace(".", "")
.split_whitespace()
.enumerate()
.for_each(|(i, si)| {
let t = match i {
0 | 4 | 5 | 6 | 7 | 8 | 14 | 15 | 18 => si[..1].to_owned(),
_ => si[0..2].to_owned(),
};
res.insert(t, i + 1);
});
res
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::sync::Arc;
use common_base::base::tokio;
use common_expression::type_check::check;
use common_expression::types::number::Int32Type;
use common_expression::types::number::NumberScalar;
use common_expression::types::DataType;
use common_expression::types::NumberDataType;
use common_expression::types::StringType;
use common_expression::BlockThresholds;
use common_expression::Column;
use common_expression::DataBlock;
use common_expression::DataField;
use common_expression::DataSchemaRefExt;
use common_expression::FromData;
use common_expression::FunctionContext;
use common_expression::RawExpr;
use common_expression::Scalar;
use common_expression::TableDataType;
use common_expression::TableField;
use common_expression::TableSchema;
use common_functions::aggregates::eval_aggr;
use common_functions::BUILTIN_FUNCTIONS;
use common_sql::evaluator::BlockOperator;
use common_storages_fuse::statistics::reducers::reduce_block_metas;
use common_storages_fuse::statistics::Trim;
use common_storages_fuse::statistics::STATS_REPLACEMENT_CHAR;
use common_storages_fuse::statistics::STATS_STRING_PREFIX_LEN;
use common_storages_fuse::FuseStorageFormat;
use databend_query::storages::fuse::io::TableMetaLocationGenerator;
use databend_query::storages::fuse::statistics::gen_columns_statistics;
use databend_query::storages::fuse::statistics::reducers;
use databend_query::storages::fuse::statistics::ClusterStatsGenerator;
use databend_query::storages::fuse::statistics::StatisticsAccumulator;
use opendal::Operator;
use rand::Rng;
use storages_common_table_meta::meta::BlockMeta;
use storages_common_table_meta::meta::ClusterStatistics;
use storages_common_table_meta::meta::ColumnStatistics;
use storages_common_table_meta::meta::Compression;
use storages_common_table_meta::meta::Statistics;
use crate::storages::fuse::block_writer::BlockWriter;
use crate::storages::fuse::table_test_fixture::TestFixture;
#[test]
fn test_ft_stats_block_stats() -> common_exception::Result<()> {
let schema = Arc::new(TableSchema::new(vec![
TableField::new("a", TableDataType::Number(NumberDataType::Int32)),
TableField::new("b", TableDataType::String),
]));
let block = DataBlock::new_from_columns(vec![
Int32Type::from_data(vec![1, 2, 3]),
StringType::from_data(vec!["aa", "aa", "bb"]),
]);
let r = gen_columns_statistics(&block, None, &schema)?;
assert_eq!(2, r.len());
let col_stats = r.get(&0).unwrap();
assert_eq!(col_stats.min, Scalar::Number(NumberScalar::Int32(1)));
assert_eq!(col_stats.max, Scalar::Number(NumberScalar::Int32(3)));
assert_eq!(col_stats.distinct_of_values, Some(3));
let col_stats = r.get(&1).unwrap();
assert_eq!(col_stats.min, Scalar::String(b"aa".to_vec()));
assert_eq!(col_stats.max, Scalar::String(b"bb".to_vec()));
assert_eq!(col_stats.distinct_of_values, Some(2));
Ok(())
}
#[test]
fn test_ft_stats_block_stats_with_column_distinct_count() -> common_exception::Result<()> {
let schema = Arc::new(TableSchema::new(vec![
TableField::new("a", TableDataType::Number(NumberDataType::Int32)),
TableField::new("b", TableDataType::String),
]));
let block = DataBlock::new_from_columns(vec![
Int32Type::from_data(vec![1, 2, 3]),
StringType::from_data(vec!["aa", "aa", "bb"]),
]);
let mut column_distinct_count = HashMap::new();
column_distinct_count.insert(0, 3);
column_distinct_count.insert(1, 2);
let r = gen_columns_statistics(&block, Some(column_distinct_count), &schema)?;
assert_eq!(2, r.len());
let col_stats = r.get(&0).unwrap();
assert_eq!(col_stats.min, Scalar::Number(NumberScalar::Int32(1)));
assert_eq!(col_stats.max, Scalar::Number(NumberScalar::Int32(3)));
assert_eq!(col_stats.distinct_of_values, Some(3));
let col_stats = r.get(&1).unwrap();
assert_eq!(col_stats.min, Scalar::String(b"aa".to_vec()));
assert_eq!(col_stats.max, Scalar::String(b"bb".to_vec()));
assert_eq!(col_stats.distinct_of_values, Some(2));
Ok(())
}
#[test]
fn test_ft_tuple_stats_block_stats() -> common_exception::Result<()> {
let schema = Arc::new(TableSchema::new(vec![TableField::new(
"a",
TableDataType::Tuple {
fields_name: vec!["a11".to_string(), "a12".to_string()],
fields_type: vec![
TableDataType::Number(NumberDataType::Int32),
TableDataType::Number(NumberDataType::Int32),
],
},
)]));
let inner_columns = vec![
Int32Type::from_data(vec![1, 2, 3]),
Int32Type::from_data(vec![4, 5, 6]),
];
let column = Column::Tuple(inner_columns);
let block = DataBlock::new_from_columns(vec![column]);
let r = gen_columns_statistics(&block, None, &schema)?;
assert_eq!(2, r.len());
let col0_stats = r.get(&0).unwrap();
assert_eq!(col0_stats.min, Scalar::Number(NumberScalar::Int32(1)));
assert_eq!(col0_stats.max, Scalar::Number(NumberScalar::Int32(3)));
let col1_stats = r.get(&1).unwrap();
assert_eq!(col1_stats.min, Scalar::Number(NumberScalar::Int32(4)));
assert_eq!(col1_stats.max, Scalar::Number(NumberScalar::Int32(6)));
Ok(())
}
#[test]
fn test_ft_stats_col_stats_reduce() -> common_exception::Result<()> {
let num_of_blocks = 10;
let rows_per_block = 3;
let val_start_with = 1;
let (schema, blocks) =
TestFixture::gen_sample_blocks_ex(num_of_blocks, rows_per_block, val_start_with);
let col_stats = blocks
.iter()
.map(|b| gen_columns_statistics(&b.clone().unwrap(), None, &schema))
.collect::<common_exception::Result<Vec<_>>>()?;
let r = reducers::reduce_block_statistics(&col_stats);
assert!(r.is_ok());
let r = r.unwrap();
assert_eq!(3, r.len());
let col0_stats = r.get(&0).unwrap();
assert_eq!(
col0_stats.min,
Scalar::Number(NumberScalar::Int32(val_start_with))
);
assert_eq!(
col0_stats.max,
Scalar::Number(NumberScalar::Int32(num_of_blocks as i32))
);
let col1_stats = r.get(&1).unwrap();
assert_eq!(
col1_stats.min,
Scalar::Number(NumberScalar::Int32(val_start_with * 2))
);
assert_eq!(
col1_stats.max,
Scalar::Number(NumberScalar::Int32((num_of_blocks * 2) as i32))
);
let col2_stats = r.get(&2).unwrap();
assert_eq!(
col2_stats.min,
Scalar::Number(NumberScalar::Int32(val_start_with * 3))
);
assert_eq!(
col2_stats.max,
Scalar::Number(NumberScalar::Int32((num_of_blocks * 3) as i32))
);
Ok(())
}
#[test]
fn test_reduce_block_statistics_in_memory_size() -> common_exception::Result<()> {
let iter = |mut idx| {
std::iter::from_fn(move || {
idx += 1;
Some((idx, ColumnStatistics {
min: Scalar::Null,
max: Scalar::Null,
null_count: 1,
in_memory_size: 1,
distinct_of_values: Some(1),
}))
})
};
let num_of_cols = 100;
// combine two statistics
let col_stats_left = HashMap::from_iter(iter(0).take(num_of_cols));
let col_stats_right = HashMap::from_iter(iter(0).take(num_of_cols));
let r = reducers::reduce_block_statistics(&[col_stats_left, col_stats_right])?;
assert_eq!(num_of_cols, r.len());
// there should be 100 columns in the result
for idx in 1..=100 {
let col_stats = r.get(&idx);
assert!(col_stats.is_some());
let col_stats = col_stats.unwrap();
// for each column, the reduced value of in_memory_size should be 1 + 1
assert_eq!(col_stats.in_memory_size, 2);
// for each column, the reduced value of null_count should be 1 + 1
assert_eq!(col_stats.null_count, 2);
}
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn test_accumulator() -> common_exception::Result<()> {
let (schema, blocks) = TestFixture::gen_sample_blocks(10, 1);
let mut stats_acc = StatisticsAccumulator::default();
let operator = Operator::new(opendal::services::Memory::default())?.finish();
let loc_generator = TableMetaLocationGenerator::with_prefix("/".to_owned());
for item in blocks {
let block = item?;
let col_stats = gen_columns_statistics(&block, None, &schema)?;
let block_writer = BlockWriter::new(&operator, &loc_generator);
let (block_meta, _index_meta) = block_writer
.write(FuseStorageFormat::Parquet, &schema, block, col_stats, None)
.await?;
stats_acc.add_with_block_meta(block_meta);
}
assert_eq!(10, stats_acc.blocks_statistics.len());
assert!(stats_acc.index_size > 0);
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn test_ft_cluster_stats_with_stats() -> common_exception::Result<()> {
let schema = DataSchemaRefExt::create(vec![DataField::new(
"a",
DataType::Number(NumberDataType::Int32),
)]);
let columns = vec![Int32Type::from_data(vec![1i32, 2, 3])];
let blocks = DataBlock::new_from_columns(columns);
let origin = Some(ClusterStatistics {
cluster_key_id: 0,
min: vec![Scalar::Number(NumberScalar::Int32(1))],
max: vec![Scalar::Number(NumberScalar::Int32(5))],
level: 0,
pages: None,
});
let block_compactor = BlockThresholds::new(1_000_000, 800_000, 100 * 1024 * 1024);
let stats_gen = ClusterStatsGenerator::new(
0,
vec![0],
0,
None,
0,
block_compactor,
vec![],
vec![],
FunctionContext::default(),
);
let stats = stats_gen.gen_with_origin_stats(&blocks, origin.clone())?;
assert!(stats.is_some());
let stats = stats.unwrap();
assert_eq!(vec![Scalar::Number(NumberScalar::Int32(1))], stats.min);
assert_eq!(vec![Scalar::Number(NumberScalar::Int32(3))], stats.max);
// add expression executor.
let expr = RawExpr::FunctionCall {
span: None,
name: "plus".to_string(),
params: vec![],
args: vec![
RawExpr::ColumnRef {
span: None,
id: 0usize,
data_type: schema.field(0).data_type().clone(),
display_name: schema.field(0).name().clone(),
},
RawExpr::Constant {
span: None,
scalar: Scalar::Number(NumberScalar::UInt64(1)),
},
],
};
let expr = check(&expr, &BUILTIN_FUNCTIONS).unwrap();
let operators = vec![BlockOperator::Map { exprs: vec![expr] }];
let stats_gen = ClusterStatsGenerator::new(
0,
vec![1],
0,
None,
0,
block_compactor,
operators,
vec![],
FunctionContext::default(),
);
let stats = stats_gen.gen_with_origin_stats(&blocks, origin.clone())?;
assert!(stats.is_some());
let stats = stats.unwrap();
assert_eq!(vec![Scalar::Number(NumberScalar::Int64(2))], stats.min);
assert_eq!(vec![Scalar::Number(NumberScalar::Int64(4))], stats.max);
// different cluster_key_id.
let stats_gen = ClusterStatsGenerator::new(
1,
vec![0],
0,
None,
0,
block_compactor,
vec![],
vec![],
FunctionContext::default(),
);
let stats = stats_gen.gen_with_origin_stats(&blocks, origin)?;
assert!(stats.is_none());
Ok(())
}
#[test]
fn test_ft_stats_block_stats_string_columns_trimming() -> common_exception::Result<()> {
let suite = || -> common_exception::Result<()> {
// prepare random strings
// 100 string, length ranges from 0 to 100 (chars)
let mut rand_strings: Vec<String> = vec![];
for _ in 0..100 {
let mut rnd = rand::thread_rng();
let rand_string: String = rand::thread_rng()
.sample_iter::<char, _>(rand::distributions::Standard)
.take(rnd.gen_range(0..1000))
.collect();
rand_strings.push(rand_string);
}
let min_expr = rand_strings.iter().min().unwrap();
let max_expr = rand_strings.iter().max().unwrap();
let data_value_min = Scalar::String(min_expr.clone().into_bytes());
let data_value_max = Scalar::String(max_expr.clone().into_bytes());
let trimmed_min = data_value_min.clone().trim_min();
let trimmed_max = data_value_max.clone().trim_max();
let meaningless_to_collect_max = is_degenerated_case(max_expr.as_str());
if meaningless_to_collect_max {
assert!(trimmed_max.is_none());
} else {
assert!(trimmed_max.is_some());
let trimmed = trimmed_max.unwrap().as_string().unwrap().clone();
assert!(char_len(&trimmed) <= STATS_STRING_PREFIX_LEN);
assert!(Scalar::String(trimmed) >= data_value_max)
}
{
assert!(trimmed_min.is_some());
let trimmed = trimmed_min.unwrap().as_string().unwrap().clone();
assert!(char_len(&trimmed) <= STATS_STRING_PREFIX_LEN);
assert!(Scalar::String(trimmed) <= data_value_min);
}
Ok(())
};
// let runs = 0..1000; // use this setting at home
let runs = 0..100;
for _ in runs {
suite()?
}
Ok(())
}
#[test]
fn test_ft_stats_block_stats_string_columns_trimming_using_eval() -> common_exception::Result<()> {
// verifies (randomly) the following assumptions:
//
// https://github.com/datafuselabs/databend/issues/7829
// > ...
// > in a way that preserves the property of min/max statistics:
// > the trimmed max should be larger than the non-trimmed one, and the trimmed min
// > should be lesser than the non-trimmed one.
let suite = || -> common_exception::Result<()> {
// prepare random strings
// 100 string, length ranges from 0 to 100 (chars)
let mut rand_strings: Vec<String> = vec![];
let rows = 100;
for _ in 0..rows {
let mut rnd = rand::thread_rng();
let rand_string: String = rand::thread_rng()
.sample_iter::<char, _>(rand::distributions::Standard)
.take(rnd.gen_range(0..1000))
.collect();
rand_strings.push(rand_string);
}
let schema = Arc::new(TableSchema::new(vec![TableField::new(
"a",
TableDataType::String,
)]));
// build test data block, which has only on column, of String type
let data_col = StringType::from_data(
rand_strings
.iter()
.map(|s| s.as_str())
.collect::<Vec<&str>>(),
);
let block = DataBlock::new_from_columns(vec![data_col.clone()]);
let min_col = eval_aggr("min", vec![], &[data_col.clone()], rows)?;
let max_col = eval_aggr("max", vec![], &[data_col], rows)?;
let min_expr = min_col.0.index(0).unwrap();
let max_expr = max_col.0.index(0).unwrap();
// generate the statistics of column
let stats_of_columns = gen_columns_statistics(&block, None, &schema).unwrap();
// check if the max value (untrimmed) is in degenerated condition:
// - the length of string value is larger or equal than STRING_PREFIX_LEN
// - AND the string has a prefix of length STRING_PREFIX_LEN, for all the char C in prefix,
// C > REPLACEMENT_CHAR; which means we can not replace any of them.
let string_max_expr = String::from_utf8(max_expr.as_string().unwrap().to_vec()).unwrap();
let meaningless_to_collect_max = is_degenerated_case(string_max_expr.as_str());
if meaningless_to_collect_max {
// no stats will be collected
assert!(stats_of_columns.get(&0).is_none())
} else {
// Finally:
// check that, trimmed "col_stats.max" always large than or equal to the untrimmed "max_expr"
let col_stats = stats_of_columns.get(&0).unwrap();
assert!(
col_stats.max >= max_expr.to_owned(),
"left [{}]\nright [{}]",
col_stats.max,
max_expr
);
// check that, trimmed "col_stats.min" always less than or equal to the untrimmed "mn_expr"
assert!(
col_stats.min <= min_expr.to_owned(),
"left [{}]\nright [{}]",
col_stats.min,
min_expr
);
}
Ok(())
};
// let runs = 0..1000; // use this at home
let runs = 0..100;
for _ in runs {
suite()?
}
Ok(())
}
fn is_degenerated_case(value: &str) -> bool {
// check if the value (untrimmed) is in degenerated condition:
// - the length of string value is larger or equal than STRING_PREFIX_LEN
// - AND the string has a prefix of length STRING_PREFIX_LEN, for all the char C in prefix,
// C > REPLACEMENT_CHAR; which means we can not replace any of them.
let larger_than_prefix_len = value.chars().count() > STATS_STRING_PREFIX_LEN;
let prefixed_with_irreplaceable_chars = value
.chars()
.take(STATS_STRING_PREFIX_LEN)
.all(|c| c >= STATS_REPLACEMENT_CHAR);
larger_than_prefix_len && prefixed_with_irreplaceable_chars
}
fn char_len(value: &[u8]) -> usize {
String::from_utf8(value.to_vec())
.unwrap()
.as_str()
.chars()
.count()
}
#[test]
fn test_reduce_block_meta() -> common_exception::Result<()> {
// case 1: empty input should return the default statistics
let block_metas: Vec<BlockMeta> = vec![];
let reduced = reduce_block_metas(&block_metas, BlockThresholds::default())?;
assert_eq!(Statistics::default(), reduced);
// case 2: accumulated variants of size index should be as expected
// reduction of ColumnStatistics, ClusterStatistics already covered by other cases
let mut rng = rand::thread_rng();
let size = 100_u64;
let location = ("".to_owned(), 0);
let mut blocks = vec![];
let mut acc_row_count = 0;
let mut acc_block_size = 0;
let mut acc_file_size = 0;
let mut acc_bloom_filter_index_size = 0;
for _ in 0..size {
let row_count = rng.gen::<u64>() / size;
let block_size = rng.gen::<u64>() / size;
let file_size = rng.gen::<u64>() / size;
let bloom_filter_index_size = rng.gen::<u64>() / size;
acc_row_count += row_count;
acc_block_size += block_size;
acc_file_size += file_size;
acc_bloom_filter_index_size += bloom_filter_index_size;
let block_meta = BlockMeta::new(
row_count,
block_size,
file_size,
HashMap::new(),
HashMap::new(),
None,
location.clone(),
None,
bloom_filter_index_size,
Compression::Lz4Raw,
);
blocks.push(block_meta);
}
let stats = reduce_block_metas(&blocks, BlockThresholds::default())?;
assert_eq!(acc_row_count, stats.row_count);
assert_eq!(acc_block_size, stats.uncompressed_byte_size);
assert_eq!(acc_file_size, stats.compressed_byte_size);
assert_eq!(acc_bloom_filter_index_size, stats.index_size);
Ok(())
}
|
use ash::vk;
use ash::prelude::VkResult;
use super::VkInstance;
use super::VkDevice;
use std::ffi::c_void;
use ash::version::EntryV1_0;
use ash::version::DeviceV1_0;
use ash::version::InstanceV1_0;
pub struct VkSkiaContext {
pub context: skia_safe::gpu::Context
}
impl VkSkiaContext {
pub fn new(instance: &VkInstance, device: &VkDevice) -> Self {
use vk::Handle;
let get_proc = |of| unsafe {
match Self::get_proc(instance, of) {
Some(f) => f as _,
None => {
error!("resolve of {} failed", of.name().to_str().unwrap());
std::ptr::null()
}
}
};
let backend_context = unsafe {
skia_safe::gpu::vk::BackendContext::new(
instance.instance.handle().as_raw() as _,
device.physical_device.as_raw() as _,
device.logical_device.handle().as_raw() as _,
(
device.queues.present_queue.as_raw() as _,
device.queue_family_indices.present_queue_family_index as usize
),
&get_proc,
)
};
let context = skia_safe::gpu::Context::new_vulkan(&backend_context).unwrap();
VkSkiaContext {
context
}
}
pub unsafe fn get_proc(
instance: &VkInstance,
of: skia_safe::gpu::vk::GetProcOf,
) -> Option<unsafe extern "system" fn() -> c_void> {
use vk::Handle;
match of {
skia_safe::gpu::vk::GetProcOf::Instance(instance_proc, name) => {
let ash_instance = vk::Instance::from_raw(instance_proc as _);
instance.entry.get_instance_proc_addr(ash_instance, name)
}
skia_safe::gpu::vk::GetProcOf::Device(device_proc, name) => {
let ash_device = vk::Device::from_raw(device_proc as _);
instance.instance.get_device_proc_addr(ash_device, name)
}
}
}
}
pub struct VkSkiaSurface {
pub device: ash::Device, // This device is owned by VkDevice, not VkSkiaSurface. TODO: Consider using a ref
pub surface: skia_safe::Surface,
pub texture: skia_safe::gpu::BackendTexture,
pub image_view: vk::ImageView,
}
impl VkSkiaSurface {
pub fn get_image_from_skia_texture(texture: &skia_safe::gpu::BackendTexture) -> vk::Image {
unsafe {
std::mem::transmute(texture.vulkan_image_info().unwrap().image)
}
}
pub fn new(device: &VkDevice, context: &mut VkSkiaContext, extent: &vk::Extent2D) -> VkResult<Self> {
let image_info = skia_safe::ImageInfo::new_n32_premul((extent.width as i32, extent.height as i32), None);
let mut surface = skia_safe::Surface::new_render_target(
&mut context.context,
skia_safe::Budgeted::YES,
&image_info,
None,
skia_safe::gpu::SurfaceOrigin::TopLeft,
None,
false,
).unwrap();
let texture = surface.get_backend_texture(skia_safe::surface::BackendHandleAccess::FlushRead).as_ref().unwrap().clone();
let image = Self::get_image_from_skia_texture(&texture);
let skia_tex_image_view_info = vk::ImageViewCreateInfo {
view_type: vk::ImageViewType::TYPE_2D,
format: vk::Format::R8G8B8A8_UNORM,
components: vk::ComponentMapping {
r: vk::ComponentSwizzle::R,
g: vk::ComponentSwizzle::G,
b: vk::ComponentSwizzle::B,
a: vk::ComponentSwizzle::A,
},
subresource_range: vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
level_count: 1,
layer_count: 1,
..Default::default()
},
image,
..Default::default()
};
let image_view = unsafe {
device
.logical_device
.create_image_view(&skia_tex_image_view_info, None)?
};
Ok(VkSkiaSurface {
device: device.logical_device.clone(),
surface,
texture,
image_view,
})
}
/// Creates a sampler appropriate for rendering skia surfaces. We don't create one per surface
/// since one can be shared among all code that renders surfaces
pub fn create_sampler(logical_device: &ash::Device) -> VkResult<vk::Sampler>{
let sampler_info = vk::SamplerCreateInfo::builder()
.mag_filter(vk::Filter::LINEAR)
.min_filter(vk::Filter::LINEAR)
.address_mode_u(vk::SamplerAddressMode::MIRRORED_REPEAT)
.address_mode_v(vk::SamplerAddressMode::MIRRORED_REPEAT)
.address_mode_w(vk::SamplerAddressMode::MIRRORED_REPEAT)
.anisotropy_enable(false)
.max_anisotropy(1.0)
.border_color(vk::BorderColor::FLOAT_OPAQUE_WHITE)
.unnormalized_coordinates(false)
.compare_enable(false)
.compare_op(vk::CompareOp::NEVER)
.mipmap_mode(vk::SamplerMipmapMode::LINEAR)
.mip_lod_bias(0.0)
.min_lod(0.0)
.max_lod(0.0);
unsafe {
logical_device.create_sampler(&sampler_info, None)
}
}
}
impl Drop for VkSkiaSurface {
fn drop(&mut self) {
unsafe {
//self.device.destroy_sampler(self.sampler, None);
self.device.destroy_image_view(self.image_view, None);
}
}
} |
use std::fs::File;
fn main() {
let path = "file_open.rs".to_string();
let f = File::open(&path);
println!("{:?}", f);
}
|
fn main() {
let image_width = 256;
let image_height = 256;
let mut r: f64;
let mut g: f64;
let mut b: f64;
let mut ir: i32;
let mut ig: i32;
let mut ib: i32;
println!("P3\n{} {}\n255\n", image_width, image_height);
for j in (0..image_height).rev() {
for i in 0..image_width {
r = (i as f64) / ((image_width - 1) as f64);
g = (j as f64) / ((image_height - 1) as f64);
b = 0.25;
// println!("Hello, world!");
ir = (r * 255.999) as i32;
ig = (g * 255.999) as i32;
ib = (b * 255.999) as i32;
print!("{} {} {}\n", ir, ig, ib);
}
}
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::VLANTG {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct EMAC_VLANTG_VLR {
bits: u16,
}
impl EMAC_VLANTG_VLR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u16 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _EMAC_VLANTG_VLW<'a> {
w: &'a mut W,
}
impl<'a> _EMAC_VLANTG_VLW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits &= !(65535 << 0);
self.w.bits |= ((value as u32) & 65535) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EMAC_VLANTG_ETVR {
bits: bool,
}
impl EMAC_VLANTG_ETVR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EMAC_VLANTG_ETVW<'a> {
w: &'a mut W,
}
impl<'a> _EMAC_VLANTG_ETVW<'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 &= !(1 << 16);
self.w.bits |= ((value as u32) & 1) << 16;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EMAC_VLANTG_VTIMR {
bits: bool,
}
impl EMAC_VLANTG_VTIMR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EMAC_VLANTG_VTIMW<'a> {
w: &'a mut W,
}
impl<'a> _EMAC_VLANTG_VTIMW<'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 &= !(1 << 17);
self.w.bits |= ((value as u32) & 1) << 17;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EMAC_VLANTG_ESVLR {
bits: bool,
}
impl EMAC_VLANTG_ESVLR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EMAC_VLANTG_ESVLW<'a> {
w: &'a mut W,
}
impl<'a> _EMAC_VLANTG_ESVLW<'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 &= !(1 << 18);
self.w.bits |= ((value as u32) & 1) << 18;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EMAC_VLANTG_VTHMR {
bits: bool,
}
impl EMAC_VLANTG_VTHMR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EMAC_VLANTG_VTHMW<'a> {
w: &'a mut W,
}
impl<'a> _EMAC_VLANTG_VTHMW<'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 &= !(1 << 19);
self.w.bits |= ((value as u32) & 1) << 19;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:15 - VLAN Tag Identifier for Receive Frames"]
#[inline(always)]
pub fn emac_vlantg_vl(&self) -> EMAC_VLANTG_VLR {
let bits = ((self.bits >> 0) & 65535) as u16;
EMAC_VLANTG_VLR { bits }
}
#[doc = "Bit 16 - Enable 12-Bit VLAN Tag Comparison"]
#[inline(always)]
pub fn emac_vlantg_etv(&self) -> EMAC_VLANTG_ETVR {
let bits = ((self.bits >> 16) & 1) != 0;
EMAC_VLANTG_ETVR { bits }
}
#[doc = "Bit 17 - VLAN Tag Inverse Match Enable"]
#[inline(always)]
pub fn emac_vlantg_vtim(&self) -> EMAC_VLANTG_VTIMR {
let bits = ((self.bits >> 17) & 1) != 0;
EMAC_VLANTG_VTIMR { bits }
}
#[doc = "Bit 18 - Enable S-VLAN"]
#[inline(always)]
pub fn emac_vlantg_esvl(&self) -> EMAC_VLANTG_ESVLR {
let bits = ((self.bits >> 18) & 1) != 0;
EMAC_VLANTG_ESVLR { bits }
}
#[doc = "Bit 19 - VLAN Tag Hash Table Match Enable"]
#[inline(always)]
pub fn emac_vlantg_vthm(&self) -> EMAC_VLANTG_VTHMR {
let bits = ((self.bits >> 19) & 1) != 0;
EMAC_VLANTG_VTHMR { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:15 - VLAN Tag Identifier for Receive Frames"]
#[inline(always)]
pub fn emac_vlantg_vl(&mut self) -> _EMAC_VLANTG_VLW {
_EMAC_VLANTG_VLW { w: self }
}
#[doc = "Bit 16 - Enable 12-Bit VLAN Tag Comparison"]
#[inline(always)]
pub fn emac_vlantg_etv(&mut self) -> _EMAC_VLANTG_ETVW {
_EMAC_VLANTG_ETVW { w: self }
}
#[doc = "Bit 17 - VLAN Tag Inverse Match Enable"]
#[inline(always)]
pub fn emac_vlantg_vtim(&mut self) -> _EMAC_VLANTG_VTIMW {
_EMAC_VLANTG_VTIMW { w: self }
}
#[doc = "Bit 18 - Enable S-VLAN"]
#[inline(always)]
pub fn emac_vlantg_esvl(&mut self) -> _EMAC_VLANTG_ESVLW {
_EMAC_VLANTG_ESVLW { w: self }
}
#[doc = "Bit 19 - VLAN Tag Hash Table Match Enable"]
#[inline(always)]
pub fn emac_vlantg_vthm(&mut self) -> _EMAC_VLANTG_VTHMW {
_EMAC_VLANTG_VTHMW { w: self }
}
}
|
use crate::cartridge::SnesCartridge;
use crate::memory::Memory;
pub struct Peripherals {
cartridge: SnesCartridge,
wram: Vec<u8>,
// apu, ppu, controllers
}
const WRAM_SIZE: usize = 128 * 1024;
impl Peripherals {
pub fn new(cartridge: SnesCartridge) -> Peripherals {
let wram = vec![0x0; WRAM_SIZE];
Peripherals {
cartridge: cartridge,
wram: wram,
}
}
fn system_area_read8(&self, bank: u8, offset: u16) -> u8 {
/*
System Area (banks 00h-3Fh and 80h-BFh)
Offset Content Speed
0000h-1FFFh Mirror of 7E0000h-7E1FFFh (first 8Kbyte of WRAM) 2.68MHz
2000h-20FFh Unused 3.58MHz
2100h-21FFh I/O Ports (B-Bus) 3.58MHz
2200h-3FFFh Unused 3.58MHz
4000h-41FFh I/O Ports (manual joypad access) 1.78MHz
4200h-5FFFh I/O Ports 3.58MHz
6000h-7FFFh Expansion 2.68MHz
*/
match (bank, offset) {
_ => panic!("unimplmented read at offset {0:04X}", offset)
}
}
fn system_area_write8(&mut self, bank: u8, offset: u16, data: u8) {
panic!("unimplemented write: {:X}:{:X}", bank, offset)
}
}
// reference: https://problemkaputt.de/fullsnes.htm#snesmemorymap
impl Memory for Peripherals {
// TODO check endianness
fn read8(&self, bank: u8, offset: u16) -> u8 {
match (bank, offset) {
(0x00 ..= 0x3f, 0x0000 ..= 0x1fff) => {
// work ram mirror
self.wram[offset as usize]
},
(0x80 ..= 0xbf, 0x0000 ..= 0x1fff) => {
// work ram mirror
self.wram[offset as usize]
},
(0x7E ..= 0x7F, _) => {
// work ram
let index = (bank as usize - 0x7e) << 16 | offset as usize;
self.wram[index as usize]
}
_ => self.cartridge.read8(bank, offset),
}
}
fn write8(&mut self, bank: u8, offset: u16, data: u8) {
match (bank, offset) {
(0x00 ..= 0x3f, 0x0000 ..= 0x1fff) => {
// work ram mirror
self.wram[offset as usize] = data
},
(0x80 ..= 0xbf, 0x0000 ..= 0x1fff) => {
// work ram mirror
self.wram[offset as usize] = data
},
(0x7E ..= 0x7F, _) => {
// work ram
let index = (bank as usize - 0x7e) << 16 | offset as usize;
self.wram[index as usize] = data
}
(0x00 ..= 0x3f, 0x8000 ..= 0xffff) => {
self.cartridge.write8(bank, offset, data)
},
_ => panic!("Unmapped write {}:{}", bank, offset)
}
}
fn read16(&self, bank: u8, offset: u16) -> u16 {
let low = self.read8(bank, offset) as u16;
let high = self.read8(bank, offset + 1) as u16;
high << 8 | low
}
fn write16(&mut self, bank: u8, offset: u16, data: u16) {
let low = (data & 0xFF) as u8;
let high = (data >> 8) as u8;
self.write8(bank, offset, low);
self.write8(bank, offset + 1, high)
}
}
|
use crate::slice::Shape2D;
use core::ops::{Bound, RangeBounds};
#[inline(always)]
pub fn calc_2d_index<S: Shape2D>(r: usize, c: usize, slice: &S) -> usize {
r * slice.get_base_col() + c
}
pub fn calc_2d_range<B: RangeBounds<usize>>(len: usize, bound: &B) -> (usize, usize) {
(
match bound.start_bound() {
Bound::Included(&i) => i,
Bound::Excluded(&i) => i + 1,
Bound::Unbounded => 0,
},
match bound.end_bound() {
Bound::Included(&i) => i + 1,
Bound::Excluded(&i) => i,
Bound::Unbounded => len,
},
)
}
|
use std::fs::File;
use std::io::Read;
use std::vec::Vec;
#[test]
fn test_info() {
let mut file = File::open("tests/data/rust_dxt5.vtf").unwrap();
let mut buf = Vec::new();
file.read_to_end(&mut buf).unwrap();
let vtf = vtf::from_bytes(&mut buf).unwrap();
assert_eq!(512, vtf.header.width);
assert_eq!(512, vtf.header.height);
assert_eq!(1, vtf.header.frames);
}
#[test]
fn test_write_header() {
let mut file = File::open("tests/data/vtf_74.vtf").unwrap();
let mut buf = Vec::new();
file.read_to_end(&mut buf).unwrap();
let vtf = vtf::from_bytes(&mut buf).unwrap();
let mut written = Vec::new();
vtf.header.write(&mut written).unwrap();
assert_eq!(written.as_slice(), &buf[0..written.len()]);
}
|
use crate::interface::{StakeAccount, YoctoNear};
use near_sdk::json_types::{ValidAccountId, U128};
/// Used to manage user accounts. The main use cases supported by this interface are:
/// 1. Users can register with the contract. Users are required to pay for account storage usage at
/// time of registration. Accounts are required to register in order to use the contract.
/// 2. Users can unregister with the contract. When a user unregisters, the account storage usage fee
/// will be refunded.
/// 3. The total number of registered users is tracked.
/// 4. Users can withdraw unstaked NEAR from STAKE that has been redeemed.
/// 5. User account info can be looked up.
pub trait AccountManagement {
/// Creates and registers a new account for the predecessor account ID.
/// - the account is required to pay for its storage. Storage fees will be escrowed and then refunded
/// when the account is unregistered - use [account_storage_escrow_fee](crate::interface::AccountManagement::account_storage_fee)
/// to lookup the required storage fee amount. Overpayment of storage fee is refunded.
///
/// Gas Requirements: 4.5 TGas
///
/// ## Panics
/// - if deposit is not enough to cover storage usage fees
/// - if account is already registered
fn register_account(&mut self);
/// In order to unregister the account all NEAR must be unstaked and withdrawn from the account.
/// The escrowed storage fee will be refunded to the account.
///
/// Gas Requirements: 8 TGas
///
/// ## Panics
/// - if account is not registered
/// - if registered account has funds
fn unregister_account(&mut self);
/// Returns the required deposit amount that is required for account registration.
///
/// Gas Requirements: 3.5 TGas
fn account_storage_fee(&self) -> YoctoNear;
/// returns true if the account is registered
///
/// Gas Requirements: 4 TGas
fn account_registered(&self, account_id: ValidAccountId) -> bool;
/// returns the total number of accounts that are registered with this contract
fn total_registered_accounts(&self) -> U128;
/// looks up the registered account
///
/// Gas Requirements: 4 TGas
fn lookup_account(&self, account_id: ValidAccountId) -> Option<StakeAccount>;
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Copied from src/ui/bin/brightness_manager
// TODO(fxb/36843) consolidate usages
use std::path::Path;
use std::{fs, io};
use byteorder::{ByteOrder, LittleEndian};
use failure::{self, bail, Error, ResultExt};
use fidl_fuchsia_hardware_input::{
DeviceMarker as SensorMarker, DeviceProxy as SensorProxy, ReportType,
};
use fuchsia_syslog::fx_log_info;
/// Unique signature for the light sensor
const HID_SENSOR_DESCRIPTOR: [u8; 4] = [5, 32, 9, 65];
#[derive(Debug)]
pub struct AmbientLightInputRpt {
pub rpt_id: u8,
pub state: u8,
pub event: u8,
pub illuminance: u16,
pub red: u16,
pub green: u16,
pub blue: u16,
}
/// Opens the sensor's device file.
/// Tries all the input devices until the one with the correct signature is found.
pub async fn open_sensor() -> Result<SensorProxy, Error> {
let input_devices_directory = "/dev/class/input";
let path = Path::new(input_devices_directory);
let entries = fs::read_dir(path)?;
for entry in entries {
let entry = entry?;
let device = open_input_device(entry.path().to_str().expect("Bad path"))?;
if let Ok(device_descriptor) = device.get_report_desc().await {
if device_descriptor.len() < 4 {
bail!("Short HID header");
}
let device_header = &device_descriptor[0..4];
if device_header == HID_SENSOR_DESCRIPTOR {
return Ok(device);
}
}
}
Err(io::Error::new(io::ErrorKind::NotFound, "no sensor found").into())
}
fn open_input_device(path: &str) -> Result<SensorProxy, Error> {
fx_log_info!("Opening sensor at {:?}", path);
let (proxy, server) =
fidl::endpoints::create_proxy::<SensorMarker>().context("Failed to create sensor proxy")?;
fdio::service_connect(path, server.into_channel())
.context("Failed to connect built-in service")?;
Ok(proxy)
}
/// Reads the sensor's HID record and decodes it.
pub async fn read_sensor(sensor: &SensorProxy) -> Result<AmbientLightInputRpt, Error> {
let report = sensor.get_report(ReportType::Input, 1).await?;
let report = report.1;
if report.len() < 11 {
bail!("Sensor HID report too short");
}
Ok(AmbientLightInputRpt {
rpt_id: report[0],
state: report[1],
event: report[2],
illuminance: LittleEndian::read_u16(&report[3..5]),
red: LittleEndian::read_u16(&report[5..7]),
green: LittleEndian::read_u16(&report[7..9]),
blue: LittleEndian::read_u16(&report[9..11]),
})
}
#[cfg(test)]
mod tests {
use super::*;
use fidl_fuchsia_hardware_input::DeviceRequest as SensorRequest;
use fuchsia_async as fasync;
use futures::prelude::*;
#[fuchsia_async::run_singlethreaded(test)]
async fn test_read_sensor() {
let (proxy, mut stream) =
fidl::endpoints::create_proxy_and_stream::<SensorMarker>().unwrap();
fasync::spawn(async move {
while let Some(request) = stream.try_next().await.unwrap() {
if let SensorRequest::GetReport { type_: _, id: _, responder } = request {
// Taken from actual sensor report
let data: [u8; 11] = [1, 1, 0, 25, 0, 10, 0, 9, 0, 6, 0];
responder.send(0, &mut data.iter().cloned()).unwrap();
}
}
});
let result = read_sensor(&proxy).await;
match result {
Ok(input_rpt) => {
assert_eq!(input_rpt.illuminance, 25);
assert_eq!(input_rpt.red, 10);
assert_eq!(input_rpt.green, 9);
assert_eq!(input_rpt.blue, 6);
}
Err(e) => {
panic!("Sensor read failed: {:?}", e);
}
}
}
}
|
#[doc = "Reader of register IER"]
pub type R = crate::R<u32, super::IER>;
#[doc = "Writer for register IER"]
pub type W = crate::W<u32, super::IER>;
#[doc = "Register IER `reset()`'s with value 0"]
impl crate::ResetValue for super::IER {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Injected context queue overflow interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum JQOVFIE_A {
#[doc = "0: Injected context queue overflow interrupt disabled"]
DISABLED = 0,
#[doc = "1: Injected context queue overflow interrupt enabled"]
ENABLED = 1,
}
impl From<JQOVFIE_A> for bool {
#[inline(always)]
fn from(variant: JQOVFIE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `JQOVFIE`"]
pub type JQOVFIE_R = crate::R<bool, JQOVFIE_A>;
impl JQOVFIE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> JQOVFIE_A {
match self.bits {
false => JQOVFIE_A::DISABLED,
true => JQOVFIE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == JQOVFIE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == JQOVFIE_A::ENABLED
}
}
#[doc = "Write proxy for field `JQOVFIE`"]
pub struct JQOVFIE_W<'a> {
w: &'a mut W,
}
impl<'a> JQOVFIE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: JQOVFIE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Injected context queue overflow interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(JQOVFIE_A::DISABLED)
}
#[doc = "Injected context queue overflow interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(JQOVFIE_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 = "Analog watchdog 3 interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AWD3IE_A {
#[doc = "0: Analog watchdog interrupt disabled"]
DISABLED = 0,
#[doc = "1: Analog watchdog interrupt enabled"]
ENABLED = 1,
}
impl From<AWD3IE_A> for bool {
#[inline(always)]
fn from(variant: AWD3IE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `AWD3IE`"]
pub type AWD3IE_R = crate::R<bool, AWD3IE_A>;
impl AWD3IE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> AWD3IE_A {
match self.bits {
false => AWD3IE_A::DISABLED,
true => AWD3IE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == AWD3IE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == AWD3IE_A::ENABLED
}
}
#[doc = "Write proxy for field `AWD3IE`"]
pub struct AWD3IE_W<'a> {
w: &'a mut W,
}
impl<'a> AWD3IE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: AWD3IE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Analog watchdog interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(AWD3IE_A::DISABLED)
}
#[doc = "Analog watchdog interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(AWD3IE_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Analog watchdog 2 interrupt enable"]
pub type AWD2IE_A = AWD3IE_A;
#[doc = "Reader of field `AWD2IE`"]
pub type AWD2IE_R = crate::R<bool, AWD3IE_A>;
#[doc = "Write proxy for field `AWD2IE`"]
pub struct AWD2IE_W<'a> {
w: &'a mut W,
}
impl<'a> AWD2IE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: AWD2IE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Analog watchdog interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(AWD3IE_A::DISABLED)
}
#[doc = "Analog watchdog interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(AWD3IE_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 = "Analog watchdog 1 interrupt enable"]
pub type AWD1IE_A = AWD3IE_A;
#[doc = "Reader of field `AWD1IE`"]
pub type AWD1IE_R = crate::R<bool, AWD3IE_A>;
#[doc = "Write proxy for field `AWD1IE`"]
pub struct AWD1IE_W<'a> {
w: &'a mut W,
}
impl<'a> AWD1IE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: AWD1IE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Analog watchdog interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(AWD3IE_A::DISABLED)
}
#[doc = "Analog watchdog interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(AWD3IE_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 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "End of injected sequence of conversions interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum JEOSIE_A {
#[doc = "0: End of injected sequence interrupt disabled"]
DISABLED = 0,
#[doc = "1: End of injected sequence interrupt enabled"]
ENABLED = 1,
}
impl From<JEOSIE_A> for bool {
#[inline(always)]
fn from(variant: JEOSIE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `JEOSIE`"]
pub type JEOSIE_R = crate::R<bool, JEOSIE_A>;
impl JEOSIE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> JEOSIE_A {
match self.bits {
false => JEOSIE_A::DISABLED,
true => JEOSIE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == JEOSIE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == JEOSIE_A::ENABLED
}
}
#[doc = "Write proxy for field `JEOSIE`"]
pub struct JEOSIE_W<'a> {
w: &'a mut W,
}
impl<'a> JEOSIE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: JEOSIE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "End of injected sequence interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(JEOSIE_A::DISABLED)
}
#[doc = "End of injected sequence interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(JEOSIE_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 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "End of injected conversion interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum JEOCIE_A {
#[doc = "0: End of injected conversion interrupt disabled"]
DISABLED = 0,
#[doc = "1: End of injected conversion interrupt enabled"]
ENABLED = 1,
}
impl From<JEOCIE_A> for bool {
#[inline(always)]
fn from(variant: JEOCIE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `JEOCIE`"]
pub type JEOCIE_R = crate::R<bool, JEOCIE_A>;
impl JEOCIE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> JEOCIE_A {
match self.bits {
false => JEOCIE_A::DISABLED,
true => JEOCIE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == JEOCIE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == JEOCIE_A::ENABLED
}
}
#[doc = "Write proxy for field `JEOCIE`"]
pub struct JEOCIE_W<'a> {
w: &'a mut W,
}
impl<'a> JEOCIE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: JEOCIE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "End of injected conversion interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(JEOCIE_A::DISABLED)
}
#[doc = "End of injected conversion interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(JEOCIE_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 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Overrun interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OVRIE_A {
#[doc = "0: Overrun interrupt disabled"]
DISABLED = 0,
#[doc = "1: Overrun interrupt enabled"]
ENABLED = 1,
}
impl From<OVRIE_A> for bool {
#[inline(always)]
fn from(variant: OVRIE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `OVRIE`"]
pub type OVRIE_R = crate::R<bool, OVRIE_A>;
impl OVRIE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> OVRIE_A {
match self.bits {
false => OVRIE_A::DISABLED,
true => OVRIE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == OVRIE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == OVRIE_A::ENABLED
}
}
#[doc = "Write proxy for field `OVRIE`"]
pub struct OVRIE_W<'a> {
w: &'a mut W,
}
impl<'a> OVRIE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: OVRIE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Overrun interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(OVRIE_A::DISABLED)
}
#[doc = "Overrun interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(OVRIE_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 = "End of regular sequence of conversions interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EOSIE_A {
#[doc = "0: End of regular sequence interrupt disabled"]
DISABLED = 0,
#[doc = "1: End of regular sequence interrupt enabled"]
ENABLED = 1,
}
impl From<EOSIE_A> for bool {
#[inline(always)]
fn from(variant: EOSIE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `EOSIE`"]
pub type EOSIE_R = crate::R<bool, EOSIE_A>;
impl EOSIE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EOSIE_A {
match self.bits {
false => EOSIE_A::DISABLED,
true => EOSIE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EOSIE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == EOSIE_A::ENABLED
}
}
#[doc = "Write proxy for field `EOSIE`"]
pub struct EOSIE_W<'a> {
w: &'a mut W,
}
impl<'a> EOSIE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EOSIE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "End of regular sequence interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(EOSIE_A::DISABLED)
}
#[doc = "End of regular sequence interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(EOSIE_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 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "End of regular conversion interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EOCIE_A {
#[doc = "0: End of regular conversion interrupt disabled"]
DISABLED = 0,
#[doc = "1: End of regular conversion interrupt enabled"]
ENABLED = 1,
}
impl From<EOCIE_A> for bool {
#[inline(always)]
fn from(variant: EOCIE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `EOCIE`"]
pub type EOCIE_R = crate::R<bool, EOCIE_A>;
impl EOCIE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EOCIE_A {
match self.bits {
false => EOCIE_A::DISABLED,
true => EOCIE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EOCIE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == EOCIE_A::ENABLED
}
}
#[doc = "Write proxy for field `EOCIE`"]
pub struct EOCIE_W<'a> {
w: &'a mut W,
}
impl<'a> EOCIE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EOCIE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "End of regular conversion interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(EOCIE_A::DISABLED)
}
#[doc = "End of regular conversion interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(EOCIE_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 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "End of sampling flag interrupt enable for regular conversions\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EOSMPIE_A {
#[doc = "0: End of regular conversion sampling phase interrupt disabled"]
DISABLED = 0,
#[doc = "1: End of regular conversion sampling phase interrupt enabled"]
ENABLED = 1,
}
impl From<EOSMPIE_A> for bool {
#[inline(always)]
fn from(variant: EOSMPIE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `EOSMPIE`"]
pub type EOSMPIE_R = crate::R<bool, EOSMPIE_A>;
impl EOSMPIE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EOSMPIE_A {
match self.bits {
false => EOSMPIE_A::DISABLED,
true => EOSMPIE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EOSMPIE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == EOSMPIE_A::ENABLED
}
}
#[doc = "Write proxy for field `EOSMPIE`"]
pub struct EOSMPIE_W<'a> {
w: &'a mut W,
}
impl<'a> EOSMPIE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EOSMPIE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "End of regular conversion sampling phase interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(EOSMPIE_A::DISABLED)
}
#[doc = "End of regular conversion sampling phase interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(EOSMPIE_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "ADC ready interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ADRDYIE_A {
#[doc = "0: ADC ready interrupt disabled"]
DISABLED = 0,
#[doc = "1: ADC ready interrupt enabled"]
ENABLED = 1,
}
impl From<ADRDYIE_A> for bool {
#[inline(always)]
fn from(variant: ADRDYIE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `ADRDYIE`"]
pub type ADRDYIE_R = crate::R<bool, ADRDYIE_A>;
impl ADRDYIE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ADRDYIE_A {
match self.bits {
false => ADRDYIE_A::DISABLED,
true => ADRDYIE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == ADRDYIE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == ADRDYIE_A::ENABLED
}
}
#[doc = "Write proxy for field `ADRDYIE`"]
pub struct ADRDYIE_W<'a> {
w: &'a mut W,
}
impl<'a> ADRDYIE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ADRDYIE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "ADC ready interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(ADRDYIE_A::DISABLED)
}
#[doc = "ADC ready interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(ADRDYIE_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) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 10 - Injected context queue overflow interrupt enable"]
#[inline(always)]
pub fn jqovfie(&self) -> JQOVFIE_R {
JQOVFIE_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 9 - Analog watchdog 3 interrupt enable"]
#[inline(always)]
pub fn awd3ie(&self) -> AWD3IE_R {
AWD3IE_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 8 - Analog watchdog 2 interrupt enable"]
#[inline(always)]
pub fn awd2ie(&self) -> AWD2IE_R {
AWD2IE_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 7 - Analog watchdog 1 interrupt enable"]
#[inline(always)]
pub fn awd1ie(&self) -> AWD1IE_R {
AWD1IE_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 6 - End of injected sequence of conversions interrupt enable"]
#[inline(always)]
pub fn jeosie(&self) -> JEOSIE_R {
JEOSIE_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 5 - End of injected conversion interrupt enable"]
#[inline(always)]
pub fn jeocie(&self) -> JEOCIE_R {
JEOCIE_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4 - Overrun interrupt enable"]
#[inline(always)]
pub fn ovrie(&self) -> OVRIE_R {
OVRIE_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 3 - End of regular sequence of conversions interrupt enable"]
#[inline(always)]
pub fn eosie(&self) -> EOSIE_R {
EOSIE_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 2 - End of regular conversion interrupt enable"]
#[inline(always)]
pub fn eocie(&self) -> EOCIE_R {
EOCIE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1 - End of sampling flag interrupt enable for regular conversions"]
#[inline(always)]
pub fn eosmpie(&self) -> EOSMPIE_R {
EOSMPIE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - ADC ready interrupt enable"]
#[inline(always)]
pub fn adrdyie(&self) -> ADRDYIE_R {
ADRDYIE_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 10 - Injected context queue overflow interrupt enable"]
#[inline(always)]
pub fn jqovfie(&mut self) -> JQOVFIE_W {
JQOVFIE_W { w: self }
}
#[doc = "Bit 9 - Analog watchdog 3 interrupt enable"]
#[inline(always)]
pub fn awd3ie(&mut self) -> AWD3IE_W {
AWD3IE_W { w: self }
}
#[doc = "Bit 8 - Analog watchdog 2 interrupt enable"]
#[inline(always)]
pub fn awd2ie(&mut self) -> AWD2IE_W {
AWD2IE_W { w: self }
}
#[doc = "Bit 7 - Analog watchdog 1 interrupt enable"]
#[inline(always)]
pub fn awd1ie(&mut self) -> AWD1IE_W {
AWD1IE_W { w: self }
}
#[doc = "Bit 6 - End of injected sequence of conversions interrupt enable"]
#[inline(always)]
pub fn jeosie(&mut self) -> JEOSIE_W {
JEOSIE_W { w: self }
}
#[doc = "Bit 5 - End of injected conversion interrupt enable"]
#[inline(always)]
pub fn jeocie(&mut self) -> JEOCIE_W {
JEOCIE_W { w: self }
}
#[doc = "Bit 4 - Overrun interrupt enable"]
#[inline(always)]
pub fn ovrie(&mut self) -> OVRIE_W {
OVRIE_W { w: self }
}
#[doc = "Bit 3 - End of regular sequence of conversions interrupt enable"]
#[inline(always)]
pub fn eosie(&mut self) -> EOSIE_W {
EOSIE_W { w: self }
}
#[doc = "Bit 2 - End of regular conversion interrupt enable"]
#[inline(always)]
pub fn eocie(&mut self) -> EOCIE_W {
EOCIE_W { w: self }
}
#[doc = "Bit 1 - End of sampling flag interrupt enable for regular conversions"]
#[inline(always)]
pub fn eosmpie(&mut self) -> EOSMPIE_W {
EOSMPIE_W { w: self }
}
#[doc = "Bit 0 - ADC ready interrupt enable"]
#[inline(always)]
pub fn adrdyie(&mut self) -> ADRDYIE_W {
ADRDYIE_W { w: self }
}
}
|
use bstr::ByteSlice;
use std::io::{self, Read};
use std::ops::Range;
use memchr::memchr;
use thiserror::Error;
use crate::object::ParseIdError;
use crate::reference::{Direct, ReferenceTarget, Symbolic};
const SYMBOLIC_PREFIX: &[u8] = b"ref: ";
const INVALID_REFERENCE_START: &[u8] = b"\n #";
pub struct Parser<R> {
buffer: Vec<u8>,
pos: usize,
reader: R,
}
#[derive(Debug, Error)]
pub enum ParseError {
#[error("reference size is too large")]
InvalidLength,
#[error("no reference data found")]
Empty,
#[error("no symbolic reference found")]
EmptySymbolic,
#[error("reference data was invalid")]
InvalidReference,
#[error("peel object id was invalid")]
InvalidPeelIdentifier,
#[error("direct reference object id was invalid")]
InvalidDirectIdentifier(
#[from]
#[source]
ParseIdError,
),
#[error("io error reading reference")]
Io(
#[from]
#[source]
io::Error,
),
}
impl<R: Read> Parser<R> {
pub fn new(reader: R) -> Self {
Parser {
buffer: Vec::new(),
reader,
pos: 0,
}
}
pub fn finished(&self) -> bool {
self.remaining_buffer().is_empty()
}
fn remaining_buffer(&self) -> &[u8] {
&self.buffer[self.pos..]
}
pub fn parse(mut self) -> Result<ReferenceTarget, ParseError> {
self.reader
.read_to_end(&mut self.buffer)
.map_err(ParseError::Io)?;
let range = self
.read_until_valid_reference_line()?
.ok_or_else(|| ParseError::Empty)?;
let mut line = &self.buffer[range];
if line.starts_with(SYMBOLIC_PREFIX) {
line = &line[SYMBOLIC_PREFIX.len()..];
}
let peel = match memchr(b' ', line) {
Some(ch_pos) => {
let p = line[..ch_pos].trim_end();
line = &line[(ch_pos + 1)..];
Some(p)
}
None => None,
};
let target = match memchr(b'/', line) {
Some(_) => ReferenceTarget::Symbolic(Symbolic::from_bytes(&line.trim_end(), peel)?),
None => ReferenceTarget::Direct(Direct::from_bytes(&line.trim_end())?),
};
Ok(target)
}
pub fn read_until_valid_reference_line(&mut self) -> Result<Option<Range<usize>>, ParseError> {
while !self.finished() {
let start = self.pos;
self.pos = match self.consume_until(b'\n') {
Some(_) => self.pos,
None => self.buffer.len(),
};
if self.reference_line_is_valid(&self.buffer[start..self.pos]) {
return Ok(Some(start..self.pos));
}
}
Ok(None)
}
pub fn reference_line_is_valid(&self, bytes: &[u8]) -> bool {
!INVALID_REFERENCE_START.contains(&bytes[0])
}
pub fn consume_until(&mut self, ch: u8) -> Option<&[u8]> {
match memchr(ch, self.remaining_buffer()) {
Some(ch_pos) => {
let result = &self.buffer[self.pos..][..ch_pos];
self.pos += ch_pos + 1;
Some(result)
}
None => None,
}
}
}
#[cfg(test)]
mod tests {
use super::{ParseError, Parser};
use crate::object::ParseIdError;
use crate::reference::{Direct, ReferenceTarget, Symbolic};
use proptest::prelude::*;
use proptest::{arbitrary::any, collection::vec, proptest};
use std::io;
fn parse_ref(bytes: &[u8]) -> Result<ReferenceTarget, ParseError> {
Parser::new(io::Cursor::new(bytes)).parse()
}
macro_rules! assert_display_eq {
($lhs:expr, $rhs:expr) => {
assert_eq!(format!("{}", $lhs), format!("{}", $rhs));
};
}
#[test]
fn test_parse_symbolic_reference_directory_format() {
assert_eq!(
parse_ref(b"ref: refs/heads/master").unwrap(),
ReferenceTarget::Symbolic(Symbolic::from_bytes(b"refs/heads/master", None).unwrap())
);
}
#[test]
fn test_parse_symbolic_reference_packed_format() {
assert_eq!(
parse_ref(b"da1a5d18c0ab0c03b20fdd91581bc90acd10d512 refs/remotes/origin/master")
.unwrap(),
ReferenceTarget::Symbolic(
Symbolic::from_bytes(
b"refs/remotes/origin/master",
Some(b"da1a5d18c0ab0c03b20fdd91581bc90acd10d512")
)
.unwrap()
)
);
}
#[test]
fn test_parse_skips_commented_lines() {
assert_eq!(
parse_ref(b"# pack-refs with: peeled fully-peeled sorted\nda1a5d18c0ab0c03b20fdd91581bc90acd10d512 refs/remotes/origin/master").unwrap(),
ReferenceTarget::Symbolic(
Symbolic::from_bytes(
b"refs/remotes/origin/master",
Some(b"da1a5d18c0ab0c03b20fdd91581bc90acd10d512")
)
.unwrap()
)
);
}
#[test]
fn test_parse_direct_reference_directory_format() {
assert_eq!(
parse_ref(b"dbaac6ca0b9ec8ff358224e7808cd5a21395b88c").unwrap(),
ReferenceTarget::Direct(
Direct::from_bytes(b"dbaac6ca0b9ec8ff358224e7808cd5a21395b88c").unwrap()
)
);
}
#[test]
fn test_parse_fails_on_empty_input() {
assert_display_eq!(ParseError::Empty, parse_ref(b"").err().unwrap());
assert_display_eq!(ParseError::Empty, parse_ref(b" ").err().unwrap());
assert_display_eq!(ParseError::Empty, parse_ref(b"\n").err().unwrap());
assert_display_eq!(ParseError::Empty, parse_ref(b"# stuff").err().unwrap());
assert_display_eq!(
ParseError::Empty,
parse_ref(b"\n\n# stuff\n\n").err().unwrap()
);
}
#[test]
fn test_parse_fails_on_bad_identifiers() {
assert_display_eq!(
ParseError::InvalidDirectIdentifier(ParseIdError::TooShort),
parse_ref(b"badid").err().unwrap()
);
assert_display_eq!(
ParseError::InvalidDirectIdentifier(ParseIdError::TooLong),
parse_ref(b"01234567890123456789012345678901234567890123456789")
.err()
.unwrap()
);
assert_display_eq!(
ParseError::InvalidDirectIdentifier(ParseIdError::TooShort),
parse_ref(b"badid ref").err().unwrap()
);
}
proptest! {
#![proptest_config(ProptestConfig {
cases: 10000, .. ProptestConfig::default()
})]
#[test]
fn randomized_data_does_not_panic(bytes in vec(any::<u8>(), ..200)) {
parse_ref(&bytes).ok();
}
}
}
|
fn main() {
let s = "u͔n͈̰̎i̙̮͚̦c͚̉o̼̩̰͗d͔̆̓ͥé";
for g in s.graphemes(true) {
println!("{}", g);
}
for c in s.chars() {
println!("{}", c);
}
for b in s.bytes() {
println!("{}", b);
}
}
|
pub mod object;
pub mod reference;
pub mod repository;
pub(crate) mod parse;
|
use crate::prelude::*;
/// Used to fuse the chained systems, such that one doesn't get a compilation
/// error even though the result of the last system isn't used.
///
/// As [SystemStage] requires that the system-chain ends with unit-type `()`
/// we have to use this to fuse the chain.
///
/// Author: @TheRuwuMeatball
pub fn dispose<T>(_: In<T>) {}
|
use crate::level_manager::Level;
#[derive(Clone, Deserialize)]
pub struct LevelManagerSettings {
pub levels: Vec<LevelSettings>,
pub description_text_color: [f32; 4],
pub locked_description_text_color: [f32; 4],
pub default_locked_description: String,
pub default_locked_text_color: [f32; 4],
}
#[derive(Clone, Deserialize)]
pub struct LevelSettings {
pub level: Level,
pub filename: String,
pub win_text: String,
pub description: String,
pub locked_description: Option<String>,
pub initially_locked: bool,
pub unlocked_by_any: Option<Vec<Level>>,
pub locked_text_color: Option<[f32; 4]>,
}
impl LevelManagerSettings {
pub fn level(&self, target: &Level) -> &LevelSettings {
self.levels
.iter()
.find(|level| &level.level == target)
.expect(&format!("Level {} should exist in settings", target))
}
}
|
#![allow(unused_imports)]
use std::io::prelude::*;
use std::path::Path;
use proconio::source::auto::AutoSource;
use std::fs;
use std::fs::File;
use std::io::Write;
const NEEDLE: &'static str = "/**===============**/";
mod solve;
use solve::main as solve;
fn read_file(input: &str) -> String {
let path = Path::new(&input);
let mut v = File::open(path).unwrap();
let mut s = String::new();
v.read_to_string(&mut s).unwrap();
s
}
fn main() {
let s = read_file("./input.txt");
let standard_inputs = s
.split(NEEDLE)
.map(|v| v.trim())
.filter(|v| !v.is_empty())
.collect::<Vec<_>>();
for s in standard_inputs {
let source = AutoSource::from(s);
solve(source);
println!(
"
============================================",
)
}
let s = read_file("./src/solve.rs");
let s = s
.split("\n")
.filter(|v| v.find("NEED TO BE COMMENT OUT WHEN SUBMIT").is_none())
.collect::<Vec<_>>()
.join("\n");
let mut file = File::create("./output/solution.rs").unwrap();
file.write_all(s.as_bytes()).unwrap();
}
|
use std::collections::HashMap;
use std::fmt::Debug;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use crate::signals::collections::Hook;
use crate::vars::mangle;
use anyhow::Result;
use async_trait::async_trait;
use fluent_langneg::{negotiate_languages, NegotiationStrategy};
use serde::Serialize;
use unic_langid::LanguageIdentifier;
#[cfg(not(feature = "devel_rasa_nlu"))]
mod snips;
#[cfg(not(feature = "devel_rasa_nlu"))]
pub use self::snips::*;
#[cfg(feature = "devel_rasa_nlu")]
mod rasa;
#[cfg(feature = "devel_rasa_nlu")]
pub use self::rasa::*;
pub trait NluManager {
type NluType: Nlu + Debug + Send;
fn ready_lang(&mut self, lang: &LanguageIdentifier) -> Result<()>;
fn add_intent(&mut self, order_name: &str, phrases: Vec<NluUtterance>);
fn add_entity(&mut self, name: String, def: EntityDef);
fn add_entity_value(&mut self, name: &str, value: String) -> Result<()>;
// Consume the struct so that we can reuse memory
fn train(
&self,
train_set_path: &Path,
engine_path: &Path,
lang: &LanguageIdentifier,
) -> Result<Self::NluType>;
}
pub trait NluManagerStatic {
fn new() -> Self;
fn list_compatible_langs() -> Vec<LanguageIdentifier>;
fn is_lang_compatible(lang: &LanguageIdentifier) -> bool {
!negotiate_languages(
&[lang],
&Self::list_compatible_langs(),
None,
NegotiationStrategy::Filtering,
)
.is_empty()
}
fn name() -> &'static str;
fn get_paths() -> (PathBuf, PathBuf);
}
#[derive(Clone, Debug)]
pub enum NluUtterance {
Direct(String),
WithEntities {
text: String,
entities: HashMap<String, EntityInstance>,
},
}
#[async_trait(?Send)]
pub trait Nlu {
async fn parse(&self, input: &str) -> Result<NluResponse>;
}
#[derive(Clone, Debug)]
pub struct EntityInstance {
pub kind: String,
pub example: String,
}
#[derive(Clone, Debug, Serialize)]
pub struct EntityData {
pub value: String,
#[serde(default)]
pub synonyms: Vec<String>,
}
#[derive(Clone, Debug)]
pub struct EntityDef {
pub data: Vec<EntityData>,
pub automatically_extensible: bool,
}
impl EntityDef {
pub fn new(data: Vec<EntityData>, automatically_extensible: bool) -> Self {
Self {
data,
automatically_extensible,
}
}
}
#[derive(Debug, Clone)]
pub enum OrderKind {
Ref(String),
Def(EntityDef),
}
#[derive(Clone, Debug)]
pub struct IntentData {
pub utts: Vec<String>,
pub slots: HashMap<String, SlotData>,
pub hook: Hook,
}
impl IntentData {
pub fn into_utterances(self, skill_name: &str) -> Vec<NluUtterance> {
let mut slots_res: HashMap<String, EntityInstance> = HashMap::new();
for (slot_name, slot_data) in self.slots.iter() {
// Handle that slot types might be defined on the spot
let (ent_kind_name, example): (_, String) = match slot_data.slot_type.clone() {
OrderKind::Ref(name) => (name, "".into()),
OrderKind::Def(def) => {
let name = mangle(skill_name, slot_name);
let example = def
.data
.first()
.as_ref()
.map(|d| d.value.clone())
.unwrap_or_else(||"".into());
(name, example)
}
};
slots_res.insert(
slot_name.to_string(),
EntityInstance {
kind: ent_kind_name,
example,
},
);
}
self.utts
.into_iter()
.map(|utt| {
if slots_res.is_empty() {
NluUtterance::Direct(utt)
} else {
NluUtterance::WithEntities {
text: utt,
entities: slots_res.clone(),
}
}
})
.collect()
}
}
#[derive(Clone, Debug)]
pub struct SlotData {
pub slot_type: OrderKind,
pub required: bool,
// In case this slot is not present in the user response but is required
// have a way of automatically asking for it
pub prompt: Option<String>,
// Second chance for asking the user for this slot
pub reprompt: Option<String>,
}
#[derive(Debug)]
pub struct NluResponse {
pub name: Option<String>,
pub confidence: f32,
pub slots: Vec<NluResponseSlot>,
}
#[derive(Debug)]
pub struct NluResponseSlot {
pub value: String,
pub name: String,
}
pub fn try_open_file_and_check(
path: &Path,
new_contents: &str,
) -> Result<Option<std::fs::File>, std::io::Error> {
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(path);
if let Ok(mut file) = file {
let mut old_file: String = String::new();
file.read_to_string(&mut old_file)?;
if old_file != new_contents {
Ok(Some(file))
} else {
Ok(None)
}
} else {
if let Some(path_parent) = path.parent() {
std::fs::create_dir_all(path_parent)?;
}
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(path)?;
Ok(Some(file))
}
}
pub fn write_contents(file: &mut File, contents: &str) -> Result<()> {
file.set_len(0)?; // Truncate file
file.seek(SeekFrom::Start(0))?; // Start from the start
file.write_all(contents[..].as_bytes())?;
file.sync_all()?;
Ok(())
}
pub fn compare_sets_and_train<F: FnOnce()>(
train_set_path: &Path,
train_set: &str,
engine_path: &Path,
callback: F,
) -> Result<()> {
if let Some(mut train_file) = try_open_file_and_check(train_set_path, train_set)? {
// Create parents
if let Some(path_parent) = engine_path.parent() {
std::fs::create_dir_all(path_parent)?;
}
// Clean engine folder
if engine_path.is_dir() {
std::fs::remove_dir_all(engine_path)?;
}
// Write train file
write_contents(&mut train_file, train_set)?;
// Train engine
callback();
}
Ok(())
}
|
#[doc = "Reader of register RTSR2"]
pub type R = crate::R<u32, super::RTSR2>;
#[doc = "Writer for register RTSR2"]
pub type W = crate::W<u32, super::RTSR2>;
#[doc = "Register RTSR2 `reset()`'s with value 0"]
impl crate::ResetValue for super::RTSR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Rising trigger event configuration bit of line 32\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RT32_A {
#[doc = "0: Rising edge trigger is disabled"]
DISABLED = 0,
#[doc = "1: Rising edge trigger is enabled"]
ENABLED = 1,
}
impl From<RT32_A> for bool {
#[inline(always)]
fn from(variant: RT32_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `RT32`"]
pub type RT32_R = crate::R<bool, RT32_A>;
impl RT32_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RT32_A {
match self.bits {
false => RT32_A::DISABLED,
true => RT32_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == RT32_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == RT32_A::ENABLED
}
}
#[doc = "Write proxy for field `RT32`"]
pub struct RT32_W<'a> {
w: &'a mut W,
}
impl<'a> RT32_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RT32_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Rising edge trigger is disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(RT32_A::DISABLED)
}
#[doc = "Rising edge trigger is enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(RT32_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) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Rising trigger event configuration bit of line 32"]
pub type RT33_A = RT32_A;
#[doc = "Reader of field `RT33`"]
pub type RT33_R = crate::R<bool, RT32_A>;
#[doc = "Write proxy for field `RT33`"]
pub struct RT33_W<'a> {
w: &'a mut W,
}
impl<'a> RT33_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RT33_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Rising edge trigger is disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(RT32_A::DISABLED)
}
#[doc = "Rising edge trigger is enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(RT32_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Rising trigger event configuration bit of line 40"]
pub type RT40_A = RT32_A;
#[doc = "Reader of field `RT40`"]
pub type RT40_R = crate::R<bool, RT32_A>;
#[doc = "Write proxy for field `RT40`"]
pub struct RT40_W<'a> {
w: &'a mut W,
}
impl<'a> RT40_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RT40_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Rising edge trigger is disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(RT32_A::DISABLED)
}
#[doc = "Rising edge trigger is enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(RT32_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 = "Rising trigger event configuration bit of line 41"]
pub type RT41_A = RT32_A;
#[doc = "Reader of field `RT41`"]
pub type RT41_R = crate::R<bool, RT32_A>;
#[doc = "Write proxy for field `RT41`"]
pub struct RT41_W<'a> {
w: &'a mut W,
}
impl<'a> RT41_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RT41_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Rising edge trigger is disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(RT32_A::DISABLED)
}
#[doc = "Rising edge trigger is enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(RT32_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
impl R {
#[doc = "Bit 0 - Rising trigger event configuration bit of line 32"]
#[inline(always)]
pub fn rt32(&self) -> RT32_R {
RT32_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Rising trigger event configuration bit of line 32"]
#[inline(always)]
pub fn rt33(&self) -> RT33_R {
RT33_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 8 - Rising trigger event configuration bit of line 40"]
#[inline(always)]
pub fn rt40(&self) -> RT40_R {
RT40_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - Rising trigger event configuration bit of line 41"]
#[inline(always)]
pub fn rt41(&self) -> RT41_R {
RT41_R::new(((self.bits >> 9) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Rising trigger event configuration bit of line 32"]
#[inline(always)]
pub fn rt32(&mut self) -> RT32_W {
RT32_W { w: self }
}
#[doc = "Bit 1 - Rising trigger event configuration bit of line 32"]
#[inline(always)]
pub fn rt33(&mut self) -> RT33_W {
RT33_W { w: self }
}
#[doc = "Bit 8 - Rising trigger event configuration bit of line 40"]
#[inline(always)]
pub fn rt40(&mut self) -> RT40_W {
RT40_W { w: self }
}
#[doc = "Bit 9 - Rising trigger event configuration bit of line 41"]
#[inline(always)]
pub fn rt41(&mut self) -> RT41_W {
RT41_W { w: self }
}
}
|
fn main() {
windows::core::build_legacy! {
Windows::Win32::Globalization::{SetThreadPreferredUILanguages, MUI_LANGUAGE_NAME},
};
}
|
#[eosio::action]
fn hi(name: eosio::AccountName) {
eosio_cdt::print!("Hello, ", name, "!");
}
eosio_cdt::abi!(hi);
|
use log::*;
use morgan_interface::account::KeyedAccount;
use morgan_interface::instruction::InstructionError;
use morgan_interface::pubkey::Pubkey;
use morgan_interface::system_instruction::{SystemError, SystemInstruction};
use morgan_interface::system_program;
const FROM_ACCOUNT_INDEX: usize = 0;
const TO_ACCOUNT_INDEX: usize = 1;
fn create_system_account(
keyed_accounts: &mut [KeyedAccount],
difs: u64,
reputations: u64,
space: u64,
program_id: &Pubkey,
) -> Result<(), SystemError> {
if !system_program::check_id(&keyed_accounts[FROM_ACCOUNT_INDEX].account.owner) {
debug!("CreateAccount: invalid account[from] owner");
Err(SystemError::SourceNotSystemAccount)?;
}
if !keyed_accounts[TO_ACCOUNT_INDEX].account.data.is_empty()
|| !system_program::check_id(&keyed_accounts[TO_ACCOUNT_INDEX].account.owner)
{
debug!(
"CreateAccount: invalid argument; account {} already in use",
keyed_accounts[TO_ACCOUNT_INDEX].unsigned_key()
);
Err(SystemError::AccountAlreadyInUse)?;
}
if difs > keyed_accounts[FROM_ACCOUNT_INDEX].account.difs {
debug!(
"CreateAccount: insufficient difs ({}, need {})",
keyed_accounts[FROM_ACCOUNT_INDEX].account.difs, difs
);
Err(SystemError::ResultWithNegativeDifs)?;
}
keyed_accounts[FROM_ACCOUNT_INDEX].account.difs -= difs;
keyed_accounts[TO_ACCOUNT_INDEX].account.difs += difs;
keyed_accounts[TO_ACCOUNT_INDEX].account.reputations += reputations;
keyed_accounts[TO_ACCOUNT_INDEX].account.owner = *program_id;
keyed_accounts[TO_ACCOUNT_INDEX].account.data = vec![0; space as usize];
keyed_accounts[TO_ACCOUNT_INDEX].account.executable = false;
Ok(())
}
fn create_system_account_with_reputation(
keyed_accounts: &mut [KeyedAccount],
reputations: u64,
space: u64,
program_id: &Pubkey,
) -> Result<(), SystemError> {
if !system_program::check_id(&keyed_accounts[FROM_ACCOUNT_INDEX].account.owner) {
debug!("CreateAccount: invalid account[from] owner");
Err(SystemError::SourceNotSystemAccount)?;
}
if !keyed_accounts[TO_ACCOUNT_INDEX].account.data.is_empty()
|| !system_program::check_id(&keyed_accounts[TO_ACCOUNT_INDEX].account.owner)
{
debug!(
"CreateAccount: invalid argument; account {} already in use",
keyed_accounts[TO_ACCOUNT_INDEX].unsigned_key()
);
Err(SystemError::AccountAlreadyInUse)?;
}
if 1 > keyed_accounts[FROM_ACCOUNT_INDEX].account.difs {
debug!(
"CreateAccount: insufficient difs ({}, need {})",
keyed_accounts[FROM_ACCOUNT_INDEX].account.difs, 1
);
Err(SystemError::ResultWithNegativeDifs)?;
}
keyed_accounts[FROM_ACCOUNT_INDEX].account.difs -= 1;
keyed_accounts[TO_ACCOUNT_INDEX].account.difs += 1;
keyed_accounts[TO_ACCOUNT_INDEX].account.reputations += reputations;
keyed_accounts[TO_ACCOUNT_INDEX].account.owner = *program_id;
keyed_accounts[TO_ACCOUNT_INDEX].account.data = vec![0; space as usize];
keyed_accounts[TO_ACCOUNT_INDEX].account.executable = false;
Ok(())
}
fn assign_account_to_program(
keyed_accounts: &mut [KeyedAccount],
program_id: &Pubkey,
) -> Result<(), SystemError> {
keyed_accounts[FROM_ACCOUNT_INDEX].account.owner = *program_id;
Ok(())
}
fn transfer_difs(
keyed_accounts: &mut [KeyedAccount],
difs: u64,
) -> Result<(), SystemError> {
if difs > keyed_accounts[FROM_ACCOUNT_INDEX].account.difs {
debug!(
"Transfer: insufficient difs ({}, need {})",
keyed_accounts[FROM_ACCOUNT_INDEX].account.difs, difs
);
Err(SystemError::ResultWithNegativeDifs)?;
}
keyed_accounts[FROM_ACCOUNT_INDEX].account.difs -= difs;
keyed_accounts[TO_ACCOUNT_INDEX].account.difs += difs;
Ok(())
}
fn transfer_reputations(
keyed_accounts: &mut [KeyedAccount],
reputations: u64,
) -> Result<(), SystemError> {
if reputations > keyed_accounts[FROM_ACCOUNT_INDEX].account.reputations {
debug!(
"Transfer: insufficient reputations ({}, need {})",
keyed_accounts[FROM_ACCOUNT_INDEX].account.reputations, reputations
);
Err(SystemError::ResultWithNegativeReputations)?;
}
keyed_accounts[FROM_ACCOUNT_INDEX].account.reputations -= reputations;
keyed_accounts[TO_ACCOUNT_INDEX].account.reputations += reputations;
Ok(())
}
pub fn process_instruction(
_program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
_tick_height: u64,
) -> Result<(), InstructionError> {
if let Ok(instruction) = bincode::deserialize(data) {
trace!("process_instruction: {:?}", instruction);
trace!("keyed_accounts: {:?}", keyed_accounts);
// All system instructions require that accounts_keys[0] be a signer
if keyed_accounts[FROM_ACCOUNT_INDEX].signer_key().is_none() {
debug!("account[from] is unsigned");
Err(InstructionError::MissingRequiredSignature)?;
}
match instruction {
SystemInstruction::CreateAccount {
difs,
reputations,
space,
program_id,
} => create_system_account(keyed_accounts, difs, reputations, space, &program_id),
SystemInstruction::CreateAccountWithReputation {
reputations,
space,
program_id,
} => create_system_account_with_reputation(keyed_accounts, reputations, space, &program_id),
SystemInstruction::Assign { program_id } => {
if !system_program::check_id(&keyed_accounts[FROM_ACCOUNT_INDEX].account.owner) {
Err(InstructionError::IncorrectProgramId)?;
}
assign_account_to_program(keyed_accounts, &program_id)
}
SystemInstruction::Transfer { difs } => transfer_difs(keyed_accounts, difs),
SystemInstruction::TransferReputations { reputations } => transfer_reputations(keyed_accounts, reputations),
}
.map_err(|e| InstructionError::CustomError(e as u32))
} else {
debug!("Invalid instruction data: {:?}", data);
Err(InstructionError::InvalidInstructionData)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bank::Bank;
use crate::bank_client::BankClient;
use bincode::serialize;
use morgan_interface::account::Account;
use morgan_interface::client::SyncClient;
use morgan_interface::genesis_block::create_genesis_block;
use morgan_interface::instruction::{AccountMeta, Instruction, InstructionError};
use morgan_interface::signature::{Keypair, KeypairUtil};
use morgan_interface::system_program;
use morgan_interface::transaction::TransactionError;
#[test]
fn test_create_system_account() {
let new_program_owner = Pubkey::new(&[9; 32]);
let from = Pubkey::new_rand();
let mut from_account = Account::new(100, 0, 0, &system_program::id());
let to = Pubkey::new_rand();
let mut to_account = Account::new(0, 0, 0, &Pubkey::default());
let mut keyed_accounts = [
KeyedAccount::new(&from, true, &mut from_account),
KeyedAccount::new(&to, false, &mut to_account),
];
create_system_account(&mut keyed_accounts, 50, 0, 2, &new_program_owner).unwrap();
let from_difs = from_account.difs;
let to_difs = to_account.difs;
let to_reputations = to_account.reputations;
let to_owner = to_account.owner;
let to_data = to_account.data.clone();
assert_eq!(from_difs, 50);
assert_eq!(to_difs, 50);
assert_eq!(to_reputations, 0);
assert_eq!(to_owner, new_program_owner);
assert_eq!(to_data, [0, 0]);
}
#[test]
fn test_create_system_account_with_reputation() {
let new_program_owner = Pubkey::new(&[9; 32]);
let from = Pubkey::new_rand();
let mut from_account = Account::new(2, 100, 0, &system_program::id());
let to = Pubkey::new_rand();
let mut to_account = Account::new(0, 0, 0, &Pubkey::default());
let mut keyed_accounts = [
KeyedAccount::new(&from, true, &mut from_account),
KeyedAccount::new(&to, false, &mut to_account),
];
create_system_account_with_reputation(&mut keyed_accounts, 50, 2, &new_program_owner).unwrap();
let from_reputations = from_account.reputations;
let to_reputations = to_account.reputations;
let to_owner = to_account.owner;
let to_data = to_account.data.clone();
assert_eq!(from_reputations, 100);
assert_eq!(to_reputations, 50);
assert_eq!(to_owner, new_program_owner);
assert_eq!(to_data, [0, 0]);
}
#[test]
fn test_create_negative_difs() {
// Attempt to create account with more difs than remaining in from_account
let new_program_owner = Pubkey::new(&[9; 32]);
let from = Pubkey::new_rand();
let mut from_account = Account::new(100, 0, 0, &system_program::id());
let to = Pubkey::new_rand();
let mut to_account = Account::new(0, 0, 0, &Pubkey::default());
let unchanged_account = to_account.clone();
let mut keyed_accounts = [
KeyedAccount::new(&from, true, &mut from_account),
KeyedAccount::new(&to, false, &mut to_account),
];
let result = create_system_account(&mut keyed_accounts, 150, 0, 2, &new_program_owner);
assert_eq!(result, Err(SystemError::ResultWithNegativeDifs));
let from_difs = from_account.difs;
assert_eq!(from_difs, 100);
assert_eq!(to_account, unchanged_account);
}
#[test]
fn test_create_negative_reputations() {
// Attempt to create account with more reputations than remaining in from_account
let new_program_owner = Pubkey::new(&[9; 32]);
let from = Pubkey::new_rand();
let mut from_account = Account::new(0, 100, 0, &system_program::id());
let to = Pubkey::new_rand();
let mut to_account = Account::new(0, 0, 0, &Pubkey::default());
let unchanged_account = to_account.clone();
let mut keyed_accounts = [
KeyedAccount::new(&from, true, &mut from_account),
KeyedAccount::new(&to, false, &mut to_account),
];
let result = create_system_account_with_reputation(&mut keyed_accounts, 150, 2, &new_program_owner);
assert_eq!(result, Err(SystemError::ResultWithNegativeDifs));
let from_reputations = from_account.reputations;
assert_eq!(from_reputations, 100);
assert_eq!(to_account, unchanged_account);
}
#[test]
fn test_create_already_owned() {
// Attempt to create system account in account already owned by another program
let new_program_owner = Pubkey::new(&[9; 32]);
let from = Pubkey::new_rand();
let mut from_account = Account::new(100, 0, 0, &system_program::id());
let original_program_owner = Pubkey::new(&[5; 32]);
let owned_key = Pubkey::new_rand();
let mut owned_account = Account::new(0, 0, 0, &original_program_owner);
let unchanged_account = owned_account.clone();
let mut keyed_accounts = [
KeyedAccount::new(&from, true, &mut from_account),
KeyedAccount::new(&owned_key, false, &mut owned_account),
];
let result = create_system_account(&mut keyed_accounts, 50, 0, 2, &new_program_owner);
assert_eq!(result, Err(SystemError::AccountAlreadyInUse));
let from_difs = from_account.difs;
assert_eq!(from_difs, 100);
assert_eq!(owned_account, unchanged_account);
}
#[test]
fn test_create_data_populated() {
// Attempt to create system account in account with populated data
let new_program_owner = Pubkey::new(&[9; 32]);
let from = Pubkey::new_rand();
let mut from_account = Account::new(100, 0, 0, &system_program::id());
let populated_key = Pubkey::new_rand();
let mut populated_account = Account {
difs: 0,
reputations: 0,
data: vec![0, 1, 2, 3],
owner: Pubkey::default(),
executable: false,
};
let unchanged_account = populated_account.clone();
let mut keyed_accounts = [
KeyedAccount::new(&from, true, &mut from_account),
KeyedAccount::new(&populated_key, false, &mut populated_account),
];
let result = create_system_account(&mut keyed_accounts, 50, 0, 2, &new_program_owner);
assert_eq!(result, Err(SystemError::AccountAlreadyInUse));
assert_eq!(from_account.difs, 100);
assert_eq!(populated_account, unchanged_account);
}
#[test]
fn test_create_not_system_account() {
let other_program = Pubkey::new(&[9; 32]);
let from = Pubkey::new_rand();
let mut from_account = Account::new(100, 0, 0, &other_program);
let to = Pubkey::new_rand();
let mut to_account = Account::new(0, 0, 0, &Pubkey::default());
let mut keyed_accounts = [
KeyedAccount::new(&from, true, &mut from_account),
KeyedAccount::new(&to, false, &mut to_account),
];
let result = create_system_account(&mut keyed_accounts, 50, 0, 2, &other_program);
assert_eq!(result, Err(SystemError::SourceNotSystemAccount));
}
#[test]
fn test_assign_account_to_program() {
let new_program_owner = Pubkey::new(&[9; 32]);
let from = Pubkey::new_rand();
let mut from_account = Account::new(100, 0, 0, &system_program::id());
let mut keyed_accounts = [KeyedAccount::new(&from, true, &mut from_account)];
assign_account_to_program(&mut keyed_accounts, &new_program_owner).unwrap();
let from_owner = from_account.owner;
assert_eq!(from_owner, new_program_owner);
// Attempt to assign account not owned by system program
let another_program_owner = Pubkey::new(&[8; 32]);
keyed_accounts = [KeyedAccount::new(&from, true, &mut from_account)];
let instruction = SystemInstruction::Assign {
program_id: another_program_owner,
};
let data = serialize(&instruction).unwrap();
let result = process_instruction(&system_program::id(), &mut keyed_accounts, &data, 0);
assert_eq!(result, Err(InstructionError::IncorrectProgramId));
assert_eq!(from_account.owner, new_program_owner);
}
#[test]
fn test_transfer_difs() {
let from = Pubkey::new_rand();
let mut from_account = Account::new(100, 0, 0, &Pubkey::new(&[2; 32])); // account owner should not matter
let to = Pubkey::new_rand();
let mut to_account = Account::new(1, 0, 0, &Pubkey::new(&[3; 32])); // account owner should not matter
let mut keyed_accounts = [
KeyedAccount::new(&from, true, &mut from_account),
KeyedAccount::new(&to, false, &mut to_account),
];
transfer_difs(&mut keyed_accounts, 50).unwrap();
let from_difs = from_account.difs;
let to_difs = to_account.difs;
assert_eq!(from_difs, 50);
assert_eq!(to_difs, 51);
// Attempt to move more difs than remaining in from_account
keyed_accounts = [
KeyedAccount::new(&from, true, &mut from_account),
KeyedAccount::new(&to, false, &mut to_account),
];
let result = transfer_difs(&mut keyed_accounts, 100);
assert_eq!(result, Err(SystemError::ResultWithNegativeDifs));
assert_eq!(from_account.difs, 50);
assert_eq!(to_account.difs, 51);
}
#[test]
fn test_transfer_reputations() {
let from = Pubkey::new_rand();
let mut from_account = Account::new(100, 100, 0, &Pubkey::new(&[2; 32])); // account owner should not matter
let to = Pubkey::new_rand();
let mut to_account = Account::new(1, 0, 0, &Pubkey::new(&[3; 32])); // account owner should not matter
let mut keyed_accounts = [
KeyedAccount::new(&from, true, &mut from_account),
KeyedAccount::new(&to, false, &mut to_account),
];
transfer_reputations(&mut keyed_accounts, 50).unwrap();
let from_reputations = from_account.reputations;
let to_reputations = to_account.reputations;
assert_eq!(from_reputations, 50);
assert_eq!(to_reputations, 50);
// Attempt to move more difs than remaining in from_account
keyed_accounts = [
KeyedAccount::new(&from, true, &mut from_account),
KeyedAccount::new(&to, false, &mut to_account),
];
let result = transfer_reputations(&mut keyed_accounts, 100);
assert_eq!(result, Err(SystemError::ResultWithNegativeReputations));
assert_eq!(from_account.difs, 100);
assert_eq!(to_account.difs, 1);
}
#[test]
fn test_system_unsigned_transaction() {
let (genesis_block, alice_keypair) = create_genesis_block(100);
let alice_pubkey = alice_keypair.pubkey();
let mallory_keypair = Keypair::new();
let mallory_pubkey = mallory_keypair.pubkey();
// Fund to account to bypass AccountNotFound error
let bank = Bank::new(&genesis_block);
let bank_client = BankClient::new(bank);
bank_client
.transfer(50, &alice_keypair, &mallory_pubkey)
.unwrap();
// Erroneously sign transaction with recipient account key
// No signature case is tested by bank `test_zero_signatures()`
let account_metas = vec![
AccountMeta::new(alice_pubkey, false),
AccountMeta::new(mallory_pubkey, true),
];
let malicious_instruction = Instruction::new(
system_program::id(),
&SystemInstruction::Transfer { difs: 10 },
account_metas,
);
assert_eq!(
bank_client
.send_instruction(&mallory_keypair, malicious_instruction)
.unwrap_err()
.unwrap(),
TransactionError::InstructionError(0, InstructionError::MissingRequiredSignature)
);
assert_eq!(bank_client.get_balance(&alice_pubkey).unwrap(), 50);
assert_eq!(bank_client.get_balance(&mallory_pubkey).unwrap(), 50);
}
}
|
mod backend;
mod instance;
mod device;
mod surface;
mod command;
mod texture;
mod buffer;
mod pipeline;
mod sync;
mod raw_context;
mod thread;
mod spinlock;
mod rt;
pub use backend::WebGLBackend;
pub use instance::{WebGLInstance, WebGLAdapter};
pub use device::WebGLDevice;
pub use surface::{WebGLSurface, WebGLSwapchain};
pub use command::{WebGLCommandBuffer, WebGLCommandSubmission};
pub use texture::{WebGLTexture, WebGLTextureView};
pub(crate) use texture::format_to_internal_gl;
pub use buffer::WebGLBuffer;
pub use pipeline::{WebGLShader, WebGLGraphicsPipeline, WebGLComputePipeline};
pub use sync::WebGLFence;
pub(crate) use raw_context::RawWebGLContext;
pub use thread::WebGLThreadDevice;
use std::sync::Arc;
pub type WebGLWork = Box<dyn FnOnce(&mut crate::thread::WebGLThreadDevice) + Send>;
pub type GLThreadSender = Arc<thread::WebGLThreadQueue>;
|
use aoc2018::*;
fn part2(mods: &[i64]) -> Option<i64> {
let mut seen = HashSet::new();
seen.insert(0);
mods.iter()
.cloned()
.cycle()
.scan(0, |a, b| {
*a += b;
Some(*a)
})
.filter(|f| !seen.insert(*f))
.next()
}
fn main() -> Result<(), Error> {
let mods = columns!(input!("day1.txt"), char::is_whitespace, i64);
assert_eq!(497, mods.iter().cloned().sum::<i64>());
assert_eq!(Some(558), part2(&mods));
Ok(())
}
|
use std::slice;
use super::{Si, Ix, Ixs};
use super::zipsl;
/// Calculate offset from `Ix` stride converting sign properly
#[inline]
pub fn stride_offset(n: Ix, stride: Ix) -> isize
{
(n as isize) * ((stride as Ixs) as isize)
}
/// Trait for the shape and index types of arrays.
///
/// `unsafe` because of the assumptions in the default methods.
///
/// ***Don't implement this trait, it's internal to the crate and will
/// evolve at will.***
pub unsafe trait Dimension : Clone + Eq {
/// `SliceArg` is the type which is used to specify slicing for this
/// dimension.
///
/// For the fixed size dimensions (tuples) it is a fixed size array
/// of the correct size, which you pass by reference. For the `Vec`
/// dimension it is a slice.
///
/// - For `Ix`: `[Si; 1]`
/// - For `(Ix, Ix)`: `[Si; 2]`
/// - and so on..
/// - For `Vec<Ix>`: `[Si]`
///
/// The easiest way to create a `&SliceArg` is using the macro
/// [`s![]`](macro.s!.html).
type SliceArg: ?Sized + AsRef<[Si]>;
fn ndim(&self) -> usize;
fn slice(&self) -> &[Ix] {
unsafe {
slice::from_raw_parts(self as *const _ as *const Ix, self.ndim())
}
}
fn slice_mut(&mut self) -> &mut [Ix] {
unsafe {
slice::from_raw_parts_mut(self as *mut _ as *mut Ix, self.ndim())
}
}
fn size(&self) -> usize {
self.slice().iter().fold(1, |s, &a| s * a as usize)
}
fn default_strides(&self) -> Self {
// Compute default array strides
// Shape (a, b, c) => Give strides (b * c, c, 1)
let mut strides = self.clone();
{
let mut it = strides.slice_mut().iter_mut().rev();
// Set first element to 1
for rs in it.by_ref() {
*rs = 1;
break;
}
let mut cum_prod = 1;
for (rs, dim) in it.zip(self.slice().iter().rev()) {
cum_prod *= *dim;
*rs = cum_prod;
}
}
strides
}
#[inline]
fn first_index(&self) -> Option<Self>
{
for ax in self.slice().iter() {
if *ax == 0 {
return None
}
}
let mut index = self.clone();
for rr in index.slice_mut().iter_mut() {
*rr = 0;
}
Some(index)
}
/// Iteration -- Use self as size, and return next index after `index`
/// or None if there are no more.
// FIXME: use &Self for index or even &mut?
#[inline]
fn next_for(&self, index: Self) -> Option<Self> {
let mut index = index;
let mut done = false;
for (&dim, ix) in zipsl(self.slice(), index.slice_mut()).rev()
{
*ix += 1;
if *ix == dim {
*ix = 0;
} else {
done = true;
break;
}
}
if done {
Some(index)
} else { None }
}
/// Return stride offset for index.
fn stride_offset(index: &Self, strides: &Self) -> isize
{
let mut offset = 0;
for (&i, &s) in zipsl(index.slice(), strides.slice()) {
offset += stride_offset(i, s);
}
offset
}
/// Return stride offset for this dimension and index.
fn stride_offset_checked(&self, strides: &Self, index: &Self) -> Option<isize>
{
let mut offset = 0;
for ((&d, &i), &s) in zipsl(zipsl(self.slice(),
index.slice()),
strides.slice())
{
if i >= d {
return None;
}
offset += stride_offset(i, s);
}
Some(offset)
}
/// Modify dimension, strides and return data pointer offset
///
/// **Panics** if `slices` does not correspond to the number of axes,
/// if any stride is 0, or if any index is out of bounds.
fn do_slices(dim: &mut Self, strides: &mut Self, slices: &Self::SliceArg) -> isize
{
let slices = slices.as_ref();
let mut offset = 0;
assert!(slices.len() == dim.slice().len());
for ((dr, sr), &slc) in zipsl(zipsl(dim.slice_mut(),
strides.slice_mut()),
slices)
{
let m = *dr;
let mi = m as Ixs;
let Si(b1, opt_e1, s1) = slc;
let e1 = opt_e1.unwrap_or(mi);
let b1 = abs_index(mi, b1);
let mut e1 = abs_index(mi, e1);
if e1 < b1 { e1 = b1; }
assert!(b1 <= m);
assert!(e1 <= m);
let m = e1 - b1;
// stride
let s = (*sr) as Ixs;
// Data pointer offset
offset += stride_offset(b1, *sr);
// Adjust for strides
assert!(s1 != 0);
// How to implement negative strides:
//
// Increase start pointer by
// old stride * (old dim - 1)
// to put the pointer completely in the other end
if s1 < 0 {
offset += stride_offset(m - 1, *sr);
}
let s_prim = s * s1;
let d = m / s1.abs() as Ix;
let r = m % s1.abs() as Ix;
let m_prim = d + if r > 0 { 1 } else { 0 };
// Update dimension and stride coordinate
*dr = m_prim;
*sr = s_prim as Ix;
}
offset
}
}
fn abs_index(len: Ixs, index: Ixs) -> Ix {
if index < 0 {
(len + index) as Ix
} else { index as Ix }
}
/// Collapse axis `axis` and shift so that only subarray `index` is
/// available.
///
/// **Panics** if `index` is larger than the size of the axis
// FIXME: Move to Dimension trait
pub fn do_sub<A, D: Dimension>(dims: &mut D, ptr: &mut *mut A, strides: &D,
axis: usize, index: Ix)
{
let dim = dims.slice()[axis];
let stride = strides.slice()[axis];
assert!(index < dim);
dims.slice_mut()[axis] = 1;
let off = stride_offset(index, stride);
unsafe {
*ptr = ptr.offset(off);
}
}
unsafe impl Dimension for () {
type SliceArg = [Si; 0];
// empty product is 1 -> size is 1
#[inline]
fn ndim(&self) -> usize { 0 }
fn slice(&self) -> &[Ix] { &[] }
fn slice_mut(&mut self) -> &mut [Ix] { &mut [] }
}
unsafe impl Dimension for Ix {
type SliceArg = [Si; 1];
#[inline]
fn ndim(&self) -> usize { 1 }
#[inline]
fn size(&self) -> usize { *self as usize }
#[inline]
fn default_strides(&self) -> Self { 1 }
#[inline]
fn first_index(&self) -> Option<Ix> {
if *self != 0 {
Some(0)
} else { None }
}
#[inline]
fn next_for(&self, mut index: Ix) -> Option<Ix> {
index += 1;
if index < *self {
Some(index)
} else { None }
}
/// Self is an index, return the stride offset
#[inline]
fn stride_offset(index: &Ix, stride: &Ix) -> isize
{
stride_offset(*index, *stride)
}
/// Return stride offset for this dimension and index.
#[inline]
fn stride_offset_checked(&self, stride: &Ix, index: &Ix) -> Option<isize>
{
if *index < *self {
Some(stride_offset(*index, *stride))
} else {
None
}
}
}
unsafe impl Dimension for (Ix, Ix) {
type SliceArg = [Si; 2];
#[inline]
fn ndim(&self) -> usize { 2 }
#[inline]
fn size(&self) -> usize { let (m, n) = *self; m as usize * n as usize }
#[inline]
fn default_strides(&self) -> Self {
// Compute default array strides
// Shape (a, b, c) => Give strides (b * c, c, 1)
(self.1, 1)
}
#[inline]
fn first_index(&self) -> Option<(Ix, Ix)> {
let (m, n) = *self;
if m != 0 && n != 0 {
Some((0, 0))
} else { None }
}
#[inline]
fn next_for(&self, index: (Ix, Ix)) -> Option<(Ix, Ix)> {
let (mut i, mut j) = index;
let (imax, jmax) = *self;
j += 1;
if j == jmax {
j = 0;
i += 1;
if i == imax {
return None;
}
}
Some((i, j))
}
/// Self is an index, return the stride offset
#[inline]
fn stride_offset(index: &(Ix, Ix), strides: &(Ix, Ix)) -> isize
{
let (i, j) = *index;
let (s, t) = *strides;
stride_offset(i, s) + stride_offset(j, t)
}
/// Return stride offset for this dimension and index.
#[inline]
fn stride_offset_checked(&self, strides: &(Ix, Ix), index: &(Ix, Ix)) -> Option<isize>
{
let (m, n) = *self;
let (i, j) = *index;
let (s, t) = *strides;
if i < m && j < n {
Some(stride_offset(i, s) + stride_offset(j, t))
} else {
None
}
}
}
unsafe impl Dimension for (Ix, Ix, Ix) {
type SliceArg = [Si; 3];
#[inline]
fn ndim(&self) -> usize { 3 }
#[inline]
fn size(&self) -> usize { let (m, n, o) = *self; m as usize * n as usize * o as usize }
#[inline]
fn next_for(&self, index: (Ix, Ix, Ix)) -> Option<(Ix, Ix, Ix)> {
let (mut i, mut j, mut k) = index;
let (imax, jmax, kmax) = *self;
k += 1;
if k == kmax {
k = 0;
j += 1;
if j == jmax {
j = 0;
i += 1;
if i == imax {
return None;
}
}
}
Some((i, j, k))
}
/// Self is an index, return the stride offset
#[inline]
fn stride_offset(index: &(Ix, Ix, Ix), strides: &(Ix, Ix, Ix)) -> isize
{
let (i, j, k) = *index;
let (s, t, u) = *strides;
stride_offset(i, s) + stride_offset(j, t) + stride_offset(k, u)
}
}
macro_rules! large_dim {
($n:expr, $($ix:ident),+) => (
unsafe impl Dimension for ($($ix),+) {
type SliceArg = [Si; $n];
#[inline]
fn ndim(&self) -> usize { $n }
}
)
}
large_dim!(4, Ix, Ix, Ix, Ix);
large_dim!(5, Ix, Ix, Ix, Ix, Ix);
large_dim!(6, Ix, Ix, Ix, Ix, Ix, Ix);
large_dim!(7, Ix, Ix, Ix, Ix, Ix, Ix, Ix);
large_dim!(8, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix);
large_dim!(9, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix);
large_dim!(10, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix);
large_dim!(11, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix);
large_dim!(12, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix);
/// Vec<Ix> is a "dynamic" index, pretty hard to use when indexing,
/// and memory wasteful, but it allows an arbitrary and dynamic number of axes.
unsafe impl Dimension for Vec<Ix>
{
type SliceArg = [Si];
fn ndim(&self) -> usize { self.len() }
fn slice(&self) -> &[Ix] { self }
fn slice_mut(&mut self) -> &mut [Ix] { self }
}
/// Helper trait to define a larger-than relation for array shapes:
/// removing one axis from *Self* gives smaller dimension *Smaller*.
pub trait RemoveAxis : Dimension {
type Smaller: Dimension;
fn remove_axis(&self, axis: usize) -> Self::Smaller;
}
macro_rules! impl_shrink(
($from:ident, $($more:ident,)*) => (
impl RemoveAxis for ($from $(,$more)*)
{
type Smaller = ($($more),*);
#[allow(unused_parens)]
#[inline]
fn remove_axis(&self, axis: usize) -> ($($more),*) {
let mut tup = ($(0 as $more),*);
{
let mut it = tup.slice_mut().iter_mut();
for (i, &d) in self.slice().iter().enumerate() {
if i == axis {
continue;
}
for rr in it.by_ref() {
*rr = d;
break
}
}
}
tup
}
}
)
);
macro_rules! impl_shrink_recursive(
($ix:ident, ) => (impl_shrink!($ix,););
($ix1:ident, $($ix:ident,)*) => (
impl_shrink_recursive!($($ix,)*);
impl_shrink!($ix1, $($ix,)*);
)
);
// 12 is the maximum number for having the Eq trait from libstd
impl_shrink_recursive!(Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix, Ix,);
impl RemoveAxis for Vec<Ix>
{
type Smaller = Vec<Ix>;
fn remove_axis(&self, axis: usize) -> Vec<Ix>
{
let mut res = self.clone();
res.remove(axis);
res
}
}
/// A tuple or fixed size array that can be used to index an array.
///
/// ```
/// use ndarray::arr2;
///
/// let mut a = arr2(&[[0, 1], [0, 0]]);
/// a[[1, 1]] = 1;
/// assert_eq!(a[[0, 1]], 1);
/// assert_eq!(a[[1, 1]], 1);
/// ```
///
/// **Note** the blanket implementation that's not visible in rustdoc:
/// `impl<D> NdIndex for D where D: Dimension { ... }`
pub unsafe trait NdIndex {
type Dim: Dimension;
#[doc(hidden)]
fn index_checked(&self, dim: &Self::Dim, strides: &Self::Dim) -> Option<isize>;
}
unsafe impl<D> NdIndex for D where D: Dimension {
type Dim = D;
fn index_checked(&self, dim: &Self::Dim, strides: &Self::Dim) -> Option<isize> {
dim.stride_offset_checked(strides, self)
}
}
unsafe impl NdIndex for [Ix; 0] {
type Dim = ();
#[inline]
fn index_checked(&self, dim: &Self::Dim, strides: &Self::Dim) -> Option<isize> {
dim.stride_offset_checked(strides, &())
}
}
unsafe impl NdIndex for [Ix; 1] {
type Dim = Ix;
#[inline]
fn index_checked(&self, dim: &Self::Dim, strides: &Self::Dim) -> Option<isize> {
dim.stride_offset_checked(strides, &self[0])
}
}
unsafe impl NdIndex for [Ix; 2] {
type Dim = (Ix, Ix);
#[inline]
fn index_checked(&self, dim: &Self::Dim, strides: &Self::Dim) -> Option<isize> {
let index = (self[0], self[1]);
dim.stride_offset_checked(strides, &index)
}
}
unsafe impl NdIndex for [Ix; 3] {
type Dim = (Ix, Ix, Ix);
#[inline]
fn index_checked(&self, dim: &Self::Dim, strides: &Self::Dim) -> Option<isize> {
let index = (self[0], self[1], self[2]);
dim.stride_offset_checked(strides, &index)
}
}
unsafe impl NdIndex for [Ix; 4] {
type Dim = (Ix, Ix, Ix, Ix);
#[inline]
fn index_checked(&self, dim: &Self::Dim, strides: &Self::Dim) -> Option<isize> {
let index = (self[0], self[1], self[2], self[3]);
dim.stride_offset_checked(strides, &index)
}
}
unsafe impl<'a> NdIndex for &'a [Ix] {
type Dim = Vec<Ix>;
fn index_checked(&self, dim: &Self::Dim, strides: &Self::Dim) -> Option<isize> {
let mut offset = 0;
for ((&d, &i), &s) in zipsl(zipsl(&dim[..], &self[..]),
strides.slice())
{
if i >= d {
return None;
}
offset += stride_offset(i, s);
}
Some(offset)
}
}
|
/// Reference: https://github.com/bytecodealliance/wasmtime/blob/master/crates/wast/src/wast.rs
use anyhow::{anyhow, bail, Context as _, Result};
use std::collections::HashMap;
use std::path::Path;
use std::str;
mod spectest;
pub use spectest::instantiate_spectest;
use wasminspect_vm::{simple_invoke_func, FuncAddr, ModuleIndex, WasmInstance, WasmValue};
use wasmparser::{validate, ModuleReader};
pub struct WastContext {
module_index_by_name: HashMap<String, ModuleIndex>,
instance: WasmInstance,
current: Option<ModuleIndex>,
}
impl WastContext {
pub fn new() -> Self {
let mut instance = WasmInstance::new();
instance.load_host_module("spectest".to_string(), instantiate_spectest());
Self {
module_index_by_name: HashMap::new(),
instance: instance,
current: None,
}
}
pub fn run_file(&mut self, path: &Path) -> Result<()> {
let bytes = std::fs::read(path).unwrap();
self.run_buffer(path.to_str().unwrap(), &bytes)
}
pub fn extract_start_section(bytes: &[u8]) -> Result<Option<u32>> {
let mut reader = ModuleReader::new(bytes)?;
while !reader.eof() {
let section = reader.read()?;
if section.code != wasmparser::SectionCode::Start {
continue;
}
match section.get_start_section_content() {
Ok(offset) => return Ok(Some(offset)),
Err(_) => continue,
}
}
return Ok(None);
}
pub fn instantiate<'a>(&self, bytes: &'a [u8]) -> Result<ModuleReader<'a>> {
validate(bytes, None)?;
Ok(ModuleReader::new(bytes)?)
}
fn module(&mut self, module_name: Option<&str>, bytes: &[u8]) -> Result<()> {
let module = self.instantiate(&bytes)?;
let start_section = Self::extract_start_section(bytes)?;
let module_index = self
.instance
.load_module_from_module(module_name.map(|n| n.to_string()), module)
.map_err(|e| anyhow!("Failed to instantiate: {}", e))?;
if let Some(start_section) = start_section {
let func_addr = FuncAddr::new_unsafe(module_index, start_section as usize);
simple_invoke_func(func_addr, vec![], &mut self.instance.store)
.map_err(|e| anyhow!("Failed to exec start func: {}", e))?;
}
self.current = Some(module_index);
if let Some(module_name) = module_name {
self.module_index_by_name
.insert(module_name.to_string(), module_index);
}
Ok(())
}
pub fn run_buffer(&mut self, filename: &str, wast: &[u8]) -> Result<()> {
use wast::WastDirective::*;
let wast = str::from_utf8(wast)?;
let adjust_wast = |mut err: wast::Error| {
err.set_path(filename.as_ref());
err.set_text(wast);
err
};
let context = |sp: wast::Span| {
let (line, col) = sp.linecol_in(wast);
format!("for directive on {}:{}:{}", filename, line + 1, col)
};
let buf = wast::parser::ParseBuffer::new(wast).map_err(adjust_wast)?;
let wast = wast::parser::parse::<wast::Wast>(&buf).map_err(adjust_wast)?;
for directive in wast.directives {
match directive {
Module(mut module) => {
let bytes = module.encode().map_err(adjust_wast)?;
self.module(module.name.map(|s| s.name()), &bytes)
.map_err(|err| anyhow!("{}, {}", err, context(module.span)))?;
}
Register {
span: _,
name,
module,
} => {
let module_index = self.get_instance(module.map(|s| s.name()))?;
self.instance.register_name(name.to_string(), module_index);
}
Invoke(i) => {
self.invoke(i.module.map(|s| s.name()), i.name, &i.args)
.map_err(|err| anyhow!("Failed to invoke {}", err))
.with_context(|| context(i.span))?;
}
AssertReturn {
span,
exec,
results,
} => match self.perform_execute(exec).with_context(|| context(span)) {
Ok(Ok(values)) => {
for (v, e) in values.iter().zip(results) {
if val_matches(v, &e)? {
continue;
}
bail!("expected {:?}, got {:?} {}", e, v, context(span))
}
}
Ok(Err(e)) => panic!("unexpected err: {}, {}", e, context(span)),
Err(e) => panic!("unexpected err: {}", e),
},
AssertTrap {
span,
exec,
message,
} => match self.perform_execute(exec).with_context(|| context(span)) {
Ok(Ok(values)) => panic!("{}\nexpected trap, got {:?}", context(span), values),
Ok(Err(t)) => {
let result = format!("{}", t);
if result.contains(message) {
continue;
}
panic!("{}\nexpected {}, got {}", context(span), message, result,)
}
Err(err) => panic!("{}", err),
},
AssertMalformed {
span,
module,
message,
} => {
let mut module = match module {
wast::QuoteModule::Module(m) => m,
// this is a `*.wat` parser test which we're not
// interested in
wast::QuoteModule::Quote(_) => return Ok(()),
};
let bytes = module.encode().map_err(adjust_wast)?;
let err = match self.module(None, &bytes) {
Ok(()) => {
panic!("{}\nexpected module to fail to instantiate", context(span))
}
Err(e) => e,
};
let error_message = format!("{:?}", err);
if !error_message.contains(&message) {
// TODO: change to panic!
println!(
"{}\nassert_malformed: expected {}, got {}",
context(span),
message,
error_message
)
}
}
AssertUnlinkable {
span,
mut module,
message,
} => {
let bytes = module.encode().map_err(adjust_wast)?;
let err = match self.module(None, &bytes) {
Ok(()) => panic!("{}\nexpected module to fail to link", context(span)),
Err(e) => e,
};
let error_message = format!("{:?}", err);
if !error_message.contains(&message) {
panic!(
"{}\nassert_unlinkable: expected {}, got {}",
context(span),
message,
error_message
)
}
}
AssertExhaustion {
span,
call,
message,
} => match self.invoke(call.module.map(|s| s.name()), call.name, &call.args) {
Ok(values) => panic!("{}\nexpected trap, got {:?}", context(span), values),
Err(t) => {
let result = format!("{}", t);
if result.contains(message) {
continue;
}
panic!("{}\nexpected {}, got {}", context(span), message, result)
}
},
AssertInvalid {
span,
mut module,
message,
} => {
let bytes = module.encode().map_err(adjust_wast)?;
let err = match self.module(None, &bytes) {
Ok(()) => panic!("{}\nexpected module to fail to build", context(span)),
Err(e) => e,
};
let error_message = format!("{:?}", err);
if !error_message.contains(&message) {
// TODO: change to panic!
println!(
"{}\nassert_invalid: expected {}, got {}",
context(span),
message,
error_message
)
}
}
}
}
Ok(())
}
fn get_instance(&self, name: Option<&str>) -> Result<ModuleIndex> {
match name {
Some(name) => self
.module_index_by_name
.get(name)
.map(|i| i.clone())
.ok_or(anyhow!("module not found with name {}", name)),
None => match self.current.clone() {
Some(current) => Ok(current),
None => panic!(),
},
}
}
/// Get the value of an exported global from an instance.
fn get(&mut self, instance_name: Option<&str>, field: &str) -> Result<Result<Vec<WasmValue>>> {
let module_index = self.get_instance(instance_name.as_ref().map(|x| &**x))?;
match self
.instance
.get_global(module_index, field)
.map(|value| vec![value])
{
Some(v) => Ok(Ok(v)),
None => Err(anyhow!("no global named {}", field)),
}
}
fn invoke(
&mut self,
module_name: Option<&str>,
func_name: &str,
args: &[wast::Expression],
) -> Result<Vec<WasmValue>> {
let module_index = self.get_instance(module_name)?;
let args = args.iter().map(const_expr).collect();
let result = self
.instance
.run(module_index, Some(func_name.to_string()), args)
.map_err(|e| anyhow!("{}", e))?;
Ok(result)
}
fn perform_execute(&mut self, exec: wast::WastExecute<'_>) -> Result<Result<Vec<WasmValue>>> {
match exec {
wast::WastExecute::Invoke(i) => {
Ok(self.invoke(i.module.map(|s| s.name()), i.name, &i.args))
}
wast::WastExecute::Module(mut module) => {
let binary = module.encode()?;
let module = self.instantiate(&binary)?;
let start_section = Self::extract_start_section(&binary)?;
let module_index = self
.instance
.load_module_from_module(None, module)
.map_err(|e| anyhow!("{}", e))?;
if let Some(start_section) = start_section {
let func_addr = FuncAddr::new_unsafe(module_index, start_section as usize);
return Ok(
simple_invoke_func(func_addr, vec![], &mut self.instance.store)
.map_err(|e| anyhow!("Failed to exec start func: {}", e)),
);
}
Ok(Ok(vec![]))
}
wast::WastExecute::Get { module, global } => self.get(module.map(|s| s.name()), global),
}
}
}
fn val_matches(actual: &WasmValue, expected: &wast::AssertExpression) -> Result<bool> {
Ok(match (actual, expected) {
(WasmValue::I32(a), wast::AssertExpression::I32(x)) => a == x,
(WasmValue::I64(a), wast::AssertExpression::I64(x)) => a == x,
(WasmValue::F32(a), wast::AssertExpression::F32(x)) => match x {
wast::NanPattern::CanonicalNan => is_canonical_f32_nan(a),
wast::NanPattern::ArithmeticNan => is_arithmetic_f32_nan(a),
wast::NanPattern::Value(expected_value) => *a == expected_value.bits,
},
(WasmValue::F64(a), wast::AssertExpression::F64(x)) => match x {
wast::NanPattern::CanonicalNan => is_canonical_f64_nan(a),
wast::NanPattern::ArithmeticNan => is_arithmetic_f64_nan(a),
wast::NanPattern::Value(expected_value) => *a == expected_value.bits,
},
(_, wast::AssertExpression::V128(_)) => bail!("V128 is not supported yet"),
_ => bail!("unexpected comparing for {:?} and {:?}", actual, expected),
})
}
fn const_expr(expr: &wast::Expression) -> WasmValue {
match &expr.instrs[0] {
wast::Instruction::I32Const(x) => WasmValue::I32(*x),
wast::Instruction::I64Const(x) => WasmValue::I64(*x),
wast::Instruction::F32Const(x) => WasmValue::F32(x.bits),
wast::Instruction::F64Const(x) => WasmValue::F64(x.bits),
wast::Instruction::V128Const(_) => panic!(),
_ => panic!(),
}
}
fn is_canonical_f32_nan(f: &u32) -> bool {
return (f & 0x7fffffff) == 0x7fc00000;
}
fn is_canonical_f64_nan(f: &u64) -> bool {
return (f & 0x7fffffffffffffff) == 0x7ff8000000000000;
}
fn is_arithmetic_f32_nan(f: &u32) -> bool {
return (f & 0x00400000) == 0x00400000;
}
fn is_arithmetic_f64_nan(f: &u64) -> bool {
return (f & 0x0008000000000000) == 0x0008000000000000;
}
|
extern crate failure;
mod bedgraph;
//mod errors;
mod runner;
mod snp;
mod stats;
use exitfailure::ExitFailure;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
#[structopt(about = "the stupid content tracker")]
enum Cli {
GC {
#[structopt(parse(from_os_str))]
infile: PathBuf,
#[structopt(parse(from_os_str), short = "o", long = "output")]
outfile: Option<PathBuf>,
#[structopt(short = "w", long = "size", default_value = "5000")]
window: usize,
#[structopt(short = "s", long = "step", default_value = "1000")]
step: usize,
},
CRI {
#[structopt(parse(from_os_str))]
infile: PathBuf,
#[structopt(parse(from_os_str), short = "o", long = "output")]
outfile: Option<PathBuf>,
#[structopt(short = "w", long = "size", default_value = "5000")]
window: usize,
#[structopt(short = "s", long = "step", default_value = "1000")]
step: usize,
},
SNP {
#[structopt(parse(from_os_str))]
infile: PathBuf,
#[structopt(parse(from_os_str))]
invcf: PathBuf,
#[structopt(parse(from_os_str), short = "o", long = "output")]
outfile: Option<PathBuf>,
},
}
fn main() -> Result<(), ExitFailure> {
match Cli::from_args() {
Cli::GC {
infile,
outfile,
window,
step,
} => runner::run_gc(&infile, &outfile, window, step)?,
Cli::CRI {
infile,
outfile,
window,
step,
} => runner::run_cri(&infile, &outfile, window, step)?,
Cli::SNP {
infile,
invcf,
outfile,
} => runner::run_ripsnp(&infile, &invcf, &outfile)?,
}
Ok(())
}
/*
("snp", Some(m)) => {
SNPConfig::parse_clap(m)
.and_then(|c| runner::run_ripsnp(&c.fasta, &c.vcf))
},
("", None) => {
println!("no subcommand");
Ok(())
},
*/
|
extern crate rand;
use rand::seq::SliceRandom;
use rand::thread_rng;
use super::cards;
use super::player::Player;
use super::status::{GameRoundResult, State};
pub const DEFAULT_SOFTPOINTS: u8 = 17;
pub struct BlackJack {
state: State,
dealer: Player,
player: Player,
card_deck: Vec<cards::Card>,
soft_points: u8,
}
impl BlackJack {
pub fn new(player: Player, dealer: Player, soft_points: u8) -> BlackJack {
BlackJack {
state: State::GameStart,
dealer,
player,
card_deck: Vec::new(),
soft_points,
}
}
pub fn end_game(&mut self) {
self.state = State::GameEnd;
}
fn end_game_round(&mut self) {
self.state = State::GameRoundEnd;
}
pub fn get_dealer(&mut self) -> &mut Player {
&mut self.dealer
}
pub fn get_player(&mut self) -> &mut Player {
&mut self.player
}
pub fn get_state(&self) -> &State {
&self.state
}
pub fn get_winner(&self) -> GameRoundResult {
let player_points = self.player.get_cards_points();
let dealer_points = self.dealer.get_cards_points();
match (player_points, dealer_points) {
(p, _d) if p > 21 => GameRoundResult::PlayerBusted,
(_p, d) if d > 21 => GameRoundResult::DealerBusted,
(p, d) if p > d => GameRoundResult::PlayerWon,
(p, d) if d > p => GameRoundResult::DealerWon,
_ => GameRoundResult::Draw,
}
}
pub fn player_hit_card(&mut self) {
if self.state != State::PlayerTurn {
return;
}
let card: cards::Card = self.get_next_card_from_deck();
self.player.add_card(card);
self.state = State::DealerTurn;
self.dealers_turn();
}
pub fn player_stand(&mut self) {
if self.state != State::PlayerTurn {
return;
}
self.player.set_bet_on_cards(true);
self.state = State::DealerTurn;
self.dealers_turn();
}
pub fn start_game(&mut self) {
self.set_card_deck();
self.state = State::GameStart;
}
pub fn start_game_round(&mut self) {
for p in [&mut self.player, &mut self.dealer] {
p.empty_cards();
p.set_bet_on_cards(false);
}
self.state = State::GameRoundStart;
for i in 1..=4 {
let card = self.get_next_card_from_deck();
match i % 2 {
0 => self.player.add_card(card),
_ => self.dealer.add_card(card),
}
}
self.state = State::PlayerTurn;
}
fn dealer_hit_card(&mut self) {
let card = self.get_next_card_from_deck();
self.dealer.add_card(card);
}
fn dealers_turn(&mut self) {
if self.state != State::DealerTurn {
return;
}
if self.is_dealer_want_to_hit() {
self.dealer_hit_card();
} else {
self.dealer.set_bet_on_cards(true);
}
let dealer_points = self.dealer.get_cards_points();
let player_points = self.player.get_cards_points();
let is_player_betting = self.player.is_bet_on_cards();
let is_dealer_betting = self.dealer.is_bet_on_cards();
match (dealer_points, player_points) {
(d, p) if d > 21 || p > 21 => self.end_game_round(),
_ => match (is_player_betting, is_dealer_betting) {
(c, d) if c && d => self.end_game_round(),
(c, d) if c && !d => self.dealers_turn(),
_ => self.state = State::PlayerTurn,
},
}
}
fn get_next_card_from_deck(&mut self) -> cards::Card {
if self.card_deck.is_empty() {
self.set_card_deck();
}
self.card_deck.remove(0)
}
fn is_dealer_want_to_hit(&self) -> bool {
matches!(self.dealer.get_cards_points(), points if points < self.soft_points)
}
fn set_card_deck(&mut self) {
self.card_deck.clear();
for card in [
cards::Card::ClubsAce,
cards::Card::ClubsTwo,
cards::Card::ClubsThree,
cards::Card::ClubsFour,
cards::Card::ClubsFive,
cards::Card::ClubsSix,
cards::Card::ClubsSeven,
cards::Card::ClubsEight,
cards::Card::ClubsNine,
cards::Card::ClubsTen,
cards::Card::ClubsJack,
cards::Card::ClubsQueen,
cards::Card::ClubsKing,
cards::Card::DiamondsAce,
cards::Card::DiamondsTwo,
cards::Card::DiamondsThree,
cards::Card::DiamondsFour,
cards::Card::DiamondsFive,
cards::Card::DiamondsSix,
cards::Card::DiamondsSeven,
cards::Card::DiamondsEight,
cards::Card::DiamondsNine,
cards::Card::DiamondsTen,
cards::Card::DiamondsJack,
cards::Card::DiamondsQueen,
cards::Card::DiamondsKing,
cards::Card::HeartsAce,
cards::Card::HeartsTwo,
cards::Card::HeartsThree,
cards::Card::HeartsFour,
cards::Card::HeartsFive,
cards::Card::HeartsSix,
cards::Card::HeartsSeven,
cards::Card::HeartsEight,
cards::Card::HeartsNine,
cards::Card::HeartsTen,
cards::Card::HeartsJack,
cards::Card::HeartsQueen,
cards::Card::HeartsKing,
cards::Card::SpadesAce,
cards::Card::SpadesTwo,
cards::Card::SpadesThree,
cards::Card::SpadesFour,
cards::Card::SpadesFive,
cards::Card::SpadesSix,
cards::Card::SpadesSeven,
cards::Card::SpadesEight,
cards::Card::SpadesNine,
cards::Card::SpadesTen,
cards::Card::SpadesJack,
cards::Card::SpadesQueen,
cards::Card::SpadesKing,
] {
self.card_deck.push(card);
}
self.shuffle_deck();
}
fn shuffle_deck(&mut self) {
let mut rng = thread_rng();
self.card_deck.shuffle(&mut rng);
}
}
|
/*!
* This crate contains an implementation of an MQTT client.
*/
#![deny(rust_2018_idioms, warnings)]
#![deny(clippy::all, clippy::pedantic)]
#![allow(
clippy::default_trait_access,
clippy::large_enum_variant,
clippy::pub_enum_variant_names,
clippy::similar_names,
clippy::single_match_else,
clippy::stutter,
clippy::too_many_arguments,
clippy::use_self
)]
mod client;
pub use self::client::{
Client, Error, Event, IoSource, PublishError, PublishHandle, ReceivedPublication,
ShutdownError, ShutdownHandle, SubscriptionUpdate, UpdateSubscriptionError,
UpdateSubscriptionHandle,
};
mod logging_framed;
pub mod proto;
|
pub mod data;
pub mod ui;
use druid::{AppLauncher, LocalizedString, WindowDesc};
use data::{AppData, Mod};
use std::io::{Error, ErrorKind, Write};
use std::{env, fs};
const WINDOW_TITLE: &str = "chum_bucket_lab";
#[derive(Clone, Debug)]
struct Config {
check_update: bool,
}
impl Config {
const DEFAULT_CONFIG: Config = Config { check_update: true };
const OPTION_UPDATE: &'static str = "--update";
fn parse_args<I>(args: I) -> Self
where
I: Iterator<Item = String>,
{
let args: Vec<_> = args.collect();
if args.len() < 3 {
return Config::DEFAULT_CONFIG.to_owned();
}
if args[1] != Config::OPTION_UPDATE {
return Config::DEFAULT_CONFIG.to_owned();
}
match args[2].parse::<bool>() {
Err(_) => Config::DEFAULT_CONFIG.to_owned(),
Ok(b) => Config { check_update: b },
}
}
}
pub fn main() {
// Get config from command line args
let config = Config::parse_args(env::args());
let main_window = WindowDesc::new(ui::ui_builder())
.title(LocalizedString::new(WINDOW_TITLE).with_placeholder("Chum Bucket Lab"));
if config.check_update {
update_modlist();
}
//TODO: Error prompt when this fails
let modlist = parse_modlist().unwrap_or_else(|_| {
println!("Failed to parse modlist");
Vec::new()
});
AppLauncher::with_window(main_window)
.delegate(ui::Delegate)
.log_to_console()
.launch(AppData::new(modlist))
.expect("launch failed");
}
fn update_modlist() {
match reqwest::blocking::get(data::URL_MODLIST).and_then(|r| r.text()) {
Ok(text) => {
if fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(data::PATH_MODLIST)
.and_then(|mut f| f.write_all(text.as_bytes()))
.is_err()
{
println!("Failed to write updated file to disk");
}
}
Err(_) => println!("Failed to retrieve modslist from internet"),
}
}
fn parse_modlist() -> std::io::Result<Vec<Mod>> {
// TODO: Consider if saving the modlist locally is even necessary
// Note: Keeping a local copy enables the app to still function even
// if we fail to download latest version even though the user has a valid
// internet connection
let file = fs::read_to_string(data::PATH_MODLIST)?;
match data::modlist_from_toml(&file) {
Err(e) => {
eprintln!("{}", e);
Err(Error::new(ErrorKind::InvalidData, e)) //Failed to deserialize file
}
Ok(modlist) => Ok(modlist),
}
}
|
use nardol::bytes::Bytes;
use nardol::bytes::FromBytes;
use nardol::bytes::IntoBytes;
use nardol::prelude::FromRon;
use nardol::prelude::IntoMessage;
use nardol::prelude::ToRon;
use nardol::prelude::Packet;
use nardol::prelude::PacketKind;
use serde::{Serialize, Deserialize};
use ron::ser;
use ron::de;
use nardol::error::{NetCommsError, NetCommsErrorKind};
use crate::Content;
use crate::ImplementedMessage;
use crate::MessageKind;
use crate::MetaData;
use crate::config::SERVER_ID;
use crate::config::SERVER_USERNAME;
use crate::user::User;
use crate::user::UserLite;
/// Enum of all possible replies from server to client.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ServerReply {
/// Used when returning an error, [String] inside holds an error message.
Error(String), // Later this string should be changed to use some kind of error enum, so client can recover from it.
/// Used when there was a successful [Request::Register](crate::request::Request::Register) or [Request::Login](crate::request::Request::Login).
User(UserLite),
}
impl ToRon for ServerReply {}
impl FromRon<'_> for ServerReply {}
pub enum ServerReplyRaw {
/// Used when returning an error, [String] inside holds an error message.
Error(String, UserLite), // Later this string should be changed to use some kind of error enum, so client can recover from it.
/// Used when there was a successful [Request::Register](crate::request::Request::Register) or [Request::Login](crate::request::Request::Login).
User(UserLite, UserLite),
}
impl IntoMessage<'_, MetaData, Content> for ServerReplyRaw {
fn into_message(self) -> Result<ImplementedMessage, NetCommsError> {
let (server_reply, recipient) = match self {
ServerReplyRaw::Error(content, recipient) => {
(ServerReply::Error(content), recipient)
},
ServerReplyRaw::User(user, recipient) => {
(ServerReply::User(user), recipient)
},
};
let mut message = ImplementedMessage::new();
let content = Content::with_data(server_reply.to_ron()?);
let content_buff = content.into_bytes();
// Recipient of Request will always be a server.
let message_kind = MessageKind::SeverReply;
let recipients = vec![recipient.username()];
let file_name = None;
let metadata = MetaData::new(&content_buff, message_kind,
UserLite::default_server(),
recipient.id(), recipients,
file_name)?;
message.set_metadata(metadata);
message.set_content(Content::from_bytes(content_buff)?);
let end_data = Packet::new(PacketKind::End, Bytes::new());
message.set_end_data(end_data);
Ok(message)
}
}
|
//! # Snapshot testing toolbox
//!
//! > When you have to treat your tests like pets, instead of [cattle][trycmd]
//!
//! `snapbox` is a snapshot-testing toolbox that is ready to use for verifying output from
//! - Function return values
//! - CLI stdout/stderr
//! - Filesystem changes
//!
//! It is also flexible enough to build your own test harness like [trycmd](https://crates.io/crates/trycmd).
//!
//! ## Which tool is right
//!
//! - [cram](https://bitheap.org/cram/): End-to-end CLI snapshotting agnostic of any programming language
//! - [trycmd](https://crates.io/crates/trycmd): For running a lot of blunt tests (limited test predicates)
//! - Particular attention is given to allow the test data to be pulled into documentation, like
//! with [mdbook](https://rust-lang.github.io/mdBook/)
//! - `snapbox`: When you want something like `trycmd` in one off
//! cases or you need to customize `trycmd`s behavior.
//! - [assert_cmd](https://crates.io/crates/assert_cmd) +
//! [assert_fs](https://crates.io/crates/assert_fs): Test cases follow a certain pattern but
//! special attention is needed in how to verify the results.
//! - Hand-written test cases: for peculiar circumstances
//!
//! ## Getting Started
//!
//! Testing Functions:
//! - [`assert_eq`][crate::assert_eq] and [`assert_matches`] for reusing diffing / pattern matching for non-snapshot testing
//! - [`assert_eq_path`][crate::assert_eq_path] and [`assert_matches_path`] for one-off assertions with the snapshot stored in a file
//! - [`harness::Harness`] for discovering test inputs and asserting against snapshot files:
//!
//! Testing Commands:
//! - [`cmd::Command`]: Process spawning for testing of non-interactive commands
//! - [`cmd::OutputAssert`]: Assert the state of a [`Command`][cmd::Command]'s
//! [`Output`][std::process::Output].
//!
//! Testing Filesystem Interactions:
//! - [`path::PathFixture`]: Working directory for tests
//! - [`Assert`]: Diff a directory against files present in a pattern directory
//!
//! You can also build your own version of these with the lower-level building blocks these are
//! made of.
//!
#![cfg_attr(feature = "document-features", doc = document_features::document_features!())]
//!
//! # Examples
//!
//! [`assert_matches`]
//! ```rust
//! snapbox::assert_matches("Hello [..] people!", "Hello many people!");
//! ```
//!
//! [`Assert`]
//! ```rust,no_run
//! let actual = "...";
//! let expected_path = "tests/fixtures/help_output_is_clean.txt";
//! snapbox::Assert::new()
//! .action_env("SNAPSHOTS")
//! .matches_path(expected_path, actual);
//! ```
//!
//! [`harness::Harness`]
#![cfg_attr(not(feature = "harness"), doc = " ```rust,ignore")]
#![cfg_attr(feature = "harness", doc = " ```rust,no_run")]
//! snapbox::harness::Harness::new(
//! "tests/fixtures/invalid",
//! setup,
//! test,
//! )
//! .select(["tests/cases/*.in"])
//! .action_env("SNAPSHOTS")
//! .test();
//!
//! fn setup(input_path: std::path::PathBuf) -> snapbox::harness::Case {
//! let name = input_path.file_name().unwrap().to_str().unwrap().to_owned();
//! let expected = input_path.with_extension("out");
//! snapbox::harness::Case {
//! name,
//! fixture: input_path,
//! expected,
//! }
//! }
//!
//! fn test(input_path: &std::path::Path) -> Result<usize, Box<dyn std::error::Error>> {
//! let raw = std::fs::read_to_string(input_path)?;
//! let num = raw.parse::<usize>()?;
//!
//! let actual = num + 10;
//!
//! Ok(actual)
//! }
//! ```
//!
//! [trycmd]: https://docs.rs/trycmd
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
mod action;
mod assert;
mod data;
mod error;
mod substitutions;
pub mod cmd;
pub mod path;
pub mod report;
pub mod utils;
#[cfg(feature = "harness")]
pub mod harness;
pub use action::Action;
pub use action::DEFAULT_ACTION_ENV;
pub use assert::Assert;
pub use data::Data;
pub use data::DataFormat;
pub use data::{Normalize, NormalizeMatches, NormalizeNewlines, NormalizePaths};
pub use error::Error;
pub use snapbox_macros::debug;
pub use substitutions::Substitutions;
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// Check if a value is the same as an expected value
///
/// When the content is text, newlines are normalized.
///
/// ```rust
/// let output = "something";
/// let expected = "something";
/// snapbox::assert_matches(expected, output);
/// ```
#[track_caller]
pub fn assert_eq(expected: impl Into<crate::Data>, actual: impl Into<crate::Data>) {
Assert::new().eq(expected, actual);
}
/// Check if a value matches a pattern
///
/// Pattern syntax:
/// - `...` is a line-wildcard when on a line by itself
/// - `[..]` is a character-wildcard when inside a line
/// - `[EXE]` matches `.exe` on Windows
///
/// Normalization:
/// - Newlines
/// - `\` to `/`
///
/// ```rust
/// let output = "something";
/// let expected = "so[..]g";
/// snapbox::assert_matches(expected, output);
/// ```
#[track_caller]
pub fn assert_matches(pattern: impl Into<crate::Data>, actual: impl Into<crate::Data>) {
Assert::new().matches(pattern, actual);
}
/// Check if a value matches the content of a file
///
/// When the content is text, newlines are normalized.
///
/// ```rust,no_run
/// let output = "something";
/// let expected_path = "tests/snapshots/output.txt";
/// snapbox::assert_eq_path(expected_path, output);
/// ```
#[track_caller]
pub fn assert_eq_path(expected_path: impl AsRef<std::path::Path>, actual: impl Into<crate::Data>) {
Assert::new()
.action_env(DEFAULT_ACTION_ENV)
.eq_path(expected_path, actual);
}
/// Check if a value matches the pattern in a file
///
/// Pattern syntax:
/// - `...` is a line-wildcard when on a line by itself
/// - `[..]` is a character-wildcard when inside a line
/// - `[EXE]` matches `.exe` on Windows
///
/// Normalization:
/// - Newlines
/// - `\` to `/`
///
/// ```rust,no_run
/// let output = "something";
/// let expected_path = "tests/snapshots/output.txt";
/// snapbox::assert_matches_path(expected_path, output);
/// ```
#[track_caller]
pub fn assert_matches_path(
pattern_path: impl AsRef<std::path::Path>,
actual: impl Into<crate::Data>,
) {
Assert::new()
.action_env(DEFAULT_ACTION_ENV)
.matches_path(pattern_path, actual);
}
/// Check if a path matches the content of another path, recursively
///
/// When the content is text, newlines are normalized.
///
/// ```rust,no_run
/// let output_root = "...";
/// let expected_root = "tests/snapshots/output.txt";
/// snapbox::assert_subset_eq(expected_root, output_root);
/// ```
#[cfg(feature = "path")]
#[track_caller]
pub fn assert_subset_eq(
expected_root: impl Into<std::path::PathBuf>,
actual_root: impl Into<std::path::PathBuf>,
) {
Assert::new()
.action_env(DEFAULT_ACTION_ENV)
.subset_eq(expected_root, actual_root);
}
/// Check if a path matches the pattern of another path, recursively
///
/// Pattern syntax:
/// - `...` is a line-wildcard when on a line by itself
/// - `[..]` is a character-wildcard when inside a line
/// - `[EXE]` matches `.exe` on Windows
///
/// Normalization:
/// - Newlines
/// - `\` to `/`
///
/// ```rust,no_run
/// let output_root = "...";
/// let expected_root = "tests/snapshots/output.txt";
/// snapbox::assert_subset_matches(expected_root, output_root);
/// ```
#[cfg(feature = "path")]
#[track_caller]
pub fn assert_subset_matches(
pattern_root: impl Into<std::path::PathBuf>,
actual_root: impl Into<std::path::PathBuf>,
) {
Assert::new()
.action_env(DEFAULT_ACTION_ENV)
.subset_matches(pattern_root, actual_root);
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use crate::sessions::Session;
#[derive(PartialEq, Eq)]
pub enum ExpiringState {
InUse(String),
// return Duration, so user can choose to use Systime or Instance
Idle { idle_time: Duration },
Aborted { need_cleanup: bool },
}
pub trait Expirable {
fn expire_state(&self) -> ExpiringState;
fn on_expire(&self);
}
impl Expirable for Arc<Session> {
fn expire_state(&self) -> ExpiringState {
if self.is_aborting() {
ExpiringState::Aborted {
need_cleanup: false,
}
} else {
match self.get_current_query_id() {
None => {
let status = self.get_status();
let status = status.read();
ExpiringState::Idle {
idle_time: Instant::now() - status.last_access(),
}
}
Some(query_id) => ExpiringState::InUse(query_id),
}
}
}
fn on_expire(&self) {}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Display;
use anyerror::AnyError;
use crate::raft_types::ChangeMembershipError;
use crate::raft_types::Fatal;
use crate::raft_types::ForwardToLeader;
use crate::ClientWriteError;
use crate::InvalidReply;
use crate::MetaNetworkError;
use crate::RaftError;
/// Errors raised when meta-service handling a request.
#[derive(thiserror::Error, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum MetaAPIError {
/// If a request can only be dealt with by a leader, it informs the caller to forward the request to a leader.
#[error(transparent)]
ForwardToLeader(#[from] ForwardToLeader),
#[error("can not forward any more: {0}")]
CanNotForward(AnyError),
/// Network error when sending a request to the leader.
#[error(transparent)]
NetworkError(#[from] MetaNetworkError),
/// Error occurs on local peer.
#[error(transparent)]
DataError(#[from] MetaDataError),
/// Error occurs on remote peer.
///
/// A server side API does not emit such an error.
/// This is used for client-side to build a remote-error when receiving server errors
#[error(transparent)]
RemoteError(MetaDataError),
}
/// Errors raised when handling a request by raft node.
#[derive(thiserror::Error, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum MetaOperationError {
/// If a request can only be dealt by a leader, it informs the caller to forward the request to a leader it knows of.
#[error(transparent)]
ForwardToLeader(#[from] ForwardToLeader),
#[error(transparent)]
DataError(#[from] MetaDataError),
}
impl From<MetaOperationError> for MetaAPIError {
fn from(e: MetaOperationError) -> Self {
match e {
MetaOperationError::ForwardToLeader(e) => e.into(),
MetaOperationError::DataError(d) => d.into(),
}
}
}
/// Errors raised when read or write meta data locally.
#[derive(thiserror::Error, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum MetaDataError {
/// Error occurred when writing a raft log.
#[error(transparent)]
WriteError(#[from] Fatal),
/// Error occurred when change raft membership.
#[error(transparent)]
ChangeMembershipError(#[from] ChangeMembershipError),
/// Error occurred when reading.
#[error(transparent)]
ReadError(#[from] MetaDataReadError),
}
/// Error occurred when a meta-node reads data.
#[derive(thiserror::Error, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[error("fail to {action}: {msg}, source: {source}")]
pub struct MetaDataReadError {
action: String,
msg: String,
#[source]
source: AnyError,
}
impl MetaDataReadError {
pub fn new(
action: impl Display,
msg: impl Display,
source: &(impl std::error::Error + 'static),
) -> Self {
Self {
action: action.to_string(),
msg: msg.to_string(),
source: AnyError::new(source),
}
}
}
impl From<MetaDataReadError> for MetaOperationError {
fn from(e: MetaDataReadError) -> Self {
let de = MetaDataError::from(e);
MetaOperationError::from(de)
}
}
impl From<InvalidReply> for MetaAPIError {
fn from(e: InvalidReply) -> Self {
let net_err = MetaNetworkError::from(e);
Self::NetworkError(net_err)
}
}
impl From<RaftError<ClientWriteError>> for MetaAPIError {
fn from(value: RaftError<ClientWriteError>) -> Self {
match value {
RaftError::APIError(cli_write_err) => {
//
match cli_write_err {
ClientWriteError::ForwardToLeader(f) => MetaAPIError::ForwardToLeader(f),
ClientWriteError::ChangeMembershipError(c) => {
MetaAPIError::DataError(MetaDataError::ChangeMembershipError(c))
}
}
}
RaftError::Fatal(f) => MetaAPIError::DataError(MetaDataError::WriteError(f)),
}
}
}
|
use fnv::FnvHashSet;
use rayon::prelude::*;
use std::fmt::Debug;
fn overlap<T: PartialEq + Clone>(a: &Vec<T>, b: &Vec<T>) -> usize {
let mut i = 0;
let index = loop {
if b.starts_with(&a[i..]) {
break i;
} else {
i += 1;
}
};
a.len() - index
}
fn contains<T: PartialEq + Clone>(a: &Vec<T>, b: &Vec<T>) -> bool {
if a.len() < b.len() {
return false;
}
a.windows(b.len()).position(|i| i == b.as_slice()).is_some()
}
fn dedup<T: PartialEq + Clone>(data: Vec<Vec<T>>) -> Vec<Vec<T>> {
let mut result = Vec::new();
'm: for i in 0..data.len() {
for j in (0..result.len()).rev() {
if contains(&result[j], &data[i]) {
continue 'm;
}
if contains(&data[i], &result[j]) {
result.remove(j);
}
}
result.push(data[i].clone());
}
result
}
fn permutation(length: usize) -> Vec<(usize, usize)> {
let mut result = vec![];
for i in 0..length {
for j in 0..length {
if i == j {
continue;
};
result.push((i, j));
}
}
result
}
fn solve<T: PartialEq + Clone + Sync>(mut data: Vec<Vec<T>>) -> Vec<T> {
data = dedup(data);
let size = data.len();
while data.len() > 1 {
println!(
"Progress {:5.2}%",
100.0 - data.len() as f64 / size as f64 * 100.0
);
let mut result: Vec<(usize, usize, usize)> = permutation(data.len())
.into_par_iter()
.map(|(i, j): (usize, usize)| (i, j, overlap(&data[i], &data[j])))
.collect();
result.sort_unstable_by_key(|x| 1000 - x.2);
let target = result[0].2;
let length = result.iter().filter(|&x| x.2 == target).count();
let mut processed: FnvHashSet<usize> = FnvHashSet::default();
for i in 0..length {
let target = result[i];
if processed.contains(&target.0) || processed.contains(&target.1) {
continue;
}
let suffix = &data[target.1][target.2..].to_vec();
data[target.0].extend_from_slice(suffix);
processed.insert(target.0);
processed.insert(target.1);
}
data = dedup(data);
}
data[0].clone()
}
pub fn process<T: PartialEq + Clone + Sync + Send + Debug>(data: Vec<Vec<T>>) -> Vec<T> {
let result = solve(data.clone());
if data.iter().all(|x| contains(&result, x)) {
println!("Verified");
}
result
}
|
extern crate num;
use num::complex::Complex;
use std::io::prelude::*;
use std::fs::File;
use std::io::BufWriter;
fn mandelbrot(c: Complex<f64>, k: f64, lp: i32) -> i32 {
let mut z: Complex<f64> = Complex::new(0.0, 0.0);
for i in 0..lp {
z = z * z + c;
if z.norm_sqr() > k {
return i
}
}
lp
}
fn main() -> std::io::Result<()> {
let x_min = -2.0;
let x_max = 2.0;
let y_min = -2.0;
let y_max = 2.0;
let lp = 20;
let step = 0.01;
let k = 4.0;
let mut file = BufWriter::new(File::create("mandel.png.data")?);
let mut x = x_min;
while x < x_max {
let mut y = y_min;
while y < y_max {
let c: Complex<f64> = Complex::new(x, y);
let n = mandelbrot(c, k, lp);
write!(file, "{:.10}\t{:.10}\t{}\n", c.re, c.im, n)?;
y += step;
}
write!(file, "\n")?;
x += step;
}
println!("Hello, world!");
Ok(())
}
|
pub use VkDescriptorPoolResetFlags::*;
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VkDescriptorPoolResetFlags {
VK_DESCRIPTOR_POOL_RESET_NULL_BIT = 0,
}
use crate::SetupVkFlags;
#[repr(C)]
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct VkDescriptorPoolResetFlagBits(u32);
SetupVkFlags!(VkDescriptorPoolResetFlags, VkDescriptorPoolResetFlagBits);
|
fn range_test() {
let mut range = 0..10;
loop {
match range.next() {
Some(x) => {
println!("{}", x);
},
None => { break; }
}
}
}
fn interator_test() {
let nums = vec![1,2,3];
for num in &nums {
println!("{}", num);
}
// same with previous code,
// right here, we use *num explictly indicate num is
// in fact a reference
for num in &nums {
println!("{}", *num);
}
// in following code, we don't use a reference
// so in for loop, num is a copy of nums[i]
for num in nums {
println!("{}", num);
}
let nums_1 = (1..100).collect::<Vec<i32>>();
for num in &nums_1 {
println!("{}", num);
}
let nums_2 =[1,2,3];
for num in nums_2.iter() {
println!("{}", num);
}
}
fn consumer_test() {
let greater_than_forty_two = (0..100)
.find(|x| *x > 42);
match greater_than_forty_two {
Some(_) => println!("We got some numbers!"),
None => println!("No numbers found :(")
}
}
fn fold_test() {
let sum = (1..4).fold(0, |sum, x| sum+x);
println!("sum is {}", sum);
}
fn adaptive_iter_test() {
// will never print anything
// cause range is lasy, and map is another iterator
// so, only when this map is consumed, then the range is
// expanded
(1..100).map(|x| println!("{}", x));
for i in (1..).take(5) {
println!("{}", i);
}
for i in (1..100).filter(|&x| x % 2 == 0 ) {
println!("{}", i);
}
for i in (1..1000)
.filter(|&x| x % 2 == 0 )
.filter(|&x| x % 3 == 0 )
.take(5)
.collect::<Vec<i32>>() {
println!("{}", i);
}
}
fn main() {
range_test();
interator_test();
consumer_test();
fold_test();
adaptive_iter_test();
}
|
use ocl::{Queue, Buffer, Kernel, Context, Program, builders::DeviceSpecifier, error::Result};
#[derive(PartialEq, Eq)]
/// An operation that can be used to map over data
pub enum Op {
Add,
Min,
Mul,
Div,
Mod,
None
}
/// A safe wrapper type for Program
pub struct MapProgram(Program);
/// A safe wrapper type for Kernel
pub struct MapKernel(Kernel, usize);
impl MapProgram {
/// Creates a new program the uses given device to apply given mapping operation over data with given context
pub fn from<D: Into<DeviceSpecifier>>(devices: D, op: Op, context: &Context) -> Result<Self> {
let src = if op == Op::None {
String::from("__kernel void __main__(__global float* buffer, float scalar) {}")
} else {
format!(r#"
__kernel void __main__(__global float* buffer, float scalar) {{
buffer[get_global_id(0)] {}= scalar;
}}
"#, match op {
Op::Add => "+",
Op::Min => "-",
Op::Mul => "*",
Op::Div => "/",
Op::Mod => "%",
Op::None => panic!("creating program failed")
})
};
Program::builder()
.devices(devices)
.src(src)
.build(&context)
.map(|program| Self(program))
}
}
impl MapKernel {
/// Creates a new kernel the runs given program using given queue to map an operation over given buffer with given value
fn from(program: &MapProgram, queue: Queue, buffer: &Buffer<f32>, val: &f32) -> Result<Self> {
let buffer_len = buffer.len();
Kernel::builder()
.program(&program.0)
.name("__main__")
.queue(queue.clone())
.global_work_size(buffer_len)
.arg(buffer)
.arg(val)
.build()
.map(|kernel| Self(kernel, buffer_len))
}
/// Executes the kernel
fn cmd_enq(&self, queue: &Queue) {
unsafe {
self.0.cmd()
.queue(&queue)
.global_work_offset(self.0.default_global_work_offset())
.global_work_size(self.1)
.local_work_size(self.0.default_local_work_size())
.enq().unwrap();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ocl::{flags, Platform, Device, Context, Queue, Program, Buffer, Kernel};
#[test]
fn test_add_unsafe() {
let src = r#"
__kernel void add(__global float* buffer, float scalar) {
buffer[get_global_id(0)] += scalar;
}
"#;
// (1) Define which platform and device(s) to use. Create a context,
// queue, and program then define some dims (compare to step 1 above).
let platform = Platform::default();
let device = Device::first(platform).unwrap();
let context = Context::builder()
.platform(platform)
.devices(device.clone())
.build().unwrap();
let program = Program::builder()
.devices(device)
.src(src)
.build(&context).unwrap();
let queue = Queue::new(&context, device, None).unwrap();
let dims = 1 << 20;
// [NOTE]: At this point we could manually assemble a ProQue by calling:
// `ProQue::new(context, queue, program, Some(dims))`. One might want to
// do this when only one program and queue are all that's needed. Wrapping
// it up into a single struct makes passing it around simpler.
// (2) Create a `Buffer`:
let buffer = Buffer::<f32>::builder()
.queue(queue.clone())
.flags(flags::MEM_READ_WRITE)
.len(dims)
.fill_val(0f32)
.build().unwrap();
// (3) Create a kernel with arguments matching those in the source above:
let kernel = Kernel::builder()
.program(&program)
.name("add")
.queue(queue.clone())
.global_work_size(dims)
.arg(&buffer)
.arg(&10.0f32)
.build().unwrap();
// (4) Run the kernel (default parameters shown for demonstration purposes):
unsafe {
kernel.cmd()
.queue(&queue)
.global_work_offset(kernel.default_global_work_offset())
.global_work_size(dims)
.local_work_size(kernel.default_local_work_size())
.enq().unwrap();
}
// (5) Read results from the device into a vector (`::block` not shown):
let mut vec = vec![0.0f32; dims];
buffer.cmd()
.queue(&queue)
.offset(0)
.read(&mut vec)
.enq().unwrap();
assert_eq!(vec, vec![10.0f32; dims]);
}
#[test]
fn test_add() {
// (1) Define which platform and device(s) to use. Create a context,
// queue, and program then define some dims (compare to step 1 above).
let platform = Platform::default();
let device = Device::first(platform).unwrap();
let context = Context::builder()
.platform(platform)
.devices(device.clone())
.build().unwrap();
let program = MapProgram::from(device, Op::Add, &context).unwrap();
let queue = Queue::new(&context, device, None).unwrap();
let dims = 1 << 20;
// [NOTE]: At this point we could manually assemble a ProQue by calling:
// `ProQue::new(context, queue, program, Some(dims))`. One might want to
// do this when only one program and queue are all that's needed. Wrapping
// it up into a single struct makes passing it around simpler.
// (2) Create a `Buffer`:
let buffer = Buffer::<f32>::builder()
.queue(queue.clone())
.flags(flags::MEM_READ_WRITE) // TODO ensure buffer is read-write
.len(dims)
.fill_val(0f32)
.build().unwrap();
// (3) Create a kernel with arguments matching those in the source above:
let kernel = MapKernel::from(&program, queue.clone(), &buffer, &10.0f32).unwrap();
// (4) Run the kernel (default parameters shown for demonstration purposes):
kernel.cmd_enq(&queue);
// (5) Read results from the device into a vector (`::block` not shown):
let mut vec = vec![0.0f32; dims];
buffer.cmd()
.queue(&queue)
.offset(0)
.read(&mut vec)
.enq().unwrap();
assert_eq!(vec, vec![10.0f32; dims]);
}
}
|
fn main() {
let result = match rand::random() {
false => "Heads",
true => "Tails",
};
println!("{}", result);
}
|
use super::VecMutator;
use crate::mutators::mutations::{Mutation, RevertMutation};
use crate::{Mutator, SubValueProvider};
pub struct Arbitrary;
#[derive(Clone)]
pub struct ArbitraryStep;
pub struct ConcreteArbitrary<T> {
value: Vec<T>,
cplx: f64,
}
pub struct RevertArbitrary<T> {
value: Vec<T>,
}
impl<T, M> RevertMutation<Vec<T>, VecMutator<T, M>> for RevertArbitrary<T>
where
T: Clone + 'static,
M: Mutator<T>,
{
#[no_coverage]
fn revert(
mut self,
_mutator: &VecMutator<T, M>,
value: &mut Vec<T>,
_cache: &mut <VecMutator<T, M> as Mutator<Vec<T>>>::Cache,
) {
std::mem::swap(value, &mut self.value);
}
}
impl<T, M> Mutation<Vec<T>, VecMutator<T, M>> for Arbitrary
where
T: Clone + 'static,
M: Mutator<T>,
{
type RandomStep = ArbitraryStep;
type Step = ArbitraryStep;
type Concrete<'a> = ConcreteArbitrary<T>;
type Revert = RevertArbitrary<T>;
#[no_coverage]
fn default_random_step(&self, mutator: &VecMutator<T, M>, _value: &Vec<T>) -> Option<Self::RandomStep> {
if mutator.m.max_complexity() == 0. {
return None;
}
Some(ArbitraryStep)
}
#[no_coverage]
fn random<'a>(
mutator: &VecMutator<T, M>,
_value: &Vec<T>,
_cache: &<VecMutator<T, M> as Mutator<Vec<T>>>::Cache,
_random_step: &Self::RandomStep,
max_cplx: f64,
) -> Self::Concrete<'a> {
let (new_value, new_cplx) = mutator.random_arbitrary(max_cplx);
ConcreteArbitrary {
value: new_value,
cplx: new_cplx,
}
}
#[no_coverage]
fn default_step(
&self,
mutator: &VecMutator<T, M>,
value: &Vec<T>,
_cache: &<VecMutator<T, M> as Mutator<Vec<T>>>::Cache,
) -> Option<Self::Step> {
self.default_random_step(mutator, value)
}
#[no_coverage]
fn from_step<'a>(
mutator: &VecMutator<T, M>,
value: &Vec<T>,
cache: &<VecMutator<T, M> as Mutator<Vec<T>>>::Cache,
step: &'a mut Self::Step,
_subvalue_provider: &dyn SubValueProvider,
max_cplx: f64,
) -> Option<Self::Concrete<'a>> {
Some(Self::random(mutator, value, cache, step, max_cplx))
}
#[no_coverage]
fn apply<'a>(
mut mutation: Self::Concrete<'a>,
_mutator: &VecMutator<T, M>,
value: &mut Vec<T>,
_cache: &mut <VecMutator<T, M> as Mutator<Vec<T>>>::Cache,
_subvalue_provider: &dyn SubValueProvider,
_max_cplx: f64,
) -> (Self::Revert, f64) {
std::mem::swap(value, &mut mutation.value);
(RevertArbitrary { value: mutation.value }, mutation.cplx)
}
}
|
use chrono_tz::Tz;
use crate::{InputValueError, InputValueResult, Scalar, ScalarType, Value};
#[Scalar(
internal,
name = "TimeZone",
specified_by_url = "http://www.iana.org/time-zones"
)]
impl ScalarType for Tz {
fn parse(value: Value) -> InputValueResult<Self> {
match value {
Value::String(s) => Ok(s.parse()?),
_ => Err(InputValueError::expected_type(value)),
}
}
fn to_value(&self) -> Value {
Value::String(self.name().to_owned())
}
}
|
use coruscant_nbt::{from_slice, to_vec, Result};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct TestStruct {
#[serde(rename = "byteTest")]
byte_test: i8,
#[serde(rename = "shortTest")]
short_test: i16,
#[serde(rename = "intTest")]
int_test: i32,
#[serde(rename = "longTest")]
long_test: i64,
#[serde(rename = "floatTest")]
float_test: f32,
#[serde(rename = "doubleTest")]
double_test: f64,
#[serde(rename = "stringTest")]
string_test: String,
#[serde(rename = "listTest (long)")]
list_long_test: [i64; 5],
#[serde(rename = "listTest (compound)")]
list_compound_test: Vec<NestedCompound>,
#[serde(
rename = "byteArrayTest (the first 1000 values of (n*n*255+n*7)%100, starting with n=0 (0, 62, 34, 16, 8, ...))"
)]
byte_array_test: Box<[i8]>,
#[serde(rename = "nested compound test")]
nested: Nested,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Nested {
egg: Food,
ham: Food,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Food {
name: String,
value: f32,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct NestedCompound {
#[serde(rename = "created-on")]
created_on: i64,
name: String,
}
fn main() -> Result<()> {
let mut byte_array_test = Vec::new();
for i in 0i32..1000 {
let value = (i * i * 255 + i * 7) % 100;
byte_array_test.push(value as i8)
}
let byte_array_test = byte_array_test.into_boxed_slice();
let value = TestStruct {
nested: Nested {
egg: Food {
name: "Eggbert".to_owned(),
value: 0.5,
},
ham: Food {
name: "Hampus".to_owned(),
value: 0.75,
},
},
byte_test: 127,
short_test: 32767,
int_test: 2147483647,
long_test: 9223372036854775807,
double_test: 0.49312871321823148,
float_test: 0.49823147058486938,
string_test: "HELLO WORLD THIS IS A TEST STRING!".to_owned(),
list_long_test: [11, 12, 13, 14, 15],
list_compound_test: vec![
NestedCompound {
created_on: 1264099775885,
name: "Compound tag #0".to_owned(),
},
NestedCompound {
created_on: 1264099775885,
name: "Compound tag #1".to_owned(),
},
],
byte_array_test,
};
let vec = to_vec(&value)?;
println!("{:?}", vec);
let ans: TestStruct = from_slice(&vec)?;
println!("{:?}", ans);
Ok(())
}
|
extern crate merkle;
mod channel;
use merkle::prelude::*;
use std::sync::{Arc, RwLock};
use rayon::prelude::*;
use std::time::Instant;
use rand::prelude::*;
use std::sync::atomic::{AtomicI64, Ordering};
use timer;
use chrono::Duration;
use crate::channel::{ContextAction, ContextActionJson};
use std::io::{Cursor, Read};
use serde_json::{Value, Map};
use std::convert::TryInto;
use std::collections::BTreeMap;
use clap::Arg;
use sysinfo::{SystemExt, Process, ProcessExt};
use tokio::process::Command;
use std::process::Output;
use tokio::io::Error;
use tokio::macros::support::Future;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let matches = clap::App::new("Merkle Storage Benchmark")
.author("mambisi.zempare@simplestaking.com")
.arg(Arg::with_name("node")
.short("n")
.long("node")
.value_name("NODE")
.takes_value(true)
.default_value("http://127.0.0.1:18732")
.help("Node base url")
)
.arg(Arg::with_name("limit")
.short("l")
.long("limit")
.value_name("LIMIT")
.takes_value(true)
.default_value("25000")
.help("Specifies the block height limit")
)
.arg(Arg::with_name("cycle")
.short("c")
.long("cycle")
.value_name("CYCLE")
.takes_value(true)
.default_value("4096")
.help("Cycle length, logs the memory usage at every cycle")
)
.get_matches();
let node = matches.value_of("node").unwrap();
let blocks_limit = matches.value_of("limit").unwrap().parse::<u64>().unwrap_or(25000);
let cycle = matches.value_of("cycle").unwrap().parse::<u64>().unwrap_or(4096);
let process_id = std::process::id();
println!("node {}, limit {}, process id: {}", node, blocks_limit, process_id);
run_benchmark(process_id, node, blocks_limit, cycle).await
}
async fn run_benchmark(process_id: u32, node: &str, blocks_limit: u64, cycle: u64) -> Result<(), Box<dyn std::error::Error>> {
let blocks_url = format!("{}/dev/chains/main/blocks?limit={}&from_block_id={}", node, blocks_limit + 10, blocks_limit);
let db = Arc::new(RwLock::new(DB::new()));
let mut storage = MerkleStorage::new(db.clone());
let mut current_cycle = 0;
let mut blocks = reqwest::get(&blocks_url)
.await?
.json::<Vec<Value>>()
.await?;
blocks.reverse();
for block in blocks {
let block = block.as_object().unwrap();
let block_hash = block.get("hash").unwrap().as_str();
let block_header = block.get("header").unwrap().as_object().unwrap();
let block_level = block_header.get("level").unwrap().as_u64().unwrap();
let block_hash = block_hash.unwrap();
let actions_url = format!("{}/dev/chains/main/actions/blocks/{}", node, block_hash);
drop(block);
let mut messages = reqwest::get(&actions_url)
.await?
.json::<Vec<ContextActionJson>>()
.await?;
for msg in &messages {
match &msg.action {
ContextAction::Set { key, value, context_hash, ignored, .. } =>
if !ignored {
storage.set(key, value);
}
ContextAction::Copy { to_key: key, from_key, context_hash, ignored, .. } =>
if !ignored {
storage.copy(from_key, key);
}
ContextAction::Delete { key, context_hash, ignored, .. } =>
if !ignored {
storage.delete(key);
}
ContextAction::RemoveRecursively { key, context_hash, ignored, .. } =>
if !ignored {
storage.delete(key);
}
ContextAction::Commit {
parent_context_hash, new_context_hash, block_hash: Some(block_hash),
author, message, date, ..
} => {
let date = *date as u64;
let hash = storage.commit(date, author.to_owned(), message.to_owned()).unwrap();
let commit_hash = hash[..].to_vec();
assert_eq!(&commit_hash, new_context_hash,
"Invalid context_hash for block: {}, expected: {}, but was: {}",
HashType::BlockHash.bytes_to_string(block_hash),
HashType::ContextHash.bytes_to_string(new_context_hash),
HashType::ContextHash.bytes_to_string(&commit_hash),
);
}
ContextAction::Checkout { context_hash, .. } => {
let context_hash_arr: EntryHash = context_hash.as_slice().try_into().unwrap();
storage.checkout(&context_hash_arr);
}
_ => (),
};
}
if block_level != 0 && block_level % cycle == 0 {
current_cycle += 1;
println!("Memory stats at cycle: {}", current_cycle);
match storage.get_merkle_stats() {
Ok(stats) => {
println!("{:#?}", stats)
}
Err(_) => {}
};
let pid = process_id.to_string();
if cfg!(target_os = "linux") || cfg!(target_os = "macos") {
let output = Command::new("ps")
.arg("-p")
.arg(&pid)
.arg("-o")
.arg("pid,%mem,rss,vsize")
.output().await;
match output {
Ok(output) => {
println!("{}", String::from_utf8_lossy(&output.stdout))
}
Err(_) => {
println!("Error executing PS")
}
}
}
}
}
Ok(())
}
|
use std::mem;
#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
struct Point {
x: f64,
y: f64,
}
#[allow(dead_code)]
struct Rectangle {
p1: Point,
p2: Point,
}
fn origin() -> Point {
Point { x: 0.0, y: 0.0 }
}
fn boxed_origin() -> Box<Point> {
// allocate on heap
Box::new(Point { x: 0.0, y: 0.0 })
}
pub fn demo() {
let point: Point = origin();
println!("{:?}", point);
let boxed_point: Box<Point> = boxed_origin();
println!("{:?}", boxed_point)
}
|
//! Filesystem paths in Windows are a total mess. This crate normalizes paths to the most
//! compatible (but still correct) format, so that you don't have to worry about the mess.
//!
//! In Windows the regular/legacy paths (`C:\foo`) are supported by all programs, but have
//! lots of bizarre restrictions for backwards compatibility with MS-DOS.
//!
//! And there are Windows NT UNC paths (`\\?\C:\foo`), which are more robust and with fewer
//! gotchas, but are rarely supported by Windows programs. Even Microsoft's own!
//!
//! This crate converts paths to legacy format whenever possible, but leaves UNC paths as-is
//! when they can't be unambiguously expressed in a simpler way. This allows legacy programs
//! to access all paths they can possibly access, and UNC-aware programs to access all paths.
//!
//! On non-Windows platforms these functions leave paths unmodified, so it's safe to use them
//! unconditionally for all platforms.
//!
//! Parsing is based on https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
//!
//! [Project homepage](https://crates.rs/crates/dunce).
#![doc(html_logo_url = "https://assets.gitlab-static.net/uploads/-/system/project/avatar/4717715/dyc.png")]
#[cfg(any(windows, test))]
use std::ffi::OsStr;
use std::fs;
use std::io;
#[cfg(windows)]
use std::os::windows::ffi::OsStrExt;
#[cfg(windows)]
use std::path::{Component, Prefix};
use std::path::{Path, PathBuf};
/// Takes any path, and when possible, converts Windows UNC paths to regular paths.
///
/// On non-Windows this is no-op.
///
/// `\\?\C:\Windows` will be converted to `C:\Windows`,
/// but `\\?\C:\COM` will be left as-is (due to a reserved filename).
///
/// Use this to pass arbitrary paths to programs that may not be UNC-aware.
/// It's generally safe to pass UNC paths to legacy programs, because
/// the paths contain a reserved character, so will gracefully fail
/// if used with wrong APIs.
///
/// This function does not perform any I/O.
///
/// Currently paths with unpaired surrogates aren't converted even if they
/// can be due to limitations of Rust's `OsStr` API.
#[inline]
pub fn simplified(path: &Path) -> &Path {
if is_safe_to_strip_unc(path) {
// unfortunately we can't safely strip prefix from a non-Unicode path
path.to_str().and_then(|s| s.get(4..)).map(Path::new).unwrap_or(path)
} else {
path
}
}
/// Like `std::fs::canonicalize()`, but on Windows it outputs the most
/// compatible form of a path instead of UNC.
#[inline(always)]
pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
let path = path.as_ref();
#[cfg(not(windows))]
{
fs::canonicalize(path)
}
#[cfg(windows)]
{
canonicalize_win(path)
}
}
#[cfg(windows)]
fn canonicalize_win(path: &Path) -> io::Result<PathBuf> {
let real_path = fs::canonicalize(path)?;
Ok(if is_safe_to_strip_unc(&real_path) {
real_path.to_str().and_then(|s| s.get(4..)).map(PathBuf::from).unwrap_or(real_path)
} else {
real_path
})
}
pub use self::canonicalize as realpath;
#[cfg(any(windows,test))]
fn windows_char_len(s: &OsStr) -> usize {
#[cfg(not(windows))]
let len = s.to_string_lossy().chars().map(|c| if c as u32 <= 0xFFFF {1} else {2}).sum();
#[cfg(windows)]
let len = s.encode_wide().count();
len
}
#[cfg(any(windows,test))]
fn is_valid_filename(file_name: &OsStr) -> bool {
let file_name = file_name.as_ref();
if windows_char_len(file_name) > 255 {
return false;
}
// Non-unicode is safe, but Rust can't reasonably losslessly operate on such strings
let file_name = if let Some(s) = file_name.to_str() {
s
} else {
return false;
};
if file_name.is_empty() {
return false;
}
// Only ASCII subset is checked, and UTF-8 is safe for that
let byte_str = file_name.as_bytes();
for &c in byte_str {
match c {
0..=31 |
b'<' | b'>' | b':' | b'"' |
b'/' | b'\\' | b'|' | b'?' | b'*' => return false,
_ => {},
}
}
// Filename can't end with . or space (except before extension, but this checks the whole name)
let last_char = byte_str[byte_str.len()-1];
if last_char == b' ' || last_char == b'.' {
return false;
}
true
}
#[cfg(any(windows, test))]
const RESERVED_NAMES: [&'static str; 22] = [
"AUX", "NUL", "PRN", "CON", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
"COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
];
#[cfg(any(windows, test))]
fn is_reserved<P: AsRef<OsStr>>(file_name: P) -> bool {
// con.txt is reserved too
if let Some(stem) = Path::new(&file_name).file_stem() {
// all reserved DOS names have ASCII-compatible stem
if let Some(name) = stem.to_str() {
// "con.. .txt" is "CON" for DOS
let trimmed = right_trim(name);
if trimmed.len() <= 4 {
for name in &RESERVED_NAMES {
if name.eq_ignore_ascii_case(trimmed) {
return true;
}
}
}
}
}
false
}
#[cfg(not(windows))]
#[inline]
fn is_safe_to_strip_unc(_path: &Path) -> bool {
false
}
#[cfg(windows)]
fn is_safe_to_strip_unc(path: &Path) -> bool {
let mut components = path.components();
match components.next() {
Some(Component::Prefix(p)) => match p.kind() {
Prefix::VerbatimDisk(..) => {},
_ => return false, // Other kinds of UNC paths
},
_ => return false, // relative or empty
}
for component in components {
match component {
Component::RootDir => {},
Component::Normal(file_name) => {
// it doesn't allocate in most cases,
// and checks are interested only in the ASCII subset, so lossy is fine
if !is_valid_filename(file_name) || is_reserved(file_name) {
return false;
}
}
_ => return false, // UNC paths take things like ".." literally
};
}
if windows_char_len(path.as_os_str()) > 260 { // However, if the path is going to be used as a directory it's 248
return false;
}
true
}
/// Trim '.' and ' '
#[cfg(any(windows, test))]
fn right_trim(mut s: &str) -> &str {
while s.len() > 0 {
let last = s.len()-1;
unsafe {
if s.as_bytes()[last] == b'.' || s.as_bytes()[last] == b' ' {
s = s.get_unchecked(0..last) // trim of ASCII byte can't break UTF-8
} else {
break;
}
}
}
s
}
#[test]
fn trim_test() {
assert_eq!("a", right_trim("a."));
assert_eq!("ą", right_trim("ą."));
assert_eq!("a", right_trim("a "));
assert_eq!("ąą", right_trim("ąą "));
assert_eq!("a", right_trim("a. . . .... "));
assert_eq!("a. . . ..ź", right_trim("a. . . ..ź.. "));
assert_eq!(" b", right_trim(" b"));
assert_eq!(" べ", right_trim(" べ"));
assert_eq!("c. c", right_trim("c. c."));
assert_eq!("。", right_trim("。"));
assert_eq!("", right_trim(""));
}
#[test]
fn reserved() {
assert!(is_reserved("CON"));
assert!(is_reserved("con"));
assert!(is_reserved("con.con"));
assert!(is_reserved("COM4"));
assert!(is_reserved("COM4.txt"));
assert!(is_reserved("COM4 .txt"));
assert!(is_reserved("con."));
assert!(is_reserved("con ."));
assert!(is_reserved("con "));
assert!(is_reserved("con . "));
assert!(is_reserved("con . .txt"));
assert!(is_reserved("con.....txt"));
assert!(is_reserved("PrN....."));
assert!(!is_reserved(" PrN....."));
assert!(!is_reserved(" CON"));
assert!(!is_reserved("COM0"));
assert!(!is_reserved("COM77"));
assert!(!is_reserved(" CON "));
assert!(!is_reserved(".CON"));
assert!(!is_reserved("@CON"));
assert!(!is_reserved("not.CON"));
assert!(!is_reserved("CON。"));
}
#[test]
fn len() {
assert_eq!(1, windows_char_len(OsStr::new("a")));
assert_eq!(1, windows_char_len(OsStr::new("€")));
assert_eq!(1, windows_char_len(OsStr::new("本")));
assert_eq!(2, windows_char_len(OsStr::new("🧐")));
assert_eq!(2, windows_char_len(OsStr::new("®®")));
}
#[test]
fn valid() {
assert!(!is_valid_filename("..".as_ref()));
assert!(!is_valid_filename(".".as_ref()));
assert!(!is_valid_filename("aaaaaaaaaa:".as_ref()));
assert!(!is_valid_filename("ą:ą".as_ref()));
assert!(!is_valid_filename("".as_ref()));
assert!(!is_valid_filename("a ".as_ref()));
assert!(!is_valid_filename(" a. ".as_ref()));
assert!(!is_valid_filename("a/".as_ref()));
assert!(!is_valid_filename("/a".as_ref()));
assert!(!is_valid_filename("/".as_ref()));
assert!(!is_valid_filename("\\".as_ref()));
assert!(!is_valid_filename("\\a".as_ref()));
assert!(!is_valid_filename("<x>".as_ref()));
assert!(!is_valid_filename("a*".as_ref()));
assert!(!is_valid_filename("?x".as_ref()));
assert!(!is_valid_filename("a\0a".as_ref()));
assert!(!is_valid_filename("\x1f".as_ref()));
assert!(!is_valid_filename(::std::iter::repeat("a").take(257).collect::<String>().as_ref()));
assert!(is_valid_filename(::std::iter::repeat("®").take(254).collect::<String>().as_ref()));
assert!(is_valid_filename("ファイル".as_ref()));
assert!(is_valid_filename("a".as_ref()));
assert!(is_valid_filename("a.aaaaaaaa".as_ref()));
assert!(is_valid_filename("a........a".as_ref()));
assert!(is_valid_filename(" b".as_ref()));
}
#[test]
#[cfg(windows)]
fn realpath_test() {
assert_eq!(r"C:\WINDOWS", canonicalize(r"C:\Windows").unwrap().to_str().unwrap().to_uppercase());
assert_ne!(r".", canonicalize(r".").unwrap().to_str().unwrap());
}
#[test]
#[cfg(windows)]
fn strip() {
assert_eq!(Path::new(r"C:\foo\😀"), simplified(Path::new(r"\\?\C:\foo\😀")));
assert_eq!(Path::new(r"\\?\serv\"), simplified(Path::new(r"\\?\serv\")));
assert_eq!(Path::new(r"\\.\C:\notdisk"), simplified(Path::new(r"\\.\C:\notdisk")));
assert_eq!(Path::new(r"\\?\GLOBALROOT\Device\ImDisk0\path\to\file.txt"), simplified(Path::new(r"\\?\GLOBALROOT\Device\ImDisk0\path\to\file.txt")));
}
#[test]
#[cfg(windows)]
fn safe() {
assert!(is_safe_to_strip_unc(Path::new(r"\\?\C:\foo\bar")));
assert!(is_safe_to_strip_unc(Path::new(r"\\?\Z:\foo\bar\")));
assert!(is_safe_to_strip_unc(Path::new(r"\\?\Z:\😀\🎃\")));
assert!(is_safe_to_strip_unc(Path::new(r"\\?\c:\foo")));
let long = ::std::iter::repeat("®").take(160).collect::<String>();
assert!(is_safe_to_strip_unc(Path::new(&format!(r"\\?\c:\{}", long))));
assert!(!is_safe_to_strip_unc(Path::new(&format!(r"\\?\c:\{}\{}", long, long))));
assert!(!is_safe_to_strip_unc(Path::new(r"\\?\C:\foo\.\bar")));
assert!(!is_safe_to_strip_unc(Path::new(r"\\?\C:\foo\..\bar")));
assert!(!is_safe_to_strip_unc(Path::new(r"\\?\c\foo")));
assert!(!is_safe_to_strip_unc(Path::new(r"\\?\c\foo/bar")));
assert!(!is_safe_to_strip_unc(Path::new(r"\\?\c:foo")));
assert!(!is_safe_to_strip_unc(Path::new(r"\\?\cc:foo")));
assert!(!is_safe_to_strip_unc(Path::new(r"\\?\c:foo\bar")));
}
|
use std::convert::TryFrom;
use std::time::Duration;
use tokio::process::Child;
use tokio::process::Command;
use sysinfo::{ProcessExt, System, SystemExt};
const CPU_VOLTAGE: f32 = 1.2;
const AMP_MAX: f32 = 0.98;
async fn watch_process(
pid: i32,
mut child: Child,
mut interval: tokio::time::Interval,
) -> Result<Vec<f32>, String> {
let mut system = System::new_all();
let mut measurements = Vec::new();
loop {
// Check if the process has terminated.
match child.try_wait() {
Ok(Some(_)) => return Ok(measurements),
Err(e) => return Err(e.to_string()),
Ok(None) => (),
}
system.refresh_all();
match system.get_process(pid) {
None => return Err(format!("cound't get process with pid: ({})", pid)),
Some(process) => measurements.push(process.cpu_usage()),
}
interval.tick().await;
}
}
pub fn calculate_energy(measurements: &[f32], poll_interval: Duration) -> f32 {
let poll_interval = poll_interval.as_secs_f32();
measurements
.iter()
.map(|m| (m / 100f32) * CPU_VOLTAGE * AMP_MAX)
.map(|watts| watts * (poll_interval as f32))
.sum()
}
pub async fn estimate_energy(args: &[String]) -> Result<f32, Box<dyn std::error::Error>> {
let child = Command::new(&args[1]).args(&args[2..]).spawn()?;
let poll_interval = Duration::from_millis(1);
let pid = child.id().ok_or("child process completed too quickly")?;
let measurements = watch_process(
i32::try_from(pid)?,
child,
tokio::time::interval(poll_interval),
)
.await?;
Ok(calculate_energy(&measurements, poll_interval))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_calculate_energy() {
let measurements = vec![400f32];
let interval = Duration::from_secs(1);
assert_eq!(
calculate_energy(&measurements, interval).round(),
4.704f32.round()
)
}
}
|
use super::*;
use std::fmt;
use std::fmt::Display;
use rand::Rng;
#[derive(Debug, Clone)]
pub struct PlayerMat {
pub tiles: Vec<FarmTile>
}
impl PlayerMat {
pub fn new() -> PlayerMat {
let mut player_mat = Vec::new();
for i in 0..15 {
let mut new_tile = FarmTile::new(i);
match i {
5|10 => {
new_tile.house = Some(HouseType::Wood);
},
_ => new_tile.house = None
}
match i {
4|9|14 => {},
_ => new_tile.surrounding_tiles.push(i+1)
}
match i {
0|5|10 => {},
_ => new_tile.surrounding_tiles.push(i-1)
}
match i {
0..5 => {},
_ => new_tile.surrounding_tiles.push(i-5)
}
match i {
10..15 => {},
_ => new_tile.surrounding_tiles.push(i+5)
}
player_mat.push(new_tile);
}
PlayerMat { tiles: player_mat }
}
/*
/// Given a number, place a fence at that location for both tiles touching that fence location
/// Returns: True, placed fence; False, already occupied
pub fn place_fence(&mut self, x: usize) -> Option<usize> {
let tile_index = x / 4;
let position = x % 4;
match position {
0 => {
{
let curr_tile = &self.tiles[tile_index];
if curr_tile.north_fence == true {
return None;
}
}
match tile_index {
0..5 => {
{
let curr_tile = &mut self.tiles[tile_index];
if curr_tile.house.is_none() && curr_tile.field.is_none() {
curr_tile.north_fence = true;
} else {
return None;
}
}
}, // Prevent underflow
_ => {
{
let curr_tile = self.tiles[tile_index].clone();
let next_tile = self.tiles[tile_index-5].clone();
// Only place a horizontal fence if one of the two adjacent tiles
// is not a house or field
if (curr_tile.house.is_none() && curr_tile.field.is_none()) ||
(next_tile.house.is_none() && next_tile.field.is_none()) {
{
let curr_tile = &mut self.tiles[tile_index];
curr_tile.north_fence = true;
}
{
let next_tile = &mut self.tiles[tile_index-5];
next_tile.south_fence = true;
}
} else {
return None;
}
}
}
}
},
1 => {
{
let curr_tile = &self.tiles[tile_index];
if curr_tile.west_fence == true {
return None;
}
}
match tile_index {
0|5|10 => {
let curr_tile = &mut self.tiles[tile_index];
if curr_tile.house.is_none() && curr_tile.field.is_none() {
curr_tile.west_fence = true;
} else {
return None;
}
}, // Prevent underflow
_ => {
{
let curr_tile = self.tiles[tile_index].clone();
let next_tile = self.tiles[tile_index-1].clone();
// Only place a vertical fence if one of the two adjacent tiles
// is not a house or field
if (curr_tile.house.is_none() && curr_tile.field.is_none()) ||
(next_tile.house.is_none() && next_tile.field.is_none()) {
{
let curr_tile = &mut self.tiles[tile_index];
curr_tile.west_fence = true;
}
{
let next_tile = &mut self.tiles[tile_index-1];
next_tile.east_fence = true;
}
} else {
return None;
}
}
}
}
},
2 => {
{
let curr_tile = &self.tiles[tile_index];
if curr_tile.south_fence == true {
return None;
}
}
match tile_index {
10..15 => { // Prevent out of bounds access
let curr_tile = &mut self.tiles[tile_index];
if curr_tile.house.is_none() && curr_tile.field.is_none() {
curr_tile.south_fence = true;
} else {
return None;
}
},
_ => {
{
let curr_tile = self.tiles[tile_index].clone();
let next_tile = self.tiles[tile_index+5].clone();
// Only place a vertical fence if one of the two adjacent tiles
// is not a house or field
if (curr_tile.house.is_none() && curr_tile.field.is_none()) ||
(next_tile.house.is_none() && next_tile.field.is_none()) {
{
let curr_tile = &mut self.tiles[tile_index];
curr_tile.south_fence = true;
}
{
let next_tile = &mut self.tiles[tile_index+5];
next_tile.north_fence = true;
}
} else {
return None;
}
}
}
}
},
3 => {
{
let curr_tile = &self.tiles[tile_index];
if curr_tile.east_fence == true {
return None;
}
}
match tile_index {
4|9|14 => {
let curr_tile = &mut self.tiles[tile_index];
if curr_tile.house.is_none() && curr_tile.field.is_none() {
curr_tile.east_fence = true;
} else {
return None;
}
}, // Prevent out of bounds access
_ => {
{
let curr_tile = self.tiles[tile_index].clone();
let next_tile = self.tiles[tile_index+1].clone();
// Only place a vertical fence if one of the two adjacent tiles
// is not a house or field
if (curr_tile.house.is_none() && curr_tile.field.is_none()) ||
(next_tile.house.is_none() && next_tile.field.is_none()) {
{
let curr_tile = &mut self.tiles[tile_index];
curr_tile.east_fence = true;
}
{
let next_tile = &mut self.tiles[tile_index+1];
next_tile.west_fence = true;
}
} else {
return None;
}
}
}
}
},
_ => panic!("Should never reach here!")
};
/*
let string_index = match position {
0 => format!("{}-{}N", x, tile_index),
1 => format!("{}-{}W", x, tile_index),
2 => format!("{}-{}S", x, tile_index),
3 => format!("{}-{}E", x, tile_index),
_ => panic!("No other valid fence position")
};
*/
return Some(tile_index);
}
*/
pub fn plow_random_field(&mut self) {
// Get vector of indexes of current fields in the player mat
let curr_fields: Vec<usize> = self.tiles
.iter()
.enumerate()
.filter(|&(i, t)| !(t.field.is_none()))
.map(|(i, t)| i)
.collect();
// Filter surrounding tiles if they are empty
let possible_fields: Vec<usize> = curr_fields.iter()
.flat_map(|&i| self.tiles[i].surrounding_tiles.clone())
.filter(|&i| self.tiles[i].is_empty())
.collect();
if possible_fields.len() == 0 {
return;
}
let random_field = ::rand::thread_rng().choose(&possible_fields).unwrap();
self.tiles[*random_field].plow();
}
pub fn current_fences(&self) -> Vec<(usize, &str)> {
let mut current_fences = Vec::new();
for (i, tile) in self.tiles.iter().enumerate() {
if tile.north_fence {
current_fences.push((i, "north"));
}
if tile.west_fence {
current_fences.push((i, "west"));
}
if tile.south_fence {
current_fences.push((i, "south"));
}
if tile.east_fence {
current_fences.push((i, "east"));
}
}
current_fences
}
/*
fn valid_fences(&self) -> bool {
let current_fences = self.current_fences();
for curr_fence in current_fences.iter() {
if let Some(&(ref endpoint_1, ref endpoint_2)) = FENCE_MAP.get(&curr_fence) {
let mut found_fences = Vec::new();
for fence in endpoint_1 {
if current_fences.contains(&fence) {
found_fences.push(fence);
}
}
for fence in endpoint_2 {
if current_fences.contains(&fence) {
found_fences.push(fence);
}
}
if found_fences.len() == 2 {
return true;
}
}
}
false
}
*/
pub fn make_pasture(&mut self, curr_pasture: Vec<usize>, available_wood: usize) -> Option<usize> {
let test_pasture = curr_pasture.clone();
// Calculate how much wood is necessary to build the pasture before actually setting it
let mut wood_needed = 0;
for tile_index in &test_pasture {
if wood_needed > available_wood {
// println!("Not enough wood for pasture..");
return None;
}
{
let curr_tile = &mut self.tiles[*tile_index];
if !curr_tile.can_be_fenced() {
panic!("Make pasture tile is currently occupied");
return None;
}
}
match tile_index {
&4|&9|&14 => {
if !self.tiles[*tile_index].west_fence {
wood_needed += 1;
}
},
_ => {
if !curr_pasture.contains(&(tile_index+1)) && !self.tiles[*tile_index].west_fence {
wood_needed += 1;
}
}
}
match tile_index {
&0|&5|&10 => {
if !self.tiles[*tile_index].east_fence {
wood_needed += 1;
}
},
_ => {
if !curr_pasture.contains(&(tile_index-1)) && !self.tiles[*tile_index].east_fence {
wood_needed += 1;
}
}
}
match tile_index {
&0|&1|&2|&3|&4 => {
if !self.tiles[*tile_index].north_fence {
wood_needed += 1;
}
},
_ => {
if !curr_pasture.contains(&(tile_index-5)) && !self.tiles[*tile_index].north_fence {
wood_needed += 1;
}
}
}
match tile_index {
&10|&11|&12|&13|&14 => {
if !self.tiles[*tile_index].south_fence {
wood_needed += 1;
}
},
_ => {
if !curr_pasture.contains(&(tile_index+5)) && !self.tiles[*tile_index].south_fence {
wood_needed += 1;
}
}
}
}
if wood_needed > available_wood {
// println!("Not enough wood for pasture..");
return None;
}
// println!("Before pasture: {:?}", curr_pasture);
// println!("{}", self);
// We have enough wood to make the pasture work.. actually set the pasture now.
for tile_index in test_pasture {
{
let curr_tile = &mut self.tiles[tile_index];
if !curr_tile.can_be_fenced() {
panic!("Make pasture tile is currently occupied");
}
curr_tile.pasture = true;
}
// let curr_tile = &mut self.tiles[tile_index];
match tile_index {
4|9|14 => { self.tiles[tile_index].east_fence = true },
_ => {
if !curr_pasture.contains(&(tile_index+1)) {
self.tiles[tile_index].east_fence = true;
self.tiles[tile_index+1].west_fence = true;
}
}
}
match tile_index {
0|5|10 => { self.tiles[tile_index].west_fence = true },
_ => {
if !curr_pasture.contains(&(tile_index-1)) {
self.tiles[tile_index].west_fence = true;
self.tiles[tile_index-1].east_fence = true;
}
}
}
match tile_index {
0..5 => { self.tiles[tile_index].north_fence = true },
_ => {
if !curr_pasture.contains(&(tile_index-5)) {
self.tiles[tile_index].north_fence = true;
self.tiles[tile_index-5].south_fence = true;
}
}
}
match tile_index {
10..15 => { self.tiles[tile_index].south_fence = true },
_ => {
if !curr_pasture.contains(&(tile_index+5)) {
self.tiles[tile_index].south_fence = true;
self.tiles[tile_index+5].north_fence = true;
}
}
}
}
// println!("[Wood: {}] After pasture: {:?}", wood_needed, curr_pasture);
// println!("{}", self);
Some(wood_needed)
}
}
impl Display for PlayerMat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for row in 0..3 {
// Top line
let mut line = String::from("+");
for i in (row*5)..(row*5)+5 {
let curr_tile = &self.tiles[i];
match curr_tile.north_fence {
true => line = format!("{} --------- +", line),
false => line = format!("{} +", line),
};
}
write!(f, "{}\n", line);
// Row - Index
match self.tiles[row*5].west_fence {
true => line = String::from("|"),
false => line = String::from(" "),
};
for i in (row*5)..(row*5)+5 {
let curr_tile = &self.tiles[i];
line = format!("{}{number:>width$} ", line, number=i, width=2);
match curr_tile.east_fence {
true => line = format!("{} |", line),
false => line = format!("{} ", line),
}
}
write!(f, "{}\n", line);
// Row - Type of Tile (House or Field)
match self.tiles[row*5].west_fence {
true => line = String::from("| "),
false => line = String::from(" "),
};
for i in (row*5)..(row*5)+5 {
let curr_tile = &self.tiles[i];
match (&curr_tile.house, &curr_tile.field, curr_tile.stable) {
(&Some(ref house), &None, false) => line = format!("{} {} ", line, house),
(&None, &Some(ref field), false) => line = format!("{} Field ", line),
(&None, &None, true) => line = format!("{} Stable ", line),
(&None, &None, false) => line = format!("{} ", line),
_ => panic!("Tile has multiple types!")
};
match curr_tile.east_fence {
true => line = format!("{}| ", line),
false => line = format!("{} ", line),
}
}
write!(f, "{}\n", line);
// Row - Count of resources on tile
match self.tiles[row*5].west_fence {
true => line = String::from("| "),
false => line = String::from(" "),
};
for i in (row*5)..(row*5)+5 {
let curr_tile = &self.tiles[i];
match (&curr_tile.animal_type, &curr_tile.field) {
(&Some(ref animal), &None) => line = format!("{}{}: {} ", line, animal, curr_tile.animal_count),
(&None, &Some(ref field)) => {
match field.count() {
0 => line = format!("{} ", line),
_ => line = format!("{} {}: {} ", line, field.crop(), field.count()),
}
}
(&None, &None) => line = format!("{} ---- ", line),
_ => panic!("Tile has multiple types!")
};
match curr_tile.east_fence {
true => line = format!("{}| ", line),
false => line = format!("{} ", line),
}
}
write!(f, "{}\n", line);
/*
// Row - Count of resources on tile
match self.tiles[row*5].west_fence {
true => line = String::from("| "),
false => line = String::from(" "),
};
for i in (row*5)..(row*5)+5 {
let curr_tile = &self.tiles[i];
match curr_tile.stable {
true => line = format!("{} Stable ", line),
false => line = format!("{} ", line),
};
match curr_tile.east_fence {
true => line = format!("{}| ", line),
false => line = format!("{} ", line),
}
}
write!(f, "{}\n", line);
*/
}
// Top line
let mut line = String::from("+");
for i in 10..15 {
let curr_tile = &self.tiles[i];
match curr_tile.south_fence {
true => line = format!("{} --------- +", line),
false => line = format!("{} +", line),
};
}
write!(f, "{}\n", line)
/*
for (i, tile) in self.tiles.iter().enumerate() {
write!(f, "N: {} W: {} S: {} E: {}|", tile.north_fence, tile.west_fence, tile.south_fence, tile.east_fence);
match i {
4|9 => write!(f, "\n"),
_ => write!(f, "")
};
}
write!(f, "\n")
*/
}
}
|
// Copyright 2020 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A label that can be edited.
//!
//! This is a bit hacky, and depends on implementation details of other widgets.
use druid::widget::prelude::*;
use druid::widget::{LabelText, TextBox};
use druid::{Color, Data, FontDescriptor, HotKey, KbKey, KeyOrValue, Selector, TextAlignment};
// we send this to ourselves if another widget takes focus, in order
// to validate and move out of editing mode
//const LOST_FOCUS: Selector = Selector::new("druid.builtin.EditableLabel-lost-focus");
const CANCEL_EDITING: Selector = Selector::new("druid.builtin.EditableLabel-cancel-editing");
const COMPLETE_EDITING: Selector = Selector::new("druid.builtin.EditableLabel-complete-editing");
/// A label with text that can be edited.
///
/// Edits are not applied to the data until editing finishes, usually when the
/// user presses <return>. If the new text generates a valid value, it is set;
/// otherwise editing continues.
///
/// Editing can be abandoned by pressing <esc>.
pub struct EditableLabel<T> {
label: LabelText<T>,
old_buffer: String,
buffer: String,
editing: bool,
text_box: TextBox<String>,
on_completion: Box<dyn Fn(&str) -> Option<T>>,
}
impl<T: Data + std::fmt::Display + std::str::FromStr> EditableLabel<T> {
/// Create a new `EditableLabel` that uses `to_string` to display a value and
/// `FromStr` to validate the input.
pub fn parse() -> Self {
Self::new(|data: &T, _: &_| data.to_string(), |s| s.parse().ok())
}
}
impl<T: Data> EditableLabel<T> {
/// Create a new `EditableLabel`.
///
/// The first argument creates a label; it should probably be a dynamic
/// or localized string.
///
/// The second argument is a closure used to compute the data from the
/// contents of the string. This is called when the user presses return,
/// or otherwise tries to navigate away from the label; if it returns
/// `Some<T>` then that is set as the new data, and the edit ends. If it
/// returns `None`, then the edit continues.
pub fn new(
text: impl Into<LabelText<T>>,
on_completion: impl Fn(&str) -> Option<T> + 'static,
) -> Self {
EditableLabel {
label: text.into(),
buffer: String::new(),
old_buffer: String::new(),
text_box: TextBox::new(),
editing: false,
on_completion: Box::new(on_completion),
}
}
/// Builder-style method to set the placeholder text.
pub fn with_placeholder(mut self, text: impl Into<String>) -> Self {
self.text_box = self.text_box.with_placeholder(text);
self
}
/// Builder-style method for setting the font.
///
/// The argument can be a [`FontDescriptor`] or a [`Key<FontDescriptor>`]
/// that refers to a font defined in the [`Env`].
///
/// [`Env`]: ../struct.Env.html
/// [`FontDescriptor`]: ../struct.FontDescriptor.html
/// [`Key<FontDescriptor>`]: ../struct.Key.html
pub fn with_font(mut self, font: impl Into<KeyOrValue<FontDescriptor>>) -> Self {
self.text_box.set_font(font);
self
}
/// Builder-style method to override the text size.
pub fn with_text_size(mut self, size: f64) -> Self {
self.text_box.set_text_size(size);
self
}
/// Builder-style method to set the text color.
pub fn with_text_color(mut self, color: impl Into<KeyOrValue<Color>>) -> Self {
self.text_box.set_text_color(color);
self
}
/// Builder-style method to set the [`TextAlignment`].
pub fn with_text_alignment(mut self, alignment: TextAlignment) -> Self {
self.text_box.set_text_alignment(alignment);
self
}
fn complete(&mut self, ctx: &mut EventCtx, data: &mut T) {
if let Some(new) = (self.on_completion)(&self.buffer) {
*data = new;
self.editing = false;
ctx.request_layout();
if ctx.has_focus() {
ctx.resign_focus();
}
} else {
// don't tab away from here if we're editing
if !ctx.has_focus() {
ctx.request_focus();
}
// ideally we would flash the background or something
}
}
fn cancel(&mut self, ctx: &mut EventCtx) {
self.editing = false;
ctx.request_layout();
ctx.resign_focus();
}
fn begin(&mut self, ctx: &mut EventCtx) {
self.editing = true;
ctx.request_layout();
}
}
impl<T: Data> Widget<T> for EditableLabel<T> {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
if self.editing {
match event {
Event::Command(cmd) if cmd.is(COMPLETE_EDITING) => self.complete(ctx, data),
Event::Command(cmd) if cmd.is(CANCEL_EDITING) => self.cancel(ctx),
Event::KeyDown(k_e) if HotKey::new(None, KbKey::Enter).matches(k_e) => {
ctx.set_handled();
self.complete(ctx, data);
}
Event::KeyDown(k_e) if HotKey::new(None, KbKey::Escape).matches(k_e) => {
ctx.set_handled();
self.cancel(ctx);
}
event => {
self.text_box.event(ctx, event, &mut self.buffer, env);
ctx.request_paint();
}
}
ctx.request_update();
} else if let Event::MouseDown(_) = event {
self.begin(ctx);
self.text_box.event(ctx, event, &mut self.buffer, env);
}
}
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
if let LifeCycle::WidgetAdded = event {
self.label.resolve(data, env);
self.buffer = self.label.display_text().to_string();
self.old_buffer = self.buffer.clone();
}
self.text_box.lifecycle(ctx, event, &self.buffer, env);
if let LifeCycle::FocusChanged(focus) = event {
// if the user focuses elsewhere, we need to reset ourselves
if !focus {
ctx.submit_command(COMPLETE_EDITING.to(ctx.widget_id()));
} else if !self.editing {
self.editing = true;
self.label.resolve(data, env);
self.buffer = self.label.display_text().to_string();
ctx.request_layout();
}
}
}
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) {
// if we're editing, the only data changes possible are from external
// sources, since we don't mutate the data until editing completes;
// so in this case, we want to use the new data, and cancel editing.
if !data.same(old_data) {
ctx.submit_command(CANCEL_EDITING.to(ctx.widget_id()));
}
let in_edit_mode = self.editing && data.same(old_data);
if in_edit_mode {
self.text_box
.update(ctx, &self.old_buffer, &self.buffer, env);
} else {
self.label.resolve(data, env);
let data_changed = self.label.display_text().as_ref() != self.buffer.as_str();
if data_changed {
let new_text = self.label.display_text().to_string();
self.text_box.update(ctx, &self.buffer, &new_text, env);
self.old_buffer = std::mem::replace(&mut self.buffer, new_text);
ctx.request_layout();
} else if ctx.env_changed() {
self.text_box.update(ctx, &self.buffer, &self.buffer, env);
ctx.request_layout();
}
}
}
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &T, env: &Env) -> Size {
self.text_box.layout(ctx, bc, &self.buffer, env)
}
fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, env: &Env) {
//FIXME: we want to paint differently when we aren't editing
//if self.editing {
//self.text_box.paint(ctx, &self.buffer, env);
//} else {
self.text_box.paint(ctx, &self.buffer, env);
//}
}
}
|
use coordinate_compression::CoordinateCompression;
use input_i_scanner::{scan_with, InputIScanner};
use join::Join;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
let n = scan_with!(_i_i, usize);
let ab = scan_with!(_i_i, (usize, usize); n);
let mut values = Vec::new();
for &(a, b) in &ab {
values.push(a - 1);
values.push(a - 1 + b);
}
let values: CoordinateCompression<usize> = values.into_iter().collect();
let m = 4_000_00;
let mut imos = vec![0i64; m + 1];
for (a, b) in &ab {
imos[values.find_index(&(a - 1))] += 1;
imos[values.find_index(&(a - 1 + b))] -= 1;
}
for i in 0..m {
imos[i + 1] += imos[i];
}
let mut ans = vec![0; n + 1];
for i in 0..m {
if imos[i] > 0 {
let l = values[i];
let r = values[i + 1];
ans[imos[i] as usize] += r - l;
}
}
println!("{}", ans[1..].iter().join(" "));
}
|
#[derive(Debug, Clone, Queryable)]
// #[table_name="ground_tiles_with_deleted"]
pub struct GroundTile {
pub id: i64,
pub type_: String,
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use fuchsia_hyper;
use futures::compat::Future01CompatExt;
use hyper;
use lazy_static::lazy_static;
use rustls::Certificate;
use std::cell::RefCell;
use std::sync::{Arc, Mutex};
use webpki;
use webpki_roots_fuchsia;
type DateTime = chrono::DateTime<chrono::FixedOffset>;
#[derive(Debug, PartialEq)]
pub enum HttpsDateError {
InvalidHostname,
NoCertificatesPresented,
InvalidDate,
NetworkError,
NoDateInResponse,
InvalidCertificateChain,
CorruptLeafCertificate,
DateFormatError,
}
impl std::error::Error for HttpsDateError {}
impl std::fmt::Display for HttpsDateError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Debug::fmt(self, f)
}
}
lazy_static! {
static ref BUILD_TIME: DateTime = {
let build_time = std::fs::read_to_string("/config/build-info/latest-commit-date")
.expect("Unable to load latest-commit-date");
DateTime::parse_from_rfc3339(&build_time.trim()).expect("Unable to parse build time")
};
}
// I'd love to drop RSA here, but google.com doesn't yet serve ECDSA
static ALLOWED_SIG_ALGS: &[&webpki::SignatureAlgorithm] = &[
&webpki::ECDSA_P256_SHA256,
&webpki::ECDSA_P256_SHA384,
&webpki::ECDSA_P384_SHA256,
&webpki::ECDSA_P384_SHA384,
&webpki::RSA_PKCS1_2048_8192_SHA256,
&webpki::RSA_PKCS1_2048_8192_SHA384,
&webpki::RSA_PKCS1_2048_8192_SHA512,
&webpki::RSA_PKCS1_3072_8192_SHA384,
];
#[derive(Default)]
// Because we don't yet have a system time we need a custom verifier
// that records the handshake information needed to perform a deferred
// trust evaluation
struct RecordingVerifier {
presented_certs: Mutex<RefCell<Vec<Certificate>>>,
}
impl RecordingVerifier {
// This is a standard TLS certificate verification, just using
// the certificate chain we stored during the TLS handshake
pub fn verify(
&self,
dns_name: webpki::DNSNameRef,
time: webpki::Time,
) -> Result<(), HttpsDateError> {
let presented_certs = self.presented_certs.lock().unwrap();
let presented_certs = presented_certs.borrow();
if presented_certs.len() == 0 {
return Err(HttpsDateError::NoCertificatesPresented);
};
let untrusted_der: Vec<&[u8]> = presented_certs
.iter()
.map(|certificate| certificate.0.as_slice())
.collect();
let leaf = webpki::EndEntityCert::from(untrusted_der[0])
.map_err(|_| HttpsDateError::CorruptLeafCertificate)?;
leaf.verify_is_valid_tls_server_cert(
ALLOWED_SIG_ALGS,
&webpki_roots_fuchsia::TLS_SERVER_ROOTS,
&untrusted_der[1..],
time,
)
.map_err(|_| HttpsDateError::InvalidCertificateChain)?;
leaf.verify_is_valid_for_dns_name(dns_name)
.map_err(|_| HttpsDateError::InvalidCertificateChain)
}
}
impl rustls::ServerCertVerifier for RecordingVerifier {
fn verify_server_cert(
&self,
_root_store: &rustls::RootCertStore,
presented_certs: &[rustls::Certificate],
_dns_name: webpki::DNSNameRef<'_>,
_ocsp_response: &[u8],
) -> Result<rustls::ServerCertVerified, rustls::TLSError> {
// Don't attempt to verify trust, just store the necessary details
// for deferred evaluation
*self.presented_certs.lock().unwrap().borrow_mut() = presented_certs.to_vec();
Ok(rustls::ServerCertVerified::assertion())
}
}
async fn get_network_time_backstop(
hostname: &str,
backstop_time: DateTime,
) -> Result<DateTime, HttpsDateError> {
let dns_name = webpki::DNSNameRef::try_from_ascii_str(hostname)
.map_err(|_| HttpsDateError::InvalidHostname)?;
let url = format!("https://{}/", hostname);
let url = url.parse::<hyper::Uri>().map_err(|_| HttpsDateError::InvalidHostname)?;
let verifier = Arc::new(RecordingVerifier::default());
// Because we don't currently have any idea what the "true" time is
// we need to use a non-standard verifier, `RecordingVerifier`, to allow
// us to defer trust evaluation until after we've parsed the response.
let mut config = rustls::ClientConfig::new();
config.root_store.add_server_trust_anchors(&webpki_roots_fuchsia::TLS_SERVER_ROOTS);
config
.dangerous()
.set_certificate_verifier(Arc::clone(&verifier) as Arc<dyn rustls::ServerCertVerifier>);
let client = fuchsia_hyper::new_https_client_dangerous(config);
let response = client.get(url).compat().await.map_err(|_| HttpsDateError::NetworkError)?;
// Ok, so now we pull the Date header out of the response.
// Technically the Date header is the date of page creation, but it's the best
// we can do in the absence of a defined "accurate time" request.
//
// This has been suggested as being wrapped by an X-HTTPSTIME header,
// or .well-known/time, but neither of these proposals appear to
// have gone anywhere.
let date_header: String = match response.headers().get("date") {
Some(date) => date.to_str().map_err(|_| HttpsDateError::DateFormatError)?.to_string(),
_ => return Err(HttpsDateError::NoDateInResponse),
};
// Per RFC7231 the date header is specified as RFC2822
let response_time = chrono::DateTime::parse_from_rfc2822(&date_header)
.map_err(|_| HttpsDateError::DateFormatError)?;
// Ensure that the response date is at least vaguely plausible: the date must
// be after the build date
if backstop_time.timestamp() > response_time.timestamp() {
return Err(HttpsDateError::InvalidDate);
}
// Finally verify the the certificate chain against the response time
let webpki_time = webpki::Time::from_seconds_since_unix_epoch(response_time.timestamp() as u64);
verifier.verify(dns_name, webpki_time)?;
Ok(response_time)
}
/// Makes a best effort to get network time via an HTTPS connection to
/// `hostname`.
///
/// # Errors
///
/// `get_network_time` will return errors for network failures, TLS failures,
/// or if the server provides a known incorrect time.
///
/// # Panics
///
/// `httpdate` needs access to the `root-ssl-certificates` and `build-info`
/// sandbox features. If they are not available this API will panic.
///
/// # Security
///
/// Validation of the TLS connection is deferred until after the handshake
/// and then performed with respect to the time provided by the remote host.
/// We ensure that the result time is at least plausible by verifying that it
/// is more recent the system build time, and we validate the TLS connection
/// against the system rootstore. This does mean that the best we can guarantee
/// is that the host certificates were valid at some point, but the server can
/// always provide a date that falls into the validity period of the certificates
/// they provide.
pub async fn get_network_time(hostname: &str) -> Result<DateTime, HttpsDateError> {
get_network_time_backstop(hostname, *BUILD_TIME).await
}
#[cfg(test)]
impl HttpsDateError {
pub fn is_network_error(&self) -> bool {
match self {
HttpsDateError::NetworkError => true,
_ => false,
}
}
pub fn is_pki_error(&self) -> bool {
use HttpsDateError::*;
match self {
NoCertificatesPresented | InvalidCertificateChain | CorruptLeafCertificate => true,
_ => false,
}
}
pub fn is_date_error(&self) -> bool {
use HttpsDateError::*;
match self {
DateFormatError | InvalidDate => true,
_ => false,
}
}
}
#[cfg(test)]
mod test {
// These tests all interpret network errors as being passing results
// in order to prevent flakiness due to unavoidable network flakiness.
use super::*;
use chrono::prelude::*;
use failure::Error;
use fuchsia_async::Executor;
#[ignore]
#[test]
fn test_get_network_time() -> Result<(), Error> {
let mut executor = Executor::new().expect("Error creating executor");
executor.run_singlethreaded(
async {
let date = get_network_time("google.com").await;
if date.is_err() {
assert!(date.unwrap_err().is_network_error());
return Ok(());
}
assert!(BUILD_TIME.timestamp() <= date?.timestamp());
Ok(())
},
)
}
#[ignore]
#[test]
fn test_far_future() -> Result<(), Error> {
let mut executor = Executor::new().expect("Error creating executor");
executor.run_singlethreaded(
async {
let future_date = FixedOffset::east(0).ymd(5000, 1, 1).and_hms(0, 0, 0);
let error =
get_network_time_backstop("google.com", future_date).await.unwrap_err();
assert!(error.is_network_error() || error == HttpsDateError::InvalidDate);
Ok(())
},
)
}
#[test]
fn test_invalid_hostname() -> Result<(), Error> {
let mut executor = Executor::new().expect("Error creating executor");
executor.run_singlethreaded(
async {
let future_date = FixedOffset::east(0).ymd(5000, 1, 1).and_hms(0, 0, 0);
let error =
get_network_time_backstop("google com", future_date).await.unwrap_err();
assert!(error.is_network_error() || error == HttpsDateError::InvalidHostname);
Ok(())
},
)
}
}
|
use super::VarResult;
use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType};
use crate::helper::err_msgs::*;
use crate::helper::str_replace;
use crate::helper::{
move_element, pine_ref_to_bool, pine_ref_to_color, pine_ref_to_i64, pine_ref_to_string,
};
use crate::runtime::context::{downcast_ctx, Ctx};
use crate::runtime::output::{OutputData, OutputInfo, PlotCharInfo};
use crate::types::{
Bool, Callable, CallableFactory, DataType, Float, Int, ParamCollectCall, PineClass, PineFrom,
PineRef, PineType, RefData, RuntimeErr, SecondType, Series, NA,
};
use std::rc::Rc;
fn pine_plot<'a>(
context: &mut dyn Ctx<'a>,
mut param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<(), RuntimeErr> {
move_tuplet!(
(
series, title, char, location, color, opacity, offset, text, textcolor, editable, size,
show_last, display
) = param
);
if !downcast_ctx(context).check_is_output_info_ready() {
let plot_info = PlotCharInfo {
title: pine_ref_to_string(title),
char: pine_ref_to_string(char),
location: pine_ref_to_string(location),
color: pine_ref_to_color(color),
opacity: pine_ref_to_i64(opacity),
offset: pine_ref_to_i64(offset),
text: pine_ref_to_string(text),
textcolor: pine_ref_to_color(textcolor),
editable: pine_ref_to_bool(editable),
size: pine_ref_to_string(size),
show_last: pine_ref_to_i64(show_last),
display: pine_ref_to_i64(display),
};
downcast_ctx(context).push_output_info(OutputInfo::PlotChar(plot_info));
}
match series {
Some(item_val) => {
let mut items: RefData<Series<Float>> = Series::implicity_from(item_val).unwrap();
downcast_ctx(context)
.push_output_data(Some(OutputData::new(vec![items.move_history()])));
Ok(())
}
_ => Err(RuntimeErr::MissingParameters(str_replace(
REQUIRED_PARAMETERS,
vec![String::from("close")],
))),
}
}
pub const VAR_NAME: &'static str = "plotchar";
pub fn declare_var<'a>() -> VarResult<'a> {
let value = PineRef::new(CallableFactory::new(|| {
Callable::new(None, Some(Box::new(ParamCollectCall::new(pine_plot))))
}));
let func_type = FunctionTypes(vec![FunctionType::new((
vec![
("series", SyntaxType::Series(SimpleSyntaxType::Float)),
("title", SyntaxType::string()),
("char", SyntaxType::string()),
("location", SyntaxType::string()),
("color", SyntaxType::color()),
("opacity", SyntaxType::int()),
("offset", SyntaxType::int()),
("text", SyntaxType::string()),
("textcolor", SyntaxType::color()),
("editable", SyntaxType::bool()),
("size", SyntaxType::string()),
("show_last", SyntaxType::int()),
("display", SyntaxType::int()),
],
SyntaxType::Void,
))]);
let syntax_type = SyntaxType::Function(Rc::new(func_type));
VarResult::new(value, syntax_type, VAR_NAME)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::runtime::{AnySeries, NoneCallback};
use crate::{LibInfo, PineParser, PineRunner};
#[test]
fn plot_info_test() {
use crate::runtime::OutputInfo;
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))],
);
let src = r"plotchar(close, title='Title', char='h', location='a', color=#00ffaa,
opacity=70, offset=15, text='hello', textcolor=#111111,
editable=true, size='t', show_last=100, display=1)";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner
.run(
&vec![(
"close",
AnySeries::from_float_vec(vec![Some(1f64), Some(2f64)]),
)],
None,
)
.unwrap();
assert_eq!(
runner.get_io_info().get_outputs(),
&vec![OutputInfo::PlotChar(PlotCharInfo {
title: Some(String::from("Title")),
char: Some(String::from("h")),
location: Some(String::from("a")),
color: Some(String::from("#00ffaa")),
opacity: Some(70),
offset: Some(15),
text: Some(String::from("hello")),
textcolor: Some(String::from("#111111")),
editable: Some(true),
size: Some(String::from("t")),
show_last: Some(100),
display: Some(1)
})]
)
}
}
|
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::{quote};
use serde::{Deserialize, Serialize};
use syn::{parse_macro_input, Expr, ExprIf, ItemImpl, ImplItem, Stmt};
#[derive(Debug, Deserialize, Serialize)]
struct EventRule {
event_expression: String,
event_routine: EventRoutine,
}
#[derive(Debug, Deserialize, Serialize)]
enum EventRoutine {
ConditionalScheduling(Vec<ConditionalScheduling>),
UnconditionalStateTransition(String),
}
#[derive(Debug, Deserialize, Serialize)]
struct ConditionalScheduling {
follow_up_event: String,
condition: String,
}
impl EventRule {
fn new_conditional_scheduling(event_expression: String, conditional_schedulings: Vec<ConditionalScheduling>) -> Self {
Self {
event_expression,
event_routine: EventRoutine::ConditionalScheduling(conditional_schedulings),
}
}
fn new_unconditional_state_transition(event_expression: String, event_routine: String) -> Self {
Self {
event_expression,
event_routine: EventRoutine::UnconditionalStateTransition(event_routine),
}
}
}
#[proc_macro_attribute]
pub fn event_rules(_attr: TokenStream, item: TokenStream) -> TokenStream {
let input = parse_macro_input!(item as ItemImpl);
let output = TokenStream::from(quote!(#input));
// Check to see if we have an impl AsModel for NewModel, an impl NewModel, or something else
let mut is_impl = false;
let mut is_impl_as_model = false;
if let None = &input.trait_ {
is_impl = true;
} else if let Some(trait_) = &input.trait_ {
if trait_.1.segments[0].ident.to_string() == "AsModel" {
is_impl_as_model = true;
}
}
let mut event_rules = Vec::new();
// Get the unconditional state transition event rules if is_impl
if is_impl {
input.items.iter()
.filter_map(|method| {
if let ImplItem::Method(method) = method {
Some(method)
} else {
None
}
})
.for_each(|method| {
let name = &method.sig.ident;
let routine = &method.block;
event_rules.push(
EventRule::new_unconditional_state_transition(
quote!(#name).to_string(),
quote!(#routine).to_string(),
)
)
});
}
// Get the conditional scheduling event rules if is_impl_as_model
if is_impl_as_model {
// populate events_ext
input.items.iter()
.filter_map(|method| {
if let ImplItem::Method(method) = method {
Some(method)
} else {
None
}
})
.filter(|method| {
&method.sig.ident.to_string() == "events_ext"
})
.for_each(|method| {
// [0] assumes the event_ext and event_int starts with a if block
if let Stmt::Expr(expr) = &method.block.stmts[0] {
if let Expr::If(if_) = expr {
let mut conditional_schedulings = Vec::new();
// Approach assumes the final else case is an error return
extract_ext_cases(&mut conditional_schedulings, if_);
event_rules.push(
EventRule::new_conditional_scheduling(
String::from("events_ext"),
conditional_schedulings,
)
)
}
}
});
// populate events_int
input.items.iter()
.filter_map(|method| {
if let ImplItem::Method(method) = method {
Some(method)
} else {
None
}
})
.filter(|method| {
&method.sig.ident.to_string() == "events_int"
})
.for_each(|method| {
// [0] assumes the event_ext and event_int starts with a if block
if let Stmt::Expr(expr) = &method.block.stmts[0] {
if let Expr::If(if_) = expr {
let mut conditional_schedulings = Vec::new();
// Approach assumes the final else case is an error return
extract_int_cases(&mut conditional_schedulings, if_);
event_rules.push(
EventRule::new_conditional_scheduling(
String::from("events_int"),
conditional_schedulings,
)
)
}
}
});
}
println!["{:?}", serde_json::to_string(&event_rules).unwrap()];
output
}
fn extract_ext_cases(cases: &mut Vec<ConditionalScheduling>, expr_if: &ExprIf) {
let cond = &expr_if.cond;
if let Stmt::Semi(expr, _) = &expr_if.then_branch.stmts[0] {
if let Expr::Try(expr_try) = expr {
if let Expr::MethodCall(method_call) = &*expr_try.expr {
let method = &method_call.method;
cases.push(
ConditionalScheduling{
follow_up_event: quote!(#method).to_string(),
condition: quote!(#cond).to_string(),
}
)
}
}
}
let else_branch = &expr_if.else_branch;
if let Some(else_) = else_branch {
if let Expr::If(next_branch) = &*else_.1 {
extract_ext_cases(cases, &next_branch)
}
}
}
fn extract_int_cases(cases: &mut Vec<ConditionalScheduling>, expr_if: &ExprIf) {
let cond = &expr_if.cond;
if let Stmt::Expr(expr) = &expr_if.then_branch.stmts[0] {
if let Expr::MethodCall(method_call) = expr {
let method = &method_call.method;
cases.push(
ConditionalScheduling{
follow_up_event: quote!(#method).to_string(),
condition: quote!(#cond).to_string(),
}
)
}
}
let else_branch = &expr_if.else_branch;
if let Some(else_) = else_branch {
if let Expr::If(next_branch) = &*else_.1 {
extract_int_cases(cases, &next_branch)
}
}
} |
//! Supported underlying libraries for arbitrary precision arithmetic.
pub mod traits;
pub mod rampimpl;
pub mod frampimpl;
pub mod numimpl;
pub mod gmpimpl;
pub mod primes;
|
pub mod config;
mod ping;
pub use ping::ping;
|
//! A watcher that adds instrumentation.
use super::watcher::{self, Watcher};
use crate::internal_events::kubernetes::instrumenting_watcher as internal_events;
use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt};
use k8s_openapi::{WatchOptional, WatchResponse};
/// A watcher that wraps another watcher with instrumentation calls.
pub struct InstrumentingWatcher<T>
where
T: Watcher,
{
inner: T,
}
impl<T> InstrumentingWatcher<T>
where
T: Watcher,
{
/// Create a new [`InstrumentingWatcher`].
pub fn new(inner: T) -> Self {
Self { inner }
}
}
impl<T> Watcher for InstrumentingWatcher<T>
where
T: Watcher,
<T as Watcher>::Stream: 'static,
{
type Object = <T as Watcher>::Object;
type InvocationError = <T as Watcher>::InvocationError;
type StreamError = <T as Watcher>::StreamError;
type Stream = BoxStream<'static, Result<WatchResponse<Self::Object>, Self::StreamError>>;
fn watch<'a>(
&'a mut self,
watch_optional: WatchOptional<'a>,
) -> BoxFuture<'a, Result<Self::Stream, watcher::invocation::Error<Self::InvocationError>>>
{
Box::pin(self.inner.watch(watch_optional).map(|result| {
result
.map(|stream| {
emit!(internal_events::WatchRequestInvoked);
Box::pin(stream.map(|item_result| {
item_result
.map(|item| {
emit!(internal_events::WatchStreamItemObtained);
item
})
.map_err(|error| {
emit!(internal_events::WatchRequestInvocationFailed {
error: &error
});
error
})
})) as BoxStream<'static, _>
})
.map_err(|error| {
emit!(internal_events::WatchRequestInvocationFailed { error: &error });
error
})
}))
}
}
|
use druid::{Color, Key};
/// Setting up color env
pub const PRIMARY: Key<Color> = Key::new("druid-components.material.color.primary");
pub const PRIMARY_VARIANT: Key<Color> = Key::new("druid-components.material.color.primary-variant-color");
pub const SECONDARY: Key<Color> = Key::new("druid-components.material.color.secondary");
pub const SECONDARY_VARIANT: Key<Color> = Key::new("druid-components.material.color.secondary-variant");
pub const BACKGROUND: Key<Color> = Key::new("druid-components.material.color.background");
pub const SURFACE: Key<Color> = Key::new("druid-components.material.color.surface");
pub const ERROR: Key<Color> = Key::new("druid-components.material.color.error");
pub const ON_PRIMARY: Key<Color> = Key::new("druid-components.material.color.on-primary");
pub const ON_SECONDARY: Key<Color> = Key::new("druid-components.material.color.on-secondary");
pub const ON_BACKGROUND: Key<Color> = Key::new("druid-components.material.color.on-background");
pub const ON_SURFACE: Key<Color> = Key::new("druid-components.material.color.on-surface");
pub const ON_ERROR: Key<Color> = Key::new("druid-components.material.color.on-error");
|
#![feature(backtrace)]
#![feature(proc_macro_hygiene, decl_macro)]
#![feature(try_trait)]
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate shells;
use yansi::Paint;
use chrono::Local;
use std::env;
use std::path::PathBuf;
use std::path::Path;
use log::{self, LevelFilter};
use std::io::Write;
use env_logger::{fmt::Color, Builder, Env};
use crate::cmd::{serve, init, job, generate};
use crate::settings::Settings;
use crate::error::log_backtrace;
mod cli;
mod cmd;
mod constants;
mod error;
mod settings;
mod storage;
mod chain;
mod util;
mod color;
fn init_logger() {
let mut builder = Builder::new();
builder.format(|formatter, record| {
let mut style = formatter.style();
style.set_bold(true);
let tar = Paint::blue("Miner Serve").bold();
match record.level() {
log::Level::Info => writeln!(
formatter,
"{} {} ({}): {}",
tar,
Local::now().format("%Y-%m-%d %H:%M:%S"),
Paint::blue("Info").bold(),
Paint::blue(record.args()).wrap()
),
log::Level::Trace => writeln!(
formatter,
"{} {} ({}): {}",
tar,
Local::now().format("%Y-%m-%d %H:%M:%S"),
Paint::magenta("Trace").bold(),
Paint::magenta(record.args()).wrap()
),
log::Level::Error => writeln!(
formatter,
"{} {} ({}): {}",
tar,
Local::now().format("%Y-%m-%d %H:%M:%S"),
Paint::red("Error").bold(),
Paint::red(record.args()).wrap()
),
log::Level::Warn => writeln!(
formatter,
"{} {} ({}): {}",
tar,
Local::now().format("%Y-%m-%d %H:%M:%S"),
Paint::yellow("Warning").bold(),
Paint::yellow(record.args()).wrap()
),
log::Level::Debug => writeln!(
formatter,
"{} {} ({}): {}",
tar,
Local::now().format("%Y-%m-%d %H:%M:%S"),
Paint::blue("Debug").bold(),
Paint::blue(record.args()).wrap()
),
}
});
if let Ok(var) = env::var("RUST_LOG") {
builder.parse_filters(&var);
} else {
// if no RUST_LOG provided, default to logging at the Warn level
builder.filter(None, LevelFilter::Warn);
}
builder.init();
}
fn main() {
init_logger();
let matches = cli::build_cli().get_matches();
let root_dir = match matches.value_of("root").unwrap() {
"." => env::current_dir().unwrap(),
path => {
let mut return_path = PathBuf::from(path);
if !Path::new(path).is_absolute() {
return_path = env::current_dir().unwrap().join(path);
}
return_path
.canonicalize()
.unwrap_or_else(|_| panic!("Cannot find root directory: {}", path))
}
};
let config_file = match matches.value_of("config") {
Some(path) => PathBuf::from(path),
None => root_dir.join("config.toml"),
};
let res = match matches.subcommand() {
("serve", Some(matches)) => {
let address = matches.value_of("address").unwrap_or_default();
let port = matches.value_of("port").unwrap_or_default().parse::<u16>().unwrap();
let settings = Settings::build(config_file).unwrap();
println!("{} {} : {}",
Paint::blue("Miner Serve ").bold(),
Local::now().format("%Y-%m-%d %H:%M:%S"),
Paint::green("Serve start").bold());
serve(&settings, address, port)
}
("init", Some(matches)) => {
let force = matches.is_present("force");
cmd::init(matches.value_of("name").unwrap(), force)
}
("generate", Some(matches)) => {
let words = matches.value_of("words").unwrap_or_default();
generate(words)
}
("job", Some(matches)) => {
let settings = Settings::build(config_file).unwrap();
job(&settings)
}
_ => unreachable!(),
};
if let Err(e) = res {
log::error!("Error: {}", e);
std::process::exit(101);
}
} |
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Start HFXO crystal oscillator"]
pub tasks_hfclkstart: TASKS_HFCLKSTART,
#[doc = "0x04 - Stop HFXO crystal oscillator"]
pub tasks_hfclkstop: TASKS_HFCLKSTOP,
#[doc = "0x08 - Start LFCLK"]
pub tasks_lfclkstart: TASKS_LFCLKSTART,
#[doc = "0x0c - Stop LFCLK"]
pub tasks_lfclkstop: TASKS_LFCLKSTOP,
#[doc = "0x10 - Start calibration of LFRC"]
pub tasks_cal: TASKS_CAL,
#[doc = "0x14 - Start calibration timer"]
pub tasks_ctstart: TASKS_CTSTART,
#[doc = "0x18 - Stop calibration timer"]
pub tasks_ctstop: TASKS_CTSTOP,
_reserved7: [u8; 228usize],
#[doc = "0x100 - HFXO crystal oscillator started"]
pub events_hfclkstarted: EVENTS_HFCLKSTARTED,
#[doc = "0x104 - LFCLK started"]
pub events_lfclkstarted: EVENTS_LFCLKSTARTED,
_reserved9: [u8; 4usize],
#[doc = "0x10c - Calibration of LFRC completed"]
pub events_done: EVENTS_DONE,
#[doc = "0x110 - Calibration timer timeout"]
pub events_ctto: EVENTS_CTTO,
_reserved11: [u8; 20usize],
#[doc = "0x128 - Calibration timer has been started and is ready to process new tasks"]
pub events_ctstarted: EVENTS_CTSTARTED,
#[doc = "0x12c - Calibration timer has been stopped and is ready to process new tasks"]
pub events_ctstopped: EVENTS_CTSTOPPED,
_reserved13: [u8; 468usize],
#[doc = "0x304 - Enable interrupt"]
pub intenset: INTENSET,
#[doc = "0x308 - Disable interrupt"]
pub intenclr: INTENCLR,
_reserved15: [u8; 252usize],
#[doc = "0x408 - Status indicating that HFCLKSTART task has been triggered"]
pub hfclkrun: HFCLKRUN,
#[doc = "0x40c - HFCLK status"]
pub hfclkstat: HFCLKSTAT,
_reserved17: [u8; 4usize],
#[doc = "0x414 - Status indicating that LFCLKSTART task has been triggered"]
pub lfclkrun: LFCLKRUN,
#[doc = "0x418 - LFCLK status"]
pub lfclkstat: LFCLKSTAT,
#[doc = "0x41c - Copy of LFCLKSRC register, set when LFCLKSTART task was triggered"]
pub lfclksrccopy: LFCLKSRCCOPY,
_reserved20: [u8; 248usize],
#[doc = "0x518 - Clock source for the LFCLK"]
pub lfclksrc: LFCLKSRC,
_reserved21: [u8; 12usize],
#[doc = "0x528 - HFXO debounce time. The HFXO is started by triggering the TASKS_HFCLKSTART task."]
pub hfxodebounce: HFXODEBOUNCE,
_reserved22: [u8; 12usize],
#[doc = "0x538 - Calibration timer interval"]
pub ctiv: CTIV,
_reserved23: [u8; 32usize],
#[doc = "0x55c - Clocking options for the trace port debug interface"]
pub traceconfig: TRACECONFIG,
_reserved24: [u8; 84usize],
#[doc = "0x5b4 - LFRC mode configuration"]
pub lfrcmode: LFRCMODE,
}
#[doc = "Start HFXO crystal oscillator"]
pub struct TASKS_HFCLKSTART {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start HFXO crystal oscillator"]
pub mod tasks_hfclkstart;
#[doc = "Stop HFXO crystal oscillator"]
pub struct TASKS_HFCLKSTOP {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Stop HFXO crystal oscillator"]
pub mod tasks_hfclkstop;
#[doc = "Start LFCLK"]
pub struct TASKS_LFCLKSTART {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start LFCLK"]
pub mod tasks_lfclkstart;
#[doc = "Stop LFCLK"]
pub struct TASKS_LFCLKSTOP {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Stop LFCLK"]
pub mod tasks_lfclkstop;
#[doc = "Start calibration of LFRC"]
pub struct TASKS_CAL {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start calibration of LFRC"]
pub mod tasks_cal;
#[doc = "Start calibration timer"]
pub struct TASKS_CTSTART {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start calibration timer"]
pub mod tasks_ctstart;
#[doc = "Stop calibration timer"]
pub struct TASKS_CTSTOP {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Stop calibration timer"]
pub mod tasks_ctstop;
#[doc = "HFXO crystal oscillator started"]
pub struct EVENTS_HFCLKSTARTED {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "HFXO crystal oscillator started"]
pub mod events_hfclkstarted;
#[doc = "LFCLK started"]
pub struct EVENTS_LFCLKSTARTED {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "LFCLK started"]
pub mod events_lfclkstarted;
#[doc = "Calibration of LFRC completed"]
pub struct EVENTS_DONE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Calibration of LFRC completed"]
pub mod events_done;
#[doc = "Calibration timer timeout"]
pub struct EVENTS_CTTO {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Calibration timer timeout"]
pub mod events_ctto;
#[doc = "Calibration timer has been started and is ready to process new tasks"]
pub struct EVENTS_CTSTARTED {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Calibration timer has been started and is ready to process new tasks"]
pub mod events_ctstarted;
#[doc = "Calibration timer has been stopped and is ready to process new tasks"]
pub struct EVENTS_CTSTOPPED {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Calibration timer has been stopped and is ready to process new tasks"]
pub mod events_ctstopped;
#[doc = "Enable interrupt"]
pub struct INTENSET {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Enable interrupt"]
pub mod intenset;
#[doc = "Disable interrupt"]
pub struct INTENCLR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Disable interrupt"]
pub mod intenclr;
#[doc = "Status indicating that HFCLKSTART task has been triggered"]
pub struct HFCLKRUN {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Status indicating that HFCLKSTART task has been triggered"]
pub mod hfclkrun;
#[doc = "HFCLK status"]
pub struct HFCLKSTAT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "HFCLK status"]
pub mod hfclkstat;
#[doc = "Status indicating that LFCLKSTART task has been triggered"]
pub struct LFCLKRUN {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Status indicating that LFCLKSTART task has been triggered"]
pub mod lfclkrun;
#[doc = "LFCLK status"]
pub struct LFCLKSTAT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "LFCLK status"]
pub mod lfclkstat;
#[doc = "Copy of LFCLKSRC register, set when LFCLKSTART task was triggered"]
pub struct LFCLKSRCCOPY {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Copy of LFCLKSRC register, set when LFCLKSTART task was triggered"]
pub mod lfclksrccopy;
#[doc = "Clock source for the LFCLK"]
pub struct LFCLKSRC {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Clock source for the LFCLK"]
pub mod lfclksrc;
#[doc = "HFXO debounce time. The HFXO is started by triggering the TASKS_HFCLKSTART task."]
pub struct HFXODEBOUNCE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "HFXO debounce time. The HFXO is started by triggering the TASKS_HFCLKSTART task."]
pub mod hfxodebounce;
#[doc = "Calibration timer interval"]
pub struct CTIV {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Calibration timer interval"]
pub mod ctiv;
#[doc = "Clocking options for the trace port debug interface"]
pub struct TRACECONFIG {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Clocking options for the trace port debug interface"]
pub mod traceconfig;
#[doc = "LFRC mode configuration"]
pub struct LFRCMODE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "LFRC mode configuration"]
pub mod lfrcmode;
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type FrameNavigationOptions = *mut ::core::ffi::c_void;
pub type LoadCompletedEventHandler = *mut ::core::ffi::c_void;
pub type NavigatedEventHandler = *mut ::core::ffi::c_void;
pub type NavigatingCancelEventArgs = *mut ::core::ffi::c_void;
pub type NavigatingCancelEventHandler = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct NavigationCacheMode(pub i32);
impl NavigationCacheMode {
pub const Disabled: Self = Self(0i32);
pub const Required: Self = Self(1i32);
pub const Enabled: Self = Self(2i32);
}
impl ::core::marker::Copy for NavigationCacheMode {}
impl ::core::clone::Clone for NavigationCacheMode {
fn clone(&self) -> Self {
*self
}
}
pub type NavigationEventArgs = *mut ::core::ffi::c_void;
pub type NavigationFailedEventArgs = *mut ::core::ffi::c_void;
pub type NavigationFailedEventHandler = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct NavigationMode(pub i32);
impl NavigationMode {
pub const New: Self = Self(0i32);
pub const Back: Self = Self(1i32);
pub const Forward: Self = Self(2i32);
pub const Refresh: Self = Self(3i32);
}
impl ::core::marker::Copy for NavigationMode {}
impl ::core::clone::Clone for NavigationMode {
fn clone(&self) -> Self {
*self
}
}
pub type NavigationStoppedEventHandler = *mut ::core::ffi::c_void;
pub type PageStackEntry = *mut ::core::ffi::c_void;
|
use std::cell::RefCell;
use self_cell::self_cell;
struct Bar<'a>(RefCell<(Option<&'a Bar<'a>>, String)>);
self_cell! {
struct Foo {
owner: (),
#[not_covariant]
dependent: Bar,
}
}
fn main() {
let mut x = Foo::new((), |_| Bar(RefCell::new((None, "Hello".to_owned()))));
x.with_dependent(|_, dep| {
dep.0.borrow_mut().0 = Some(dep);
});
x.with_dependent_mut(|_, dep| {
let r1 = dep.0.get_mut();
let string_ref_1 = &mut r1.1;
let mut r2 = r1.0.unwrap().0.borrow_mut();
let string_ref_2 = &mut r2.1;
let s = &string_ref_1[..];
string_ref_2.clear();
string_ref_2.shrink_to_fit();
println!("{}", s); // prints garbage
});
}
|
use super::Vessel;
use crate::codec::{Decode, Encode};
use crate::{remote_type, RemoteEnum, RemoteObject};
remote_type!(
/// Used to interact with CommNet for a given vessel. Obtained by calling `Vessel::comms()`.
object SpaceCenter.Comms {
properties: {
{
CanCommunicate {
/// Returns whether the vessel can communicate with KSC.
///
/// **Game Scenes**: Flight
get: can_communicate -> bool
}
}
{
CanTransmitScience {
/// Returns whether the vessel can transmit science data to KSC.
///
/// **Game Scenes**: Flight
get: can_transmit_science -> bool
}
}
{
SignalStrength {
/// Returns the signal strength to KSC.
///
/// **Game Scenes**: Flight
get: signal_strength -> f64
}
}
{
SignalDelay {
/// Returns the signal delay to KSC in seconds.
///
/// **Game Scenes**: Flight
get: signal_delay -> f64
}
}
{
Power {
/// Returns the combined power of all active antennae on the vessel.
///
/// **Game Scenes**: Flight
get: power -> f64
}
}
{
ControlPath {
/// Returns the combined power of all active antennae on the vessel.
///
/// **Game Scenes**: Flight
get: control_path -> Vec<CommLink>
}
}
}
});
remote_type!(
/// Represents a communication node in the network. For example, a vessel or the KSC.
object SpaceCenter.CommLink {
properties: {
{
Type {
/// Returns the type of link
///
/// **Game Scenes**: Flight
get: link_type -> CommLinkType
}
}
{
SignalStrength {
/// Returns the signal strength of the link.
///
/// **Game Scenes**: Flight
get: signal_strength -> f64
}
}
{
Start {
/// Returns the start point of the link.
///
/// **Game Scenes**: Flight
get: start -> CommNode
}
}
{
End {
/// Returns the end point of the link.
///
/// **Game Scenes**: Flight
get: end -> CommNode
}
}
}
});
remote_type!(
/// Represents a communication node in the network. For example, a vessel or the KSC.
object SpaceCenter.CommNode {
properties: {
{
Name {
/// Returns the name of the communication node.
///
/// **Game Scenes**: Flight
get: name -> String
}
}
{
IsHome {
/// Returns whether the communication node is on Kerbin.
///
/// **Game Scenes**: Flight
get: is_home -> bool
}
}
{
IsControlPoint {
/// Returns whether the communication node is a control point, for example
/// a manned vessel.
///
/// **Game Scenes**: Flight
get: is_control_point -> bool
}
}
{
IsVessel {
/// Returns whether the communication node is a vessel.
///
/// **Game Scenes**: Flight
get: is_vessel -> bool
}
}
{
Vessel {
/// Returns the vessel for this communication node.
///
/// **Game Scenes**: Flight
get: vessel -> Option<Vessel>
}
}
}
});
remote_type!(
/// The type of communication link.
enum CommLinkType {
/// Link is to a base station on Kerbin.
Home = 0,
/// Link is to a control source, for example a manned spacecraft.
Control = 1,
/// Link is to a relay satellite.
Relay = 2,
}
);
|
use regex::Regex;
use std::{collections::HashMap, collections::HashSet, fs};
const FILENAME: &str = "inputs/inputday4";
pub fn solve() {
let input = fs::read_to_string(FILENAME).expect("Failed to read file");
let re = Regex::new(r"([a-z]+:[^\s]+)").unwrap();
let mut total: i32 = 0;
let mut total_part2: i32 = 0;
for password in input.split("\n\n") {
match process_passport(&password, &re, false) {
Ok(_) => total += 1,
Err(_) => {}
}
match process_passport(&password, &re, true) {
Ok(_) => total_part2 += 1,
Err(_) => {}
}
}
println!("Answer to day 4 part 1 is {}", total);
println!("Answer to day 4 part 2 is {}", total_part2);
}
fn process_passport(pass: &str, re: &Regex, extra_checks: bool) -> Result<(), &'static str> {
let matches = re.captures_iter(pass);
let keys: HashMap<&str, &str> = matches
.into_iter()
.map(|captures| {
let mut parts = captures
.get(0)
.expect("Failed to get capture")
.as_str()
.split(':');
(parts.next().unwrap(), parts.next().unwrap())
})
.into_iter()
.collect();
let required_keys: HashSet<&str> = vec!["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid"]
.into_iter()
.collect();
let missing_keys: HashSet<&str> = required_keys
.iter()
.filter(|&k| !keys.keys().any(|x| x == k))
.map(|k| *k)
.collect();
if missing_keys.len() > 0 && !(missing_keys.len() == 1 && missing_keys.contains("cid")) {
return Err("Missing fields");
}
if extra_checks {
// byr
let byr: i32 = keys["byr"].parse().unwrap();
if byr < 1920 || byr > 2002 {
return Err("Byr incorrect");
}
// eyr
let iyr: i32 = keys["iyr"].parse().unwrap();
if iyr < 2010 || iyr > 2020 {
return Err("Iyr incorrect");
}
// eyr
let eyr: i32 = keys["eyr"].parse().unwrap();
if eyr < 2020 || eyr > 2030 {
return Err("Eyr incorrect");
}
// hgt
let hgt = keys["hgt"];
if hgt.ends_with("cm") {
let n: i32 = hgt[0..hgt.len() - 2].parse().unwrap();
if n < 150 || n > 193 {
return Err("Height in cm incorrect");
}
} else if hgt.ends_with("in") {
let n: i32 = hgt[0..hgt.len() - 2].parse().unwrap();
if n < 59 || n > 76 {
return Err("Height in in incorrect");
}
} else {
return Err("Hgt wrong");
}
// hcl
if !Regex::new(r"\#[a-f0-9]{6}").unwrap().is_match(keys["hcl"]) {
return Err("Hcl no match");
}
// ecl
let options: HashSet<&str> = vec!["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
.into_iter()
.collect();
if !options.contains(keys["ecl"]) {
return Err("Ecl not found");
}
// pid
if keys["pid"].len() != 9 {
return Err("Incorrect length pid");
}
match keys["pid"].parse::<i32>() {
Ok(_) => {}
Err(_) => return Err("Failed to parse pid"),
}
}
Ok(())
}
|
extern crate cg_tracing;
use cg_tracing::prelude::*;
fn main() {
let (w, mut p, path) = utils::from_json("./example/test.json", register! {});
w.render(&mut p);
p.save_png(&path);
}
|
use input_i_scanner::InputIScanner;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
let (s, t, x) = scan!((u32, u32, u32));
let ans = if s < t {
if x >= s && x < t {
"Yes"
} else {
"No"
}
} else {
if x >= t && x < s {
"No"
} else {
"Yes"
}
};
println!("{}", ans);
}
|
#[derive(Copy, Clone)]
pub enum TextureDimensionality {
Zero,
One,
Two,
Three,
}
pub struct BTexImageFormat<'a> {
pub name: &'a str,
pub compatible_1d: bool,
pub compatible_2d: bool,
pub compatible_3d: bool,
}
impl<'a> BTexImageFormat<'a> {
pub fn is_dimensionality_compatible(&self, dimensionality: TextureDimensionality) -> bool {
use TextureDimensionality::*;
match dimensionality {
Zero => true,
One => self.compatible_1d,
Two => self.compatible_2d,
Three => self.compatible_3d,
}
}
}
pub struct BTexHeaderInfo {
pub version: u32,
pub header_length: u32,
pub offset_table_length: u32,
}
pub struct BTexTextureInfo<'g> {
pub dimensionality: TextureDimensionality,
pub width: u32,
pub height: u32,
pub depth: u32,
pub levels: u32,
pub layers: u32,
pub attributes: u32,
pub image_format: &'g BTexImageFormat<'g>,
}
impl<'g> BTexTextureInfo<'g> {
pub fn is_sparse(&self) -> bool {
(self.attributes & 0x1 != 0)
}
}
pub struct BTexOffsetTable {
pub offsets: Vec<PixelDataOffset>,
}
pub struct PixelDataOffset {
pub offset: u64,
pub length: u64,
}
|
#![allow(clippy::too_many_arguments)]
#![warn(clippy::cast_lossless, clippy::match_ref_pats)]
#[cfg(feature = "profiler")]
#[macro_use]
extern crate thread_profiler;
#[macro_use]
extern crate log;
use std::path::Path;
use crow::{
glutin::{
dpi::LogicalSize,
event::Event,
event_loop::{ControlFlow, EventLoop},
window::Icon,
window::WindowBuilder,
},
image, Context, DrawConfig, Texture,
};
pub mod config;
pub mod data;
pub mod environment;
pub mod init;
pub mod input;
pub mod physics;
pub mod ressources;
pub mod save;
pub mod spritesheet;
pub mod systems;
pub mod time;
use crate::{
config::GameConfig, data::Components, environment::WorldData, ressources::Ressources,
save::SaveData, systems::Systems,
};
#[cfg(feature = "editor")]
use environment::{CHUNK_HEIGHT, CHUNK_WIDTH};
pub struct GlobalState {
pub s: Systems,
pub r: Ressources,
pub c: Components,
pub ctx: Context,
event_loop: EventLoop<()>,
}
impl GlobalState {
pub fn new(
config: GameConfig,
world_data: WorldData,
save_data: SaveData,
) -> Result<Self, crow::Error> {
let icon = load_window_icon(&config.window.icon_path).unwrap();
#[cfg(not(feature = "editor"))]
let window_size = (
config.window.size.0 * config.window.scale,
config.window.size.1 * config.window.scale,
);
#[cfg(feature = "editor")]
let window_size = (
CHUNK_WIDTH as u32 * config.window.scale,
CHUNK_HEIGHT as u32 * config.window.scale,
);
let event_loop = EventLoop::new();
let ctx = Context::new(
WindowBuilder::new()
.with_inner_size(LogicalSize::<u32>::from(window_size))
.with_title(&config.window.title)
.with_window_icon(Some(icon)),
&event_loop,
)?;
Ok(GlobalState {
s: Systems::new(),
r: Ressources::new(config, world_data, save_data),
c: Components::new(),
ctx,
event_loop,
})
}
pub fn run<F>(self, mut frame: F) -> !
where
F: 'static
+ FnMut(
&mut Context,
&mut Texture,
&mut Systems,
&mut Components,
&mut Ressources,
) -> Result<bool, crow::Error>,
{
let GlobalState {
mut s,
mut r,
mut c,
mut ctx,
event_loop,
} = self;
#[cfg(not(feature = "editor"))]
let mut screen_buffer = Texture::new(&mut ctx, r.config.window.size).unwrap();
#[cfg(feature = "editor")]
let mut screen_buffer =
Texture::new(&mut ctx, (CHUNK_WIDTH as u32, CHUNK_HEIGHT as u32)).unwrap();
r.time.restart();
event_loop.run(
move |event: Event<()>, _window_target: _, control_flow: &mut ControlFlow| match event {
Event::NewEvents(_) => r.input_state.clear_events(),
Event::MainEventsCleared => ctx.window().request_redraw(),
Event::RedrawRequested(_) => {
#[cfg(feature = "profiler")]
profile_scope!("frame");
let mut surface = ctx.surface();
ctx.clear_color(&mut screen_buffer, (0.3, 0.3, 0.8, 1.0));
ctx.clear_depth(&mut screen_buffer);
for event in r.input_state.events() {
if &input::InputEvent::KeyDown(r.config.input.debug_toggle) == event {
r.debug_draw = !r.debug_draw;
}
}
if frame(&mut ctx, &mut screen_buffer, &mut s, &mut c, &mut r).unwrap() {
*control_flow = ControlFlow::Exit;
}
let fadeout = r.fadeout.as_ref().map_or(0.0, |f| f.current);
let color_modulation = [
[1.0 - fadeout, 0.0, 0.0, 0.0],
[0.0, 1.0 - fadeout, 0.0, 0.0],
[0.0, 0.0, 1.0 - fadeout, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
ctx.draw(
&mut surface,
&screen_buffer,
(0, 0),
&DrawConfig {
scale: (r.config.window.scale, r.config.window.scale),
color_modulation,
..Default::default()
},
);
ctx.present(surface).unwrap();
r.time.frame();
}
Event::LoopDestroyed => {
#[cfg(feature = "profiler")]
thread_profiler::write_profile("profile.json");
}
e => {
if r.input_state.update(e, &r.config.window) {
*control_flow = ControlFlow::Exit;
}
}
},
)
}
}
#[cfg(feature = "editor")]
pub fn editor_frame(
ctx: &mut Context,
screen_buffer: &mut Texture,
s: &mut Systems,
c: &mut Components,
r: &mut Ressources,
) -> Result<bool, crow::Error> {
s.editor.run(ctx, c, r)?;
systems::draw::scene(
ctx,
screen_buffer,
&c.positions,
&c.sprites,
&c.depths,
&c.mirrored,
&c.colliders,
&c.cameras,
)?;
if r.debug_draw {
systems::draw::debug_colliders(ctx, screen_buffer, &c.positions, &c.colliders, &c.cameras)?;
}
Ok(false)
}
pub fn game_frame(
ctx: &mut Context,
screen_buffer: &mut Texture,
s: &mut Systems,
c: &mut Components,
r: &mut Ressources,
) -> Result<bool, crow::Error> {
s.input_buffer.run(
r.input_state.events(),
&mut r.pressed_space,
&r.config.input_buffer,
&r.config.input,
);
s.camera.run(
&c.player_state,
&c.positions,
&c.previous_positions,
&mut c.velocities,
&c.cameras,
&r.time,
&r.config.camera,
);
s.gravity
.run(&c.gravity, &mut c.velocities, &r.time, &r.config.gravity);
let mut collisions = s.physics.run(
&c.velocities,
&c.colliders,
&mut c.previous_positions,
&mut c.positions,
&mut c.grounded,
&r.time,
);
s.bridge_collision.run(
&c.positions,
&c.previous_positions,
&c.colliders,
&c.ignore_bridges,
&mut collisions,
);
s.fixed_collision.run(
&mut c.positions,
&c.previous_positions,
&mut c.grounded,
&mut c.wall_collisions,
&mut c.velocities,
&c.colliders,
&collisions,
);
s.player.run(c, r, &collisions);
s.environment.run(ctx, c, r)?;
s.fadeout.run(&mut r.fadeout);
s.animation
.run(&mut c.sprites, &mut c.animations, &mut r.animation_storage);
s.delayed_actions(ctx, c, r)?;
systems::draw::scene(
ctx,
screen_buffer,
&c.positions,
&c.sprites,
&c.depths,
&c.mirrored,
&c.colliders,
&c.cameras,
)?;
if r.debug_draw {
systems::draw::debug_colliders(ctx, screen_buffer, &c.positions, &c.colliders, &c.cameras)?;
}
Ok(false)
}
pub fn load_window_icon<P: AsRef<Path>>(path: P) -> Result<Icon, image::ImageError> {
let icon = image::open(path)?.to_rgba();
let icon_dimensions = icon.dimensions();
Ok(Icon::from_rgba(icon.into_raw(), icon_dimensions.0, icon_dimensions.1).unwrap())
}
|
use projecteuler::digits;
use projecteuler::helper;
fn main() {
helper::check_bench(|| solve(99));
assert_eq!(solve(99), 1587000);
dbg!(solve(99));
}
fn solve(percent: usize) -> usize {
let mut total = 1;
let mut count = 0;
while count * 100 != total * percent {
total += 1;
if is_bouncy(total) {
count += 1;
}
}
total
}
fn is_bouncy(n: usize) -> bool {
let (inc, dec, _) =
digits::digits_iterator(n).fold((true, true, None), |(inc, dec, last), d| {
if let Some(last_d) = last {
(inc && last_d <= d, dec && last_d >= d, Some(d))
} else {
(true, true, Some(d))
}
});
!inc && !dec
}
|
use winapi::shared::{
windef::HBRUSH,
minwindef::{UINT, WPARAM, LPARAM}
};
use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, ES_NUMBER, ES_LEFT, ES_CENTER, ES_RIGHT, WS_TABSTOP, ES_AUTOHSCROLL},
wingdi::DeleteObject,
};
use crate::win32::window_helper as wh;
use crate::win32::base_helper::{check_hwnd, to_utf16};
use crate::{Font, NwgError, HTextAlign, RawEventHandler};
use super::{ControlBase, ControlHandle};
use std::cell::RefCell;
use std::ops::Range;
use std::char;
const NOT_BOUND: &'static str = "TextInput is not yet bound to a winapi object";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: TextInput handle is not HWND!";
bitflags! {
/**
The text input flags
* VISIBLE: The text input is immediatly visible after creation
* DISABLED: The text input cannot be interacted with by the user. It also has a grayed out look.
* NUMBER: The text input only accepts number
* AUTO_SCROLL: The text input automatically scrolls text to the right by 10 characters when the user types a character
at the end of the line. When the user presses the ENTER key, the control scrolls all text back to position zero.
* TAB_STOP: The text input can be selected using tab navigation
*/
pub struct TextInputFlags: u32 {
const VISIBLE = WS_VISIBLE;
const DISABLED = WS_DISABLED;
const NUMBER = ES_NUMBER;
const AUTO_SCROLL = ES_AUTOHSCROLL;
const TAB_STOP = WS_TABSTOP;
}
}
/**
An edit control is a rectangular control window to permit the user to enter and edit text by typing on the keyboard
This control only allow a single line input. For block of text, use `TextBox`.
Winapi documentation: https://docs.microsoft.com/en-us/windows/win32/controls/about-edit-controls#text-and-input-styles
TextInput is not behind any features.
**Builder parameters:**
* `parent`: **Required.** The text input parent container.
* `text`: The text input text.
* `size`: The text input size.
* `position`: The text input position.
* `flags`: A combination of the TextInputFlags values.
* `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi
* `font`: The font used for the text input text
* `limit`: The maximum number of character that can be inserted in the control
* `readonly`: If the text input should allow user input or not
* `password`: The password character. If set to None, the textinput is a regular control.
* `align`: The alignment of the text in the text input
* `background_color`: The color of the textinput top and bottom padding. This is not the white background under the text.
* `focus`: The control receive focus after being created
**Control events:**
* `OnTextInput`: When a TextInput value is changed
* `MousePress(_)`: Generic mouse press events on the button
* `OnMouseMove`: Generic mouse mouse event
* `OnMouseWheel`: Generic mouse wheel event
```rust
use native_windows_gui as nwg;
fn build_box(tbox: &mut nwg::TextInput, window: &nwg::Window, font: &nwg::Font) {
nwg::TextInput::builder()
.text("Hello")
.font(Some(font))
.parent(window)
.build(tbox);
}
```
*/
#[derive(Default)]
pub struct TextInput {
pub handle: ControlHandle,
background_brush: Option<HBRUSH>,
handler0: RefCell<Option<RawEventHandler>>,
}
impl TextInput {
pub fn builder<'a>() -> TextInputBuilder<'a> {
TextInputBuilder {
text: "",
placeholder_text: None,
size: (100, 25),
position: (0, 0),
flags: None,
ex_flags: 0,
limit: 0,
password: None,
align: HTextAlign::Left,
readonly: false,
focus: false,
font: None,
parent: None,
background_color: None,
}
}
/// Return the font of the control
pub fn font(&self) -> Option<Font> {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let font_handle = wh::get_window_font(handle);
if font_handle.is_null() {
None
} else {
Some(Font { handle: font_handle })
}
}
/// Set the font of the control
pub fn set_font(&self, font: Option<&Font>) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_font(handle, font.map(|f| f.handle), true); }
}
/// Return the password character displayed by the text input. If the input is not a password, return None.
pub fn password_char(&self) -> Option<char> {
use winapi::um::winuser::EM_GETPASSWORDCHAR;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let raw_char = wh::send_message(handle, EM_GETPASSWORDCHAR as u32, 0, 0) as u32;
match raw_char {
0 => None,
v => char::from_u32(v)
}
}
/// Set or Remove the password character displayed by the text input.
/// If the input is not a password all character are re-rendered with the new character
pub fn set_password_char(&self, c: Option<char>) {
use winapi::um::winuser::{InvalidateRect, EM_SETPASSWORDCHAR};
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::send_message(handle, EM_SETPASSWORDCHAR as u32, c.map(|c| c as usize).unwrap_or(0), 0);
// The control needs to be manually refreshed
unsafe { InvalidateRect(handle, ::std::ptr::null(), 1); }
}
/// Return the number of maximum character allowed in this text input
pub fn limit(&self) -> u32 {
use winapi::um::winuser::EM_GETLIMITTEXT;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::send_message(handle, EM_GETLIMITTEXT as u32, 0, 0) as u32
}
/// Set the number of maximum character allowed in this text input
/// If `limit` is 0, the text length is set to 0x7FFFFFFE characters
pub fn set_limit(&self, limit: usize) {
use winapi::um::winuser::EM_SETLIMITTEXT;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::send_message(handle, EM_SETLIMITTEXT as u32, limit, 0);
}
/// Check if the content of the text input was modified after it's creation
pub fn modified(&self) -> bool {
use winapi::um::winuser::EM_GETMODIFY;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::send_message(handle, EM_GETMODIFY as u32, 0, 0) != 0
}
/// Manually set modified flag of the text input
pub fn set_modified(&self, e: bool) {
use winapi::um::winuser::EM_SETMODIFY;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::send_message(handle, EM_SETMODIFY as u32, e as usize, 0);
}
/// Undo the last action by the user in the control
pub fn undo(&self) {
use winapi::um::winuser::EM_UNDO;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::send_message(handle, EM_UNDO as u32, 0, 0);
}
/// Return the selected range of characters by the user in the text input
pub fn selection(&self) -> Range<u32> {
use winapi::um::winuser::EM_GETSEL;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let mut start = 0u32;
let mut end = 0u32;
let ptr1 = &mut start as *mut u32;
let ptr2 = &mut end as *mut u32;
wh::send_message(handle, EM_GETSEL as UINT, ptr1 as WPARAM, ptr2 as LPARAM);
start..end
}
/// Return the selected range of characters by the user in the text input
pub fn set_selection(&self, r: Range<u32>) {
use winapi::um::winuser::EM_SETSEL;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::send_message(handle, EM_SETSEL as u32, r.start as usize, r.end as isize);
}
/// Return the length of the user input in the control. This is better than `input.text().len()` as it
/// does not allocate a string in memory
pub fn len(&self) -> u32 {
use winapi::um::winuser::EM_LINELENGTH;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::send_message(handle, EM_LINELENGTH as u32, 0, 0) as u32
}
/// Return true if the TextInput value cannot be edited. Retrurn false otherwise.
/// A user can still copy text from a readonly TextEdit (unlike disabled)
pub fn readonly(&self) -> bool {
use winapi::um::winuser::ES_READONLY;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::get_style(handle) & ES_READONLY == ES_READONLY
}
/// Set the readonly flag of the text input
/// A user can still copy text from a readonly TextEdit (unlike disabled)
pub fn set_readonly(&self, r: bool) {
use winapi::um::winuser::EM_SETREADONLY;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::send_message(handle, EM_SETREADONLY as u32, r as WPARAM, 0);
}
/// Return true if the control currently has the keyboard focus
pub fn focus(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_focus(handle) }
}
/// Set the keyboard focus on the button
pub fn set_focus(&self) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_focus(handle); }
}
/// Return true if the control user can interact with the control, return false otherwise
pub fn enabled(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_enabled(handle) }
}
/// Enable or disable the control
pub fn set_enabled(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_enabled(handle, v) }
}
/// Return true if the control is visible to the user. Will return true even if the
/// control is outside of the parent client view (ex: at the position (10000, 10000))
pub fn visible(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_visibility(handle) }
}
/// Show or hide the control to the user
pub fn set_visible(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_visibility(handle, v) }
}
/// Return the size of the button in the parent window
pub fn size(&self) -> (u32, u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_size(handle) }
}
/// Set the size of the button in the parent window
pub fn set_size(&self, x: u32, y: u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
}
/// Return the position of the button in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Set the position of the button in the parent window
pub fn set_position(&self, x: i32, y: i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_position(handle, x, y) }
}
/// Return the text displayed in the TextInput
pub fn text(&self) -> String {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_text(handle) }
}
/// Set the text displayed in the TextInput
pub fn set_text<'a>(&self, v: &'a str) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_text(handle, v) }
}
/// Return the placeholder text displayed in the TextInput
/// when it is empty and does not have focus. The string returned will be
/// as long as the user specified, however it might be longer or shorter than
/// the actual placeholder text.
pub fn placeholder_text<'a>(&self, text_length: usize) -> String {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use winapi::shared::ntdef::WCHAR;
use winapi::um::commctrl::EM_GETCUEBANNER;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let mut placeholder_text: Vec<WCHAR> = Vec::with_capacity(text_length);
unsafe {
placeholder_text.set_len(text_length);
wh::send_message(handle, EM_GETCUEBANNER, placeholder_text.as_mut_ptr() as WPARAM, placeholder_text.len() as LPARAM);
OsString::from_wide(&placeholder_text).into_string().unwrap_or("".to_string())
}
}
/// Set the placeholder text displayed in the TextInput
/// when it is empty and does not have focus
pub fn set_placeholder_text<'a>(&self, v: Option<&'a str>) {
use winapi::um::commctrl::EM_SETCUEBANNER;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let placeholder_text = v.unwrap_or("");
let text = to_utf16(placeholder_text);
wh::send_message(handle, EM_SETCUEBANNER, 0, text.as_ptr() as LPARAM);
}
/// Winapi class name used during control creation
pub fn class_name(&self) -> &'static str {
"EDIT"
}
/// Winapi base flags used during window creation
pub fn flags(&self) -> u32 {
::winapi::um::winuser::WS_VISIBLE
}
/// Winapi flags required by the control
pub fn forced_flags(&self) -> u32 {
use winapi::um::winuser::{WS_BORDER, WS_CHILD};
WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL | WS_CHILD
}
/// Center the text vertically. Can't believe that must be manually hacked in.
fn hook_non_client_size(&mut self, bg: Option<[u8; 3]>) {
use crate::bind_raw_event_handler_inner;
use winapi::shared::windef::{HGDIOBJ, RECT, POINT};
use winapi::um::winuser::{WM_NCCALCSIZE, WM_NCPAINT, WM_SIZE, DT_CALCRECT, DT_LEFT, NCCALCSIZE_PARAMS, COLOR_WINDOW,};
use winapi::um::winuser::{SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOMOVE, SWP_FRAMECHANGED};
use winapi::um::winuser::{GetDC, DrawTextW, ReleaseDC, GetClientRect, GetWindowRect, FillRect, ScreenToClient, SetWindowPos};
use winapi::um::wingdi::{SelectObject, CreateSolidBrush, RGB};
use std::{mem, ptr};
if self.handle.blank() { panic!("{}", NOT_BOUND); }
self.handle.hwnd().expect(BAD_HANDLE);
let brush = match bg {
Some(c) => {
let b = unsafe { CreateSolidBrush(RGB(c[0], c[1], c[2])) };
self.background_brush = Some(b);
b
},
None => COLOR_WINDOW as HBRUSH
};
unsafe {
let handler = bind_raw_event_handler_inner(&self.handle, 0, move |hwnd, msg, w, l| {
match msg {
WM_NCCALCSIZE => {
if w == 0 { return None }
// Calculate client area height needed for a font
let font_handle = wh::get_window_font(hwnd);
let mut r: RECT = mem::zeroed();
let dc = GetDC(hwnd);
let old = SelectObject(dc, font_handle as HGDIOBJ);
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
let client_height = r.bottom;
SelectObject(dc, old);
ReleaseDC(hwnd, dc);
// Calculate NC area to center text.
let mut client: RECT = mem::zeroed();
let mut window: RECT = mem::zeroed();
GetClientRect(hwnd, &mut client);
GetWindowRect(hwnd, &mut window);
let window_height = window.bottom - window.top;
let center = ((window_height - client_height) / 2) - 4;
// Save the info
let info_ptr: *mut NCCALCSIZE_PARAMS = l as *mut NCCALCSIZE_PARAMS;
let info = &mut *info_ptr;
info.rgrc[0].top += center;
info.rgrc[0].bottom -= center;
},
WM_NCPAINT => {
let mut window: RECT = mem::zeroed();
let mut client: RECT = mem::zeroed();
GetWindowRect(hwnd, &mut window);
GetClientRect(hwnd, &mut client);
let mut pt1 = POINT {x: window.left, y: window.top};
ScreenToClient(hwnd, &mut pt1);
let mut pt2 = POINT {x: window.right, y: window.bottom};
ScreenToClient(hwnd, &mut pt2);
let top = RECT {
left: 0,
top: pt1.y,
right: client.right,
bottom: client.top
};
let bottom = RECT {
left: 0,
top: client.bottom,
right: client.right,
bottom: pt2.y
};
let dc = GetDC(hwnd);
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
ReleaseDC(hwnd, dc);
},
WM_SIZE => {
SetWindowPos(hwnd, ptr::null_mut(), 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
},
_ => {}
}
None
});
*self.handler0.borrow_mut() = Some(handler.unwrap());
}
}
}
impl Drop for TextInput {
fn drop(&mut self) {
use crate::unbind_raw_event_handler;
let handler = self.handler0.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
if let Some(bg) = self.background_brush {
unsafe { DeleteObject(bg as _); }
}
self.handle.destroy();
}
}
pub struct TextInputBuilder<'a> {
text: &'a str,
placeholder_text: Option<&'a str>,
size: (i32, i32),
position: (i32, i32),
flags: Option<TextInputFlags>,
ex_flags: u32,
limit: usize,
password: Option<char>,
align: HTextAlign,
readonly: bool,
font: Option<&'a Font>,
parent: Option<ControlHandle>,
background_color: Option<[u8; 3]>,
focus: bool,
}
impl<'a> TextInputBuilder<'a> {
pub fn flags(mut self, flags: TextInputFlags) -> TextInputBuilder<'a> {
self.flags = Some(flags);
self
}
pub fn ex_flags(mut self, flags: u32) -> TextInputBuilder<'a> {
self.ex_flags = flags;
self
}
pub fn text(mut self, text: &'a str) -> TextInputBuilder<'a> {
self.text = text;
self
}
pub fn placeholder_text(mut self, placeholder_text: Option<&'a str>) -> TextInputBuilder<'a> {
self.placeholder_text = placeholder_text;
self
}
pub fn size(mut self, size: (i32, i32)) -> TextInputBuilder<'a> {
self.size = size;
self
}
pub fn position(mut self, pos: (i32, i32)) -> TextInputBuilder<'a> {
self.position = pos;
self
}
pub fn limit(mut self, limit: usize) -> TextInputBuilder<'a> {
self.limit = limit;
self
}
pub fn password(mut self, psw: Option<char>) -> TextInputBuilder<'a> {
self.password = psw;
self
}
pub fn align(mut self, align: HTextAlign) -> TextInputBuilder<'a> {
self.align = align;
self
}
pub fn readonly(mut self, read: bool) -> TextInputBuilder<'a> {
self.readonly = read;
self
}
pub fn font(mut self, font: Option<&'a Font>) -> TextInputBuilder<'a> {
self.font = font;
self
}
pub fn background_color(mut self, color: Option<[u8;3]>) -> TextInputBuilder<'a> {
self.background_color = color;
self
}
pub fn focus(mut self, focus: bool) -> TextInputBuilder<'a> {
self.focus = focus;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> TextInputBuilder<'a> {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut TextInput) -> Result<(), NwgError> {
let mut flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags());
match self.align {
HTextAlign::Left => flags |= ES_LEFT,
HTextAlign::Center => flags |= ES_CENTER,
HTextAlign::Right => {
flags |= ES_RIGHT;
flags &= !ES_AUTOHSCROLL;
},
}
let parent = match self.parent {
Some(p) => Ok(p),
None => Err(NwgError::no_parent("TextInput"))
}?;
*out = Default::default();
out.handle = ControlBase::build_hwnd()
.class_name(out.class_name())
.forced_flags(out.forced_flags())
.flags(flags)
.ex_flags(self.ex_flags)
.size(self.size)
.position(self.position)
.text(self.text)
.parent(Some(parent))
.build()?;
out.hook_non_client_size(self.background_color);
if self.limit > 0 {
out.set_limit(self.limit);
}
if self.password.is_some() {
out.set_password_char(self.password)
}
if self.readonly {
out.set_readonly(self.readonly);
}
if self.focus {
out.set_focus();
}
if self.font.is_some() {
out.set_font(self.font);
} else {
out.set_font(Font::global_default().as_ref());
}
if self.placeholder_text.is_some() {
out.set_placeholder_text(self.placeholder_text);
}
Ok(())
}
}
impl PartialEq for TextInput {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
|
use proconio::input;
fn main() {
input! {
n: usize,
lr: [(usize, usize); n],
};
const M: usize = 2_000_00;
let mut cum_sum = vec![0_i64; M + 2];
for (l, r) in lr {
cum_sum[l] += 1;
cum_sum[r] -= 1;
}
for i in 1..=(M + 1) {
cum_sum[i] += cum_sum[i - 1];
}
assert_eq!(cum_sum[M + 1], 0);
let mut ans = Vec::new();
let mut ok = false;
let mut left = 0;
for i in 1..=(M + 1) {
if cum_sum[i] == 0 {
if ok {
assert_ne!(left, 0);
ans.push((left, i));
ok = false;
left = 0; // ?
}
} else {
if !ok {
ok = true;
left = i;
}
}
}
for (l, r) in ans {
println!("{} {}", l, r);
}
}
|
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarks;
mod crypto;
#[cfg(any(feature = "runtime-benchmarks", test))]
mod mock;
mod module_impl;
mod offchain_error;
#[cfg(test)]
mod tests;
mod weights;
use alloc::vec::Vec;
use frame_support::{
debug, decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchResult, traits::Get,
};
use frame_system::{
ensure_none, ensure_signed,
offchain::{AppCrypto, SendTransactionTypes, SigningTypes},
};
use offchain_error::*;
use orml_traits::{MultiCurrency, MultiReservableCurrency};
use sp_arithmetic::traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub};
use sp_runtime::traits::Zero;
use vln_commons::{AccountRate, Asset, Destination, OfferRate, PairPrice};
pub use crypto::*;
pub use module_impl::module_impl_offchain::*;
pub use weights::*;
type AccountRateTy<T> = AccountRate<<T as frame_system::Trait>::AccountId, Balance<T>>;
type Balance<T> =
<<T as Trait>::Collateral as MultiCurrency<<T as frame_system::Trait>::AccountId>>::Balance;
type OfferRateTy<T> = OfferRate<Balance<T>>;
type LiquidityMembers = pallet_membership::DefaultInstance;
pub trait Trait:
SendTransactionTypes<Call<Self>> + SigningTypes + pallet_membership::Trait<LiquidityMembers>
where
Balance<Self>: LiquidityProviderBalance,
{
type Asset: MultiCurrency<Self::AccountId, Balance = Balance<Self>, CurrencyId = Asset>;
type Collateral: MultiReservableCurrency<Self::AccountId, CurrencyId = Asset>;
type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>;
type OffchainAuthority: AppCrypto<Self::Public, Self::Signature>;
type OffchainUnsignedInterval: Get<Self::BlockNumber>;
type WeightInfo: WeightInfo;
}
decl_error! {
pub enum Error for Module<T: Trait> {
MustBeCollateral,
NoFunds,
TransferMustBeGreaterThanZero,
DestinationNotSupported
}
}
decl_event!(
pub enum Event<T>
where
AccountId = <T as frame_system::Trait>::AccountId,
Balance = Balance<T>,
{
Attestation(AccountId, Asset),
Members(Vec<AccountId>),
Transfer(AccountId, AccountId, Balance),
}
);
decl_module! {
pub struct Module<T: Trait> for enum Call
where
origin: T::Origin
{
type Error = Error<T>;
fn deposit_event() = default;
#[weight = T::WeightInfo::attest()]
pub fn attest(
origin,
asset: Asset,
balance: Balance<T>,
offer_rates: Vec<OfferRateTy<T>>
) -> DispatchResult
{
match asset {
Asset::Btc | Asset::Cop | Asset::Usdv | Asset::Ves => {
Err(crate::Error::<T>::MustBeCollateral.into())
},
Asset::Collateral(collateral) => {
let who = ensure_signed(origin)?;
Self::update_account_rates(&who, asset, offer_rates);
Self::do_attest(who.clone(), Asset::Usdv, balance)?;
T::Collateral::deposit(collateral.into(), &who, balance)?;
T::Collateral::reserve(collateral.into(), &who, balance)?;
Self::deposit_event(RawEvent::Attestation(who, collateral.into()));
Ok(())
}
}
}
#[weight = T::WeightInfo::members()]
pub fn members(origin) -> DispatchResult {
let _ = ensure_signed(origin)?;
let members = pallet_membership::Module::<T, LiquidityMembers>::members();
Self::deposit_event(RawEvent::Members(members));
Ok(())
}
#[weight = T::WeightInfo::submit_pair_prices()]
pub fn submit_pair_prices(
origin,
pair_prices: Vec<PairPrice<Balance<T>>>,
_signature: T::Signature,
) -> DispatchResult {
ensure_none(origin)?;
<PairPrices<T>>::mutate(|old_pair_prices| {
if Self::incoming_pair_prices_are_valid(&pair_prices) {
old_pair_prices.clear();
old_pair_prices.extend(pair_prices);
}
else {
debug::error!("Invalid pair prices");
}
});
let current_block = <frame_system::Module<T>>::block_number();
<NextUnsignedAt<T>>::put(current_block + T::OffchainUnsignedInterval::get());
Ok(())
}
#[weight = T::WeightInfo::transfer()]
pub fn transfer(
origin,
to: Destination<<T as frame_system::Trait>::AccountId>,
to_amount: Balance<T>,
) -> DispatchResult
{
// process transfer based on the destination type
match to {
// preform onchain transfer for vln address
Destination::Vln(to_address) => {
let from = ensure_signed(origin)?;
if to_amount.is_zero() {
return Err(crate::Error::<T>::TransferMustBeGreaterThanZero.into());
}
Self::transfer_evenly(from, to_address, to_amount)?;
Ok(())
}
// skip all other destinations for now
_ => Err(crate::Error::<T>::DestinationNotSupported.into())
}
}
#[weight = T::WeightInfo::update_offer_rates()]
pub fn update_offer_rates(
origin,
asset: Asset,
offer_rates: Vec<OfferRateTy<T>>
) -> DispatchResult
{
let who = ensure_signed(origin)?;
Self::update_account_rates(&who, asset, offer_rates);
Ok(())
}
fn offchain_worker(block_number: T::BlockNumber) {
if let Err(e) = Self::fetch_pair_prices_and_submit_tx(block_number) {
debug::error!("Offchain error: {}", e);
}
}
}
}
decl_storage! {
trait Store for Module<T: Trait> as LiquidityProviderStorage {
pub AccountRates get(fn account_rates):
double_map hasher(twox_64_concat) Asset,
hasher(twox_64_concat) Asset => Vec<AccountRateTy<T>>;
pub NextUnsignedAt get(fn next_unsigned_at): T::BlockNumber;
pub PairPrices get(fn prices): Vec<PairPrice<Balance<T>>>
}
}
pub trait LiquidityProviderBalance:
CheckedAdd + CheckedDiv + CheckedMul + CheckedSub + From<u32>
{
}
impl<T> LiquidityProviderBalance for T where
T: CheckedAdd + CheckedDiv + CheckedMul + CheckedSub + From<u32>
{
}
|
use cell_gc::with_heap;
#[test]
fn add_in_lambda() {
with_heap(|hs| {
let mut env = Nil;
env.push_env(
hs,
Rc::new("+".to_string()),
Builtin(GCLeaf::new(BuiltinFnPtr(add))),
);
let program = lisp!(
((lambda (x y z) (+ x (+ y z))) 3 4 5)
, hs);
let result = eval(hs, program, &env);
assert_eq!(result, Ok(Int(12)));
});
}
|
// revisions: base nll
// ignore-compare-mode-nll
//[nll] compile-flags: -Z borrowck=mir
//[base] check-fail
//[nll] check-pass
// known-bug
// This should pass, but we end up with `A::Iter<'ai>: Sized` for some specific
// `'ai`. We also know that `for<'at> A::Iter<'at>: Sized` from the definition,
// but we prefer param env candidates. We changed this to preference in #92191,
// but this led to unintended consequences (#93262). Suprisingly, this passes
// under NLL. So only a bug in migrate mode.
#![feature(generic_associated_types)]
use std::marker::PhantomData;
pub trait GenAssoc<T> {
type Iter<'at>;
fn iter(&self) -> Self::Iter<'_>;
fn reborrow<'longt: 'shortt, 'shortt>(iter: Self::Iter<'longt>) -> Self::Iter<'shortt>;
}
pub struct Wrapper<'a, T: 'a, A: GenAssoc<T>> {
a: A::Iter<'a>,
_p: PhantomData<T>,
}
impl<'ai, T: 'ai, A: GenAssoc<T>> GenAssoc<T> for Wrapper<'ai, T, A>
where
A::Iter<'ai>: Clone,
{
type Iter<'b> = ();
fn iter<'s>(&'s self) -> Self::Iter<'s> {
let a = A::reborrow::<'ai, 's>(self.a.clone());
}
fn reborrow<'long: 'short, 'short>(iter: Self::Iter<'long>) -> Self::Iter<'short> {
()
}
}
fn main() {}
|
pub mod cache;
pub mod entry;
pub mod entry_tag;
pub mod tag;
|
use projecteuler::digits;
use projecteuler::helper;
use projecteuler::square_roots;
fn main() {
helper::check_bench(|| {
solve();
});
assert_eq!(solve(), 1389019170);
dbg!(solve());
}
fn solve() -> usize {
let (mut low, _) = square_roots::sqrt(1020304050607080900);
let (_, high) = square_roots::sqrt(1929394959697989990);
low = (low / 10) * 10;
(low..=high).step_by(10).filter(is_answer).next().unwrap()
}
fn is_answer(n: &usize) -> bool {
let square = n * n;
if square < 1020304050607080900 {
return false;
}
//dbg!(n, square);
digits::digits_iterator(square)
.step_by(2)
.zip([1, 2, 3, 4, 5, 6, 7, 8, 9, 0].iter().rev())
.all(|(a, b)| a == *b)
}
|
//! Represents the response to FlightSQL `GetSqlInfo` requests and
//! handles the conversion to/from the format specified in the
//! [Arrow FlightSQL Specification].
//!
//! <
//! info_name: uint32 not null,
//! value: dense_union<
//! string_value: utf8,
//! bool_value: bool,
//! bigint_value: int64,
//! int32_bitmask: int32,
//! string_list: list<string_data: utf8>
//! int32_to_int32_list_map: map<key: int32, value: list<$data$: int32>>
//! >
//!
//! where there is one row per requested piece of metadata information.
//!
//!
//! [Arrow FlightSQL Specification]: https://github.com/apache/arrow/blob/f1eece9f276184063c9c35011e8243eb3b071233/format/FlightSql.proto#L33-L42
mod meta;
use arrow_flight::sql::{
metadata::{SqlInfoData, SqlInfoDataBuilder},
SqlInfo, SqlNullOrdering, SqlSupportedCaseSensitivity, SqlSupportedTransactions,
SupportedSqlGrammar,
};
use once_cell::sync::Lazy;
use meta::{
SQL_INFO_DATE_TIME_FUNCTIONS, SQL_INFO_NUMERIC_FUNCTIONS, SQL_INFO_SQL_KEYWORDS,
SQL_INFO_STRING_FUNCTIONS, SQL_INFO_SYSTEM_FUNCTIONS,
};
#[allow(non_snake_case)]
static INSTANCE: Lazy<SqlInfoData> = Lazy::new(|| {
// The following are not defined in the [`SqlInfo`], but are
// documented at
// https://arrow.apache.org/docs/format/FlightSql.html#protocol-buffer-definitions.
let SqlInfoFlightSqlServerSql = 4;
let SqlInfoFlightSqlServerSubstrait = 5;
//let SqlInfoFlightSqlServerSubstraitMinVersion = 6;
//let SqlInfoFlightSqlServerSubstraitMaxVersion = 7;
let SqlInfoFlightSqlServerTransaction = 8;
let SqlInfoFlightSqlServerCancel = 9;
let SqlInfoFlightSqlServerStatementTimeout = 100;
let SqlInfoFlightSqlServerTransactionTimeout = 101;
// Copied from https://github.com/influxdata/idpe/blob/85aa7a52b40f173cc4d79ac02b3a4a13e82333c4/queryrouter/internal/server/flightsql_handler.go#L208-L275
let mut builder = SqlInfoDataBuilder::new();
// Server information
builder.append(SqlInfo::FlightSqlServerName, "InfluxDB IOx");
builder.append(SqlInfo::FlightSqlServerVersion, "2");
// 1.3 comes from https://github.com/apache/arrow/blob/f9324b79bf4fc1ec7e97b32e3cce16e75ef0f5e3/format/Schema.fbs#L24
builder.append(SqlInfo::FlightSqlServerArrowVersion, "1.3");
builder.append(SqlInfo::FlightSqlServerReadOnly, true);
builder.append(SqlInfoFlightSqlServerSql, true);
builder.append(SqlInfoFlightSqlServerSubstrait, false);
builder.append(
SqlInfoFlightSqlServerTransaction,
SqlSupportedTransactions::SqlTransactionUnspecified as i32,
);
// don't yetsupport `CancelQuery` action
builder.append(SqlInfoFlightSqlServerCancel, false);
builder.append(SqlInfoFlightSqlServerStatementTimeout, 0i32);
builder.append(SqlInfoFlightSqlServerTransactionTimeout, 0i32);
// SQL syntax information
builder.append(SqlInfo::SqlDdlCatalog, false);
builder.append(SqlInfo::SqlDdlSchema, false);
builder.append(SqlInfo::SqlDdlTable, false);
builder.append(
SqlInfo::SqlIdentifierCase,
SqlSupportedCaseSensitivity::SqlCaseSensitivityLowercase as i32,
);
builder.append(SqlInfo::SqlIdentifierQuoteChar, r#"""#);
builder.append(
SqlInfo::SqlQuotedIdentifierCase,
SqlSupportedCaseSensitivity::SqlCaseSensitivityCaseInsensitive as i32,
);
builder.append(SqlInfo::SqlAllTablesAreSelectable, true);
builder.append(
SqlInfo::SqlNullOrdering,
SqlNullOrdering::SqlNullsSortedHigh as i32,
);
builder.append(SqlInfo::SqlKeywords, SQL_INFO_SQL_KEYWORDS);
builder.append(SqlInfo::SqlNumericFunctions, SQL_INFO_NUMERIC_FUNCTIONS);
builder.append(SqlInfo::SqlStringFunctions, SQL_INFO_STRING_FUNCTIONS);
builder.append(SqlInfo::SqlSystemFunctions, SQL_INFO_SYSTEM_FUNCTIONS);
builder.append(SqlInfo::SqlDatetimeFunctions, SQL_INFO_DATE_TIME_FUNCTIONS);
builder.append(SqlInfo::SqlSearchStringEscape, "\\");
builder.append(SqlInfo::SqlExtraNameCharacters, "");
builder.append(SqlInfo::SqlSupportsColumnAliasing, true);
builder.append(SqlInfo::SqlNullPlusNullIsNull, true);
// Skip SqlSupportsConvert (which is the map of the conversions that are supported);
// .with_sql_info(SqlInfo::SqlSupportsConvert, TBD);
// https://github.com/influxdata/influxdb_iox/issues/7253
builder.append(SqlInfo::SqlSupportsTableCorrelationNames, false);
builder.append(SqlInfo::SqlSupportsDifferentTableCorrelationNames, false);
builder.append(SqlInfo::SqlSupportsExpressionsInOrderBy, true);
builder.append(SqlInfo::SqlSupportsOrderByUnrelated, true);
builder.append(SqlInfo::SqlSupportedGroupBy, 3i32);
builder.append(SqlInfo::SqlSupportsLikeEscapeClause, true);
builder.append(SqlInfo::SqlSupportsNonNullableColumns, true);
builder.append(
SqlInfo::SqlSupportedGrammar,
SupportedSqlGrammar::SqlCoreGrammar as i32,
);
// report IOx supports all ansi 92
builder.append(SqlInfo::SqlAnsi92SupportedLevel, 0b111_i32);
builder.append(SqlInfo::SqlSupportsIntegrityEnhancementFacility, false);
builder.append(SqlInfo::SqlOuterJoinsSupportLevel, 2i32);
builder.append(SqlInfo::SqlSchemaTerm, "schema");
builder.append(SqlInfo::SqlProcedureTerm, "procedure");
builder.append(SqlInfo::SqlCatalogAtStart, false);
builder.append(SqlInfo::SqlSchemasSupportedActions, 0i32);
builder.append(SqlInfo::SqlCatalogsSupportedActions, 0i32);
builder.append(SqlInfo::SqlSupportedPositionedCommands, 0i32);
builder.append(SqlInfo::SqlSelectForUpdateSupported, false);
builder.append(SqlInfo::SqlStoredProceduresSupported, false);
builder.append(SqlInfo::SqlSupportedSubqueries, 15i32);
builder.append(SqlInfo::SqlCorrelatedSubqueriesSupported, true);
builder.append(SqlInfo::SqlSupportedUnions, 3i32);
// For max lengths, report max arrow string length (IOx
// doesn't enfore many of these limits yet
builder.append(SqlInfo::SqlMaxBinaryLiteralLength, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxCharLiteralLength, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxColumnNameLength, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxColumnsInGroupBy, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxColumnsInIndex, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxColumnsInOrderBy, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxColumnsInSelect, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxColumnsInTable, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxConnections, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxCursorNameLength, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxIndexLength, i32::MAX as i64);
builder.append(SqlInfo::SqlDbSchemaNameLength, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxProcedureNameLength, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxCatalogNameLength, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxRowSize, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxRowSizeIncludesBlobs, true);
builder.append(SqlInfo::SqlMaxStatementLength, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxStatements, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxTableNameLength, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxTablesInSelect, i32::MAX as i64);
builder.append(SqlInfo::SqlMaxUsernameLength, i32::MAX as i64);
builder.append(SqlInfo::SqlDefaultTransactionIsolation, 0i64);
builder.append(SqlInfo::SqlTransactionsSupported, false);
builder.append(SqlInfo::SqlSupportedTransactionsIsolationLevels, 0i32);
builder.append(SqlInfo::SqlDataDefinitionCausesTransactionCommit, false);
builder.append(SqlInfo::SqlDataDefinitionsInTransactionsIgnored, true);
builder.append(SqlInfo::SqlSupportedResultSetTypes, 0i32);
builder.append(
SqlInfo::SqlSupportedConcurrenciesForResultSetUnspecified,
0i32,
);
builder.append(
SqlInfo::SqlSupportedConcurrenciesForResultSetForwardOnly,
0i32,
);
builder.append(
SqlInfo::SqlSupportedConcurrenciesForResultSetScrollSensitive,
0i32,
);
builder.append(
SqlInfo::SqlSupportedConcurrenciesForResultSetScrollInsensitive,
0i32,
);
builder.append(SqlInfo::SqlBatchUpdatesSupported, false);
builder.append(SqlInfo::SqlSavepointsSupported, false);
builder.append(SqlInfo::SqlNamedParametersSupported, false);
builder.append(SqlInfo::SqlLocatorsUpdateCopy, false);
builder.append(SqlInfo::SqlStoredFunctionsUsingCallSyntaxSupported, false);
builder.build().expect("Successfully built metadata")
});
/// Return a [`SqlInfoData`] that describes IOx's capablities
pub fn iox_sql_info_data() -> &'static SqlInfoData {
&INSTANCE
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::SMIS {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct I2C_SMIS_DATAMISR {
bits: bool,
}
impl I2C_SMIS_DATAMISR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _I2C_SMIS_DATAMISW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SMIS_DATAMISW<'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 &= !(1 << 0);
self.w.bits |= ((value as u32) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct I2C_SMIS_STARTMISR {
bits: bool,
}
impl I2C_SMIS_STARTMISR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _I2C_SMIS_STARTMISW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SMIS_STARTMISW<'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 &= !(1 << 1);
self.w.bits |= ((value as u32) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct I2C_SMIS_STOPMISR {
bits: bool,
}
impl I2C_SMIS_STOPMISR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _I2C_SMIS_STOPMISW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SMIS_STOPMISW<'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 &= !(1 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct I2C_SMIS_DMARXMISR {
bits: bool,
}
impl I2C_SMIS_DMARXMISR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _I2C_SMIS_DMARXMISW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SMIS_DMARXMISW<'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 &= !(1 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct I2C_SMIS_DMATXMISR {
bits: bool,
}
impl I2C_SMIS_DMATXMISR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _I2C_SMIS_DMATXMISW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SMIS_DMATXMISW<'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 &= !(1 << 4);
self.w.bits |= ((value as u32) & 1) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct I2C_SMIS_TXMISR {
bits: bool,
}
impl I2C_SMIS_TXMISR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _I2C_SMIS_TXMISW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SMIS_TXMISW<'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 &= !(1 << 5);
self.w.bits |= ((value as u32) & 1) << 5;
self.w
}
}
#[doc = r"Value of the field"]
pub struct I2C_SMIS_RXMISR {
bits: bool,
}
impl I2C_SMIS_RXMISR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _I2C_SMIS_RXMISW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SMIS_RXMISW<'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 &= !(1 << 6);
self.w.bits |= ((value as u32) & 1) << 6;
self.w
}
}
#[doc = r"Value of the field"]
pub struct I2C_SMIS_TXFEMISR {
bits: bool,
}
impl I2C_SMIS_TXFEMISR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _I2C_SMIS_TXFEMISW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SMIS_TXFEMISW<'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 &= !(1 << 7);
self.w.bits |= ((value as u32) & 1) << 7;
self.w
}
}
#[doc = r"Value of the field"]
pub struct I2C_SMIS_RXFFMISR {
bits: bool,
}
impl I2C_SMIS_RXFFMISR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _I2C_SMIS_RXFFMISW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SMIS_RXFFMISW<'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 &= !(1 << 8);
self.w.bits |= ((value as u32) & 1) << 8;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Data Masked Interrupt Status"]
#[inline(always)]
pub fn i2c_smis_datamis(&self) -> I2C_SMIS_DATAMISR {
let bits = ((self.bits >> 0) & 1) != 0;
I2C_SMIS_DATAMISR { bits }
}
#[doc = "Bit 1 - Start Condition Masked Interrupt Status"]
#[inline(always)]
pub fn i2c_smis_startmis(&self) -> I2C_SMIS_STARTMISR {
let bits = ((self.bits >> 1) & 1) != 0;
I2C_SMIS_STARTMISR { bits }
}
#[doc = "Bit 2 - Stop Condition Masked Interrupt Status"]
#[inline(always)]
pub fn i2c_smis_stopmis(&self) -> I2C_SMIS_STOPMISR {
let bits = ((self.bits >> 2) & 1) != 0;
I2C_SMIS_STOPMISR { bits }
}
#[doc = "Bit 3 - Receive DMA Masked Interrupt Status"]
#[inline(always)]
pub fn i2c_smis_dmarxmis(&self) -> I2C_SMIS_DMARXMISR {
let bits = ((self.bits >> 3) & 1) != 0;
I2C_SMIS_DMARXMISR { bits }
}
#[doc = "Bit 4 - Transmit DMA Masked Interrupt Status"]
#[inline(always)]
pub fn i2c_smis_dmatxmis(&self) -> I2C_SMIS_DMATXMISR {
let bits = ((self.bits >> 4) & 1) != 0;
I2C_SMIS_DMATXMISR { bits }
}
#[doc = "Bit 5 - Transmit FIFO Request Interrupt Mask"]
#[inline(always)]
pub fn i2c_smis_txmis(&self) -> I2C_SMIS_TXMISR {
let bits = ((self.bits >> 5) & 1) != 0;
I2C_SMIS_TXMISR { bits }
}
#[doc = "Bit 6 - Receive FIFO Request Interrupt Mask"]
#[inline(always)]
pub fn i2c_smis_rxmis(&self) -> I2C_SMIS_RXMISR {
let bits = ((self.bits >> 6) & 1) != 0;
I2C_SMIS_RXMISR { bits }
}
#[doc = "Bit 7 - Transmit FIFO Empty Interrupt Mask"]
#[inline(always)]
pub fn i2c_smis_txfemis(&self) -> I2C_SMIS_TXFEMISR {
let bits = ((self.bits >> 7) & 1) != 0;
I2C_SMIS_TXFEMISR { bits }
}
#[doc = "Bit 8 - Receive FIFO Full Interrupt Mask"]
#[inline(always)]
pub fn i2c_smis_rxffmis(&self) -> I2C_SMIS_RXFFMISR {
let bits = ((self.bits >> 8) & 1) != 0;
I2C_SMIS_RXFFMISR { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Data Masked Interrupt Status"]
#[inline(always)]
pub fn i2c_smis_datamis(&mut self) -> _I2C_SMIS_DATAMISW {
_I2C_SMIS_DATAMISW { w: self }
}
#[doc = "Bit 1 - Start Condition Masked Interrupt Status"]
#[inline(always)]
pub fn i2c_smis_startmis(&mut self) -> _I2C_SMIS_STARTMISW {
_I2C_SMIS_STARTMISW { w: self }
}
#[doc = "Bit 2 - Stop Condition Masked Interrupt Status"]
#[inline(always)]
pub fn i2c_smis_stopmis(&mut self) -> _I2C_SMIS_STOPMISW {
_I2C_SMIS_STOPMISW { w: self }
}
#[doc = "Bit 3 - Receive DMA Masked Interrupt Status"]
#[inline(always)]
pub fn i2c_smis_dmarxmis(&mut self) -> _I2C_SMIS_DMARXMISW {
_I2C_SMIS_DMARXMISW { w: self }
}
#[doc = "Bit 4 - Transmit DMA Masked Interrupt Status"]
#[inline(always)]
pub fn i2c_smis_dmatxmis(&mut self) -> _I2C_SMIS_DMATXMISW {
_I2C_SMIS_DMATXMISW { w: self }
}
#[doc = "Bit 5 - Transmit FIFO Request Interrupt Mask"]
#[inline(always)]
pub fn i2c_smis_txmis(&mut self) -> _I2C_SMIS_TXMISW {
_I2C_SMIS_TXMISW { w: self }
}
#[doc = "Bit 6 - Receive FIFO Request Interrupt Mask"]
#[inline(always)]
pub fn i2c_smis_rxmis(&mut self) -> _I2C_SMIS_RXMISW {
_I2C_SMIS_RXMISW { w: self }
}
#[doc = "Bit 7 - Transmit FIFO Empty Interrupt Mask"]
#[inline(always)]
pub fn i2c_smis_txfemis(&mut self) -> _I2C_SMIS_TXFEMISW {
_I2C_SMIS_TXFEMISW { w: self }
}
#[doc = "Bit 8 - Receive FIFO Full Interrupt Mask"]
#[inline(always)]
pub fn i2c_smis_rxffmis(&mut self) -> _I2C_SMIS_RXFFMISW {
_I2C_SMIS_RXFFMISW { w: self }
}
}
|
use std::collections::HashMap;
use lazy_static::lazy_static;
use proc_macro2::TokenStream;
use syn::{
parse::{Parse, ParseStream},
token, ItemEnum, Path,
};
use crate::utils::*;
pub(crate) fn attribute(args: TokenStream, input: TokenStream) -> TokenStream {
expand(args, input).unwrap_or_else(|e| e.to_compile_error())
}
macro_rules! trait_map {
($map:ident, $($(#[$meta:meta])* <$ident:expr, [$($deps:expr),*]>,)*) => {$(
$(#[$meta])*
$map.insert($ident, &[$($deps),*]);
)*};
}
lazy_static! {
static ref TRAIT_DEPENDENCIES: HashMap<&'static str, &'static [&'static str]> = {
let mut map: HashMap<&'static str, &'static [&'static str]> = HashMap::new();
trait_map! {
map,
<"Copy", ["Clone"]>,
<"Eq", ["PartialEq"]>,
<"PartialOrd", ["PartialEq"]>,
<"Ord", ["PartialOrd", "Eq", "PartialEq"]>,
#[cfg(feature = "ops")]
<"DerefMut", ["Deref"]>,
#[cfg(feature = "ops")]
<"IndexMut", ["Index"]>,
#[cfg(feature = "fn_traits")]
<"Fn", ["FnMut", "FnOnce"]>,
#[cfg(feature = "fn_traits")]
<"FnMut", ["FnOnce"]>,
<"DoubleEndedIterator", ["Iterator"]>,
<"ExactSizeIterator", ["Iterator"]>,
<"FusedIterator", ["Iterator"]>,
<"TrustedLen", ["Iterator"]>,
#[cfg(feature = "std")]
<"BufRead", ["Read"]>,
#[cfg(feature = "std")]
<"io::BufRead", ["io::Read"]>,
#[cfg(feature = "std")]
<"Error", ["Display", "Debug"]>,
#[cfg(feature = "rayon")]
<"rayon::IndexedParallelIterator", ["rayon::ParallelIterator"]>,
}
map
};
}
macro_rules! alias_map {
($map:expr, $($(#[$meta:meta])* $($arm:ident)::*,)*) => {$(
$(#[$meta])*
$map.insert(crate::derive::$($arm)::*::NAME[0], crate::derive::$($arm)::*::NAME[1]);
$(#[$meta])*
$map.insert(crate::derive::$($arm)::*::NAME[1], crate::derive::$($arm)::*::NAME[0]);
)*};
}
lazy_static! {
static ref ALIAS_MAP: HashMap<&'static str, &'static str> = {
let mut map = HashMap::new();
alias_map! {
map,
// core
core::fmt::debug,
core::fmt::display,
// std
#[cfg(feature = "std")]
std::io::read,
#[cfg(feature = "std")]
std::io::buf_read,
#[cfg(feature = "std")]
std::io::seek,
#[cfg(feature = "std")]
std::io::write,
}
map
};
}
type DeriveFn = fn(&'_ Data, &'_ mut Vec<ItemImpl>) -> Result<()>;
macro_rules! derive_map {
($map:expr, $($(#[$meta:meta])* $($arm:ident)::*,)*) => {$(
$(#[$meta])*
crate::derive::$($arm)::*::NAME.iter().for_each(|name| {
if $map.insert(*name, crate::derive::$($arm)::*::derive as DeriveFn).is_some() {
panic!("`#[enum_derive]` internal error: there are multiple `{}`", name);
}
});
)*};
}
lazy_static! {
static ref DERIVE_MAP: HashMap<&'static str, DeriveFn> = {
let mut map = HashMap::new();
derive_map!(
map,
// core
#[cfg(feature = "convert")]
core::convert::as_mut,
#[cfg(feature = "convert")]
core::convert::as_ref,
core::fmt::debug,
core::fmt::display,
#[cfg(feature = "fmt")]
core::fmt::pointer,
#[cfg(feature = "fmt")]
core::fmt::binary,
#[cfg(feature = "fmt")]
core::fmt::octal,
#[cfg(feature = "fmt")]
core::fmt::upper_hex,
#[cfg(feature = "fmt")]
core::fmt::lower_hex,
#[cfg(feature = "fmt")]
core::fmt::upper_exp,
#[cfg(feature = "fmt")]
core::fmt::lower_exp,
core::fmt::write,
core::iter::iterator,
core::iter::double_ended_iterator,
core::iter::exact_size_iterator,
core::iter::fused_iterator,
#[cfg(feature = "trusted_len")]
core::iter::trusted_len,
core::iter::extend,
#[cfg(feature = "ops")]
core::ops::deref,
#[cfg(feature = "ops")]
core::ops::deref_mut,
#[cfg(feature = "ops")]
core::ops::index,
#[cfg(feature = "ops")]
core::ops::index_mut,
#[cfg(feature = "ops")]
core::ops::range_bounds,
#[cfg(feature = "fn_traits")]
core::ops::fn_,
#[cfg(feature = "fn_traits")]
core::ops::fn_mut,
#[cfg(feature = "fn_traits")]
core::ops::fn_once,
#[cfg(feature = "generator_trait")]
core::ops::generator,
core::future,
// std
#[cfg(feature = "std")]
std::io::read,
#[cfg(feature = "std")]
std::io::buf_read,
#[cfg(feature = "std")]
std::io::seek,
#[cfg(feature = "std")]
std::io::write,
#[cfg(feature = "std")]
std::error,
// type impls
#[cfg(feature = "transpose_methods")]
ty_impls::transpose,
// futures
#[cfg(feature = "futures")]
external::futures::stream,
#[cfg(feature = "futures")]
external::futures::sink,
#[cfg(feature = "futures")]
external::futures::async_read,
#[cfg(feature = "futures")]
external::futures::async_write,
#[cfg(feature = "futures")]
external::futures::async_seek,
#[cfg(feature = "futures")]
external::futures::async_buf_read,
// futures01
#[cfg(feature = "futures01")]
external::futures01::future,
#[cfg(feature = "futures01")]
external::futures01::stream,
#[cfg(feature = "futures01")]
external::futures01::sink,
// rayon
#[cfg(feature = "rayon")]
external::rayon::par_iter,
#[cfg(feature = "rayon")]
external::rayon::indexed_par_iter,
#[cfg(feature = "rayon")]
external::rayon::par_extend,
// serde
#[cfg(feature = "serde")]
external::serde::serialize,
);
map
};
}
struct Args {
inner: Vec<(String, Path)>,
}
impl Parse for Args {
fn parse(input: ParseStream<'_>) -> Result<Self> {
fn to_trimed_string(p: &Path) -> String {
p.to_token_stream().to_string().replace(" ", "")
}
let mut inner = Vec::new();
while !input.is_empty() {
let value = input.parse()?;
inner.push((to_trimed_string(&value), value));
if !input.is_empty() {
let _: token::Comma = input.parse()?;
}
}
Ok(Self { inner })
}
}
fn expand(args: TokenStream, input: TokenStream) -> Result<TokenStream> {
fn alias_exists(s: &str, v: &[(&str, Option<&Path>)]) -> bool {
ALIAS_MAP.get(s).map_or(false, |x| v.iter().any(|(s, _)| s == x))
}
let span = input.clone();
let mut item = syn::parse2::<ItemEnum>(input).map_err(|e| {
error!(span, "the `#[enum_derive]` attribute may only be used on enums: {}", e)
})?;
let data = Data { data: EnumData::new(&item)?, span };
let args = syn::parse2::<Args>(args)?.inner;
let args = args.iter().fold(Vec::new(), |mut v, (s, arg)| {
if let Some(traits) = TRAIT_DEPENDENCIES.get(&&**s) {
traits.iter().filter(|&x| !args.iter().any(|(s, _)| s == x)).for_each(|s| {
if !alias_exists(s, &v) {
v.push((s, None))
}
});
}
if !alias_exists(s, &v) {
v.push((s, Some(arg)));
}
v
});
let mut derive = Vec::new();
let mut items = Vec::new();
for (s, arg) in args {
match (DERIVE_MAP.get(&s), arg) {
(Some(f), _) => (&*f)(&data, &mut items)
.map_err(|e| error!(data.span, "`enum_derive({})` {}", s, e))?,
(_, Some(arg)) => derive.push(arg),
_ => {}
}
}
if !derive.is_empty() {
item.attrs.push(syn::parse_quote!(#[derive(#(#derive),*)]));
}
let mut item = item.into_token_stream();
item.extend(items.into_iter().map(ToTokens::into_token_stream));
Ok(item)
}
|
//!
//! Traits for trait bounds
//!
use crate::internal::TraitBounds;
/// Provides methods to add trait bounds to elements.
pub trait TraitBoundExt {
/// Add a single trait bound.
fn add_trait_bound(&mut self, trait_bound: impl ToString) -> &mut Self;
/// Add multiple trait bounds at once.
fn add_trait_bounds(
&mut self,
trait_bounds: impl IntoIterator<Item = impl ToString>,
) -> &mut Self;
}
impl<T: TraitBounds> TraitBoundExt for T {
/// Add a single trait bound.
fn add_trait_bound(&mut self, trait_bound: impl ToString) -> &mut Self {
self.trait_bounds_mut().push(trait_bound.to_string());
self
}
/// Add multiple trait bounds at once.
fn add_trait_bounds(
&mut self,
trait_bounds: impl IntoIterator<Item = impl ToString>,
) -> &mut Self {
self.trait_bounds_mut()
.extend(trait_bounds.into_iter().map(|t| t.to_string()));
self
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::string::String;
use spin::RwLock;
use spin::Mutex;
use core::ops::Deref;
use core::any::Any;
use alloc::vec::Vec;
use alloc::sync::Arc;
use socket::unix::transport::unix::BoundEndpoint;
use super::super::host::hostinodeop::*;
use super::super::super::qlib::common::*;
use super::super::super::qlib::auth::*;
use super::super::super::qlib::linux_def::*;
use super::super::super::task::*;
use super::super::super::kernel::time::*;
use super::super::super::kernel::waiter::*;
use super::super::super::Kernel;
use super::super::super::qlib::mem::seq::*;
use super::super::super::qlib::mem::io::*;
use super::super::super::kernel::waiter::qlock::*;
use super::super::super::id_mgr::*;
use super::super::inode::*;
use super::super::mount::*;
use super::super::attr::*;
use super::super::file::*;
use super::super::dirent::*;
use super::super::dentry::*;
use super::super::flags::*;
use super::super::fsutil::inode::*;
use super::super::fsutil::file::*;
pub struct RandomDevice(pub RwLock<InodeSimpleAttributesInternal>);
impl Default for RandomDevice {
fn default() -> Self {
return Self(RwLock::new(Default::default()))
}
}
impl Deref for RandomDevice {
type Target = RwLock<InodeSimpleAttributesInternal>;
fn deref(&self) -> &RwLock<InodeSimpleAttributesInternal> {
&self.0
}
}
impl RandomDevice {
pub fn New(task: &Task, owner: &FileOwner, mode: &FileMode) -> Self {
let attr = InodeSimpleAttributesInternal::New(task, owner, &FilePermissions::FromMode(*mode), FSMagic::TMPFS_MAGIC);
return Self(RwLock::new(attr))
}
}
impl InodeOperations for RandomDevice {
fn as_any(&self) -> &Any {
return self
}
fn IopsType(&self) -> IopsType {
return IopsType::RandomDevice;
}
fn InodeType(&self) -> InodeType {
return InodeType::CharacterDevice;
}
fn InodeFileType(&self) -> InodeFileType{
return InodeFileType::Random;
}
fn WouldBlock(&self) -> bool {
return true;
}
fn Lookup(&self, _task: &Task, _dir: &Inode, _name: &str) -> Result<Dirent> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn Create(&self, _task: &Task, _dir: &mut Inode, _name: &str, _flags: &FileFlags, _perm: &FilePermissions) -> Result<File> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn CreateDirectory(&self, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn CreateLink(&self, _task: &Task, _dir: &mut Inode, _oldname: &str, _newname: &str) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn CreateHardLink(&self, _task: &Task, _dir: &mut Inode, _target: &Inode, _name: &str) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn CreateFifo(&self, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn Remove(&self, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn RemoveDirectory(&self, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn Rename(&self, _task: &Task, _dir: &mut Inode, _oldParent: &Inode, _oldname: &str, _newParent: &Inode, _newname: &str, _replacement: bool) -> Result<()> {
return Err(Error::SysError(SysErr::EINVAL))
}
fn Bind(&self, _task: &Task, _dir: &Inode, _name: &str, _data: &BoundEndpoint, _perms: &FilePermissions) -> Result<Dirent> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn BoundEndpoint(&self, _task: &Task, _inode: &Inode, _path: &str) -> Option<BoundEndpoint> {
return None
}
fn GetFile(&self, _task: &Task, _dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> {
let mut flags = flags;
flags.Pread = true;
flags.PWrite = true;
let fops = RandomFileOperations {};
let f = FileInternal {
UniqueId: UniqueID(),
Dirent: dirent.clone(),
flags: Mutex::new((flags, None)),
offset: QLock::New(0),
FileOp: Arc::new(fops),
};
return Ok(File(Arc::new(f)))
}
fn UnstableAttr(&self, _task: &Task, _dir: &Inode) -> Result<UnstableAttr> {
let u = self.read().unstable;
return Ok(u)
}
fn Getxattr(&self, _dir: &Inode, _name: &str) -> Result<String> {
return Err(Error::SysError(SysErr::EOPNOTSUPP))
}
fn Setxattr(&self, _dir: &mut Inode, _name: &str, _value: &str) -> Result<()> {
return Err(Error::SysError(SysErr::EOPNOTSUPP))
}
fn Listxattr(&self, _dir: &Inode) -> Result<Vec<String>> {
return Err(Error::SysError(SysErr::EOPNOTSUPP))
}
fn Check(&self, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> {
return ContextCanAccessFile(task, inode, reqPerms)
}
fn SetPermissions(&self, task: &Task, _dir: &mut Inode, p: FilePermissions) -> bool {
self.write().unstable.SetPermissions(task, &p);
return true;
}
fn SetOwner(&self, task: &Task, _dir: &mut Inode, owner: &FileOwner) -> Result<()> {
self.write().unstable.SetOwner(task, owner);
return Ok(())
}
fn SetTimestamps(&self, task: &Task, _dir: &mut Inode, ts: &InterTimeSpec) -> Result<()> {
self.write().unstable.SetTimestamps(task, ts);
return Ok(())
}
fn Truncate(&self, _task: &Task, _dir: &mut Inode, _size: i64) -> Result<()> {
return Ok(())
}
fn Allocate(&self, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> {
return Ok(())
}
fn ReadLink(&self, _task: &Task,_dir: &Inode) -> Result<String> {
return Err(Error::SysError(SysErr::ENOLINK))
}
fn GetLink(&self, _task: &Task, _dir: &Inode) -> Result<Dirent> {
return Err(Error::SysError(SysErr::ENOLINK))
}
fn AddLink(&self, _task: &Task) {
self.write().unstable.Links += 1;
}
fn DropLink(&self, _task: &Task) {
self.write().unstable.Links -= 1;
}
fn IsVirtual(&self) -> bool {
return true
}
fn Sync(&self) -> Result<()> {
return Err(Error::SysError(SysErr::ENOSYS));
}
fn StatFS(&self, _task: &Task) -> Result<FsInfo> {
return Err(Error::SysError(SysErr::ENOSYS))
}
fn Mappable(&self) -> Result<HostInodeOp> {
return Err(Error::SysError(SysErr::ENODEV))
}
}
pub struct RandomFileOperations {}
impl Waitable for RandomFileOperations {
fn Readiness(&self, _task: &Task, mask: EventMask) -> EventMask {
return mask;
}
fn EventRegister(&self, _task: &Task,_e: &WaitEntry, _mask: EventMask) {
}
fn EventUnregister(&self, _task: &Task,_e: &WaitEntry) {
}
}
impl SpliceOperations for RandomFileOperations {}
impl FileOperations for RandomFileOperations {
fn as_any(&self) -> &Any {
return self
}
fn FopsType(&self) -> FileOpsType {
return FileOpsType::RandomFileOperations
}
fn Seekable(&self) -> bool {
return true;
}
fn Seek(&self, task: &Task, f: &File, whence: i32, current: i64, offset: i64) -> Result<i64> {
return SeekWithDirCursor(task, f, whence, current, offset, None)
}
fn ReadDir(&self, _task: &Task, _f: &File, _offset: i64, _serializer: &mut DentrySerializer) -> Result<i64> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn ReadAt(&self, task: &Task, _f: &File, dsts: &mut [IoVec], _offset: i64, _blocking: bool) -> Result<i64> {
let len = IoVec::NumBytes(dsts);
let buf = DataBuff::New(len);
let mut ioReader = RandomReader {};
let mut reader = FromIOReader {
reader: &mut ioReader,
};
let ret = reader.ReadToBlocks(BlockSeq::NewFromSlice(&buf.Iovs()))?;
task.CopyDataOutToIovs(&buf.buf[0..ret as usize], dsts)?;
return Ok(ret);
}
fn WriteAt(&self, _task: &Task, _f: &File, srcs: &[IoVec], _offset: i64, _blocking: bool) -> Result<i64> {
return Ok(IoVec::NumBytes(srcs) as i64)
}
fn Append(&self, task: &Task, f: &File, srcs: &[IoVec]) -> Result<(i64, i64)> {
let n = self.WriteAt(task, f, srcs, 0, false)?;
return Ok((n, 0))
}
fn Fsync(&self, _task: &Task, _f: &File, _start: i64, _end: i64, _syncType: SyncType) -> Result<()> {
return Ok(())
}
fn Flush(&self, _task: &Task, _f: &File) -> Result<()> {
return Ok(())
}
fn UnstableAttr(&self, task: &Task, f: &File) -> Result<UnstableAttr> {
let inode = f.Dirent.Inode();
return inode.UnstableAttr(task);
}
fn Ioctl(&self, _task: &Task, _f: &File, _fd: i32, _request: u64, _val: u64) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTTY))
}
fn IterateDir(&self, _task: &Task, _d: &Dirent, _dirCtx: &mut DirCtx, _offset: i32) -> (i32, Result<i64>) {
return (0, Err(Error::SysError(SysErr::ENOTDIR)))
}
fn Mappable(&self) -> Result<HostInodeOp> {
return Err(Error::SysError(SysErr::ENODEV))
}
}
impl SockOperations for RandomFileOperations {}
pub struct RandomReader {}
impl IOReader for RandomReader {
fn Read(&mut self, buf: &mut [u8]) -> Result<i64> {
let res = Kernel::HostSpace::GetRandom(&buf[0] as *const _ as u64, buf.len() as u64, 0);
if res < 0 {
return Err(Error::SysError(-res as i32))
}
return Ok(res)
}
} |
use std::fmt;
/// Represents what type of file will be codegen'd
///
/// Currently supports two output types:
///
/// * Textual assembly (i.e. `foo.s`)
/// * Object code (i.e. `foo.o`)
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub enum CodeGenFileType {
Assembly = 0,
Object,
}
/// Represents the speed optimization level to apply during codegen
///
/// The default level is equivalent to -02
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub enum CodeGenOptLevel {
Other,
None,
Less,
Default,
Aggressive,
}
impl Default for CodeGenOptLevel {
fn default() -> Self {
Self::Default
}
}
impl fmt::Display for CodeGenOptLevel {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Other => f.write_str("other"),
Self::None => f.write_str("none"),
Self::Less => f.write_str("less"),
Self::Default => f.write_str("default"),
Self::Aggressive => f.write_str("aggressive"),
}
}
}
/// Represents the size optimization level to apply during codegen
///
/// The default level is equivalent to -O2
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub enum CodeGenOptSize {
Other,
None,
Default,
Aggressive,
}
impl Default for CodeGenOptSize {
fn default() -> Self {
Self::Default
}
}
impl fmt::Display for CodeGenOptSize {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Other => f.write_str("other"),
Self::None => f.write_str("none"),
Self::Default => f.write_str("default"),
Self::Aggressive => f.write_str("aggressive"),
}
}
}
/// Converts the unified OptLevel enum from the frontend to the speed/size opt level enums for LLVM
pub fn to_llvm_opt_settings(cfg: firefly_session::OptLevel) -> (CodeGenOptLevel, CodeGenOptSize) {
use firefly_session::OptLevel;
match cfg {
OptLevel::No => (CodeGenOptLevel::None, CodeGenOptSize::None),
OptLevel::Less => (CodeGenOptLevel::Less, CodeGenOptSize::None),
OptLevel::Default => (CodeGenOptLevel::Default, CodeGenOptSize::None),
OptLevel::Aggressive => (CodeGenOptLevel::Aggressive, CodeGenOptSize::None),
OptLevel::Size => (CodeGenOptLevel::Default, CodeGenOptSize::Default),
OptLevel::SizeMin => (CodeGenOptLevel::Default, CodeGenOptSize::Aggressive),
}
}
|
//! A [`PartitionProvider`] implementation that hits the [`Catalog`] to resolve
//! the partition id and persist offset.
use std::sync::Arc;
use async_trait::async_trait;
use backoff::{Backoff, BackoffConfig};
use data_types::{NamespaceId, Partition, PartitionKey, TableId};
use iox_catalog::interface::Catalog;
use observability_deps::tracing::debug;
use parking_lot::Mutex;
use super::r#trait::PartitionProvider;
use crate::{
buffer_tree::{
namespace::NamespaceName,
partition::{PartitionData, SortKeyState},
table::TableMetadata,
},
deferred_load::DeferredLoad,
};
/// A [`PartitionProvider`] implementation that hits the [`Catalog`] to resolve
/// the partition id and persist offset, returning an initialised
/// [`PartitionData`].
#[derive(Debug)]
pub(crate) struct CatalogPartitionResolver {
catalog: Arc<dyn Catalog>,
backoff_config: BackoffConfig,
}
impl CatalogPartitionResolver {
/// Construct a [`CatalogPartitionResolver`] that looks up partitions in
/// `catalog`.
pub(crate) fn new(catalog: Arc<dyn Catalog>) -> Self {
Self {
catalog,
backoff_config: Default::default(),
}
}
async fn get(
&self,
partition_key: PartitionKey,
table_id: TableId,
) -> Result<Partition, iox_catalog::interface::Error> {
self.catalog
.repositories()
.await
.partitions()
.create_or_get(partition_key, table_id)
.await
}
}
#[async_trait]
impl PartitionProvider for CatalogPartitionResolver {
async fn get_partition(
&self,
partition_key: PartitionKey,
namespace_id: NamespaceId,
namespace_name: Arc<DeferredLoad<NamespaceName>>,
table_id: TableId,
table: Arc<DeferredLoad<TableMetadata>>,
) -> Arc<Mutex<PartitionData>> {
debug!(
%partition_key,
%table_id,
%table,
"upserting partition in catalog"
);
let p = Backoff::new(&self.backoff_config)
.retry_all_errors("resolve partition", || {
self.get(partition_key.clone(), table_id)
})
.await
.expect("retry forever");
Arc::new(Mutex::new(PartitionData::new(
p.transition_partition_id(),
// Use the caller's partition key instance, as it MAY be shared with
// other instance, but the instance returned from the catalog
// definitely has no other refs.
partition_key,
namespace_id,
namespace_name,
table_id,
table,
SortKeyState::Provided(p.sort_key()),
)))
}
}
#[cfg(test)]
mod tests {
// Harmless in tests - saves a bunch of extra vars.
#![allow(clippy::await_holding_lock)]
use std::{sync::Arc, time::Duration};
use assert_matches::assert_matches;
use iox_catalog::{
partition_lookup,
test_helpers::{arbitrary_namespace, arbitrary_table},
};
use super::*;
use crate::buffer_tree::table::TableName;
const TABLE_NAME: &str = "bananas";
const NAMESPACE_NAME: &str = "ns-bananas";
const PARTITION_KEY: &str = "platanos";
#[tokio::test]
async fn test_resolver() {
let metrics = Arc::new(metric::Registry::default());
let catalog: Arc<dyn Catalog> =
Arc::new(iox_catalog::mem::MemCatalog::new(Arc::clone(&metrics)));
let (namespace_id, table_id) = {
let mut repos = catalog.repositories().await;
let ns = arbitrary_namespace(&mut *repos, NAMESPACE_NAME).await;
let table = arbitrary_table(&mut *repos, TABLE_NAME, &ns).await;
(ns.id, table.id)
};
let callers_partition_key = PartitionKey::from(PARTITION_KEY);
let table_name = TableName::from(TABLE_NAME);
let resolver = CatalogPartitionResolver::new(Arc::clone(&catalog));
let got = resolver
.get_partition(
callers_partition_key.clone(),
namespace_id,
Arc::new(DeferredLoad::new(
Duration::from_secs(1),
async { NamespaceName::from(NAMESPACE_NAME) },
&metrics,
)),
table_id,
Arc::new(DeferredLoad::new(
Duration::from_secs(1),
async {
TableMetadata::new_for_testing(
TableName::from(TABLE_NAME),
Default::default(),
)
},
&metrics,
)),
)
.await;
// Ensure the table name is available.
let _ = got.lock().table().get().await.name();
assert_eq!(got.lock().namespace_id(), namespace_id);
assert_eq!(
got.lock().table().get().await.name().to_string(),
table_name.to_string()
);
assert_matches!(got.lock().sort_key(), SortKeyState::Provided(None));
assert!(got.lock().partition_key.ptr_eq(&callers_partition_key));
let mut repos = catalog.repositories().await;
let id = got.lock().partition_id.clone();
let got = partition_lookup(repos.as_mut(), &id)
.await
.unwrap()
.expect("partition not created");
assert_eq!(got.table_id, table_id);
assert_eq!(got.partition_key, PartitionKey::from(PARTITION_KEY));
}
}
|
use serde::{de::DeserializeSeed, Deserialize, Deserializer};
use std::{
io::{Read, Seek},
marker::PhantomData,
};
pub fn from_read_seek<'de, Source: Read + Seek, T: Deserialize<'de>>(
data: &'de mut Source,
) -> Result<T, <de::Deserializer<Source> as Deserializer>::Error> {
from_read_seek_seed(data, PhantomData)
}
pub fn from_read_seek_seed<'de, Source: Read + Seek, Seed: DeserializeSeed<'de>>(
data: &'de mut Source,
seed: Seed,
) -> Result<Seed::Value, <de::Deserializer<Source> as serde::de::Deserializer>::Error> {
seed.deserialize(de::Deserializer(data))
}
|
#![allow(dead_code)]
use crate::{aocbail, utils};
use utils::{AOCResult, AOCError};
pub fn day13() {
let input = utils::get_input("day13");
println!("shuttle_search part 1: {:?}", find_schedule(input).unwrap());
let input = utils::get_input("day13");
println!("shuttle_search part 2: {:?}", chinese_remainder_theorem(input).unwrap());
}
pub fn find_schedule(mut input: impl Iterator<Item = String>) -> AOCResult<u32> {
let departure = input.next()?.parse::<u32>()?;
let raw_schedules = input.next()?;
let mut min_id = 0;
let mut min_wait_time = 0;
for raw_schedule in raw_schedules.split(",") {
if raw_schedule == "x" {
continue;
}
let schedule_id = raw_schedule.parse::<u32>()?;
let wait_time = ((departure / schedule_id) + 1) * schedule_id - departure;
if min_id == 0 || wait_time < min_wait_time {
min_id = schedule_id;
min_wait_time = wait_time;
}
}
Ok(min_id * min_wait_time)
}
pub fn mod_inverse(a: u64, m: u64) -> AOCResult<u64> {
for x in 1..m {
if (a * x) % m == 1 {
return Ok(x);
}
}
println!("failed for {} {}", a, m);
aocbail!("mod_inverse failed!");
}
pub fn chinese_remainder_theorem(mut input: impl Iterator<Item = String>) -> AOCResult<u64> {
let _ = input.next()?;
let raw_schedules = input.next()?;
let mut buses = Vec::new();
let mut big_n = 1;
for (i, raw_schedule) in raw_schedules.split(",").enumerate() {
if raw_schedule == "x" {
continue;
}
let bus = raw_schedule.parse::<i64>()?;
let mut offset = bus - i as i64;
while offset < 0 {
offset += bus;
}
big_n *= bus as u64;
buses.push((offset as u64, bus as u64));
}
let mut sum = 0;
for (a, n) in buses.iter() {
let coprime = big_n / n;
sum += a * coprime * mod_inverse(coprime, *n)?;
}
Ok(sum % big_n)
}
#[test]
pub fn test_day13() {
let input = utils::get_input("test_day13");
assert_eq!(find_schedule(input).unwrap(), 295);
assert_eq!(mod_inverse(10, 17).unwrap(), 12);
let input = utils::get_input("test_day13_2");
assert_eq!(chinese_remainder_theorem(input).unwrap(), 3417);
}
|
use bitflags::bitflags;
use std::{cell::RefCell, collections::VecDeque, rc::Rc};
bitflags! {
/// flags defining what part of the app need to update
pub struct NeedsUpdate: u32 {
/// app::update
const ALL = 0b001;
/// diff may have changed (app::update_diff)
const DIFF = 0b010;
/// commands might need updating (app::update_commands)
const COMMANDS = 0b100;
}
}
///
pub enum InternalEvent {
///
ConfirmResetFile(String),
///
ResetFile(String),
///
AddHunk(u64),
///
ShowMsg(String),
///
Update(NeedsUpdate),
}
///
pub type Queue = Rc<RefCell<VecDeque<InternalEvent>>>;
|
use std::fmt;
use std::collections::HashMap;
use std::collections::hash_map::RandomState;
use async_std::io::{Read};
use crate::{Error, read_head, read_headers, validate_size_constraint};
#[derive(Debug)]
pub struct Response {
status_code: usize,
status_message: String,
version: String,
headers: HashMap<String, String>,
}
impl Response {
pub fn new() -> Self {
Self {
status_code: 200,
status_message: String::from("OK"),
version: String::from("HTTP/1.1"),
headers: HashMap::with_hasher(RandomState::new()),
}
}
pub async fn read<I>(stream: &mut I, limit: Option<usize>) -> Result<Self, Error>
where
I: Read + Unpin,
{
let mut req = Self::new();
let mut length = 0;
let mut head = Vec::new();
length += read_head(stream, &mut head).await?;
validate_size_constraint(length, limit)?;
req.set_version(match head.get(0) {
Some(version) => version,
None => return Err(Error::InvalidData),
});
req.set_status_code(match head.get(1) {
Some(code) => match code.parse::<usize>() {
Ok(code) => code,
Err(_) => return Err(Error::InvalidData),
},
None => return Err(Error::InvalidData),
});
req.set_status_message(match head.get(2) {
Some(message) => message,
None => return Err(Error::InvalidData),
});
read_headers(stream, &mut req.headers, match limit {
Some(limit) => Some(limit - length),
None => None,
}).await?;
Ok(req)
}
pub fn status_code(&self) -> usize {
self.status_code
}
pub fn status_message(&self) -> &String {
&self.status_message
}
pub fn version(&self) -> &String {
&self.version
}
pub fn headers(&self) -> &HashMap<String, String> {
&self.headers
}
pub fn header<N: Into<String>>(&self, name: N) -> Option<&String> {
self.headers.get(&name.into())
}
pub fn has_status_code(&self, value: usize) -> bool {
self.status_code == value
}
pub fn has_version<V: Into<String>>(&self, value: V) -> bool {
self.version == value.into()
}
pub fn has_headers(&self) -> bool {
!self.headers.is_empty()
}
pub fn has_header<N: Into<String>>(&self, name: N) -> bool {
self.headers.contains_key(&name.into())
}
pub fn set_status_code(&mut self, value: usize) {
self.status_code = value;
}
pub fn set_status_message<V: Into<String>>(&mut self, value: V) {
self.status_message = value.into();
}
pub fn set_version<V: Into<String>>(&mut self, value: V) {
self.version = value.into();
}
pub fn set_header<N: Into<String>, V: Into<String>>(&mut self, name: N, value: V) {
self.headers.insert(name.into(), value.into());
}
pub fn remove_header<N: Into<String>>(&mut self, name: N) {
self.headers.remove(&name.into());
}
pub fn clear_headers(&mut self) {
self.headers.clear();
}
pub fn to_string(&self) -> String {
let mut output = String::new();
if !self.has_version("HTTP/0.9") {
output.push_str(&format!("{} {} {}\r\n", self.version, self.status_code, self.status_message));
for (name, value) in self.headers.iter() {
output.push_str(&format!("{}: {}\r\n", name, value));
}
output.push_str("\r\n");
}
output
}
}
impl fmt::Display for Response {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.to_string())
}
}
impl From<Response> for String {
fn from(item: Response) -> String {
item.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[async_std::test]
async fn creates_from_stream() {
let stream = String::from("HTTP/1.1 200 OK\r\nH: V\r\n\r\n");
let res = Response::read(&mut stream.as_bytes(), None).await.unwrap();
assert_eq!(res.status_code(), 200);
assert_eq!(res.status_message(), "OK");
assert_eq!(res.version(), "HTTP/1.1");
assert_eq!(res.headers().len(), 1);
assert_eq!(res.header("H").unwrap(), "V");
}
}
|
pub struct Solution;
impl Solution {
pub fn trap(height: Vec<i32>) -> i32 {
let n = height.len();
if n == 0 {
return 0;
}
let mut a = vec![0; n];
a[0] = height[0];
for i in 1..n {
a[i] = a[i - 1].max(height[i]);
}
let mut b = vec![0; n];
b[n - 1] = height[n - 1];
for i in 1..n {
b[n - 1 - i] = b[n - i].max(height[n - 1 - i]);
}
let mut area = 0;
for i in 0..n {
area += a[i].min(b[i]) - height[i];
}
area
}
}
#[test]
fn test0042() {
assert_eq!(Solution::trap(vec![0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]), 6);
assert_eq!(Solution::trap(vec![]), 0);
}
|
// 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.
// Test that duplicate auto trait bounds in trait objects don't create new types.
#[allow(unused_assignments)]
use std::marker::Send as SendAlias;
// A dummy trait for the non-auto trait.
trait Trait {}
// A dummy struct to implement Trait, Send, and .
struct Struct;
impl Trait for Struct {}
// These three functions should be equivalent.
fn takes_dyn_trait_send(_: Box<dyn Trait + Send>) {}
fn takes_dyn_trait_send_send(_: Box<dyn Trait + Send + Send>) {}
fn takes_dyn_trait_send_sendalias(_: Box<dyn Trait + Send + SendAlias>) {}
impl dyn Trait + Send + Send {
fn do_nothing(&self) {}
}
fn main() {
// 1. Moving into a variable with more Sends and back.
let mut dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
let dyn_trait_send_send: Box<dyn Trait + Send + Send> = dyn_trait_send;
dyn_trait_send = dyn_trait_send_send;
// 2. Calling methods with different number of Sends.
let dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
takes_dyn_trait_send_send(dyn_trait_send);
let dyn_trait_send_send = Box::new(Struct) as Box<dyn Trait + Send + Send>;
takes_dyn_trait_send(dyn_trait_send_send);
// 3. Aliases to the trait are transparent.
let dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
takes_dyn_trait_send_sendalias(dyn_trait_send);
// 4. Calling an impl that duplicates an auto trait.
let dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
dyn_trait_send.do_nothing();
}
|
extern crate csv;
use serde::Serialize;
use std::env;
use std::error::Error;
use std::ffi::OsString;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::{BufWriter, Write};
use std::process;
//use serde_json::{json, Value};
use std::collections::BTreeMap;
type Record = BTreeMap<String, String>;
#[derive(Default, Debug, Serialize)]
struct Criterion {
text: String,
hinting: String,
}
#[derive(Default, Debug, Serialize)]
struct Database {
children: BTreeMap<String, Database>,
data: Record,
inclusion_criteria: Vec<Criterion>,
exclusion_criteria: Vec<Criterion>,
}
impl Database {
fn insert_path(&mut self, path: &[&str]) -> &mut Self {
// node is a mutable reference to the current database
let mut node = self;
// iterate through the path
for &subkey in path.iter() {
// insert the new database object if necessary and
// set node to (a mutable reference to) the child node
node = node
.children
.entry(subkey.to_string())
.or_insert_with(Database::default);
}
node
}
}
fn populate_criteria(node: &mut Database, url: &String) {
println!("Scraping: {}", url);
let criterion: Criterion = Criterion {
text: String::from("Text1"),
..Criterion::default()
};
node.inclusion_criteria.push(criterion);
let criterion2: Criterion = Criterion {
text: String::from("Text2"),
..Criterion::default()
};
node.inclusion_criteria.push(criterion2);
}
fn populate_record(db: &mut Database, record: &mut Record) -> Result<String, Box<dyn Error>> {
let nct_trial = record.get("NCT Number").unwrap().as_str();
let subkeys = vec![nct_trial];
let node = db.insert_path(&subkeys);
node.data = record.clone();
let url = record.get("URL").unwrap();
populate_criteria(node, url);
let db_json = serde_json::to_string(&db).unwrap();
Ok(db_json.clone())
}
#[tokio::main]
async fn run() -> Result<(), Box<dyn Error>> {
let in_file_path = get_first_arg()?;
let in_file = File::open(in_file_path)?;
let mut rdr = csv::ReaderBuilder::new()
.has_headers(true)
.from_reader(in_file);
let out_file = OpenOptions::new()
.append(false)
.write(true)
.create(true)
.open("clinical_trials.json")
.expect("Unable to open file.");
let mut out_file = BufWriter::new(out_file);
let mut db = Database {
children: BTreeMap::new(),
data: Record::new(),
inclusion_criteria: Vec::new(),
exclusion_criteria: Vec::new(),
};
let mut completed_record: String = String::new();
for result in rdr.deserialize() {
let mut record: Record = result?;
completed_record = populate_record(&mut db, &mut record).unwrap();
}
out_file
.write_all(completed_record.as_bytes())
.expect("Unable to write to file.");
Ok(())
}
/// Returns the first positional argument sent to this process. If there are no
/// positional arguments, then this returns an error.
fn get_first_arg() -> Result<OsString, Box<dyn Error>> {
match env::args_os().nth(1) {
None => Err(From::from("expected 1 argument, but got none")),
Some(file_path) => Ok(file_path),
}
}
fn main() {
if let Err(err) = run() {
println!("{}", err);
process::exit(1);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.