hexsha
stringlengths 40
40
| size
int64 4
1.05M
| content
stringlengths 4
1.05M
| avg_line_length
float64 1.33
100
| max_line_length
int64 1
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
f8449c6ec1255a7079b2ceccb4eb8ffb15b5c454 | 3,047 | use crate::avm1::activation::Activation;
use crate::avm1::error::Error;
use crate::avm1::object::Object;
use crate::avm1::property_decl::{define_properties_on, Declaration};
use crate::avm1::{AvmString, ScriptObject, Value};
use crate::avm_warn;
use gc_arena::MutationContext;
use std::convert::Into;
const OBJECT_DECLS: &[Declaration] = declare_properties! {
"PolicyFileResolver" => method(policy_file_resolver);
"allowDomain" => method(allow_domain);
"allowInsecureDomain" => method(allow_insecure_domain);
"loadPolicyFile" => method(load_policy_file);
"escapeDomain" => method(escape_domain);
"sandboxType" => property(get_sandbox_type);
"chooseLocalSwfPath" => property(get_choose_local_swf_path);
};
fn allow_domain<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "System.security.allowDomain() not implemented");
Ok(Value::Undefined)
}
fn allow_insecure_domain<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(
activation,
"System.security.allowInsecureDomain() not implemented"
);
Ok(Value::Undefined)
}
fn load_policy_file<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(
activation,
"System.security.allowInsecureDomain() not implemented"
);
Ok(Value::Undefined)
}
fn escape_domain<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "System.security.escapeDomain() not implemented");
Ok(Value::Undefined)
}
fn get_sandbox_type<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
Ok(AvmString::new(
activation.context.gc_context,
activation.context.system.sandbox_type.to_string(),
)
.into())
}
fn get_choose_local_swf_path<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(
activation,
"System.security.chooseLocalSwfPath() not implemented"
);
Ok(Value::Undefined)
}
fn policy_file_resolver<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(
activation,
"System.security.chooseLocalSwfPath() not implemented"
);
Ok(Value::Undefined)
}
pub fn create<'gc>(
gc_context: MutationContext<'gc, '_>,
proto: Option<Object<'gc>>,
fn_proto: Object<'gc>,
) -> Object<'gc> {
let security = ScriptObject::object(gc_context, proto);
define_properties_on(OBJECT_DECLS, gc_context, security, fn_proto);
security.into()
}
| 28.476636 | 76 | 0.643256 |
d5acf82207dc7bed424ea5827b4973a662497e5c | 544 | use super::*;
use windows::{core::*, UI::ViewManagement::*};
fn accent_impl() -> Result<Color> {
let settings = UISettings::new()?;
let accent = settings.GetColorValue(UIColorType::Accent)?;
Ok(Color {
r: accent.R,
g: accent.G,
b: accent.B,
})
}
pub fn accent() -> Color {
accent_impl().unwrap_or_else(|e| {
if cfg!(debug_assertions) {
eprintln!("WARNING: {}", e.message());
}
Color {
r: 0,
g: 120,
b: 215,
}
})
}
| 20.923077 | 62 | 0.487132 |
61c297e0d76db8f0a76e062e22faeaff0b240fb4 | 12,712 | // Copyright 2015-2017 Benjamin Fry <[email protected]>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use std::iter::Chain;
use std::slice::Iter;
use std::sync::Arc;
use cfg_if::cfg_if;
use crate::authority::{LookupObject, LookupOptions};
use crate::client::rr::LowerName;
use crate::proto::rr::{Record, RecordSet, RecordType, RrsetRecords};
/// The result of a lookup on an Authority
///
/// # Lifetimes
///
/// * `'c` - the catalogue lifetime
/// * `'r` - the recordset lifetime, subset of 'c
/// * `'q` - the queries lifetime
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum AuthLookup {
/// No records
Empty,
// TODO: change the result of a lookup to a set of chained iterators...
/// Records
Records {
/// Authoritative answers
answers: LookupRecords,
/// Optional set of LookupRecords
additionals: Option<LookupRecords>,
},
/// Soa only differs from Records in that the lifetime on the name is from the authority, and not the query
SOA(LookupRecords),
/// An axfr starts with soa, chained to all the records, then another soa...
AXFR {
/// The first SOA record in an AXFR response
start_soa: LookupRecords,
/// The records to return
records: LookupRecords,
/// The last SOA record of an AXFR (matches the first)
end_soa: LookupRecords,
},
}
impl AuthLookup {
/// Construct an answer with additional section
pub fn answers(answers: LookupRecords, additionals: Option<LookupRecords>) -> Self {
Self::Records {
answers,
additionals,
}
}
/// Returns true if either the associated Records are empty, or this is a NameExists or NxDomain
pub fn is_empty(&self) -> bool {
// TODO: this needs to be cheap
self.was_empty()
}
/// This is an NxDomain or NameExists, and has no associated records
///
/// this consumes the iterator, and verifies it is empty
pub fn was_empty(&self) -> bool {
self.iter().count() == 0
}
/// Conversion to an iterator
pub fn iter(&self) -> AuthLookupIter<'_> {
self.into_iter()
}
/// Does not panic, but will return no records if it is not of that type
pub fn unwrap_records(self) -> LookupRecords {
match self {
// TODO: this is ugly, what about the additionals?
AuthLookup::Records { answers, .. } => answers,
_ => LookupRecords::default(),
}
}
/// Takes the additional records, leaving behind None
pub fn take_additionals(&mut self) -> Option<LookupRecords> {
match self {
AuthLookup::Records {
ref mut additionals,
..
} => additionals.take(),
_ => None,
}
}
}
impl LookupObject for AuthLookup {
fn is_empty(&self) -> bool {
Self::is_empty(self)
}
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = &'a Record> + Send + 'a> {
let boxed_iter = Self::iter(self);
Box::new(boxed_iter)
}
fn take_additionals(&mut self) -> Option<Box<dyn LookupObject>> {
let additionals = Self::take_additionals(self);
additionals.map(|a| Box::new(a) as Box<dyn LookupObject>)
}
}
impl Default for AuthLookup {
fn default() -> Self {
Self::Empty
}
}
impl<'a> IntoIterator for &'a AuthLookup {
type Item = &'a Record;
type IntoIter = AuthLookupIter<'a>;
fn into_iter(self) -> Self::IntoIter {
match self {
AuthLookup::Empty => AuthLookupIter::Empty,
// TODO: what about the additionals? is IntoIterator a bad idea?
AuthLookup::Records { answers: r, .. } | AuthLookup::SOA(r) => {
AuthLookupIter::Records(r.into_iter())
}
AuthLookup::AXFR {
start_soa,
records,
end_soa,
} => AuthLookupIter::AXFR(start_soa.into_iter().chain(records).chain(end_soa)),
}
}
}
/// An iterator over an Authority Lookup
#[allow(clippy::large_enum_variant)]
pub enum AuthLookupIter<'r> {
/// The empty set
Empty,
/// An iteration over a set of Records
Records(LookupRecordsIter<'r>),
/// An iteration over an AXFR
AXFR(Chain<Chain<LookupRecordsIter<'r>, LookupRecordsIter<'r>>, LookupRecordsIter<'r>>),
}
impl<'r> Iterator for AuthLookupIter<'r> {
type Item = &'r Record;
fn next(&mut self) -> Option<Self::Item> {
match self {
AuthLookupIter::Empty => None,
AuthLookupIter::Records(i) => i.next(),
AuthLookupIter::AXFR(i) => i.next(),
}
}
}
impl<'a> Default for AuthLookupIter<'a> {
fn default() -> Self {
AuthLookupIter::Empty
}
}
impl From<LookupRecords> for AuthLookup {
fn from(lookup: LookupRecords) -> Self {
Self::Records {
answers: lookup,
additionals: None,
}
}
}
/// An iterator over an ANY query for Records.
///
/// The length of this result cannot be known without consuming the iterator.
///
/// # Lifetimes
///
/// * `'r` - the record_set's lifetime, from the catalog
/// * `'q` - the lifetime of the query/request
#[derive(Debug)]
pub struct AnyRecords {
lookup_options: LookupOptions,
rrsets: Vec<Arc<RecordSet>>,
query_type: RecordType,
query_name: LowerName,
}
impl AnyRecords {
/// construct a new lookup of any set of records
pub fn new(
lookup_options: LookupOptions,
// TODO: potentially very expensive
rrsets: Vec<Arc<RecordSet>>,
query_type: RecordType,
query_name: LowerName,
) -> Self {
Self {
lookup_options,
rrsets,
query_type,
query_name,
}
}
fn iter(&self) -> AnyRecordsIter<'_> {
self.into_iter()
}
}
impl<'r> IntoIterator for &'r AnyRecords {
type Item = &'r Record;
type IntoIter = AnyRecordsIter<'r>;
fn into_iter(self) -> Self::IntoIter {
AnyRecordsIter {
lookup_options: self.lookup_options,
// TODO: potentially very expensive
rrsets: self.rrsets.iter(),
rrset: None,
records: None,
query_type: self.query_type,
query_name: &self.query_name,
}
}
}
/// An iteration over a lookup for any Records
#[allow(unused)]
pub struct AnyRecordsIter<'r> {
lookup_options: LookupOptions,
rrsets: Iter<'r, Arc<RecordSet>>,
rrset: Option<&'r RecordSet>,
records: Option<RrsetRecords<'r>>,
query_type: RecordType,
query_name: &'r LowerName,
}
impl<'r> Iterator for AnyRecordsIter<'r> {
type Item = &'r Record;
fn next(&mut self) -> Option<Self::Item> {
use std::borrow::Borrow;
let query_type = self.query_type;
let query_name = self.query_name;
loop {
if let Some(ref mut records) = self.records {
let record = records
.by_ref()
.filter(|rr_set| {
query_type == RecordType::ANY || rr_set.record_type() != RecordType::SOA
})
.find(|rr_set| {
query_type == RecordType::AXFR
|| &LowerName::from(rr_set.name()) == query_name
});
if record.is_some() {
return record;
}
}
self.rrset = self.rrsets.next().map(Borrow::borrow);
// if there are no more RecordSets, then return
self.rrset?;
// getting here, we must have exhausted our records from the rrset
cfg_if! {
if #[cfg(feature = "dnssec")] {
self.records = Some(
self.rrset
.expect("rrset should not be None at this point")
.records(self.lookup_options.is_dnssec(), self.lookup_options.supported_algorithms()),
);
} else {
self.records = Some(self.rrset.expect("rrset should not be None at this point").records_without_rrsigs());
}
}
}
}
}
/// The result of a lookup
#[derive(Debug)]
pub enum LookupRecords {
/// The empty set of records
Empty,
/// The associate records
Records {
/// LookupOptions for the request, e.g. dnssec and supported algorithms
lookup_options: LookupOptions,
/// the records found based on the query
records: Arc<RecordSet>,
},
/// Vec of disjoint record sets
ManyRecords(LookupOptions, Vec<Arc<RecordSet>>),
// TODO: need a better option for very large zone xfrs...
/// A generic lookup response where anything is desired
AnyRecords(AnyRecords),
}
impl LookupRecords {
/// Construct a new LookupRecords
pub fn new(lookup_options: LookupOptions, records: Arc<RecordSet>) -> Self {
Self::Records {
lookup_options,
records,
}
}
/// Construct a new LookupRecords over a set of ResordSets
pub fn many(lookup_options: LookupOptions, mut records: Vec<Arc<RecordSet>>) -> Self {
// we're reversing the records because they are output in reverse order, via pop()
records.reverse();
Self::ManyRecords(lookup_options, records)
}
/// This is an NxDomain or NameExists, and has no associated records
///
/// this consumes the iterator, and verifies it is empty
pub fn was_empty(&self) -> bool {
self.iter().count() == 0
}
/// Conversion to an iterator
pub fn iter(&self) -> LookupRecordsIter<'_> {
self.into_iter()
}
}
impl Default for LookupRecords {
fn default() -> Self {
Self::Empty
}
}
impl<'a> IntoIterator for &'a LookupRecords {
type Item = &'a Record;
type IntoIter = LookupRecordsIter<'a>;
#[allow(unused_variables)]
fn into_iter(self) -> Self::IntoIter {
match self {
LookupRecords::Empty => LookupRecordsIter::Empty,
LookupRecords::Records {
lookup_options,
records,
} => LookupRecordsIter::RecordsIter(
lookup_options.rrset_with_supported_algorithms(records),
),
LookupRecords::ManyRecords(lookup_options, r) => LookupRecordsIter::ManyRecordsIter(
r.iter()
.map(|r| lookup_options.rrset_with_supported_algorithms(r))
.collect(),
None,
),
LookupRecords::AnyRecords(r) => LookupRecordsIter::AnyRecordsIter(r.iter()),
}
}
}
/// Iterator over lookup records
pub enum LookupRecordsIter<'r> {
/// An iteration over batch record type results
AnyRecordsIter(AnyRecordsIter<'r>),
/// An iteration over a single RecordSet
RecordsIter(RrsetRecords<'r>),
/// An iteration over many rrsets
ManyRecordsIter(Vec<RrsetRecords<'r>>, Option<RrsetRecords<'r>>),
/// An empty set
Empty,
}
impl<'r> Default for LookupRecordsIter<'r> {
fn default() -> Self {
LookupRecordsIter::Empty
}
}
impl<'r> Iterator for LookupRecordsIter<'r> {
type Item = &'r Record;
fn next(&mut self) -> Option<Self::Item> {
match self {
LookupRecordsIter::Empty => None,
LookupRecordsIter::AnyRecordsIter(current) => current.next(),
LookupRecordsIter::RecordsIter(current) => current.next(),
LookupRecordsIter::ManyRecordsIter(set, ref mut current) => loop {
if let Some(o) = current.as_mut().and_then(Iterator::next) {
return Some(o);
}
*current = set.pop();
if current.is_none() {
return None;
}
},
}
}
}
impl From<AnyRecords> for LookupRecords {
fn from(rrset_records: AnyRecords) -> Self {
Self::AnyRecords(rrset_records)
}
}
impl LookupObject for LookupRecords {
fn is_empty(&self) -> bool {
Self::was_empty(self)
}
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = &'a Record> + Send + 'a> {
Box::new(self.iter())
}
fn take_additionals(&mut self) -> Option<Box<dyn LookupObject>> {
None
}
}
| 29.562791 | 126 | 0.578272 |
87d4153ee20e17d1caf3da50504015916dac31cf | 4,051 | #[doc = "Counter compare values\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cc](cc) module"]
pub type CC = crate::Reg<u32, _CC>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CC;
#[doc = "`read()` method returns [cc::R](cc::R) reader structure"]
impl crate::Readable for CC {}
#[doc = "`write(|w| ..)` method takes [cc::W](cc::W) writer structure"]
impl crate::Writable for CC {}
#[doc = "Counter compare values"]
pub mod cc;
#[doc = "Control and status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [csr](csr) module"]
pub type CSR = crate::Reg<u32, _CSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CSR;
#[doc = "`read()` method returns [csr::R](csr::R) reader structure"]
impl crate::Readable for CSR {}
#[doc = "`write(|w| ..)` method takes [csr::W](csr::W) writer structure"]
impl crate::Writable for CSR {}
#[doc = "Control and status register"]
pub mod csr;
#[doc = "Direct access to the PWM counter\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ctr](ctr) module"]
pub type CTR = crate::Reg<u32, _CTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CTR;
#[doc = "`read()` method returns [ctr::R](ctr::R) reader structure"]
impl crate::Readable for CTR {}
#[doc = "`write(|w| ..)` method takes [ctr::W](ctr::W) writer structure"]
impl crate::Writable for CTR {}
#[doc = "Direct access to the PWM counter"]
pub mod ctr;
#[doc = "INT and FRAC form a fixed-point fractional number.\\n Counting rate is system clock frequency divided by this number.\\n Fractional division uses simple 1st-order sigma-delta.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [div](div) module"]
pub type DIV = crate::Reg<u32, _DIV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DIV;
#[doc = "`read()` method returns [div::R](div::R) reader structure"]
impl crate::Readable for DIV {}
#[doc = "`write(|w| ..)` method takes [div::W](div::W) writer structure"]
impl crate::Writable for DIV {}
#[doc = "INT and FRAC form a fixed-point fractional number.\\n Counting rate is system clock frequency divided by this number.\\n Fractional division uses simple 1st-order sigma-delta."]
pub mod div;
#[doc = "Counter wrap value\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [top](top) module"]
pub type TOP = crate::Reg<u32, _TOP>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TOP;
#[doc = "`read()` method returns [top::R](top::R) reader structure"]
impl crate::Readable for TOP {}
#[doc = "`write(|w| ..)` method takes [top::W](top::W) writer structure"]
impl crate::Writable for TOP {}
#[doc = "Counter wrap value"]
pub mod top;
| 72.339286 | 552 | 0.6902 |
61aeb99d0339ca3a51370b2a5e7d2754665b7870 | 4,182 | use std::f64::INFINITY;
use std::fmt;
use crate::errors::{Result, TaError};
use crate::{Low, Next, Period, Reset};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// Returns the lowest value in a given time frame.
///
/// # Parameters
///
/// * `period` - Size of the time frame (integer greater than 0). Default value
/// is 14.
///
/// # Example
///
/// ```
/// use ta::indicators::Minimum;
/// use ta::Next;
///
/// let mut min = Minimum::new(3).unwrap();
/// assert_eq!(min.next(10.0), 10.0);
/// assert_eq!(min.next(11.0), 10.0);
/// assert_eq!(min.next(12.0), 10.0);
/// assert_eq!(min.next(13.0), 11.0);
/// ```
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct Minimum {
period: usize,
min_index: usize,
cur_index: usize,
deque: Box<[f64]>,
}
impl Minimum {
pub fn new(period: usize) -> Result<Self> {
match period {
0 => Err(TaError::InvalidParameter),
_ => Ok(Self {
period,
min_index: 0,
cur_index: 0,
deque: vec![INFINITY; period].into_boxed_slice(),
}),
}
}
fn find_min_index(&self) -> usize {
let mut min = ::std::f64::INFINITY;
let mut index: usize = 0;
for (i, &val) in self.deque.iter().enumerate() {
if val < min {
min = val;
index = i;
}
}
index
}
}
impl Period for Minimum {
fn period(&self) -> usize {
self.period
}
}
impl Next<f64> for Minimum {
type Output = f64;
fn next(&mut self, input: f64) -> Self::Output {
self.deque[self.cur_index] = input;
if input < self.deque[self.min_index] {
self.min_index = self.cur_index;
} else if self.min_index == self.cur_index {
self.min_index = self.find_min_index();
}
self.cur_index = if self.cur_index + 1 < self.period {
self.cur_index + 1
} else {
0
};
self.deque[self.min_index]
}
}
impl<T: Low> Next<&T> for Minimum {
type Output = f64;
fn next(&mut self, input: &T) -> Self::Output {
self.next(input.low())
}
}
impl Reset for Minimum {
fn reset(&mut self) {
for i in 0..self.period {
self.deque[i] = INFINITY;
}
}
}
impl Default for Minimum {
fn default() -> Self {
Self::new(14).unwrap()
}
}
impl fmt::Display for Minimum {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "MIN({})", self.period)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_helper::*;
test_indicator!(Minimum);
#[test]
fn test_new() {
assert!(Minimum::new(0).is_err());
assert!(Minimum::new(1).is_ok());
}
#[test]
fn test_next() {
let mut min = Minimum::new(3).unwrap();
assert_eq!(min.next(4.0), 4.0);
assert_eq!(min.next(1.2), 1.2);
assert_eq!(min.next(5.0), 1.2);
assert_eq!(min.next(3.0), 1.2);
assert_eq!(min.next(4.0), 3.0);
assert_eq!(min.next(6.0), 3.0);
assert_eq!(min.next(7.0), 4.0);
assert_eq!(min.next(8.0), 6.0);
assert_eq!(min.next(-9.0), -9.0);
assert_eq!(min.next(0.0), -9.0);
}
#[test]
fn test_next_with_bars() {
fn bar(low: f64) -> Bar {
Bar::new().low(low)
}
let mut min = Minimum::new(3).unwrap();
assert_eq!(min.next(&bar(4.0)), 4.0);
assert_eq!(min.next(&bar(4.0)), 4.0);
assert_eq!(min.next(&bar(1.2)), 1.2);
assert_eq!(min.next(&bar(5.0)), 1.2);
}
#[test]
fn test_reset() {
let mut min = Minimum::new(10).unwrap();
assert_eq!(min.next(5.0), 5.0);
assert_eq!(min.next(7.0), 5.0);
min.reset();
assert_eq!(min.next(8.0), 8.0);
}
#[test]
fn test_default() {
Minimum::default();
}
#[test]
fn test_display() {
let indicator = Minimum::new(10).unwrap();
assert_eq!(format!("{}", indicator), "MIN(10)");
}
}
| 22.483871 | 79 | 0.512434 |
4a63a4886de4f7d2e23da53b3a1473bf22439a5f | 4,440 | use std::collections::HashMap;
use crate::net::message;
use crate::leader::tag::Tag;
use tokio::time::{sleep, Duration, Instant};
use tokio::sync::{oneshot, Mutex, mpsc};
use std::sync::Arc;
#[derive(Debug)]
pub enum HeartbeatOutput {
HeartbeatNotReceived(String),
}
pub struct HeartbeatMonitor {
following: Option<String>,
peers: HashMap<String, message::Sender>,
last_heartbeat: Arc<Mutex<HashMap<String,Instant>>>,
output_receiver: mpsc::Receiver<HeartbeatOutput>,
_shutdown_sender: oneshot::Sender<()>,
}
impl HeartbeatMonitor {
pub fn new(peers: HashMap<String, message::Sender>, following: Option<String>) -> Self {
let (shutdown_sender, mut shutdown_receiver) = oneshot::channel();
let (mut output_sender, output_receiver) = mpsc::channel(1);
let mut last_heartbeat = HashMap::new();
if let Some(following) = &following {
last_heartbeat.insert(following.clone(), Instant::now());
} else {
for (peer, _) in peers.iter() {
last_heartbeat.insert(peer.clone(), Instant::now());
}
}
let last_heartbeat = Arc::new(Mutex::new(last_heartbeat));
if following.is_none() {
let peers = peers.clone();
tokio::spawn(async move {
loop {
tokio::select! {
_ = sleep(Duration::from_millis(100)) => {}
_ = &mut shutdown_receiver => {
return;
}
}
send_heartbeats(&peers).await;
check(&mut output_sender).await;
}
});
} else {
let following = following.as_ref().unwrap().clone();
let last_heartbeat = last_heartbeat.clone();
tokio::spawn(async move {
loop {
tokio::select! {
_ = sleep(Duration::from_millis(100)) => {}
_ = &mut shutdown_receiver => {
return;
}
}
check_heartbeat_received(&following, &last_heartbeat, &mut output_sender).await;
}
});
}
HeartbeatMonitor {
following,
peers,
last_heartbeat,
output_receiver,
_shutdown_sender: shutdown_sender
}
}
pub async fn recv(&mut self) -> Option<HeartbeatOutput> {
self.output_receiver.recv().await
}
pub async fn heartbeat_received(&self, from: String) {
self.last_heartbeat.lock().await.insert(from, Instant::now());
if let Some(following) = &self.following {
if let Some(sender) = self.peers.get(following) {
let sender = sender.clone();
let msg = vec![Tag::Heartbeat as u8];
tokio::spawn(async move {
tokio::select! {
_ = sender.send(msg) => {}
_ = sleep(Duration::from_millis(100)) => {
log::debug!("sending timed out");
}
}
});
}
}
}
}
async fn check_heartbeat_received(following: &String,
last_heartbeat: &Arc<Mutex<HashMap<String,Instant>>>,
output_sender: &mut mpsc::Sender<HeartbeatOutput>) {
if last_heartbeat.lock().await.get(following).unwrap().elapsed() > Duration::from_millis(250) {
log::debug!("heartbeat missed for {}", following);
if let Err(_) = output_sender.send(HeartbeatOutput::HeartbeatNotReceived(following.clone())).await {
log::trace!("could not send heartbeat output");
}
}
}
async fn check(_output_sender: &mut mpsc::Sender<HeartbeatOutput>) {
// TODO
}
async fn send_heartbeats(peers: &HashMap<String, message::Sender>) {
let msg = vec![Tag::Heartbeat as u8];
for (_, sender) in peers.iter() {
let msg = msg.clone();
let sender = sender.clone();
tokio::spawn(async move {
tokio::select! {
_ = sender.send(msg) => {}
_ = sleep(Duration::from_millis(100)) => {
log::debug!("sending timed out");
}
}
});
}
}
| 35.238095 | 108 | 0.513063 |
6116fea9d14310b05b97f76fca446c990812a493 | 1,233 | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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 crate::api_client::Client;
use crate::common::ui::{Status, UIWriter, UI};
use crate::error::{Error, Result};
use crate::{PRODUCT, VERSION};
pub fn start(ui: &mut UI, bldr_url: &str, origin: &str) -> Result<()> {
let api_client = Client::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::APIClient)?;
ui.status(Status::Determining, format!("channels for {}.", origin))?;
match api_client.list_channels(origin, false) {
Ok(channels) => {
println!("{}", channels.join("\n"));
Ok(())
}
Err(e) => Err(Error::APIClient(e)),
}
}
| 36.264706 | 94 | 0.673966 |
fb626a450f3e3945646668e7bb660ff58200d1df | 5,247 | use std::sync::MutexGuard;
use crate::{palette::ColorPalette, MEM};
pub fn reset(mutex_guard: Option<&mut MutexGuard<[u8; 0x8000]>>) {
let mut mutex;
let mg = match mutex_guard {
Some(mg) => mg,
None => {
mutex = MEM.lock().unwrap();
&mut mutex
}
};
reset_palette(Some(mg), false);
reset_palette(Some(mg), true);
}
pub fn reset_palette(mutex_guard: Option<&mut MutexGuard<[u8; 0x8000]>>, draw: bool) {
let mut mutex;
let mg = match mutex_guard {
Some(mg) => mg,
None => {
mutex = MEM.lock().unwrap();
&mut mutex
}
};
for col in 0..16 {
let offset;
if draw {
offset = (0x5f00 + col) as usize;
} else {
offset = (0x5f10 + col) as usize;
}
mg[offset] = col as u8
}
}
pub fn get_draw_palette(
mutex_guard: Option<&MutexGuard<[u8; 0x8000]>>,
col: ColorPalette,
) -> (ColorPalette, bool) {
let mutex;
let mg = match mutex_guard {
Some(mg) => mg,
None => {
mutex = MEM.lock().unwrap();
&mutex
}
};
let idx = (0x5f00 + i32::from(col)) as usize;
let val = mg[idx];
let transparent = ((val >> 4) & 0b1) != 0;
(ColorPalette::from((val & 0b1111) as i32), transparent)
}
pub fn set_draw_palette(
mutex_guard: Option<&mut MutexGuard<[u8; 0x8000]>>,
col: ColorPalette,
set_col: Option<ColorPalette>,
set_transparent: Option<bool>,
) {
let mut mutex;
let mg = match mutex_guard {
Some(mg) => mg,
None => {
mutex = MEM.lock().unwrap();
&mut mutex
}
};
let idx = (0x5f00 + i32::from(col)) as usize;
let mut val = mg[idx];
if let Some(color) = set_col {
val = (val & 0b1_0000) | i32::from(color) as u8;
}
if let Some(transparent) = set_transparent {
val = (match transparent {
false => 0,
true => 1,
} << 4)
| (val & 0b1111);
}
mg[idx] = val;
}
pub fn get_screen_palette(
mutex_guard: Option<&MutexGuard<[u8; 0x8000]>>,
col: ColorPalette,
) -> ColorPalette {
let mutex;
let mg = match mutex_guard {
Some(mg) => mg,
None => {
mutex = MEM.lock().unwrap();
&mutex
}
};
let idx = (0x5f10 + i32::from(col)) as usize;
let val = mg[idx];
ColorPalette::from((val & 0b1111) as i32)
}
pub fn set_screen_palette(
mutex_guard: Option<&mut MutexGuard<[u8; 0x8000]>>,
col: ColorPalette,
set_col: ColorPalette,
) {
let mut mutex;
let mg = match mutex_guard {
Some(mg) => mg,
None => {
mutex = MEM.lock().unwrap();
&mut mutex
}
};
let idx = (0x5f10 + i32::from(col)) as usize;
mg[idx] = i32::from(set_col) as u8;
}
pub fn get_pen_color(mutex_guard: Option<&MutexGuard<[u8; 0x8000]>>) -> ColorPalette {
let mutex;
let mg = match mutex_guard {
Some(mg) => mg,
None => {
mutex = MEM.lock().unwrap();
&mutex
}
};
ColorPalette::from((mg[0x5f25] & 0b1111) as i32)
}
pub fn set_pen_color(mutex_guard: Option<&mut MutexGuard<[u8; 0x8000]>>, col: ColorPalette) {
let mut mutex;
let mg = match mutex_guard {
Some(mg) => mg,
None => {
mutex = MEM.lock().unwrap();
&mut mutex
}
};
let idx = 0x5f25;
let old_val = mg[idx];
mg[idx] = (old_val & 0b1111_0000) | i32::from(col) as u8;
}
pub fn get_print_cursor(mutex_guard: Option<&MutexGuard<[u8; 0x8000]>>) -> (u8, u8) {
let mutex;
let mg = match mutex_guard {
Some(mg) => mg,
None => {
mutex = MEM.lock().unwrap();
&mutex
}
};
let x = mg[0x5f26];
let y = mg[0x5f27];
(x, y)
}
pub fn set_print_cursor(
mutex_guard: Option<&mut MutexGuard<[u8; 0x8000]>>,
x: Option<u8>,
y: Option<u8>,
) {
let mut mutex;
let mg = match mutex_guard {
Some(mg) => mg,
None => {
mutex = MEM.lock().unwrap();
&mut mutex
}
};
if let Some(x) = x {
mg[0x5f26] = x;
}
if let Some(y) = y {
mg[0x5f27] = y;
}
}
pub fn get_camera_offset(mutex_guard: Option<&MutexGuard<[u8; 0x8000]>>) -> (i32, i32) {
let mutex;
let mg = match mutex_guard {
Some(mg) => mg,
None => {
mutex = MEM.lock().unwrap();
&mutex
}
};
let x: u16 = ((mg[0x5f29] as u16) << 8) | mg[0x5f28] as u16;
let y: u16 = ((mg[0x5f2b] as u16) << 8) | mg[0x5f2a] as u16;
(x as i32, y as i32)
}
pub fn set_camera_offset(
mutex_guard: Option<&mut MutexGuard<[u8; 0x8000]>>,
x: Option<i32>,
y: Option<i32>,
) {
let mut mutex;
let mg = match mutex_guard {
Some(mg) => mg,
None => {
mutex = MEM.lock().unwrap();
&mut mutex
}
};
if let Some(x) = x {
mg[0x5f28] = x as u8;
mg[0x5f29] = (x >> 8) as u8;
}
if let Some(y) = y {
mg[0x5f2a] = y as u8;
mg[0x5f2b] = (y >> 8) as u8;
}
}
| 22.32766 | 93 | 0.502763 |
718d63a58381f8533e0ed3e40aa87727f8b81655 | 50,332 | #[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::F3R2 {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct FB0R {
bits: bool,
}
impl FB0R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB1R {
bits: bool,
}
impl FB1R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB2R {
bits: bool,
}
impl FB2R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB3R {
bits: bool,
}
impl FB3R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB4R {
bits: bool,
}
impl FB4R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB5R {
bits: bool,
}
impl FB5R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB6R {
bits: bool,
}
impl FB6R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB7R {
bits: bool,
}
impl FB7R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB8R {
bits: bool,
}
impl FB8R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB9R {
bits: bool,
}
impl FB9R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB10R {
bits: bool,
}
impl FB10R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB11R {
bits: bool,
}
impl FB11R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB12R {
bits: bool,
}
impl FB12R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB13R {
bits: bool,
}
impl FB13R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB14R {
bits: bool,
}
impl FB14R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB15R {
bits: bool,
}
impl FB15R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB16R {
bits: bool,
}
impl FB16R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB17R {
bits: bool,
}
impl FB17R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB18R {
bits: bool,
}
impl FB18R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB19R {
bits: bool,
}
impl FB19R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB20R {
bits: bool,
}
impl FB20R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB21R {
bits: bool,
}
impl FB21R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB22R {
bits: bool,
}
impl FB22R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB23R {
bits: bool,
}
impl FB23R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB24R {
bits: bool,
}
impl FB24R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB25R {
bits: bool,
}
impl FB25R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB26R {
bits: bool,
}
impl FB26R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB27R {
bits: bool,
}
impl FB27R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB28R {
bits: bool,
}
impl FB28R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB29R {
bits: bool,
}
impl FB29R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB30R {
bits: bool,
}
impl FB30R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct FB31R {
bits: bool,
}
impl FB31R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Proxy"]
pub struct _FB0W<'a> {
w: &'a mut W,
}
impl<'a> _FB0W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB1W<'a> {
w: &'a mut W,
}
impl<'a> _FB1W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB2W<'a> {
w: &'a mut W,
}
impl<'a> _FB2W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB3W<'a> {
w: &'a mut W,
}
impl<'a> _FB3W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB4W<'a> {
w: &'a mut W,
}
impl<'a> _FB4W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB5W<'a> {
w: &'a mut W,
}
impl<'a> _FB5W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB6W<'a> {
w: &'a mut W,
}
impl<'a> _FB6W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB7W<'a> {
w: &'a mut W,
}
impl<'a> _FB7W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB8W<'a> {
w: &'a mut W,
}
impl<'a> _FB8W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 8;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB9W<'a> {
w: &'a mut W,
}
impl<'a> _FB9W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 9;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB10W<'a> {
w: &'a mut W,
}
impl<'a> _FB10W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 10;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB11W<'a> {
w: &'a mut W,
}
impl<'a> _FB11W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 11;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB12W<'a> {
w: &'a mut W,
}
impl<'a> _FB12W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB13W<'a> {
w: &'a mut W,
}
impl<'a> _FB13W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 13;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB14W<'a> {
w: &'a mut W,
}
impl<'a> _FB14W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 14;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB15W<'a> {
w: &'a mut W,
}
impl<'a> _FB15W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 15;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB16W<'a> {
w: &'a mut W,
}
impl<'a> _FB16W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 16;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB17W<'a> {
w: &'a mut W,
}
impl<'a> _FB17W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 17;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB18W<'a> {
w: &'a mut W,
}
impl<'a> _FB18W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 18;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB19W<'a> {
w: &'a mut W,
}
impl<'a> _FB19W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 19;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB20W<'a> {
w: &'a mut W,
}
impl<'a> _FB20W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 20;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB21W<'a> {
w: &'a mut W,
}
impl<'a> _FB21W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 21;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB22W<'a> {
w: &'a mut W,
}
impl<'a> _FB22W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 22;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB23W<'a> {
w: &'a mut W,
}
impl<'a> _FB23W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 23;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB24W<'a> {
w: &'a mut W,
}
impl<'a> _FB24W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 24;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB25W<'a> {
w: &'a mut W,
}
impl<'a> _FB25W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 25;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB26W<'a> {
w: &'a mut W,
}
impl<'a> _FB26W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 26;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB27W<'a> {
w: &'a mut W,
}
impl<'a> _FB27W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 27;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB28W<'a> {
w: &'a mut W,
}
impl<'a> _FB28W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 28;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB29W<'a> {
w: &'a mut W,
}
impl<'a> _FB29W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 29;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB30W<'a> {
w: &'a mut W,
}
impl<'a> _FB30W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 30;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FB31W<'a> {
w: &'a mut W,
}
impl<'a> _FB31W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 31;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Filter bits"]
#[inline]
pub fn fb0(&self) -> FB0R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB0R { bits }
}
#[doc = "Bit 1 - Filter bits"]
#[inline]
pub fn fb1(&self) -> FB1R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB1R { bits }
}
#[doc = "Bit 2 - Filter bits"]
#[inline]
pub fn fb2(&self) -> FB2R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB2R { bits }
}
#[doc = "Bit 3 - Filter bits"]
#[inline]
pub fn fb3(&self) -> FB3R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB3R { bits }
}
#[doc = "Bit 4 - Filter bits"]
#[inline]
pub fn fb4(&self) -> FB4R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB4R { bits }
}
#[doc = "Bit 5 - Filter bits"]
#[inline]
pub fn fb5(&self) -> FB5R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB5R { bits }
}
#[doc = "Bit 6 - Filter bits"]
#[inline]
pub fn fb6(&self) -> FB6R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB6R { bits }
}
#[doc = "Bit 7 - Filter bits"]
#[inline]
pub fn fb7(&self) -> FB7R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB7R { bits }
}
#[doc = "Bit 8 - Filter bits"]
#[inline]
pub fn fb8(&self) -> FB8R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB8R { bits }
}
#[doc = "Bit 9 - Filter bits"]
#[inline]
pub fn fb9(&self) -> FB9R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB9R { bits }
}
#[doc = "Bit 10 - Filter bits"]
#[inline]
pub fn fb10(&self) -> FB10R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB10R { bits }
}
#[doc = "Bit 11 - Filter bits"]
#[inline]
pub fn fb11(&self) -> FB11R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB11R { bits }
}
#[doc = "Bit 12 - Filter bits"]
#[inline]
pub fn fb12(&self) -> FB12R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB12R { bits }
}
#[doc = "Bit 13 - Filter bits"]
#[inline]
pub fn fb13(&self) -> FB13R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 13;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB13R { bits }
}
#[doc = "Bit 14 - Filter bits"]
#[inline]
pub fn fb14(&self) -> FB14R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 14;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB14R { bits }
}
#[doc = "Bit 15 - Filter bits"]
#[inline]
pub fn fb15(&self) -> FB15R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 15;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB15R { bits }
}
#[doc = "Bit 16 - Filter bits"]
#[inline]
pub fn fb16(&self) -> FB16R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 16;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB16R { bits }
}
#[doc = "Bit 17 - Filter bits"]
#[inline]
pub fn fb17(&self) -> FB17R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 17;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB17R { bits }
}
#[doc = "Bit 18 - Filter bits"]
#[inline]
pub fn fb18(&self) -> FB18R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 18;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB18R { bits }
}
#[doc = "Bit 19 - Filter bits"]
#[inline]
pub fn fb19(&self) -> FB19R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 19;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB19R { bits }
}
#[doc = "Bit 20 - Filter bits"]
#[inline]
pub fn fb20(&self) -> FB20R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 20;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB20R { bits }
}
#[doc = "Bit 21 - Filter bits"]
#[inline]
pub fn fb21(&self) -> FB21R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 21;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB21R { bits }
}
#[doc = "Bit 22 - Filter bits"]
#[inline]
pub fn fb22(&self) -> FB22R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 22;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB22R { bits }
}
#[doc = "Bit 23 - Filter bits"]
#[inline]
pub fn fb23(&self) -> FB23R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 23;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB23R { bits }
}
#[doc = "Bit 24 - Filter bits"]
#[inline]
pub fn fb24(&self) -> FB24R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 24;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB24R { bits }
}
#[doc = "Bit 25 - Filter bits"]
#[inline]
pub fn fb25(&self) -> FB25R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 25;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB25R { bits }
}
#[doc = "Bit 26 - Filter bits"]
#[inline]
pub fn fb26(&self) -> FB26R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 26;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB26R { bits }
}
#[doc = "Bit 27 - Filter bits"]
#[inline]
pub fn fb27(&self) -> FB27R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 27;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB27R { bits }
}
#[doc = "Bit 28 - Filter bits"]
#[inline]
pub fn fb28(&self) -> FB28R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 28;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB28R { bits }
}
#[doc = "Bit 29 - Filter bits"]
#[inline]
pub fn fb29(&self) -> FB29R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 29;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB29R { bits }
}
#[doc = "Bit 30 - Filter bits"]
#[inline]
pub fn fb30(&self) -> FB30R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 30;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB30R { bits }
}
#[doc = "Bit 31 - Filter bits"]
#[inline]
pub fn fb31(&self) -> FB31R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 31;
((self.bits >> OFFSET) & MASK as u32) != 0
};
FB31R { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Filter bits"]
#[inline]
pub fn fb0(&mut self) -> _FB0W {
_FB0W { w: self }
}
#[doc = "Bit 1 - Filter bits"]
#[inline]
pub fn fb1(&mut self) -> _FB1W {
_FB1W { w: self }
}
#[doc = "Bit 2 - Filter bits"]
#[inline]
pub fn fb2(&mut self) -> _FB2W {
_FB2W { w: self }
}
#[doc = "Bit 3 - Filter bits"]
#[inline]
pub fn fb3(&mut self) -> _FB3W {
_FB3W { w: self }
}
#[doc = "Bit 4 - Filter bits"]
#[inline]
pub fn fb4(&mut self) -> _FB4W {
_FB4W { w: self }
}
#[doc = "Bit 5 - Filter bits"]
#[inline]
pub fn fb5(&mut self) -> _FB5W {
_FB5W { w: self }
}
#[doc = "Bit 6 - Filter bits"]
#[inline]
pub fn fb6(&mut self) -> _FB6W {
_FB6W { w: self }
}
#[doc = "Bit 7 - Filter bits"]
#[inline]
pub fn fb7(&mut self) -> _FB7W {
_FB7W { w: self }
}
#[doc = "Bit 8 - Filter bits"]
#[inline]
pub fn fb8(&mut self) -> _FB8W {
_FB8W { w: self }
}
#[doc = "Bit 9 - Filter bits"]
#[inline]
pub fn fb9(&mut self) -> _FB9W {
_FB9W { w: self }
}
#[doc = "Bit 10 - Filter bits"]
#[inline]
pub fn fb10(&mut self) -> _FB10W {
_FB10W { w: self }
}
#[doc = "Bit 11 - Filter bits"]
#[inline]
pub fn fb11(&mut self) -> _FB11W {
_FB11W { w: self }
}
#[doc = "Bit 12 - Filter bits"]
#[inline]
pub fn fb12(&mut self) -> _FB12W {
_FB12W { w: self }
}
#[doc = "Bit 13 - Filter bits"]
#[inline]
pub fn fb13(&mut self) -> _FB13W {
_FB13W { w: self }
}
#[doc = "Bit 14 - Filter bits"]
#[inline]
pub fn fb14(&mut self) -> _FB14W {
_FB14W { w: self }
}
#[doc = "Bit 15 - Filter bits"]
#[inline]
pub fn fb15(&mut self) -> _FB15W {
_FB15W { w: self }
}
#[doc = "Bit 16 - Filter bits"]
#[inline]
pub fn fb16(&mut self) -> _FB16W {
_FB16W { w: self }
}
#[doc = "Bit 17 - Filter bits"]
#[inline]
pub fn fb17(&mut self) -> _FB17W {
_FB17W { w: self }
}
#[doc = "Bit 18 - Filter bits"]
#[inline]
pub fn fb18(&mut self) -> _FB18W {
_FB18W { w: self }
}
#[doc = "Bit 19 - Filter bits"]
#[inline]
pub fn fb19(&mut self) -> _FB19W {
_FB19W { w: self }
}
#[doc = "Bit 20 - Filter bits"]
#[inline]
pub fn fb20(&mut self) -> _FB20W {
_FB20W { w: self }
}
#[doc = "Bit 21 - Filter bits"]
#[inline]
pub fn fb21(&mut self) -> _FB21W {
_FB21W { w: self }
}
#[doc = "Bit 22 - Filter bits"]
#[inline]
pub fn fb22(&mut self) -> _FB22W {
_FB22W { w: self }
}
#[doc = "Bit 23 - Filter bits"]
#[inline]
pub fn fb23(&mut self) -> _FB23W {
_FB23W { w: self }
}
#[doc = "Bit 24 - Filter bits"]
#[inline]
pub fn fb24(&mut self) -> _FB24W {
_FB24W { w: self }
}
#[doc = "Bit 25 - Filter bits"]
#[inline]
pub fn fb25(&mut self) -> _FB25W {
_FB25W { w: self }
}
#[doc = "Bit 26 - Filter bits"]
#[inline]
pub fn fb26(&mut self) -> _FB26W {
_FB26W { w: self }
}
#[doc = "Bit 27 - Filter bits"]
#[inline]
pub fn fb27(&mut self) -> _FB27W {
_FB27W { w: self }
}
#[doc = "Bit 28 - Filter bits"]
#[inline]
pub fn fb28(&mut self) -> _FB28W {
_FB28W { w: self }
}
#[doc = "Bit 29 - Filter bits"]
#[inline]
pub fn fb29(&mut self) -> _FB29W {
_FB29W { w: self }
}
#[doc = "Bit 30 - Filter bits"]
#[inline]
pub fn fb30(&mut self) -> _FB30W {
_FB30W { w: self }
}
#[doc = "Bit 31 - Filter bits"]
#[inline]
pub fn fb31(&mut self) -> _FB31W {
_FB31W { w: self }
}
}
| 25.771633 | 60 | 0.464456 |
3996841eebb61793b412825742c8b678744491d9 | 8,325 | use crate::utils::{
build_compact_block, build_compact_block_with_prefilled, clear_messages, wait_until,
};
use crate::{Net, Node, Spec, TestProtocol};
use ckb_chain_spec::ChainSpec;
use ckb_core::header::HeaderBuilder;
use ckb_network::PeerIndex;
use ckb_protocol::{get_root, RelayMessage, RelayPayload, SyncMessage, SyncPayload};
use ckb_sync::NetworkProtocol;
use log::info;
use numext_fixed_hash::{h256, H256};
use std::time::Duration;
pub struct CompactBlockBasic;
impl CompactBlockBasic {
// Case: Sent to node0 a parent-unknown empty block, node0 should be unable to reconstruct
// it and send us back a `GetHeaders` message
pub fn test_empty_parent_unknown_compact_block(
&self,
net: &Net,
node: &Node,
peer_id: PeerIndex,
) {
node.generate_block();
let _ = net.receive();
let parent_unknown_block = node
.new_block_builder(None, None, None)
.header_builder(HeaderBuilder::default().parent_hash(h256!("0x123456")))
.build();
let tip_block = node.get_tip_block();
net.send(
NetworkProtocol::RELAY.into(),
peer_id,
build_compact_block(&parent_unknown_block),
);
let ret = wait_until(10, move || node.get_tip_block() != tip_block);
assert!(!ret, "Node0 should reconstruct empty block failed");
let (_, _, data) = net.receive();
let message = get_root::<SyncMessage>(&data).unwrap();
assert_eq!(
message.payload_type(),
SyncPayload::GetHeaders,
"Node0 should send back GetHeaders message for unknown parent header"
);
}
// Case: Send to node0 a parent-known empty block, node0 should be able to reconstruct it
pub fn test_empty_compact_block(&self, net: &Net, node: &Node, peer_id: PeerIndex) {
node.generate_block();
let _ = net.receive();
let new_empty_block = node.new_block(None, None, None);
net.send(
NetworkProtocol::RELAY.into(),
peer_id,
build_compact_block(&new_empty_block),
);
let ret = wait_until(10, move || node.get_tip_block() == new_empty_block);
assert!(ret, "Node0 should reconstruct empty block successfully");
clear_messages(net);
}
// Case: Send to node0 a block with all transactions prefilled, node0 should be able to reconstruct it
pub fn test_all_prefilled_compact_block(&self, net: &Net, node: &Node, peer_id: PeerIndex) {
node.generate_block();
let _ = net.receive();
// Proposal a tx, and grow up into proposal window
let new_tx = node.new_transaction(node.get_tip_block().transactions()[0].hash().clone());
node.submit_block(
&node
.new_block_builder(None, None, None)
.proposal(new_tx.proposal_short_id())
.build(),
);
node.generate_blocks(3);
// Relay a block contains `new_tx` as committed
let new_block = node
.new_block_builder(None, None, None)
.transaction(new_tx)
.build();
net.send(
NetworkProtocol::RELAY.into(),
peer_id,
build_compact_block_with_prefilled(&new_block, vec![1]),
);
let ret = wait_until(10, move || node.get_tip_block() == new_block);
assert!(
ret,
"Node0 should reconstruct all-prefilled block successfully"
);
clear_messages(net);
}
// Case: Send to node0 a block which missing a tx, node0 should send `GetBlockTransactions`
// back for requesting these missing txs
pub fn test_missing_txs_compact_block(&self, net: &Net, node: &Node, peer_id: PeerIndex) {
// Proposal a tx, and grow up into proposal window
let new_tx = node.new_transaction(node.get_tip_block().transactions()[0].hash().clone());
node.submit_block(
&node
.new_block_builder(None, None, None)
.proposal(new_tx.proposal_short_id())
.build(),
);
node.generate_blocks(3);
// Net consume and ignore the recent blocks
(0..4).for_each(|_| {
net.receive();
});
// Relay a block contains `new_tx` as committed, but not include in prefilled
let new_block = node
.new_block_builder(None, None, None)
.transaction(new_tx)
.build();
net.send(
NetworkProtocol::RELAY.into(),
peer_id,
build_compact_block(&new_block),
);
let ret = wait_until(10, move || node.get_tip_block() == new_block);
assert!(!ret, "Node0 should be unable to reconstruct the block");
let (_, _, data) = net.receive();
let message = get_root::<RelayMessage>(&data).unwrap();
assert_eq!(
message.payload_type(),
RelayPayload::GetBlockTransactions,
"Node0 should send GetBlockTransactions message for missing transactions",
);
clear_messages(net);
}
pub fn test_lose_get_block_transactions(
&self,
net: &Net,
node0: &Node,
node1: &Node,
peer_id0: PeerIndex,
) {
node0.generate_block();
let new_tx = node0.new_transaction(node0.get_tip_block().transactions()[0].hash().clone());
node0.submit_block(
&node0
.new_block_builder(None, None, None)
.proposal(new_tx.proposal_short_id())
.build(),
);
// Proposal a tx, and grow up into proposal window
node0.generate_blocks(6);
// Make node0 and node1 reach the same height
node1.generate_block();
node0.connect(node1);
node0.waiting_for_sync(node1, node0.get_tip_block().header().number());
// Net consume and ignore the recent blocks
clear_messages(net);
// Construct a new block contains one transaction
let block = node0
.new_block_builder(None, None, None)
.transaction(new_tx)
.build();
// Net send the compact block to node0, but dose not send the corresponding missing
// block transactions. It will make node0 unable to reconstruct the complete block
net.send(
NetworkProtocol::RELAY.into(),
peer_id0,
build_compact_block(&block),
);
let (_, _, data) = net
.receive_timeout(Duration::from_secs(10))
.expect("receive GetBlockTransactions");
let message = get_root::<RelayMessage>(&data).unwrap();
assert_eq!(
message.payload_type(),
RelayPayload::GetBlockTransactions,
"Node0 should send GetBlockTransactions message for missing transactions",
);
// Submit the new block to node1. We expect node1 will relay the new block to node0.
node1.submit_block(&block);
node1.waiting_for_sync(node0, node1.get_tip_block().header().number());
}
}
impl Spec for CompactBlockBasic {
fn run(&self, net: Net) {
info!("Running CompactBlockBasic");
let peer_ids = net
.nodes
.iter()
.map(|node| {
net.connect(node);
let (peer_id, _, _) = net.receive();
peer_id
})
.collect::<Vec<PeerIndex>>();
clear_messages(&net);
self.test_empty_compact_block(&net, &net.nodes[0], peer_ids[0]);
self.test_empty_parent_unknown_compact_block(&net, &net.nodes[0], peer_ids[0]);
self.test_all_prefilled_compact_block(&net, &net.nodes[0], peer_ids[0]);
self.test_missing_txs_compact_block(&net, &net.nodes[0], peer_ids[0]);
self.test_lose_get_block_transactions(&net, &net.nodes[0], &net.nodes[1], peer_ids[0]);
}
fn test_protocols(&self) -> Vec<TestProtocol> {
vec![TestProtocol::sync(), TestProtocol::relay()]
}
fn connect_all(&self) -> bool {
false
}
fn modify_chain_spec(&self) -> Box<dyn Fn(&mut ChainSpec) -> ()> {
Box::new(|mut spec_config| {
spec_config.params.cellbase_maturity = 5;
})
}
}
| 35.576923 | 106 | 0.597958 |
7a3a335ea6d9f8cf29c398f2210c2215a057284d | 20,234 | //! Fairings: callbacks at attach, launch, request, and response time.
//!
//! Fairings allow for structured interposition at various points in the
//! application lifetime. Fairings can be seen as a restricted form of
//! "middleware". A fairing is an arbitrary structure with methods representing
//! callbacks that Rocket will run at requested points in a program. You can use
//! fairings to rewrite or record information about requests and responses, or
//! to perform an action once a Rocket application has launched.
//!
//! To learn more about writing a fairing, see the [`Fairing`] trait
//! documentation. You can also use [`AdHoc`] to create a fairing on-the-fly
//! from a closure or function.
//!
//! ## Attaching
//!
//! You must inform Rocket about fairings that you wish to be active by calling
//! [`Rocket::attach()`] method on the application's [`Rocket`] instance and
//! passing in the appropriate [`Fairing`]. For instance, to attach fairings
//! named `req_fairing` and `res_fairing` to a new Rocket instance, you might
//! write:
//!
//! ```rust
//! # use rocket::fairing::AdHoc;
//! # let req_fairing = AdHoc::on_request("Request", |_, _| Box::pin(async move {}));
//! # let res_fairing = AdHoc::on_response("Response", |_, _| Box::pin(async move {}));
//! let rocket = rocket::ignite()
//! .attach(req_fairing)
//! .attach(res_fairing);
//! ```
//!
//! Once a fairing is attached, Rocket will execute it at the appropriate time,
//! which varies depending on the fairing implementation. See the [`Fairing`]
//! trait documentation for more information on the dispatching of fairing
//! methods.
//!
//! [`Fairing`]: crate::fairing::Fairing
//!
//! ## Ordering
//!
//! `Fairing`s are executed in the order in which they are attached: the first
//! attached fairing has its callbacks executed before all others. Because
//! fairing callbacks may not be commutative, the order in which fairings are
//! attached may be significant. Because of this, it is important to communicate
//! to the user every consequence of a fairing.
//!
//! Furthermore, a `Fairing` should take care to act locally so that the actions
//! of other `Fairings` are not jeopardized. For instance, unless it is made
//! abundantly clear, a fairing should not rewrite every request.
use crate::{Cargo, Rocket, Request, Response, Data};
mod fairings;
mod ad_hoc;
mod info_kind;
pub(crate) use self::fairings::Fairings;
pub use self::ad_hoc::AdHoc;
pub use self::info_kind::{Info, Kind};
// We might imagine that a request fairing returns an `Outcome`. If it returns
// `Success`, we don't do any routing and use that response directly. Same if it
// returns `Failure`. We only route if it returns `Forward`. I've chosen not to
// go this direction because I feel like request guards are the correct
// mechanism to use here. In other words, enabling this at the fairing level
// encourages implicit handling, a bad practice. Fairings can still, however,
// return a default `Response` if routing fails via a response fairing. For
// instance, to automatically handle preflight in CORS, a response fairing can
// check that the user didn't handle the `OPTIONS` request (404) and return an
// appropriate response. This allows the users to handle `OPTIONS` requests
// when they'd like but default to the fairing when they don't want to.
/// Trait implemented by fairings: Rocket's structured middleware.
///
/// # Considerations
///
/// Fairings are a large hammer that can easily be abused and misused. If you
/// are considering writing a `Fairing` implementation, first consider if it is
/// appropriate to do so. While middleware is often the best solution to some
/// problems in other frameworks, it is often a suboptimal solution in Rocket.
/// This is because Rocket provides richer mechanisms such as [request guards]
/// and [data guards] that can be used to accomplish the same objective in a
/// cleaner, more composable, and more robust manner.
///
/// As a general rule of thumb, only _globally applicable actions_ should be
/// implemented via fairings. For instance, you should _not_ use a fairing to
/// implement authentication or authorization (preferring to use a [request
/// guard] instead) _unless_ the authentication or authorization applies to the
/// entire application. On the other hand, you _should_ use a fairing to record
/// timing and/or usage statistics or to implement global security policies.
///
/// [request guard]: crate::request::FromRequest
/// [request guards]: crate::request::FromRequest
/// [data guards]: crate::data::FromTransformedData
///
/// ## Fairing Callbacks
///
/// There are four kinds of fairing callbacks: attach, launch, request, and
/// response. A fairing can request any combination of these callbacks through
/// the `kind` field of the `Info` structure returned from the `info` method.
/// Rocket will only invoke the callbacks set in the `kind` field.
///
/// The four callback kinds are as follows:
///
/// * **Attach (`on_attach`)**
///
/// An attach callback, represented by the [`Fairing::on_attach()`] method,
/// is called when a fairing is first attached via [`Rocket::attach()`]
/// method. The state of the `Rocket` instance is, at this point, not
/// finalized, as the user may still add additional information to the
/// `Rocket` instance. As a result, it is unwise to depend on the state of
/// the `Rocket` instance.
///
/// An attach callback can arbitrarily modify the `Rocket` instance being
/// constructed. It returns `Ok` if it would like launching to proceed
/// nominally and `Err` otherwise. If an attach callback returns `Err`,
/// launch will be aborted. All attach callbacks are executed on `launch`,
/// even if one or more signal a failure.
///
/// * **Launch (`on_launch`)**
///
/// A launch callback, represented by the [`Fairing::on_launch()`] method,
/// is called immediately before the Rocket application has launched. At
/// this point, Rocket has opened a socket for listening but has not yet
/// begun accepting connections. A launch callback can inspect the `Rocket`
/// instance being launched.
///
/// * **Request (`on_request`)**
///
/// A request callback, represented by the [`Fairing::on_request()`] method,
/// is called just after a request is received, immediately after
/// pre-processing the request with method changes due to `_method` form
/// fields. At this point, Rocket has parsed the incoming HTTP request into
/// [`Request`] and [`Data`] structures but has not routed the request. A
/// request callback can modify the request at will and [`Data::peek()`]
/// into the incoming data. It may not, however, abort or respond directly
/// to the request; these issues are better handled via [request guards] or
/// via response callbacks. Any modifications to a request are persisted and
/// can potentially alter how a request is routed.
///
/// * **Response (`on_response`)**
///
/// A response callback, represented by the [`Fairing::on_response()`]
/// method, is called when a response is ready to be sent to the client. At
/// this point, Rocket has completed all routing, including to error
/// catchers, and has generated the would-be final response. A response
/// callback can modify the response at will. For example, a response
/// callback can provide a default response when the user fails to handle
/// the request by checking for 404 responses. Note that a given `Request`
/// may have changed between `on_request` and `on_response` invocations.
/// Apart from any change made by other fairings, Rocket sets the method for
/// `HEAD` requests to `GET` if there is no matching `HEAD` handler for that
/// request. Additionally, Rocket will automatically strip the body for
/// `HEAD` requests _after_ response fairings have run.
///
/// # Implementing
///
/// A `Fairing` implementation has one required method: [`info`]. A `Fairing`
/// can also implement any of the available callbacks: `on_attach`, `on_launch`,
/// `on_request`, and `on_response`. A `Fairing` _must_ set the appropriate
/// callback kind in the `kind` field of the returned `Info` structure from
/// [`info`] for a callback to actually be called by Rocket.
///
/// ## Fairing `Info`
///
/// Every `Fairing` must implement the [`info`] method, which returns an
/// [`Info`] structure. This structure is used by Rocket to:
///
/// 1. Assign a name to the `Fairing`.
///
/// This is the `name` field, which can be any arbitrary string. Name your
/// fairing something illustrative. The name will be logged during the
/// application's launch procedures.
///
/// 2. Determine which callbacks to actually issue on the `Fairing`.
///
/// This is the `kind` field of type [`Kind`]. This field is a bitset that
/// represents the kinds of callbacks the fairing wishes to receive. Rocket
/// will only invoke the callbacks that are flagged in this set. `Kind`
/// structures can be `or`d together to represent any combination of kinds
/// of callbacks. For instance, to request launch and response callbacks,
/// return a `kind` field with the value `Kind::Launch | Kind::Response`.
///
/// [`info`]: Fairing::info()
///
/// ## Restrictions
///
/// A `Fairing` must be [`Send`] + [`Sync`] + `'static`. This means that the
/// fairing must be sendable across thread boundaries (`Send`), thread-safe
/// (`Sync`), and have only `'static` references, if any (`'static`). Note that
/// these bounds _do not_ prohibit a `Fairing` from holding state: the state
/// need simply be thread-safe and statically available or heap allocated.
///
/// ## Async Trait
///
/// [`Fairing`] is an _async_ trait. Implementations of `Fairing` must be
/// decorated with an attribute of `#[rocket::async_trait]`:
///
/// ```rust
/// use rocket::{Cargo, Rocket, Request, Data, Response};
/// use rocket::fairing::{Fairing, Info, Kind};
///
/// # struct MyType;
/// #[rocket::async_trait]
/// impl Fairing for MyType {
/// fn info(&self) -> Info {
/// /* ... */
/// # unimplemented!()
/// }
///
/// async fn on_attach(&self, rocket: Rocket) -> Result<Rocket, Rocket> {
/// /* ... */
/// # unimplemented!()
/// }
///
/// fn on_launch(&self, cargo: &Cargo) {
/// /* ... */
/// # unimplemented!()
/// }
///
/// async fn on_request(&self, req: &mut Request<'_>, data: &Data) {
/// /* ... */
/// # unimplemented!()
/// }
///
/// async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {
/// /* ... */
/// # unimplemented!()
/// }
/// }
/// ```
///
/// ## Example
///
/// Imagine that we want to record the number of `GET` and `POST` requests that
/// our application has received. While we could do this with [request guards]
/// and [managed state](crate::request::State), it would require us to annotate every
/// `GET` and `POST` request with custom types, polluting handler signatures.
/// Instead, we can create a simple fairing that acts globally.
///
/// The `Counter` fairing below records the number of all `GET` and `POST`
/// requests received. It makes these counts available at a special `'/counts'`
/// path.
///
/// ```rust
/// use std::future::Future;
/// use std::io::Cursor;
/// use std::pin::Pin;
/// use std::sync::atomic::{AtomicUsize, Ordering};
///
/// use rocket::{Request, Data, Response};
/// use rocket::fairing::{Fairing, Info, Kind};
/// use rocket::http::{Method, ContentType, Status};
///
/// #[derive(Default)]
/// struct Counter {
/// get: AtomicUsize,
/// post: AtomicUsize,
/// }
///
/// #[rocket::async_trait]
/// impl Fairing for Counter {
/// fn info(&self) -> Info {
/// Info {
/// name: "GET/POST Counter",
/// kind: Kind::Request | Kind::Response
/// }
/// }
///
/// async fn on_request(&self, req: &mut Request<'_>, _: &Data) {
/// if req.method() == Method::Get {
/// self.get.fetch_add(1, Ordering::Relaxed);
/// } else if req.method() == Method::Post {
/// self.post.fetch_add(1, Ordering::Relaxed);
/// }
/// }
///
/// async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {
/// // Don't change a successful user's response, ever.
/// if res.status() != Status::NotFound {
/// return
/// }
///
/// if req.method() == Method::Get && req.uri().path() == "/counts" {
/// let get_count = self.get.load(Ordering::Relaxed);
/// let post_count = self.post.load(Ordering::Relaxed);
///
/// let body = format!("Get: {}\nPost: {}", get_count, post_count);
/// res.set_status(Status::Ok);
/// res.set_header(ContentType::Plain);
/// res.set_sized_body(body.len(), Cursor::new(body));
/// }
/// }
/// }
/// ```
///
/// ## Request-Local State
///
/// Fairings can use [request-local state] to persist or carry data between
/// requests and responses, or to pass data to a request guard.
///
/// As an example, the following fairing uses request-local state to time
/// requests, setting an `X-Response-Time` header on all responses with the
/// elapsed time. It also exposes the start time of a request via a `StartTime`
/// request guard.
///
/// ```rust
/// # use std::future::Future;
/// # use std::pin::Pin;
/// # use std::time::{Duration, SystemTime};
/// # use rocket::{Request, Data, Response};
/// # use rocket::fairing::{Fairing, Info, Kind};
/// # use rocket::http::Status;
/// # use rocket::request::{self, FromRequest};
/// #
/// /// Fairing for timing requests.
/// pub struct RequestTimer;
///
/// /// Value stored in request-local state.
/// #[derive(Copy, Clone)]
/// struct TimerStart(Option<SystemTime>);
///
/// #[rocket::async_trait]
/// impl Fairing for RequestTimer {
/// fn info(&self) -> Info {
/// Info {
/// name: "Request Timer",
/// kind: Kind::Request | Kind::Response
/// }
/// }
///
/// /// Stores the start time of the request in request-local state.
/// async fn on_request(&self, request: &mut Request<'_>, _: &Data) {
/// // Store a `TimerStart` instead of directly storing a `SystemTime`
/// // to ensure that this usage doesn't conflict with anything else
/// // that might store a `SystemTime` in request-local cache.
/// request.local_cache(|| TimerStart(Some(SystemTime::now())));
/// }
///
/// /// Adds a header to the response indicating how long the server took to
/// /// process the request.
/// async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {
/// let start_time = req.local_cache(|| TimerStart(None));
/// if let Some(Ok(duration)) = start_time.0.map(|st| st.elapsed()) {
/// let ms = duration.as_secs() * 1000 + duration.subsec_millis() as u64;
/// res.set_raw_header("X-Response-Time", format!("{} ms", ms));
/// }
/// }
/// }
///
/// /// Request guard used to retrieve the start time of a request.
/// #[derive(Copy, Clone)]
/// pub struct StartTime(pub SystemTime);
///
/// // Allows a route to access the time a request was initiated.
/// #[rocket::async_trait]
/// impl<'a, 'r> FromRequest<'a, 'r> for StartTime {
/// type Error = ();
///
/// async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, ()> {
/// match *request.local_cache(|| TimerStart(None)) {
/// TimerStart(Some(time)) => request::Outcome::Success(StartTime(time)),
/// TimerStart(None) => request::Outcome::Failure((Status::InternalServerError, ())),
/// }
/// }
/// }
/// ```
///
/// [request-local state]: https://rocket.rs/v0.5/guide/state/#request-local-state
#[crate::async_trait]
pub trait Fairing: Send + Sync + 'static {
/// Returns an [`Info`] structure containing the `name` and [`Kind`] of this
/// fairing. The `name` can be any arbitrary string. `Kind` must be an `or`d
/// set of `Kind` variants.
///
/// This is the only required method of a `Fairing`. All other methods have
/// no-op default implementations.
///
/// Rocket will only dispatch callbacks to this fairing for the kinds in the
/// `kind` field of the returned `Info` structure. For instance, if
/// `Kind::Launch | Kind::Request` is used, then Rocket will only call the
/// `on_launch` and `on_request` methods of the fairing. Similarly, if
/// `Kind::Response` is used, Rocket will only call the `on_response` method
/// of this fairing.
///
/// # Example
///
/// An `info` implementation for `MyFairing`: a fairing named "My Custom
/// Fairing" that is both a launch and response fairing.
///
/// ```rust
/// use rocket::fairing::{Fairing, Info, Kind};
///
/// struct MyFairing;
///
/// impl Fairing for MyFairing {
/// fn info(&self) -> Info {
/// Info {
/// name: "My Custom Fairing",
/// kind: Kind::Launch | Kind::Response
/// }
/// }
/// }
/// ```
fn info(&self) -> Info;
/// The attach callback. Returns `Ok` if launch should proceed and `Err` if
/// launch should be aborted.
///
/// This method is called when a fairing is attached if `Kind::Attach` is in
/// the `kind` field of the `Info` structure for this fairing. The `rocket`
/// parameter is the `Rocket` instance that is currently being built for
/// this application.
///
/// ## Default Implementation
///
/// The default implementation of this method simply returns `Ok(rocket)`.
async fn on_attach(&self, rocket: Rocket) -> Result<Rocket, Rocket> { Ok(rocket) }
/// The launch callback.
///
/// This method is called just prior to launching the application if
/// `Kind::Launch` is in the `kind` field of the `Info` structure for this
/// fairing. The `Cargo` parameter corresponds to the application that
/// will be launched.
///
/// ## Default Implementation
///
/// The default implementation of this method does nothing.
#[allow(unused_variables)]
fn on_launch(&self, cargo: &Cargo) {}
/// The request callback.
///
/// This method is called when a new request is received if `Kind::Request`
/// is in the `kind` field of the `Info` structure for this fairing. The
/// `&mut Request` parameter is the incoming request, and the `&Data`
/// parameter is the incoming data in the request.
///
/// ## Default Implementation
///
/// The default implementation of this method does nothing.
#[allow(unused_variables)]
async fn on_request(&self, req: &mut Request<'_>, data: &Data) {}
/// The response callback.
///
/// This method is called when a response is ready to be issued to a client
/// if `Kind::Response` is in the `kind` field of the `Info` structure for
/// this fairing. The `&Request` parameter is the request that was routed,
/// and the `&mut Response` parameter is the resulting response.
///
/// ## Default Implementation
///
/// The default implementation of this method does nothing.
#[allow(unused_variables)]
async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {}
}
#[crate::async_trait]
impl<T: Fairing> Fairing for std::sync::Arc<T> {
#[inline]
fn info(&self) -> Info {
(self as &T).info()
}
#[inline]
async fn on_attach(&self, rocket: Rocket) -> Result<Rocket, Rocket> {
(self as &T).on_attach(rocket).await
}
#[inline]
fn on_launch(&self, cargo: &Cargo) {
(self as &T).on_launch(cargo)
}
#[inline]
async fn on_request(&self, req: &mut Request<'_>, data: &Data) {
(self as &T).on_request(req, data).await;
}
#[inline]
async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {
(self as &T).on_response(req, res).await;
}
}
| 41.633745 | 97 | 0.638826 |
50c2c458c4bde5e885b98b69b55f51f353af1e1c | 6,217 | #![doc = include_str!("../docs/response.md")]
use crate::body::{Bytes, Full};
use http::{header, HeaderValue};
mod redirect;
pub mod sse;
#[doc(no_inline)]
#[cfg(feature = "json")]
pub use crate::Json;
#[doc(no_inline)]
#[cfg(feature = "headers")]
pub use crate::TypedHeader;
#[doc(no_inline)]
pub use crate::Extension;
#[doc(inline)]
pub use axum_core::response::{
AppendHeaders, ErrorResponse, IntoResponse, IntoResponseParts, Response, ResponseParts, Result,
};
#[doc(inline)]
pub use self::{redirect::Redirect, sse::Sse};
/// An HTML response.
///
/// Will automatically get `Content-Type: text/html`.
#[derive(Clone, Copy, Debug)]
pub struct Html<T>(pub T);
impl<T> IntoResponse for Html<T>
where
T: Into<Full<Bytes>>,
{
fn into_response(self) -> Response {
(
[(
header::CONTENT_TYPE,
HeaderValue::from_static(mime::TEXT_HTML_UTF_8.as_ref()),
)],
self.0.into(),
)
.into_response()
}
}
impl<T> From<T> for Html<T> {
fn from(inner: T) -> Self {
Self(inner)
}
}
#[cfg(test)]
mod tests {
use crate::extract::Extension;
use crate::{body::Body, routing::get, Router};
use axum_core::response::IntoResponse;
use http::HeaderMap;
use http::{StatusCode, Uri};
// just needs to compile
#[allow(dead_code)]
fn impl_trait_result_works() {
async fn impl_trait_ok() -> Result<impl IntoResponse, ()> {
Ok(())
}
async fn impl_trait_err() -> Result<(), impl IntoResponse> {
Err(())
}
async fn impl_trait_both(uri: Uri) -> Result<impl IntoResponse, impl IntoResponse> {
if uri.path() == "/" {
Ok(())
} else {
Err(())
}
}
async fn impl_trait(uri: Uri) -> impl IntoResponse {
if uri.path() == "/" {
Ok(())
} else {
Err(())
}
}
Router::<Body>::new()
.route("/", get(impl_trait_ok))
.route("/", get(impl_trait_err))
.route("/", get(impl_trait_both))
.route("/", get(impl_trait));
}
// just needs to compile
#[allow(dead_code)]
fn tuple_responses() {
async fn status() -> impl IntoResponse {
StatusCode::OK
}
async fn status_headermap() -> impl IntoResponse {
(StatusCode::OK, HeaderMap::new())
}
async fn status_header_array() -> impl IntoResponse {
(StatusCode::OK, [("content-type", "text/plain")])
}
async fn status_headermap_body() -> impl IntoResponse {
(StatusCode::OK, HeaderMap::new(), String::new())
}
async fn status_header_array_body() -> impl IntoResponse {
(
StatusCode::OK,
[("content-type", "text/plain")],
String::new(),
)
}
async fn status_headermap_impl_into_response() -> impl IntoResponse {
(StatusCode::OK, HeaderMap::new(), impl_into_response())
}
async fn status_header_array_impl_into_response() -> impl IntoResponse {
(
StatusCode::OK,
[("content-type", "text/plain")],
impl_into_response(),
)
}
fn impl_into_response() -> impl IntoResponse {}
async fn status_header_array_extension_body() -> impl IntoResponse {
(
StatusCode::OK,
[("content-type", "text/plain")],
Extension(1),
String::new(),
)
}
async fn status_header_array_extension_mixed_body() -> impl IntoResponse {
(
StatusCode::OK,
[("content-type", "text/plain")],
Extension(1),
HeaderMap::new(),
String::new(),
)
}
//
async fn headermap() -> impl IntoResponse {
HeaderMap::new()
}
async fn header_array() -> impl IntoResponse {
[("content-type", "text/plain")]
}
async fn headermap_body() -> impl IntoResponse {
(HeaderMap::new(), String::new())
}
async fn header_array_body() -> impl IntoResponse {
([("content-type", "text/plain")], String::new())
}
async fn headermap_impl_into_response() -> impl IntoResponse {
(HeaderMap::new(), impl_into_response())
}
async fn header_array_impl_into_response() -> impl IntoResponse {
([("content-type", "text/plain")], impl_into_response())
}
async fn header_array_extension_body() -> impl IntoResponse {
(
[("content-type", "text/plain")],
Extension(1),
String::new(),
)
}
async fn header_array_extension_mixed_body() -> impl IntoResponse {
(
[("content-type", "text/plain")],
Extension(1),
HeaderMap::new(),
String::new(),
)
}
Router::<Body>::new()
.route("/", get(status))
.route("/", get(status_headermap))
.route("/", get(status_header_array))
.route("/", get(status_headermap_body))
.route("/", get(status_header_array_body))
.route("/", get(status_headermap_impl_into_response))
.route("/", get(status_header_array_impl_into_response))
.route("/", get(status_header_array_extension_body))
.route("/", get(status_header_array_extension_mixed_body))
.route("/", get(headermap))
.route("/", get(header_array))
.route("/", get(headermap_body))
.route("/", get(header_array_body))
.route("/", get(headermap_impl_into_response))
.route("/", get(header_array_impl_into_response))
.route("/", get(header_array_extension_body))
.route("/", get(header_array_extension_mixed_body));
}
}
| 28.004505 | 99 | 0.516165 |
4a32d405db20cc02b6fdcb6cffd7331b2ad4f07b | 6,878 | #![cfg(target_os = "macos")]
use std::os::raw::c_void;
use crate::{
dpi::LogicalSize,
event_loop::EventLoopWindowTarget,
monitor::MonitorHandle,
window::{Window, WindowBuilder},
};
/// Additional methods on `Window` that are specific to MacOS.
pub trait WindowExtMacOS {
/// Returns a pointer to the cocoa `NSWindow` that is used by this window.
///
/// The pointer will become invalid when the `Window` is destroyed.
fn ns_window(&self) -> *mut c_void;
/// Returns a pointer to the cocoa `NSView` that is used by this window.
///
/// The pointer will become invalid when the `Window` is destroyed.
fn ns_view(&self) -> *mut c_void;
/// Returns whether or not the window is in simple fullscreen mode.
fn simple_fullscreen(&self) -> bool;
/// Toggles a fullscreen mode that doesn't require a new macOS space.
/// Returns a boolean indicating whether the transition was successful (this
/// won't work if the window was already in the native fullscreen).
///
/// This is how fullscreen used to work on macOS in versions before Lion.
/// And allows the user to have a fullscreen window without using another
/// space or taking control over the entire monitor.
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool;
}
impl WindowExtMacOS for Window {
#[inline]
fn ns_window(&self) -> *mut c_void {
self.window.ns_window()
}
#[inline]
fn ns_view(&self) -> *mut c_void {
self.window.ns_view()
}
#[inline]
fn simple_fullscreen(&self) -> bool {
self.window.simple_fullscreen()
}
#[inline]
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool {
self.window.set_simple_fullscreen(fullscreen)
}
}
/// Corresponds to `NSApplicationActivationPolicy`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ActivationPolicy {
/// Corresponds to `NSApplicationActivationPolicyRegular`.
Regular,
/// Corresponds to `NSApplicationActivationPolicyAccessory`.
Accessory,
/// Corresponds to `NSApplicationActivationPolicyProhibited`.
Prohibited,
}
impl Default for ActivationPolicy {
fn default() -> Self {
ActivationPolicy::Regular
}
}
/// Additional methods on `WindowBuilder` that are specific to MacOS.
///
/// **Note:** Properties dealing with the titlebar will be overwritten by the `with_decorations` method
/// on the base `WindowBuilder`:
///
/// - `with_titlebar_transparent`
/// - `with_title_hidden`
/// - `with_titlebar_hidden`
/// - `with_titlebar_buttons_hidden`
/// - `with_fullsize_content_view`
pub trait WindowBuilderExtMacOS {
/// Sets the activation policy for the window being built.
fn with_activation_policy(self, activation_policy: ActivationPolicy) -> WindowBuilder;
/// Enables click-and-drag behavior for the entire window, not just the titlebar.
fn with_movable_by_window_background(self, movable_by_window_background: bool)
-> WindowBuilder;
/// Makes the titlebar transparent and allows the content to appear behind it.
fn with_titlebar_transparent(self, titlebar_transparent: bool) -> WindowBuilder;
/// Hides the window title.
fn with_title_hidden(self, title_hidden: bool) -> WindowBuilder;
/// Hides the window titlebar.
fn with_titlebar_hidden(self, titlebar_hidden: bool) -> WindowBuilder;
/// Hides the window titlebar buttons.
fn with_titlebar_buttons_hidden(self, titlebar_buttons_hidden: bool) -> WindowBuilder;
/// Makes the window content appear behind the titlebar.
fn with_fullsize_content_view(self, fullsize_content_view: bool) -> WindowBuilder;
/// Build window with `resizeIncrements` property. Values must not be 0.
fn with_resize_increments(self, increments: LogicalSize<f64>) -> WindowBuilder;
fn with_disallow_hidpi(self, disallow_hidpi: bool) -> WindowBuilder;
}
impl WindowBuilderExtMacOS for WindowBuilder {
#[inline]
fn with_activation_policy(mut self, activation_policy: ActivationPolicy) -> WindowBuilder {
self.platform_specific.activation_policy = activation_policy;
self
}
#[inline]
fn with_movable_by_window_background(
mut self,
movable_by_window_background: bool,
) -> WindowBuilder {
self.platform_specific.movable_by_window_background = movable_by_window_background;
self
}
#[inline]
fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> WindowBuilder {
self.platform_specific.titlebar_transparent = titlebar_transparent;
self
}
#[inline]
fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> WindowBuilder {
self.platform_specific.titlebar_hidden = titlebar_hidden;
self
}
#[inline]
fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> WindowBuilder {
self.platform_specific.titlebar_buttons_hidden = titlebar_buttons_hidden;
self
}
#[inline]
fn with_title_hidden(mut self, title_hidden: bool) -> WindowBuilder {
self.platform_specific.title_hidden = title_hidden;
self
}
#[inline]
fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> WindowBuilder {
self.platform_specific.fullsize_content_view = fullsize_content_view;
self
}
#[inline]
fn with_resize_increments(mut self, increments: LogicalSize<f64>) -> WindowBuilder {
self.platform_specific.resize_increments = Some(increments.into());
self
}
#[inline]
fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> WindowBuilder {
self.platform_specific.disallow_hidpi = disallow_hidpi;
self
}
}
/// Additional methods on `MonitorHandle` that are specific to MacOS.
pub trait MonitorHandleExtMacOS {
/// Returns the identifier of the monitor for Cocoa.
fn native_id(&self) -> u32;
/// Returns a pointer to the NSScreen representing this monitor.
fn ns_screen(&self) -> Option<*mut c_void>;
}
impl MonitorHandleExtMacOS for MonitorHandle {
#[inline]
fn native_id(&self) -> u32 {
self.inner.native_identifier()
}
fn ns_screen(&self) -> Option<*mut c_void> {
self.inner.ns_screen().map(|s| s as *mut c_void)
}
}
/// Additional methods on `EventLoopWindowTarget` that are specific to macOS.
pub trait EventLoopWindowTargetExtMacOS {
/// Hide the entire application. In most applications this is typically triggered with Command-H.
fn hide_application(&self);
}
impl<T> EventLoopWindowTargetExtMacOS for EventLoopWindowTarget<T> {
fn hide_application(&self) {
let cls = objc::runtime::Class::get("NSApplication").unwrap();
let app: cocoa::base::id = unsafe { msg_send![cls, sharedApplication] };
unsafe { msg_send![app, hide: 0] }
}
}
| 34.737374 | 103 | 0.699186 |
ed56b968da7fda039f856e6c1badb0550055fd42 | 4,884 | use cast::{u64, u8};
use codemap::CodeMap;
use codemap_diagnostic::{ColorConfig, Diagnostic, Emitter, Level, SpanLabel, SpanStyle};
use serde::Deserialize;
use serde_taml::de::{from_taml_str, EncodeError};
use std::{borrow::Cow, io::stdout, iter};
use taml::diagnostics::{DiagnosticLabel, DiagnosticLabelPriority, DiagnosticType};
use tap::{Conv, Pipe};
#[allow(non_camel_case_types)]
type tamlDiagnostic = taml::diagnostics::Diagnostic<usize>;
#[derive(Debug, Deserialize)]
struct DataLiteral {
#[serde(with = "serde_bytes")]
data: Vec<u8>,
}
#[test]
fn unsupported_characters() {
let text = "data: <Windows-1252:Bonjour ! До свидания!>\n";
let mut diagnostics = vec![];
from_taml_str::<DataLiteral, _>(
text,
&mut diagnostics,
&[
("Windows-1252", &|text| {
// See <ftp://ftp.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT>.
// `#` (0x23) is used as spacer.
const INSERT_0X80: &str = "€#‚ƒ„…†‡ˆ‰Š‹Œ#Ž##‘’“”•–—˜™š›œ#žŸ";
let mut chars = text.char_indices();
#[allow(clippy::never_loop)]
let mut error_start = 'success: loop {
let mut encoded = vec![];
for (i, d) in chars.by_ref() {
encoded.push(match d {
'\0'..='\u{7F}' | '\u{A0}'..='\u{FF}' => u8(d.conv::<u32>()).unwrap(),
_ => {
match INSERT_0X80
.chars()
.enumerate()
.find_map(|(o, c)| (d == c).then(|| o))
{
Some(o) => u8(0x80 + o).unwrap(),
None => break 'success i,
}
}
})
}
return Ok(Cow::Owned(encoded));
}
.pipe(Some);
let mut errors = vec![];
for (i, d) in chars.chain(iter::once((text.len(), 'a'))) {
if matches!(d, '\0'..='\u{7F}' | '\u{A0}'..='\u{FF}') || INSERT_0X80.contains(d)
{
error_start.take().into_iter().for_each(|error_start| {
errors.push(EncodeError {
unescaped_input_span: error_start..i,
message: Cow::Owned(format!(
"Unsupported character(s): `{}`.",
&text[error_start..i]
)),
})
})
} else {
error_start.get_or_insert(i);
}
}
Err(errors)
}),
("UTF-8", &|text| Ok(Cow::Borrowed(text.as_bytes()))),
],
)
.unwrap_err();
assert_eq!(
diagnostics.as_slice(),
&[tamlDiagnostic {
type_: DiagnosticType::EncodeFailed,
labels: vec![
DiagnosticLabel::new(
"Unsupported character(s): `До`.",
30..34,
DiagnosticLabelPriority::Primary,
),
DiagnosticLabel::new(
"Unsupported character(s): `свидания`.",
35..51,
DiagnosticLabelPriority::Primary,
),
DiagnosticLabel::new(
"Encoding specified here.",
7..19,
DiagnosticLabelPriority::Auxiliary,
),
DiagnosticLabel::new(
"Hint: Available encodings are: `Windows-1252`, `UTF-8`.",
None,
DiagnosticLabelPriority::Auxiliary,
)
]
}]
);
report(text, diagnostics)
}
#[test]
fn unknown_encoding() {
let text = "data: <UTF-7:Bonjour ! До свидания!>\n";
let mut diagnostics = vec![];
from_taml_str::<DataLiteral, _>(
text,
&mut diagnostics,
&[("UTF-8", &|text| Ok(Cow::Borrowed(text.as_bytes())))],
)
.unwrap_err();
assert_eq!(
diagnostics.as_slice(),
&[tamlDiagnostic {
type_: DiagnosticType::UnknownEncoding,
labels: vec![
DiagnosticLabel::new(
"Unrecognized encoding `UTF-7`.",
7..12,
DiagnosticLabelPriority::Primary,
),
DiagnosticLabel::new(
"Hint: Available encodings are: `UTF-8`.",
None,
DiagnosticLabelPriority::Auxiliary,
)
]
}]
);
report(text, diagnostics)
}
fn report(text: &str, diagnostics: Vec<tamlDiagnostic>) {
let mut codemap = CodeMap::new();
let file_span = codemap.add_file("TAML".to_string(), text.to_string()).span;
let diagnostics: Vec<_> = diagnostics
.into_iter()
.map(|diagnostic| Diagnostic {
code: Some(diagnostic.code()),
level: match diagnostic.level() {
taml::diagnostics::DiagnosticLevel::Warning => Level::Warning,
taml::diagnostics::DiagnosticLevel::Error => Level::Error,
},
message: diagnostic.message().to_string(),
spans: diagnostic
.labels
.into_iter()
.map(|label| SpanLabel {
label: label.caption.map(|c| c.to_string()),
style: match label.priority {
taml::diagnostics::DiagnosticLabelPriority::Primary => SpanStyle::Primary,
taml::diagnostics::DiagnosticLabelPriority::Auxiliary => {
SpanStyle::Secondary
}
},
span: match label.span {
Some(span) => file_span.subspan(u64(span.start), u64(span.end)),
None => file_span.subspan(file_span.len(), file_span.len()),
},
})
.collect(),
})
.collect();
if !diagnostics.is_empty() {
// Not great, but seems to help a bit with output weirdness.
let stdout = stdout();
let _stdout_lock = stdout.lock();
Emitter::stderr(ColorConfig::Auto, Some(&codemap)).emit(&diagnostics)
}
}
| 27.133333 | 88 | 0.608927 |
7aa626221aea5748b64982fec32c811974c9d532 | 130 | fn f() {
block_flow.base.stacking_relative_position_of_display_port = self.base.stacking_relative_position_of_display_port;
}
| 32.5 | 118 | 0.838462 |
186d9b2b665e4ffdce698d31507e367d6362d1f9 | 10,498 | use serde::Deserialize;
use crate::query::Query;
use crate::{Client, Result};
/// A struct representing a Subsonic user.
#[derive(Debug, Deserialize)]
pub struct User {
/// A user's name.
pub username: String,
/// A user's email address.
pub email: String,
/// A user may be limited to the bit rate of media they may stream. Any
/// higher sampled media will be downsampled to their limit. A limit of `0`
/// disables this.
#[serde(rename = "maxBitRate")]
#[serde(default)]
pub max_bit_rate: u64,
/// Whether the user is allowed to scrobble their songs to last.fm.
#[serde(rename = "scrobblingEnabled")]
pub scrobbling_enabled: bool,
/// Whether the user is authenticated in LDAP.
#[serde(rename = "ldapAuthenticated")]
#[serde(default)]
pub ldap_authenticated: bool,
/// Whether the user is an administrator.
#[serde(rename = "adminRole")]
pub admin_role: bool,
/// Whether the user is allowed to manage their own settings and change
/// their password.
#[serde(rename = "settingsRole")]
pub settings_role: bool,
/// Whether the user is allowed to download media.
#[serde(rename = "downloadRole")]
pub download_role: bool,
/// Whether the user is allowed to upload media.
#[serde(rename = "uploadRole")]
pub upload_role: bool,
/// Whether the user is allowed to modify or delete playlists.
#[serde(rename = "playlistRole")]
pub playlist_role: bool,
/// Whether the user is allowed to change cover art and media tags.
#[serde(rename = "coverArtRole")]
pub cover_art_role: bool,
/// Whether the user is allowed to create and edit comments and
/// ratings.
#[serde(rename = "commentRole")]
pub comment_role: bool,
/// Whether the user is allowed to administrate podcasts.
#[serde(rename = "podcastRole")]
pub podcast_role: bool,
/// Whether the user is allowed to play media.
#[serde(rename = "streamRole")]
pub stream_role: bool,
/// Whether the user is allowed to control the jukebox.
#[serde(rename = "jukeboxRole")]
pub jukebox_role: bool,
/// Whether the user is allowed to share content.
#[serde(rename = "shareRole")]
pub share_role: bool,
/// Whether the user is allowed to start video conversions.
#[serde(rename = "videoConversionRole")]
pub video_conversion_role: bool,
/// The date the user's avatar was last changed (as an ISO8601
/// timestamp).
#[serde(rename = "avatarLastChanged")]
pub avatar_last_changed: String,
/// The list of media folders the user has access to.
#[serde(rename = "folder")]
pub folders: Vec<u64>,
#[serde(default)]
_private: bool,
}
impl User {
/// Fetches a single user's information from the server.
pub fn get(client: &Client, username: &str) -> Result<User> {
let res = client.get("getUser", Query::with("username", username))?;
Ok(serde_json::from_value::<User>(res)?)
}
/// Lists all users on the server.
///
/// # Errors
///
/// Attempting to use this method as a non-administrative user (when
/// creating the `Client`) will result in a [`NotAuthorized`] error.
///
/// [`NotAuthorized`]: ./enum.ApiError.html#variant.NotAuthorized
pub fn list(client: &Client) -> Result<Vec<User>> {
let user = client.get("getUsers", Query::none())?;
Ok(get_list_as!(user, User))
}
/// Changes the user's password.
///
/// # Errors
///
/// A user may only change their own password, and only if they have the
/// `settings_role` permission, unless they are an administrator.
pub fn change_password(&self, client: &Client, password: &str) -> Result<()> {
let args = Query::with("username", self.username.as_str())
.arg("password", password)
.build();
client.get("changePassword", args)?;
Ok(())
}
/// Returns the user's avatar image as a collection of bytes.
///
/// The method makes no guarantee as to the encoding of the image, but does
/// guarantee that it is a valid image file.
pub fn avatar(&self, client: &Client) -> Result<Vec<u8>> {
client.get_bytes("getAvatar", Query::with("username", self.username.as_str()))
}
/// Creates a new local user to be pushed to the server.
///
/// See the [`UserBuilder`] struct for more details.
///
/// [`UserBuilder`]: struct.UserBuilder.html
pub fn create(username: &str, password: &str, email: &str) -> UserBuilder {
UserBuilder::new(username, password, email)
}
/// Removes the user from the Subsonic server.
pub fn delete(&self, client: &Client) -> Result<()> {
client.get(
"deleteUser",
Query::with("username", self.username.as_str()),
)?;
Ok(())
}
/// Pushes any changes made to the user to the server.
///
/// # Examples
///
/// ```no_run
/// extern crate sunk;
/// use sunk::{Client, User};
///
/// # fn run() -> sunk::Result<()> {
/// let client = Client::new("http://demo.subsonic.org", "guest3", "guest")?;
/// let mut user = User::get(&client, "guest")?;
///
/// // Update email
/// user.email = "[email protected]".to_string();
/// // Disable commenting
/// user.comment_role = false;
/// // Update on server
/// user.update(&client)?;
/// # Ok(())
/// # }
/// # fn main() {
/// # run().unwrap();
/// # }
/// ```
pub fn update(&self, client: &Client) -> Result<()> {
let args = Query::with("username", self.username.as_ref())
.arg("email", self.email.as_ref())
.arg("ldapAuthenticated", self.ldap_authenticated)
.arg("adminRole", self.admin_role)
.arg("settingsRole", self.settings_role)
.arg("streamRole", self.stream_role)
.arg("jukeboxRole", self.jukebox_role)
.arg("downloadRole", self.download_role)
.arg("uploadRole", self.upload_role)
.arg("coverArt_role", self.cover_art_role)
.arg("commentRole", self.comment_role)
.arg("podcastRole", self.podcast_role)
.arg("shareRole", self.share_role)
.arg("videoConversionRole", self.video_conversion_role)
.arg_list("musicFolderId", &self.folders.clone())
.arg("maxBitRate", self.max_bit_rate)
.build();
client.get("updateUser", args)?;
Ok(())
}
}
/// A new user to be created.
#[derive(Clone, Debug, Default)]
pub struct UserBuilder {
username: String,
password: String,
email: String,
ldap_authenticated: bool,
admin_role: bool,
settings_role: bool,
stream_role: bool,
jukebox_role: bool,
download_role: bool,
upload_role: bool,
cover_art_role: bool,
comment_role: bool,
podcast_role: bool,
share_role: bool,
video_conversion_role: bool,
folders: Vec<u64>,
max_bit_rate: u64,
}
macro_rules! build {
($f:ident: $t:ty) => {
pub fn $f(&mut self, $f: $t) -> &mut UserBuilder {
self.$f = $f.into();
self
}
};
}
impl UserBuilder {
/// Begins creating a new user.
fn new(username: &str, password: &str, email: &str) -> UserBuilder {
UserBuilder {
username: username.to_string(),
password: password.to_string(),
email: email.to_string(),
..UserBuilder::default()
}
}
/// Sets the user's username.
build!(username: &str);
/// Sets the user's password.
build!(password: &str);
/// Set's the user's email.
build!(email: &str);
/// Enables LDAP authentication for the user.
build!(ldap_authenticated: bool);
/// Bestows admin rights onto the user.
build!(admin_role: bool);
/// Allows the user to change personal settings and their own password.
build!(settings_role: bool);
/// Allows the user to play files.
build!(stream_role: bool);
/// Allows the user to play files in jukebox mode.
build!(jukebox_role: bool);
/// Allows the user to download files.
build!(download_role: bool);
/// Allows the user to upload files.
build!(upload_role: bool);
/// Allows the user to change cover art and tags.
build!(cover_art_role: bool);
/// Allows the user to create and edit comments and ratings.
build!(comment_role: bool);
/// Allows the user to administrate podcasts.
build!(podcast_role: bool);
/// Allows the user to share files with others.
build!(share_role: bool);
/// Allows the user to start video coversions.
build!(video_conversion_role: bool);
/// IDs of the music folders the user is allowed to access.
build!(folders: &[u64]);
/// The maximum bit rate (in Kbps) the user is allowed to stream at. Higher
/// bit rate streams will be downsampled to their limit.
build!(max_bit_rate: u64);
/// Pushes a defined new user to the Subsonic server.
pub fn create(&self, client: &Client) -> Result<()> {
let args = Query::with("username", self.username.as_ref())
.arg("password", self.password.as_ref())
.arg("email", self.email.as_ref())
.arg("ldapAuthenticated", self.ldap_authenticated)
.arg("adminRole", self.admin_role)
.arg("settingsRole", self.settings_role)
.arg("streamRole", self.stream_role)
.arg("jukeboxRole", self.jukebox_role)
.arg("downloadRole", self.download_role)
.arg("uploadRole", self.upload_role)
.arg("coverArt_role", self.cover_art_role)
.arg("commentRole", self.comment_role)
.arg("podcastRole", self.podcast_role)
.arg("shareRole", self.share_role)
.arg("videoConversionRole", self.video_conversion_role)
.arg_list("musicFolderId", &self.folders)
.arg("maxBitRate", self.max_bit_rate)
.build();
client.get("createUser", args)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_util;
#[test]
fn remote_parse_user() {
let mut srv = test_util::demo_site().unwrap();
let guest = User::get(&mut srv, "guest3").unwrap();
assert_eq!(guest.username, "guest3");
assert!(guest.stream_role);
assert!(!guest.admin_role);
}
}
| 35.110368 | 86 | 0.604972 |
e672a4b56d914820af0b5a5bf6e51f7c603c78f4 | 7,610 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#![deny(warnings)]
#![deny(rust_2018_idioms)]
#![deny(clippy::all)]
use docblock_syntax::DocblockSource;
use graphql_syntax::GraphQLSource;
use std::iter::Peekable;
use std::str::CharIndices;
pub enum JavaScriptSourceFeature {
GraphQL(GraphQLSource),
Docblock(DocblockSource),
}
impl JavaScriptSourceFeature {
pub fn as_graphql_source(self) -> GraphQLSource {
match self {
JavaScriptSourceFeature::GraphQL(source) => source,
JavaScriptSourceFeature::Docblock(source) => GraphQLSource {
text: source.text,
line_index: source.line_index,
column_index: source.column_index,
},
}
}
}
/// A wrapper around a peekable char iterator that tracks
/// the column and line indicies.
pub struct CharReader<'a> {
chars: Peekable<CharIndices<'a>>,
line_index: usize,
column_index: usize,
}
impl<'a> CharReader<'a> {
pub fn new(input: &'a str) -> Self {
let chars = input.char_indices().peekable();
CharReader {
chars,
line_index: 0,
column_index: 0,
}
}
}
impl<'a> Iterator for CharReader<'a> {
type Item = (usize, char);
fn next(&mut self) -> Option<Self::Item> {
let pair = self.chars.next();
if let Some((_index, ch)) = pair {
match ch {
// Line terminators: https://www.ecma-international.org/ecma-262/#sec-line-terminators
'\u{000A}' | '\u{000D}' | '\u{2028}' | '\u{2029}' => {
// <CRLF>
if ch == '\u{000D}' {
if let Some((_, ch)) = self.chars.peek() {
if ch == &'\u{00A}' {
return pair;
}
}
}
self.line_index += 1;
self.column_index = 0;
}
_ => {
self.column_index += 1;
}
}
}
pair
}
}
/// Extract graphql`text` literals and @RelayResolver comments from JS-like code.
// This should work for Flow or TypeScript alike.
pub fn extract(input: &str) -> Vec<JavaScriptSourceFeature> {
let mut res = Vec::new();
if !input.contains("graphql`") && !input.contains("@RelayResolver") {
return res;
}
let mut it = CharReader::new(input);
'code: while let Some((i, c)) = it.next() {
match c {
'g' => {
for expected in ['r', 'a', 'p', 'h', 'q', 'l', '`'] {
if let Some((_, c)) = it.next() {
if c != expected {
consume_identifier(&mut it);
continue 'code;
}
}
}
let start = i;
let line_index = it.line_index;
let column_index = it.column_index;
let mut has_visited_first_char = false;
for (i, c) in &mut it {
match c {
'`' => {
let end = i;
let text = &input[start + 8..end];
res.push(JavaScriptSourceFeature::GraphQL(GraphQLSource::new(
text,
line_index,
column_index,
)));
continue 'code;
}
' ' | '\n' | '\r' | '\t' => {}
'a'..='z' | 'A'..='Z' | '#' => {
if !has_visited_first_char {
has_visited_first_char = true;
}
}
_ => {
if !has_visited_first_char {
continue 'code;
}
}
}
}
}
'a'..='z' | 'A'..='Z' | '_' => {
consume_identifier(&mut it);
}
// Skip over template literals. Unfortunately, this isn't enough to
// deal with nested template literals and runs a risk of skipping
// over too much code -- so it is disabled.
// '`' => {
// while let Some((_, c)) = it.next() {
// match c {
// '`' => {
// continue 'code;
// }
// '\\' => {
// it.next();
// }
// _ => {}
// }
// }
// }
'"' => consume_string(&mut it, '"'),
'\'' => consume_string(&mut it, '\''),
'/' => {
match it.next() {
Some((_, '/')) => {
consume_line_comment(&mut it);
}
Some((_, '*')) => {
let start = i;
let line_index = it.line_index;
let column_index = it.column_index;
let mut prev_c = ' '; // arbitrary character other than *
let mut first = true;
for (i, c) in &mut it {
// Hack for template literals containing /*, see D21256605:
if first && c == '`' {
break;
}
first = false;
if prev_c == '*' && c == '/' {
let end = i;
let text = &input[start + 2..end - 1];
if text.contains("@RelayResolver") {
res.push(JavaScriptSourceFeature::Docblock(
DocblockSource::new(text, line_index, column_index),
));
}
continue 'code;
}
prev_c = c;
}
}
_ => {}
}
}
_ => {}
};
}
res
}
fn consume_identifier(it: &mut CharReader<'_>) {
for (_, c) in it {
match c {
'a'..='z' | 'A'..='Z' | '_' | '0'..='9' => {}
_ => {
return;
}
}
}
}
fn consume_line_comment(it: &mut CharReader<'_>) {
for (_, c) in it {
match c {
'\n' | '\r' => {
break;
}
_ => {}
}
}
}
fn consume_string(it: &mut CharReader<'_>, quote: char) {
while let Some((_, c)) = it.next() {
match c {
'\\' => {
it.next();
}
'\'' | '"' if c == quote => {
return;
}
'\n' | '\r' => {
// Unexpected newline, terminate the string parsing to recover
return;
}
_ => {}
}
}
}
| 33.086957 | 102 | 0.365177 |
14a6f09a1c69d7cd9601df05ac586314b311f2e6 | 3,031 | // Copyright (c) 2019 Stefan Lankes, RWTH Aachen University
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use alloc::boxed::Box;
use arch::percore::*;
use core::mem;
use scheduler::task::TaskHandlePriorityQueue;
struct CondQueue {
queue: TaskHandlePriorityQueue,
id: usize,
}
impl CondQueue {
pub fn new(id: usize) -> Self {
CondQueue {
queue: TaskHandlePriorityQueue::new(),
id: id,
}
}
}
impl Drop for CondQueue {
fn drop(&mut self) {
debug!("Drop queue for condition variable with id 0x{:x}", self.id);
}
}
unsafe fn __sys_destroy_queue(ptr: usize) -> i32 {
let id = ptr as *mut usize;
if id.is_null() {
debug!("sys_wait: ivalid address to condition variable");
return -1;
}
if *id != 0 {
let cond = Box::from_raw((*id) as *mut CondQueue);
mem::drop(cond);
// reset id
*id = 0;
}
0
}
#[no_mangle]
pub unsafe fn sys_destroy_queue(ptr: usize) -> i32 {
kernel_function!(__sys_destroy_queue(ptr))
}
unsafe fn __sys_notify(ptr: usize, count: i32) -> i32 {
let id = ptr as *const usize;
if id.is_null() || *id == 0 {
// invalid argument
debug!("sys_notify: invalid address to condition variable");
return -1;
}
let cond = &mut *((*id) as *mut CondQueue);
if count < 0 {
// Wake up all task that has been waiting for this condition variable
while let Some(task) = cond.queue.pop() {
core_scheduler().custom_wakeup(task);
}
} else {
for _ in 0..count {
// Wake up any task that has been waiting for this condition variable
if let Some(task) = cond.queue.pop() {
core_scheduler().custom_wakeup(task);
} else {
debug!("Unable to wakeup task");
}
}
}
0
}
#[no_mangle]
pub unsafe fn sys_notify(ptr: usize, count: i32) -> i32 {
kernel_function!(__sys_notify(ptr, count))
}
unsafe fn __sys_add_queue(ptr: usize, timeout_ns: i64) -> i32 {
let id = ptr as *mut usize;
if id.is_null() {
debug!("sys_wait: ivalid address to condition variable");
return -1;
}
if *id == 0 {
debug!("Create condition variable queue");
let queue = Box::new(CondQueue::new(ptr));
*id = Box::into_raw(queue) as usize;
}
let wakeup_time = if timeout_ns <= 0 {
None
} else {
Some(timeout_ns as u64 / 1000)
};
// Block the current task and add it to the wakeup queue.
let core_scheduler = core_scheduler();
core_scheduler.block_current_task(wakeup_time);
let cond = &mut *((*id) as *mut CondQueue);
cond.queue.push(core_scheduler.get_current_task_handle());
0
}
#[no_mangle]
pub unsafe fn sys_add_queue(ptr: usize, timeout_ns: i64) -> i32 {
kernel_function!(__sys_add_queue(ptr, timeout_ns))
}
fn __sys_wait(_ptr: usize) -> i32 {
// Switch to the next task.
core_scheduler().reschedule();
0
}
#[no_mangle]
pub fn sys_wait(ptr: usize) -> i32 {
kernel_function!(__sys_wait(ptr))
}
| 22.619403 | 77 | 0.676015 |
8af75fdb3dca947950ddd5a4244f8c79fd433c71 | 1,555 | //! Ed25519: Schnorr signatures using the twisted Edwards form of Curve25519
//!
//! Described in RFC 8032: <https://tools.ietf.org/html/rfc8032>
//!
//! This module contains two convenience methods for signing and verifying
//! Ed25519 signatures which work with any signer or verifier.
//!
//! # Example (with ed25519-dalek)
//!
//! ```nobuild
//! extern crate signatory;
//! extern crate signatory_dalek; // or another Ed25519 provider
//!
//! use signatory::ed25519;
//! use signatory_dalek::{Ed25519Signer, Ed25519Verifier};
//!
//! // Create a private key (a.k.a. a "seed") and use it to generate a signature
//! let seed = ed25519::Seed::generate();
//! let signer = Ed25519Signer::from(&seed);
//! let msg = "How are you? Fine, thank you.";
//!
//! // Sign a message
//! let sig = ed25519::sign(&signer, msg.as_bytes()).unwrap();
//!
//! // Get the public key for the given signer and make a verifier
//! let pk = ed25519::public_key(&signer).unwrap();
//! let verifier = Ed25519Verifier::from(&pk);
//! assert!(ed25519::verify(&verifier, msg.as_bytes(), &sig).is_ok());
//! ```
mod public_key;
mod seed;
#[cfg(feature = "test-vectors")]
#[macro_use]
mod test_macros;
/// RFC 8032 Ed25519 test vectors
#[cfg(feature = "test-vectors")]
mod test_vectors;
#[cfg(feature = "test-vectors")]
pub use self::test_vectors::TEST_VECTORS;
pub use self::{
public_key::{PublicKey, PUBLIC_KEY_SIZE},
seed::{Seed, SEED_SIZE},
};
// Import `Signature` type from the `ed25519` crate
pub use ::ed25519::{Signature, SIGNATURE_LENGTH as SIGNATURE_SIZE};
| 30.490196 | 80 | 0.684244 |
edb170551f2031d39519a2fbcc33d16740a75cfd | 1,560 | use crate::source::SourcePoll;
use core::pin::Pin;
use core::task::Context;
use super::Source;
/// An interface for calling poll_events on trait objects when state is not known.
///
/// Simply passes through poll_events to the underlying `Source`
pub trait StatelessSource {
/// The type used for timestamping events and states.
type Time: Ord + Copy;
/// The type of events emitted by the stream.
type Event: Sized;
/// Attempt to determine information about the set of events before `time` without generating a state. this function behaves the same as [`poll_forget`](Source::poll_forget) but returns `()` instead of [`State`](Source::State). This function should be used in all situations when the state is not actually needed, as the implementer of the trait may be able to do less work.
///
/// if you do not need to use the state, this should be preferred over poll. For example, if you are simply verifying the stream does not have new events before a time t, poll_ignore_state could be faster than poll (with a custom implementation).
fn poll_events(
self: Pin<&mut Self>,
time: Self::Time,
cx: &mut Context<'_>,
) -> SourcePoll<Self::Time, Self::Event, ()>;
}
impl<S> StatelessSource for S
where
S: Source,
{
type Time = S::Time;
type Event = S::Event;
fn poll_events(
self: Pin<&mut Self>,
time: Self::Time,
cx: &mut Context<'_>,
) -> SourcePoll<Self::Time, Self::Event, ()> {
<Self as Source>::poll_events(self, time, cx)
}
}
| 36.27907 | 378 | 0.671795 |
e226d67844edccb7f3525f671acef8bc1d0c706d | 393 | fn main()
{
let v1 = vec![ 1, 2, 3 ];
println!( "all elements of {:?} are greater than zero : {}", v1, v1.iter().all( | &e | e > 0 ) );
// : all elements of [1, 2, 3] are greater than zero : true
let v2 = [ 1, 2, -3 ];
println!( "all elements of {:?} are greater than zero : {}", v2, v2.iter().all( | &e | e > 0 ) );
// : all elements of [1, 2, -3] are greater than zero : false
}
| 39.3 | 99 | 0.524173 |
ccdc7b833e714401c32f84fd8b7d7a4f5aa06268 | 1,110 | // 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 move restrictions are enforced on overloaded unary operations
fn move_then_borrow<T: Not<T> + Clone>(x: T) {
!x;
x.clone(); //~ ERROR: use of moved value
}
fn move_borrowed<T: Not<T>>(x: T, mut y: T) {
let m = &x;
let n = &mut y;
!x; //~ ERROR: cannot move out of `x` because it is borrowed
!y; //~ ERROR: cannot move out of `y` because it is borrowed
}
fn illegal_dereference<T: Not<T>>(mut x: T, y: T) {
let m = &mut x;
let n = &y;
!*m; //~ ERROR: cannot move out of dereference of `&mut`-pointer
!*n; //~ ERROR: cannot move out of dereference of `&`-pointer
}
fn main() {}
| 29.210526 | 74 | 0.654054 |
647593609979c88259380e5fa08bf340aa8b919c | 6,907 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 super::models;
use super::requests;
use bytes::{Buf, Bytes, IntoBuf};
use rusoto_lambda::{InvocationRequest, InvocationResponse, Lambda, LambdaClient};
use serde::de::DeserializeOwned;
use serde::Deserialize;
use std::default::Default;
#[derive(Default, Debug, Clone)]
pub struct Configuration {
record_lambda: String,
metadata_lambda: String,
region: String,
}
impl Configuration {
pub fn new(lambda: String) -> Configuration {
Configuration {
record_lambda: lambda.clone(),
metadata_lambda: lambda.clone(),
region: "us-east-1".to_string(),
}
}
}
/// The Planner class is responsible to resolve the metadata for each federation call.
/// The first step is to check for tables and extract the table layout, once the table
/// layout is fetched, we can extract the splits and based on the splits execute the
/// ReadRecordRequests for each Split.
pub struct Planner {
config: Configuration,
client: LambdaClient,
}
impl Planner {
/// Instantiates a new Planner object configured with a Configuration
/// object.
pub fn new(c: Configuration) -> Self {
let r = c.region.as_str().parse().unwrap();
Planner {
config: c,
client: LambdaClient::new(r),
}
}
/// Generic invoke method to handle the request serialization and invocation.
/// The return value is automatically inferred and populated based on
/// the caller.
fn invoke<T>(&mut self, body: String) -> T
where
T: DeserializeOwned,
{
// Setup the request
let mut lambda_fun = InvocationRequest::default();
lambda_fun.function_name = self.config.metadata_lambda.clone();
// COnvert body to Bytes
lambda_fun.payload = Some(Bytes::from(body));
trace!("Invoking lambda function: {}", lambda_fun.function_name);
let result_future = self.client.invoke(lambda_fun);
let result = result_future.sync().unwrap();
// print the body
let payload = result.payload.unwrap();
trace!("{}", std::str::from_utf8(&payload).unwrap());
let reader = payload.into_buf().reader();
trace!("Result: {:?}", reader);
return serde_json::from_reader(reader).unwrap();
}
/// For a given catalog name, list all schemas inside the catalog
pub fn list_schemas(&mut self) -> requests::ListSchemasResponse {
let req = requests::ListSchemasRequest::default();
// Request should be converted to JSON
let body = serde_json::to_string(&req).unwrap();
let res: requests::ListSchemasResponse = self.invoke(body);
trace!("{:?}", res);
return res;
}
pub fn list_tables(
&mut self,
catalog_name: String,
schema_name: String,
) -> requests::ListTablesResponse {
let req = requests::ListTablesRequest::new(&"".to_owned(), &catalog_name, &schema_name);
let body = serde_json::to_string(&req).unwrap();
let res: requests::ListTablesResponse = self.invoke(body);
trace!("{:?}", res);
return res;
}
pub fn get_table(
&mut self,
catalog_name: String,
schema_name: String,
table_name: String,
) -> requests::GetTableResponse {
let req = requests::GetTableRequest::new(catalog_name, schema_name, table_name);
let body = serde_json::to_string(&req).unwrap();
let res: requests::GetTableResponse = self.invoke(body);
trace!("{:?}", res);
return res;
}
pub fn get_table_layout(
&mut self,
catalog_name: String,
table_name: models::TableName,
constraints: models::Constraints,
schema: models::Schema,
partition_cols: Vec<String>,
) -> requests::GetTableLayoutResponse {
let query_id = "".to_string();
let req = requests::GetTableLayoutRequest::new(
query_id,
catalog_name,
table_name,
constraints,
schema,
partition_cols,
);
let body = serde_json::to_string(&req).unwrap();
let res: requests::GetTableLayoutResponse = self.invoke(body);
trace!("{:?}", res);
return res;
}
pub fn get_splits(
&mut self,
query_id: String,
catalog_name: String,
table_name: models::TableName,
partitions: models::Block,
partition_cols: Vec<String>,
constraints: models::Constraints,
continuation_token: Option<String>,
) -> requests::GetSplitsResponse {
let req = requests::GetSplitsRequest::new(
query_id,
catalog_name,
table_name,
partitions,
partition_cols,
constraints,
continuation_token,
);
let body = serde_json::to_string(&req).unwrap();
trace!("{:?}", body);
let res: requests::GetSplitsResponse = self.invoke(body);
trace!("{:?}", res);
return res;
}
}
/// Wrapper class for the execution of a request against the lambda function.
pub struct Executor {
config: Configuration,
client: LambdaClient,
}
impl Executor {
/// Instantiates a new Planner object configured with a Configuration
/// object.
pub fn new(c: Configuration) -> Self {
let r = c.region.as_str().parse().unwrap();
Self {
config: c,
client: LambdaClient::new(r),
}
}
pub fn read_records(&mut self, req: requests::ReadRecordRequest) {
trace!("Entering read_records()");
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn default_test() {
let c = Configuration::default();
assert!(c.record_lambda.is_empty());
assert!(c.metadata_lambda.is_empty());
}
#[test]
fn test_config_setup() {
let c = Configuration::new("this-is-my-arn".to_string());
assert_eq!("this-is-my-arn".to_string(), c.record_lambda);
assert_eq!(c.metadata_lambda, c.record_lambda);
}
}
| 32.125581 | 96 | 0.62357 |
50af05310079ddda961b616c7715635ddf220d73 | 7,744 | // Copyright (c) 2018 Colin Finck, RWTH Aachen University
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use crate::arch::x86_64::kernel::irq;
use crate::arch::x86_64::kernel::processor;
use crate::arch::x86_64::kernel::BOOT_INFO;
use crate::environment;
use core::hint::spin_loop;
use x86::io::*;
const CMOS_COMMAND_PORT: u16 = 0x70;
const CMOS_DATA_PORT: u16 = 0x71;
const CMOS_DISABLE_NMI: u8 = 1 << 7;
const CMOS_SECOND_REGISTER: u8 = 0x00;
const CMOS_MINUTE_REGISTER: u8 = 0x02;
const CMOS_HOUR_REGISTER: u8 = 0x04;
const CMOS_DAY_REGISTER: u8 = 0x07;
const CMOS_MONTH_REGISTER: u8 = 0x08;
const CMOS_YEAR_REGISTER: u8 = 0x09;
const CMOS_STATUS_REGISTER_A: u8 = 0x0A;
const CMOS_STATUS_REGISTER_B: u8 = 0x0B;
const CMOS_UPDATE_IN_PROGRESS_FLAG: u8 = 1 << 7;
const CMOS_24_HOUR_FORMAT_FLAG: u8 = 1 << 1;
const CMOS_BINARY_FORMAT_FLAG: u8 = 1 << 2;
const CMOS_12_HOUR_PM_FLAG: u8 = 0x80;
struct Rtc {
cmos_format: u8,
}
impl Rtc {
fn new() -> Self {
irq::disable();
Self {
cmos_format: Self::read_cmos_register(CMOS_STATUS_REGISTER_B),
}
}
const fn is_24_hour_format(&self) -> bool {
self.cmos_format & CMOS_24_HOUR_FORMAT_FLAG > 0
}
const fn is_binary_format(&self) -> bool {
self.cmos_format & CMOS_BINARY_FORMAT_FLAG > 0
}
const fn time_is_pm(hour: u8) -> bool {
hour & CMOS_12_HOUR_PM_FLAG > 0
}
/// Returns the binary value for a given value in BCD (Binary-Coded Decimal).
const fn convert_bcd_value(value: u8) -> u8 {
((value / 16) * 10) + (value & 0xF)
}
/// Returns the number of microseconds since the epoch from a given date.
/// Inspired by Linux Kernel's mktime64(), see kernel/time/time.c.
fn microseconds_from_date(
year: u16,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
) -> u64 {
let (m, y) = if month > 2 {
(u64::from(month - 2), u64::from(year))
} else {
(u64::from(month + 12 - 2), u64::from(year - 1))
};
let days_since_epoch =
(y / 4 - y / 100 + y / 400 + 367 * m / 12 + u64::from(day)) + y * 365 - 719_499;
let hours_since_epoch = days_since_epoch * 24 + u64::from(hour);
let minutes_since_epoch = hours_since_epoch * 60 + u64::from(minute);
let seconds_since_epoch = minutes_since_epoch * 60 + u64::from(second);
seconds_since_epoch * 1_000_000u64
}
fn read_cmos_register(register: u8) -> u8 {
unsafe {
outb(CMOS_COMMAND_PORT, CMOS_DISABLE_NMI | register);
inb(CMOS_DATA_PORT)
}
}
fn read_datetime_register(&self, register: u8) -> u8 {
let value = Self::read_cmos_register(register);
// Every date/time register may either be in binary or in BCD format.
// Convert BCD values if necessary.
if self.is_binary_format() {
value
} else {
Self::convert_bcd_value(value)
}
}
fn read_all_values(&self) -> u64 {
// Reading year, month, and day is straightforward.
let year = u16::from(self.read_datetime_register(CMOS_YEAR_REGISTER)) + 2000;
let month = self.read_datetime_register(CMOS_MONTH_REGISTER);
let day = self.read_datetime_register(CMOS_DAY_REGISTER);
// The hour register is a bitch.
// On top of being in either binary or BCD format, it may also be in 12-hour
// or 24-hour format.
let mut hour = Self::read_cmos_register(CMOS_HOUR_REGISTER);
let mut is_pm = false;
// Check and mask off a potential PM flag if the hour is given in 12-hour format.
if !self.is_24_hour_format() {
is_pm = Self::time_is_pm(hour);
hour &= !CMOS_12_HOUR_PM_FLAG;
}
// Now convert a BCD number to binary if necessary (after potentially masking off the PM flag above).
if !self.is_binary_format() {
hour = Self::convert_bcd_value(hour);
}
// If the hour is given in 12-hour format, do the necessary calculations to convert it into 24 hours.
if !self.is_24_hour_format() {
if hour == 12 {
// 12:00 AM is 00:00 and 12:00 PM is 12:00 (see is_pm below) in 24-hour format.
hour = 0;
}
if is_pm {
// {01:00 PM, 02:00 PM, ...} is {13:00, 14:00, ...} in 24-hour format.
hour += 12;
}
}
// The minute and second registers are straightforward again.
let minute = self.read_datetime_register(CMOS_MINUTE_REGISTER);
let second = self.read_datetime_register(CMOS_SECOND_REGISTER);
// Convert it all to microseconds and return the result.
Self::microseconds_from_date(year, month, day, hour, minute, second)
}
pub fn get_microseconds_since_epoch(&self) -> u64 {
loop {
// If a clock update is currently in progress, wait until it is finished.
while Self::read_cmos_register(CMOS_STATUS_REGISTER_A) & CMOS_UPDATE_IN_PROGRESS_FLAG
> 0
{
spin_loop();
}
// Get the current time in microseconds since the epoch.
let microseconds_since_epoch_1 = self.read_all_values();
// If the clock is already updating the time again, the read values may be inconsistent
// and we have to repeat this process.
if Self::read_cmos_register(CMOS_STATUS_REGISTER_A) & CMOS_UPDATE_IN_PROGRESS_FLAG > 0 {
continue;
}
// Get the current time again and verify that it's the same we last read.
let microseconds_since_epoch_2 = self.read_all_values();
if microseconds_since_epoch_1 == microseconds_since_epoch_2 {
// Both times are identical, so we have read consistent values and can exit the loop.
return microseconds_since_epoch_1;
}
}
}
}
impl Drop for Rtc {
fn drop(&mut self) {
irq::enable();
}
}
/**
* Returns a (year, month, day, hour, minute, second) tuple from the given time in microseconds since the epoch.
* Inspired from https://howardhinnant.github.io/date_algorithms.html#civil_from_days
*/
fn date_from_microseconds(microseconds_since_epoch: u64) -> (u16, u8, u8, u8, u8, u8) {
let seconds_since_epoch = microseconds_since_epoch / 1_000_000;
let second = (seconds_since_epoch % 60) as u8;
let minutes_since_epoch = seconds_since_epoch / 60;
let minute = (minutes_since_epoch % 60) as u8;
let hours_since_epoch = minutes_since_epoch / 60;
let hour = (hours_since_epoch % 24) as u8;
let days_since_epoch = hours_since_epoch / 24;
let days = days_since_epoch + 719_468;
let era = days / 146_097;
let day_of_era = days % 146_097;
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36524 - day_of_era / 146_096) / 365;
let mut year = (year_of_era + era * 400) as u16;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let internal_month = (5 * day_of_year + 2) / 153;
let day = (day_of_year - (153 * internal_month + 2) / 5 + 1) as u8;
let mut month = internal_month as u8;
if internal_month < 10 {
month += 3;
} else {
month -= 9;
}
if month <= 2 {
year += 1;
}
(year, month, day, hour, minute, second)
}
pub fn get_boot_time() -> u64 {
unsafe { core::ptr::read_volatile(&(*BOOT_INFO).boot_gtod) }
}
pub fn init() {
let mut microseconds_offset = get_boot_time();
if microseconds_offset == 0 && !environment::is_uhyve() {
// Get the current time in microseconds since the epoch (1970-01-01) from the x86 RTC.
// Subtract the timer ticks to get the actual time when HermitCore-rs was booted.
let rtc = Rtc::new();
microseconds_offset = rtc.get_microseconds_since_epoch() - processor::get_timer_ticks();
unsafe { core::ptr::write_volatile(&mut (*BOOT_INFO).boot_gtod, microseconds_offset) }
}
let (year, month, day, hour, minute, second) = date_from_microseconds(microseconds_offset);
info!(
"HermitCore-rs booted on {:04}-{:02}-{:02} at {:02}:{:02}:{:02}",
year, month, day, hour, minute, second
);
}
| 31.737705 | 112 | 0.701188 |
5bf797b3d7c24381b135534240c9f2d8ea7671d5 | 235 | #[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Card {
pub id: i32,
pub text: String,
pub count: u32,
pub uses: i32,
pub rounds: i32,
pub personal: bool,
pub remote: bool,
pub unique: bool,
}
| 19.583333 | 47 | 0.612766 |
c19a3f8bdae8df2384b2e0c65542b23c40b5747b | 1,495 | // Copyright 2018 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate prometheus;
extern crate prometheus_static_metric;
use prometheus_static_metric::make_static_metric;
make_static_metric! {
pub label_enum Methods {
post,
get,
put,
delete,
}
pub label_enum MethodsWithName {
post: "post_name",
}
}
#[test]
fn test_format() {
assert_eq!("post", Methods::post.get_str());
assert_eq!("post", format!("{}", Methods::post));
assert_eq!("post", format!("{:?}", Methods::post));
assert_eq!("delete", Methods::delete.get_str());
assert_eq!("delete", format!("{}", Methods::delete));
assert_eq!("delete", format!("{:?}", Methods::delete));
assert_eq!("post_name", MethodsWithName::post.get_str());
assert_eq!("post_name", format!("{}", MethodsWithName::post));
assert_eq!("post_name", format!("{:?}", MethodsWithName::post));
}
#[test]
fn test_equal() {
assert_eq!(Methods::post, Methods::post);
assert_ne!(Methods::post, Methods::get);
}
| 29.9 | 70 | 0.664214 |
d5f9c5041ec5d409d1a718eecf1d47f4d94d900d | 8,663 | mod model;
mod uploader;
use async_trait::async_trait;
use http::Uri;
use model::endpoint::Endpoint;
use opentelemetry::sdk::resource::ResourceDetector;
use opentelemetry::sdk::resource::SdkProvidedResourceDetector;
use opentelemetry::sdk::trace::Config;
use opentelemetry::sdk::Resource;
use opentelemetry::{
global, sdk,
sdk::export::{trace, ExportError},
sdk::trace::TraceRuntime,
trace::{TraceError, TracerProvider},
KeyValue,
};
use opentelemetry_http::HttpClient;
use opentelemetry_semantic_conventions as semcov;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
/// Default Zipkin collector endpoint
const DEFAULT_COLLECTOR_ENDPOINT: &str = "http://127.0.0.1:9411/api/v2/spans";
/// Zipkin span exporter
#[derive(Debug)]
pub struct Exporter {
local_endpoint: Endpoint,
uploader: uploader::Uploader,
}
impl Exporter {
fn new(local_endpoint: Endpoint, client: Box<dyn HttpClient>, collector_endpoint: Uri) -> Self {
Exporter {
local_endpoint,
uploader: uploader::Uploader::new(client, collector_endpoint),
}
}
}
/// Create a new Zipkin exporter pipeline builder.
pub fn new_pipeline() -> ZipkinPipelineBuilder {
ZipkinPipelineBuilder::default()
}
/// Builder for `ExporterConfig` struct.
#[derive(Debug)]
pub struct ZipkinPipelineBuilder {
service_name: Option<String>,
service_addr: Option<SocketAddr>,
collector_endpoint: String,
trace_config: Option<sdk::trace::Config>,
client: Option<Box<dyn HttpClient>>,
}
impl Default for ZipkinPipelineBuilder {
fn default() -> Self {
ZipkinPipelineBuilder {
#[cfg(feature = "reqwest-blocking-client")]
client: Some(Box::new(reqwest::blocking::Client::new())),
#[cfg(all(
not(feature = "reqwest-blocking-client"),
not(feature = "surf-client"),
feature = "reqwest-client"
))]
client: Some(Box::new(reqwest::Client::new())),
#[cfg(all(
not(feature = "reqwest-client"),
not(feature = "reqwest-blocking-client"),
feature = "surf-client"
))]
client: Some(Box::new(surf::Client::new())),
#[cfg(all(
not(feature = "reqwest-client"),
not(feature = "surf-client"),
not(feature = "reqwest-blocking-client")
))]
client: None,
service_name: None,
service_addr: None,
collector_endpoint: DEFAULT_COLLECTOR_ENDPOINT.to_string(),
trace_config: None,
}
}
}
impl ZipkinPipelineBuilder {
/// Initial a Zipkin span exporter.
///
/// Returns error if the endpoint is not valid or if no http client is provided.
pub fn init_exporter(mut self) -> Result<Exporter, TraceError> {
let (_, endpoint) = self.init_config_and_endpoint();
self.init_exporter_with_endpoint(endpoint)
}
fn init_config_and_endpoint(&mut self) -> (Config, Endpoint) {
let service_name = self.service_name.take();
if let Some(service_name) = service_name {
let config = if let Some(mut cfg) = self.trace_config.take() {
cfg.resource = cfg.resource.map(|r| {
let without_service_name = r
.iter()
.filter(|(k, _v)| **k != semcov::resource::SERVICE_NAME)
.map(|(k, v)| KeyValue::new(k.clone(), v.clone()))
.collect::<Vec<KeyValue>>();
Arc::new(Resource::new(without_service_name))
});
cfg
} else {
Config {
resource: Some(Arc::new(Resource::empty())),
..Default::default()
}
};
(config, Endpoint::new(service_name, self.service_addr))
} else {
let service_name = SdkProvidedResourceDetector
.detect(Duration::from_secs(0))
.get(semcov::resource::SERVICE_NAME)
.unwrap()
.to_string();
(
Config {
// use a empty resource to prevent TracerProvider to assign a service name.
resource: Some(Arc::new(Resource::empty())),
..Default::default()
},
Endpoint::new(service_name, self.service_addr),
)
}
}
fn init_exporter_with_endpoint(self, endpoint: Endpoint) -> Result<Exporter, TraceError> {
if let Some(client) = self.client {
let exporter = Exporter::new(
endpoint,
client,
self.collector_endpoint
.parse()
.map_err::<Error, _>(Into::into)?,
);
Ok(exporter)
} else {
Err(Error::NoHttpClient.into())
}
}
/// Install the Zipkin trace exporter pipeline with a simple span processor.
pub fn install_simple(mut self) -> Result<sdk::trace::Tracer, TraceError> {
let (config, endpoint) = self.init_config_and_endpoint();
let exporter = self.init_exporter_with_endpoint(endpoint)?;
let mut provider_builder =
sdk::trace::TracerProvider::builder().with_simple_exporter(exporter);
provider_builder = provider_builder.with_config(config);
let provider = provider_builder.build();
let tracer = provider.tracer("opentelemetry-zipkin", Some(env!("CARGO_PKG_VERSION")));
let _ = global::set_tracer_provider(provider);
Ok(tracer)
}
/// Install the Zipkin trace exporter pipeline with a batch span processor using the specified
/// runtime.
pub fn install_batch<R: TraceRuntime>(
mut self,
runtime: R,
) -> Result<sdk::trace::Tracer, TraceError> {
let (config, endpoint) = self.init_config_and_endpoint();
let exporter = self.init_exporter_with_endpoint(endpoint)?;
let mut provider_builder =
sdk::trace::TracerProvider::builder().with_batch_exporter(exporter, runtime);
provider_builder = provider_builder.with_config(config);
let provider = provider_builder.build();
let tracer = provider.tracer("opentelemetry-zipkin", Some(env!("CARGO_PKG_VERSION")));
let _ = global::set_tracer_provider(provider);
Ok(tracer)
}
/// Assign the service name under which to group traces.
pub fn with_service_name<T: Into<String>>(mut self, name: T) -> Self {
self.service_name = Some(name.into());
self
}
/// Assign client implementation
pub fn with_http_client<T: HttpClient + 'static>(mut self, client: T) -> Self {
self.client = Some(Box::new(client));
self
}
/// Assign the service name under which to group traces.
pub fn with_service_address(mut self, addr: SocketAddr) -> Self {
self.service_addr = Some(addr);
self
}
/// Assign the Zipkin collector endpoint
pub fn with_collector_endpoint<T: Into<String>>(mut self, endpoint: T) -> Self {
self.collector_endpoint = endpoint.into();
self
}
/// Assign the SDK trace configuration.
pub fn with_trace_config(mut self, config: sdk::trace::Config) -> Self {
self.trace_config = Some(config);
self
}
}
#[async_trait]
impl trace::SpanExporter for Exporter {
/// Export spans to Zipkin collector.
async fn export(&mut self, batch: Vec<trace::SpanData>) -> trace::ExportResult {
let zipkin_spans = batch
.into_iter()
.map(|span| model::into_zipkin_span(self.local_endpoint.clone(), span))
.collect();
self.uploader.upload(zipkin_spans).await
}
}
/// Wrap type for errors from opentelemetry zipkin
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Error {
/// No http client implementation found. User should provide one or enable features.
#[error("http client must be set, users can enable reqwest or surf feature to use http client implementation within create")]
NoHttpClient,
/// Http requests failed
#[error("http request failed with {0}")]
RequestFailed(#[from] http::Error),
/// The uri provided is invalid
#[error("invalid uri")]
InvalidUri(#[from] http::uri::InvalidUri),
/// Other errors
#[error("export error: {0}")]
Other(String),
}
impl ExportError for Error {
fn exporter_name(&self) -> &'static str {
"zipkin"
}
}
| 34.513944 | 129 | 0.599677 |
b9f0d7ed67628862e65222ab0354395afbeae8da | 4,624 | #[doc = "Register `MUTEX[%s]` reader"]
pub struct R(crate::R<MUTEX_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<MUTEX_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::convert::From<crate::R<MUTEX_SPEC>> for R {
fn from(reader: crate::R<MUTEX_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `MUTEX[%s]` writer"]
pub struct W(crate::W<MUTEX_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<MUTEX_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl core::convert::From<crate::W<MUTEX_SPEC>> for W {
fn from(writer: crate::W<MUTEX_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Mutex register n\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MUTEX_A {
#[doc = "0: Mutex n is in unlocked state"]
UNLOCKED = 0,
#[doc = "1: Mutex n is in locked state"]
LOCKED = 1,
}
impl From<MUTEX_A> for bool {
#[inline(always)]
fn from(variant: MUTEX_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `MUTEX` reader - Mutex register n"]
pub struct MUTEX_R(crate::FieldReader<bool, MUTEX_A>);
impl MUTEX_R {
pub(crate) fn new(bits: bool) -> Self {
MUTEX_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MUTEX_A {
match self.bits {
false => MUTEX_A::UNLOCKED,
true => MUTEX_A::LOCKED,
}
}
#[doc = "Checks if the value of the field is `UNLOCKED`"]
#[inline(always)]
pub fn is_unlocked(&self) -> bool {
**self == MUTEX_A::UNLOCKED
}
#[doc = "Checks if the value of the field is `LOCKED`"]
#[inline(always)]
pub fn is_locked(&self) -> bool {
**self == MUTEX_A::LOCKED
}
}
impl core::ops::Deref for MUTEX_R {
type Target = crate::FieldReader<bool, MUTEX_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `MUTEX` writer - Mutex register n"]
pub struct MUTEX_W<'a> {
w: &'a mut W,
}
impl<'a> MUTEX_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MUTEX_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Mutex n is in unlocked state"]
#[inline(always)]
pub fn unlocked(self) -> &'a mut W {
self.variant(MUTEX_A::UNLOCKED)
}
#[doc = "Mutex n is in locked state"]
#[inline(always)]
pub fn locked(self) -> &'a mut W {
self.variant(MUTEX_A::LOCKED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 0 - Mutex register n"]
#[inline(always)]
pub fn mutex(&self) -> MUTEX_R {
MUTEX_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Mutex register n"]
#[inline(always)]
pub fn mutex(&mut self) -> MUTEX_W {
MUTEX_W { w: self }
}
#[doc = "Writes raw bits to the register."]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Description collection: Mutex register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mutex](index.html) module"]
pub struct MUTEX_SPEC;
impl crate::RegisterSpec for MUTEX_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [mutex::R](R) reader structure"]
impl crate::Readable for MUTEX_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [mutex::W](W) writer structure"]
impl crate::Writable for MUTEX_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets MUTEX[%s]
to value 0"]
impl crate::Resettable for MUTEX_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 29.265823 | 424 | 0.579369 |
2285cbfd26f73a8ae465ac59a70c6cd77f671009 | 4,201 | use crate::leaderArrange::LeaderSchedule;
use crate::stakingUtils;
use morgan_runtime::bank::Bank;
use morgan_interface::pubkey::Pubkey;
use morgan_interface::timing::NUM_CONSECUTIVE_LEADER_SLOTS;
/// Return the leader schedule for the given epoch.
pub fn leader_schedule(epoch_height: u64, bank: &Bank) -> Option<LeaderSchedule> {
stakingUtils::staked_nodes_at_epoch(bank, epoch_height).map(|stakes| {
let mut seed = [0u8; 32];
seed[0..8].copy_from_slice(&epoch_height.to_le_bytes());
let mut stakes: Vec<_> = stakes.into_iter().collect();
sort_stakes(&mut stakes);
LeaderSchedule::new(
&stakes,
seed,
bank.get_slots_in_epoch(epoch_height),
NUM_CONSECUTIVE_LEADER_SLOTS,
)
})
}
/// Return the leader for the given slot.
pub fn slot_leader_at(slot: u64, bank: &Bank) -> Option<Pubkey> {
let (epoch, slot_index) = bank.get_epoch_and_slot_index(slot);
leader_schedule(epoch, bank).map(|leader_schedule| leader_schedule[slot_index])
}
// Returns the number of ticks remaining from the specified tick_height to the end of the
// slot implied by the tick_height
pub fn num_ticks_left_in_slot(bank: &Bank, tick_height: u64) -> u64 {
bank.ticks_per_slot() - tick_height % bank.ticks_per_slot() - 1
}
pub fn tick_height_to_slot(ticks_per_slot: u64, tick_height: u64) -> u64 {
tick_height / ticks_per_slot
}
fn sort_stakes(stakes: &mut Vec<(Pubkey, u64)>) {
// Sort first by stake. If stakes are the same, sort by pubkey to ensure a
// deterministic result.
// Note: Use unstable sort, because we dedup right after to remove the equal elements.
stakes.sort_unstable_by(|(l_pubkey, l_stake), (r_pubkey, r_stake)| {
if r_stake == l_stake {
r_pubkey.cmp(&l_pubkey)
} else {
r_stake.cmp(&l_stake)
}
});
// Now that it's sorted, we can do an O(n) dedup.
stakes.dedup();
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stakingUtils;
use morgan_runtime::genesis_utils::{
create_genesis_block_with_leader, BOOTSTRAP_LEADER_DIFS,
};
#[test]
fn test_leader_schedule_via_bank() {
let pubkey = Pubkey::new_rand();
let genesis_block =
create_genesis_block_with_leader(0, &pubkey, BOOTSTRAP_LEADER_DIFS).genesis_block;
let bank = Bank::new(&genesis_block);
let pubkeys_and_stakes: Vec<_> = stakingUtils::staked_nodes(&bank).into_iter().collect();
let seed = [0u8; 32];
let leader_schedule = LeaderSchedule::new(
&pubkeys_and_stakes,
seed,
genesis_block.slots_per_epoch,
NUM_CONSECUTIVE_LEADER_SLOTS,
);
assert_eq!(leader_schedule[0], pubkey);
assert_eq!(leader_schedule[1], pubkey);
assert_eq!(leader_schedule[2], pubkey);
}
#[test]
fn test_leader_scheduler1_basic() {
let pubkey = Pubkey::new_rand();
let genesis_block = create_genesis_block_with_leader(
BOOTSTRAP_LEADER_DIFS,
&pubkey,
BOOTSTRAP_LEADER_DIFS,
)
.genesis_block;
let bank = Bank::new(&genesis_block);
assert_eq!(slot_leader_at(bank.slot(), &bank).unwrap(), pubkey);
}
#[test]
fn test_sort_stakes_basic() {
let pubkey0 = Pubkey::new_rand();
let pubkey1 = Pubkey::new_rand();
let mut stakes = vec![(pubkey0, 1), (pubkey1, 2)];
sort_stakes(&mut stakes);
assert_eq!(stakes, vec![(pubkey1, 2), (pubkey0, 1)]);
}
#[test]
fn test_sort_stakes_with_dup() {
let pubkey0 = Pubkey::new_rand();
let pubkey1 = Pubkey::new_rand();
let mut stakes = vec![(pubkey0, 1), (pubkey1, 2), (pubkey0, 1)];
sort_stakes(&mut stakes);
assert_eq!(stakes, vec![(pubkey1, 2), (pubkey0, 1)]);
}
#[test]
fn test_sort_stakes_with_equal_stakes() {
let pubkey0 = Pubkey::default();
let pubkey1 = Pubkey::new_rand();
let mut stakes = vec![(pubkey0, 1), (pubkey1, 1)];
sort_stakes(&mut stakes);
assert_eq!(stakes, vec![(pubkey1, 1), (pubkey0, 1)]);
}
}
| 33.608 | 97 | 0.633897 |
181a1a61552f5b7463faa496d7adc76083e29d4c | 71,636 | use std::borrow::Cow;
use std::cmp::min;
use itertools::Itertools;
use syntax::parse::token::{DelimToken, LitKind};
use syntax::source_map::{BytePos, Span};
use syntax::{ast, ptr};
use crate::chains::rewrite_chain;
use crate::closures;
use crate::comment::{
combine_strs_with_missing_comments, comment_style, contains_comment, recover_comment_removed,
rewrite_comment, rewrite_missing_comment, CharClasses, FindUncommented,
};
use crate::config::lists::*;
use crate::config::{Config, ControlBraceStyle, IndentStyle};
use crate::lists::{
definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
struct_lit_tactic, write_list, ListFormatting, Separator,
};
use crate::macros::{rewrite_macro, MacroPosition};
use crate::matches::rewrite_match;
use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
use crate::rewrite::{Rewrite, RewriteContext};
use crate::shape::{Indent, Shape};
use crate::source_map::{LineRangeUtils, SpanUtils};
use crate::spanned::Spanned;
use crate::string::{rewrite_string, StringFormat};
use crate::types::{rewrite_path, PathContext};
use crate::utils::{
colon_spaces, contains_skip, count_newlines, first_line_ends_with, inner_attributes,
last_line_extendable, last_line_width, mk_sp, outer_attributes, semicolon_for_expr,
unicode_str_width, wrap_str,
};
use crate::vertical::rewrite_with_alignment;
use crate::visitor::FmtVisitor;
impl Rewrite for ast::Expr {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
format_expr(self, ExprType::SubExpression, context, shape)
}
}
#[derive(Copy, Clone, PartialEq)]
pub(crate) enum ExprType {
Statement,
SubExpression,
}
pub(crate) fn format_expr(
expr: &ast::Expr,
expr_type: ExprType,
context: &RewriteContext<'_>,
shape: Shape,
) -> Option<String> {
skip_out_of_file_lines_range!(context, expr.span);
if contains_skip(&*expr.attrs) {
return Some(context.snippet(expr.span()).to_owned());
}
let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
shape.sub_width(1)?
} else {
shape
};
let expr_rw = match expr.kind {
ast::ExprKind::Array(ref expr_vec) => rewrite_array(
"",
expr_vec.iter(),
expr.span,
context,
shape,
choose_separator_tactic(context, expr.span),
None,
),
ast::ExprKind::Lit(ref l) => {
if let Some(expr_rw) = rewrite_literal(context, l, shape) {
Some(expr_rw)
} else {
if let LitKind::StrRaw(_) = l.token.kind {
Some(context.snippet(l.span).trim().into())
} else {
None
}
}
}
ast::ExprKind::Call(ref callee, ref args) => {
let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
let callee_str = callee.rewrite(context, shape)?;
rewrite_call(context, &callee_str, args, inner_span, shape)
}
ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
// FIXME: format comments between operands and operator
rewrite_all_pairs(expr, shape, context).or_else(|| {
rewrite_pair(
&**lhs,
&**rhs,
PairParts::infix(&format!(" {} ", context.snippet(op.span))),
context,
shape,
context.config.binop_separator(),
)
})
}
ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
context,
path,
fields,
base.as_ref().map(|e| &**e),
&expr.attrs,
expr.span,
shape,
),
ast::ExprKind::Tup(ref items) => {
rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
}
ast::ExprKind::Let(..) => None,
ast::ExprKind::If(..)
| ast::ExprKind::ForLoop(..)
| ast::ExprKind::Loop(..)
| ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
.and_then(|control_flow| control_flow.rewrite(context, shape)),
ast::ExprKind::Block(ref block, opt_label) => {
match expr_type {
ExprType::Statement => {
if is_unsafe_block(block) {
rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
} else if let rw @ Some(_) =
rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
{
// Rewrite block without trying to put it in a single line.
rw
} else {
let prefix = block_prefix(context, block, shape)?;
rewrite_block_with_visitor(
context,
&prefix,
block,
Some(&expr.attrs),
opt_label,
shape,
true,
)
}
}
ExprType::SubExpression => {
rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
}
}
}
ast::ExprKind::Match(ref cond, ref arms) => {
rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
}
ast::ExprKind::Path(ref qself, ref path) => {
rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
}
ast::ExprKind::Assign(ref lhs, ref rhs) => {
rewrite_assignment(context, lhs, rhs, None, shape)
}
ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
rewrite_assignment(context, lhs, rhs, Some(op), shape)
}
ast::ExprKind::Continue(ref opt_label) => {
let id_str = match *opt_label {
Some(label) => format!(" {}", label.ident),
None => String::new(),
};
Some(format!("continue{}", id_str))
}
ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
let id_str = match *opt_label {
Some(label) => format!(" {}", label.ident),
None => String::new(),
};
if let Some(ref expr) = *opt_expr {
rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
} else {
Some(format!("break{}", id_str))
}
}
ast::ExprKind::Yield(ref opt_expr) => {
if let Some(ref expr) = *opt_expr {
rewrite_unary_prefix(context, "yield ", &**expr, shape)
} else {
Some("yield".to_string())
}
}
ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => {
closures::rewrite_closure(
capture, is_async, movability, fn_decl, body, expr.span, context, shape,
)
}
ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
rewrite_chain(expr, context, shape)
}
ast::ExprKind::Mac(ref mac) => {
rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
wrap_str(
context.snippet(expr.span).to_owned(),
context.config.max_width(),
shape,
)
})
}
ast::ExprKind::Ret(None) => Some("return".to_owned()),
ast::ExprKind::Ret(Some(ref expr)) => {
rewrite_unary_prefix(context, "return ", &**expr, shape)
}
ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
ast::ExprKind::AddrOf(mutability, ref expr) => {
rewrite_expr_addrof(context, mutability, expr, shape)
}
ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
&**expr,
&**ty,
PairParts::infix(" as "),
context,
shape,
SeparatorPlace::Front,
),
ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
&**expr,
&**ty,
PairParts::infix(": "),
context,
shape,
SeparatorPlace::Back,
),
ast::ExprKind::Index(ref expr, ref index) => {
rewrite_index(&**expr, &**index, context, shape)
}
ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
&**expr,
&*repeats.value,
PairParts::new("[", "; ", "]"),
context,
shape,
SeparatorPlace::Back,
),
ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
let delim = match limits {
ast::RangeLimits::HalfOpen => "..",
ast::RangeLimits::Closed => "..=",
};
fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
match lhs.kind {
ast::ExprKind::Lit(ref lit) => match lit.kind {
ast::LitKind::FloatUnsuffixed(..) => {
context.snippet(lit.span).ends_with('.')
}
_ => false,
},
ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, &expr),
_ => false,
}
}
fn needs_space_after_range(rhs: &ast::Expr) -> bool {
match rhs.kind {
// Don't format `.. ..` into `....`, which is invalid.
//
// This check is unnecessary for `lhs`, because a range
// starting from another range needs parentheses as `(x ..) ..`
// (`x .. ..` is a range from `x` to `..`).
ast::ExprKind::Range(None, _, _) => true,
_ => false,
}
}
let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
let space_if = |b: bool| if b { " " } else { "" };
format!(
"{}{}{}",
lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
delim,
rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
)
};
match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
(Some(lhs), Some(rhs)) => {
let sp_delim = if context.config.spaces_around_ranges() {
format!(" {} ", delim)
} else {
default_sp_delim(Some(lhs), Some(rhs))
};
rewrite_pair(
&*lhs,
&*rhs,
PairParts::infix(&sp_delim),
context,
shape,
context.config.binop_separator(),
)
}
(None, Some(rhs)) => {
let sp_delim = if context.config.spaces_around_ranges() {
format!("{} ", delim)
} else {
default_sp_delim(None, Some(rhs))
};
rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
}
(Some(lhs), None) => {
let sp_delim = if context.config.spaces_around_ranges() {
format!(" {}", delim)
} else {
default_sp_delim(Some(lhs), None)
};
rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
}
(None, None) => Some(delim.to_owned()),
}
}
// We do not format these expressions yet, but they should still
// satisfy our width restrictions.
ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
ast::ExprKind::TryBlock(ref block) => {
if let rw @ Some(_) =
rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
{
rw
} else {
// 9 = `try `
let budget = shape.width.saturating_sub(9);
Some(format!(
"{}{}",
"try ",
rewrite_block(
block,
Some(&expr.attrs),
None,
context,
Shape::legacy(budget, shape.indent)
)?
))
}
}
ast::ExprKind::Async(capture_by, _node_id, ref block) => {
let mover = if capture_by == ast::CaptureBy::Value {
"move "
} else {
""
};
if let rw @ Some(_) = rewrite_single_line_block(
context,
format!("{}{}", "async ", mover).as_str(),
block,
Some(&expr.attrs),
None,
shape,
) {
rw
} else {
// 6 = `async `
let budget = shape.width.saturating_sub(6);
Some(format!(
"{}{}{}",
"async ",
mover,
rewrite_block(
block,
Some(&expr.attrs),
None,
context,
Shape::legacy(budget, shape.indent)
)?
))
}
}
ast::ExprKind::Await(_) => rewrite_chain(expr, context, shape),
ast::ExprKind::Err => None,
};
expr_rw
.and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
.and_then(|expr_str| {
let attrs = outer_attributes(&expr.attrs);
let attrs_str = attrs.rewrite(context, shape)?;
let span = mk_sp(
attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
expr.span.lo(),
);
combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
})
}
pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
name: &'a str,
exprs: impl Iterator<Item = &'a T>,
span: Span,
context: &'a RewriteContext<'_>,
shape: Shape,
force_separator_tactic: Option<SeparatorTactic>,
delim_token: Option<DelimToken>,
) -> Option<String> {
overflow::rewrite_with_square_brackets(
context,
name,
exprs,
shape,
span,
force_separator_tactic,
delim_token,
)
}
fn rewrite_empty_block(
context: &RewriteContext<'_>,
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
label: Option<ast::Label>,
prefix: &str,
shape: Shape,
) -> Option<String> {
if block_has_statements(&block) {
return None;
}
let label_str = rewrite_label(label);
if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
return None;
}
if !block_contains_comment(context, block) && shape.width >= 2 {
return Some(format!("{}{}{{}}", prefix, label_str));
}
// If a block contains only a single-line comment, then leave it on one line.
let user_str = context.snippet(block.span);
let user_str = user_str.trim();
if user_str.starts_with('{') && user_str.ends_with('}') {
let comment_str = user_str[1..user_str.len() - 1].trim();
if block.stmts.is_empty()
&& !comment_str.contains('\n')
&& !comment_str.starts_with("//")
&& comment_str.len() + 4 <= shape.width
{
return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
}
}
None
}
fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
Some(match block.rules {
ast::BlockCheckMode::Unsafe(..) => {
let snippet = context.snippet(block.span);
let open_pos = snippet.find_uncommented("{")?;
// Extract comment between unsafe and block start.
let trimmed = &snippet[6..open_pos].trim();
if !trimmed.is_empty() {
// 9 = "unsafe {".len(), 7 = "unsafe ".len()
let budget = shape.width.checked_sub(9)?;
format!(
"unsafe {} ",
rewrite_comment(
trimmed,
true,
Shape::legacy(budget, shape.indent + 7),
context.config,
)?
)
} else {
"unsafe ".to_owned()
}
}
ast::BlockCheckMode::Default => String::new(),
})
}
fn rewrite_single_line_block(
context: &RewriteContext<'_>,
prefix: &str,
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
label: Option<ast::Label>,
shape: Shape,
) -> Option<String> {
if is_simple_block(context, block, attrs) {
let expr_shape = shape.offset_left(last_line_width(prefix))?;
let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
let label_str = rewrite_label(label);
let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
if result.len() <= shape.width && !result.contains('\n') {
return Some(result);
}
}
None
}
pub(crate) fn rewrite_block_with_visitor(
context: &RewriteContext<'_>,
prefix: &str,
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
label: Option<ast::Label>,
shape: Shape,
has_braces: bool,
) -> Option<String> {
if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
return rw;
}
let mut visitor = FmtVisitor::from_context(context);
visitor.block_indent = shape.indent;
visitor.is_if_else_block = context.is_if_else_block();
match (block.rules, label) {
(ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
let snippet = context.snippet(block.span);
let open_pos = snippet.find_uncommented("{")?;
visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
}
(ast::BlockCheckMode::Default, None) => {
visitor.last_pos = block.span.lo();
if let Some(attrs) = attrs {
if let Some(first) = attrs.first() {
let first_lo_span = first.span.lo();
if first_lo_span < visitor.last_pos {
visitor.last_pos = first_lo_span;
}
}
}
}
}
let inner_attrs = attrs.map(inner_attributes);
let label_str = rewrite_label(label);
visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
let visitor_context = visitor.get_context();
context
.skipped_range
.borrow_mut()
.append(&mut visitor_context.skipped_range.borrow_mut());
Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
}
impl Rewrite for ast::Block {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
rewrite_block(self, None, None, context, shape)
}
}
fn rewrite_block(
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
label: Option<ast::Label>,
context: &RewriteContext<'_>,
shape: Shape,
) -> Option<String> {
let prefix = block_prefix(context, block, shape)?;
// shape.width is used only for the single line case: either the empty block `{}`,
// or an unsafe expression `unsafe { e }`.
if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
return rw;
}
let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
if let Some(ref result_str) = result {
if result_str.lines().count() <= 3 {
if let rw @ Some(_) =
rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
{
return rw;
}
}
}
result
}
// Rewrite condition if the given expression has one.
pub(crate) fn rewrite_cond(
context: &RewriteContext<'_>,
expr: &ast::Expr,
shape: Shape,
) -> Option<String> {
match expr.kind {
ast::ExprKind::Match(ref cond, _) => {
// `match `cond` {`
let cond_shape = match context.config.indent_style() {
IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
IndentStyle::Block => shape.offset_left(8)?,
};
cond.rewrite(context, cond_shape)
}
_ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
let alt_block_sep =
String::from("\n") + &shape.indent.block_only().to_string(context.config);
control_flow
.rewrite_cond(context, shape, &alt_block_sep)
.and_then(|rw| Some(rw.0))
}),
}
}
// Abstraction over control flow expressions
#[derive(Debug)]
struct ControlFlow<'a> {
cond: Option<&'a ast::Expr>,
block: &'a ast::Block,
else_block: Option<&'a ast::Expr>,
label: Option<ast::Label>,
pat: Option<&'a ast::Pat>,
keyword: &'a str,
matcher: &'a str,
connector: &'a str,
allow_single_line: bool,
// HACK: `true` if this is an `if` expression in an `else if`.
nested_if: bool,
span: Span,
}
fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
match expr.kind {
ast::ExprKind::Let(ref pat, ref cond) => (Some(pat), cond),
_ => (None, expr),
}
}
// FIXME: Refactor this.
fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
match expr.kind {
ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
let (pat, cond) = extract_pats_and_cond(cond);
Some(ControlFlow::new_if(
cond,
pat,
if_block,
else_block.as_ref().map(|e| &**e),
expr_type == ExprType::SubExpression,
false,
expr.span,
))
}
ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
}
ast::ExprKind::Loop(ref block, label) => {
Some(ControlFlow::new_loop(block, label, expr.span))
}
ast::ExprKind::While(ref cond, ref block, label) => {
let (pat, cond) = extract_pats_and_cond(cond);
Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
}
_ => None,
}
}
fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
pat.map_or("", |_| "let")
}
impl<'a> ControlFlow<'a> {
fn new_if(
cond: &'a ast::Expr,
pat: Option<&'a ast::Pat>,
block: &'a ast::Block,
else_block: Option<&'a ast::Expr>,
allow_single_line: bool,
nested_if: bool,
span: Span,
) -> ControlFlow<'a> {
let matcher = choose_matcher(pat);
ControlFlow {
cond: Some(cond),
block,
else_block,
label: None,
pat,
keyword: "if",
matcher,
connector: " =",
allow_single_line,
nested_if,
span,
}
}
fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
ControlFlow {
cond: None,
block,
else_block: None,
label,
pat: None,
keyword: "loop",
matcher: "",
connector: "",
allow_single_line: false,
nested_if: false,
span,
}
}
fn new_while(
pat: Option<&'a ast::Pat>,
cond: &'a ast::Expr,
block: &'a ast::Block,
label: Option<ast::Label>,
span: Span,
) -> ControlFlow<'a> {
let matcher = choose_matcher(pat);
ControlFlow {
cond: Some(cond),
block,
else_block: None,
label,
pat,
keyword: "while",
matcher,
connector: " =",
allow_single_line: false,
nested_if: false,
span,
}
}
fn new_for(
pat: &'a ast::Pat,
cond: &'a ast::Expr,
block: &'a ast::Block,
label: Option<ast::Label>,
span: Span,
) -> ControlFlow<'a> {
ControlFlow {
cond: Some(cond),
block,
else_block: None,
label,
pat: Some(pat),
keyword: "for",
matcher: "",
connector: " in",
allow_single_line: false,
nested_if: false,
span,
}
}
fn rewrite_single_line(
&self,
pat_expr_str: &str,
context: &RewriteContext<'_>,
width: usize,
) -> Option<String> {
assert!(self.allow_single_line);
let else_block = self.else_block?;
let fixed_cost = self.keyword.len() + " { } else { }".len();
if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
if !is_simple_block(context, self.block, None)
|| !is_simple_block(context, else_node, None)
|| pat_expr_str.contains('\n')
{
return None;
}
let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
let expr = &self.block.stmts[0];
let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
let new_width = new_width.checked_sub(if_str.len())?;
let else_expr = &else_node.stmts[0];
let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
if if_str.contains('\n') || else_str.contains('\n') {
return None;
}
let result = format!(
"{} {} {{ {} }} else {{ {} }}",
self.keyword, pat_expr_str, if_str, else_str
);
if result.len() <= width {
return Some(result);
}
}
None
}
}
/// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
/// shape's indent.
fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
let mut leading_whitespaces = 0;
for c in pat_str.chars().rev() {
match c {
'\n' => break,
_ if c.is_whitespace() => leading_whitespaces += 1,
_ => leading_whitespaces = 0,
}
}
leading_whitespaces > start_column
}
impl<'a> ControlFlow<'a> {
fn rewrite_pat_expr(
&self,
context: &RewriteContext<'_>,
expr: &ast::Expr,
shape: Shape,
offset: usize,
) -> Option<String> {
debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
let cond_shape = shape.offset_left(offset)?;
if let Some(pat) = self.pat {
let matcher = if self.matcher.is_empty() {
self.matcher.to_owned()
} else {
format!("{} ", self.matcher)
};
let pat_shape = cond_shape
.offset_left(matcher.len())?
.sub_width(self.connector.len())?;
let pat_string = pat.rewrite(context, pat_shape)?;
let comments_lo = context
.snippet_provider
.span_after(self.span, self.connector.trim());
let missing_comments = if let Some(comment) =
rewrite_missing_comment(mk_sp(comments_lo, expr.span.lo()), cond_shape, context)
{
if !self.connector.is_empty() && !comment.is_empty() {
if comment_style(&comment, false).is_line_comment() || comment.contains("\n") {
let newline = &pat_shape
.indent
.block_indent(context.config)
.to_string_with_newline(context.config);
// An extra space is added when the lhs and rhs are joined
// so we need to remove one space from the end to ensure
// the comment and rhs are aligned.
let mut suffix = newline.as_ref().to_string();
if !suffix.is_empty() {
suffix.truncate(suffix.len() - 1);
}
format!("{}{}{}", newline, comment, suffix)
} else {
format!(" {}", comment)
}
} else {
comment
}
} else {
"".to_owned()
};
let result = format!(
"{}{}{}{}",
matcher, pat_string, self.connector, missing_comments
);
return rewrite_assign_rhs(context, result, expr, cond_shape);
}
let expr_rw = expr.rewrite(context, cond_shape);
// The expression may (partially) fit on the current line.
// We do not allow splitting between `if` and condition.
if self.keyword == "if" || expr_rw.is_some() {
return expr_rw;
}
// The expression won't fit on the current line, jump to next.
let nested_shape = shape
.block_indent(context.config.tab_spaces())
.with_max_width(context.config);
let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
expr.rewrite(context, nested_shape)
.map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
}
fn rewrite_cond(
&self,
context: &RewriteContext<'_>,
shape: Shape,
alt_block_sep: &str,
) -> Option<(String, usize)> {
// Do not take the rhs overhead from the upper expressions into account
// when rewriting pattern.
let new_width = context.budget(shape.used_width());
let fresh_shape = Shape {
width: new_width,
..shape
};
let constr_shape = if self.nested_if {
// We are part of an if-elseif-else chain. Our constraints are tightened.
// 7 = "} else " .len()
fresh_shape.offset_left(7)?
} else {
fresh_shape
};
let label_string = rewrite_label(self.label);
// 1 = space after keyword.
let offset = self.keyword.len() + label_string.len() + 1;
let pat_expr_string = match self.cond {
Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
None => String::new(),
};
let brace_overhead =
if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
// 2 = ` {`
2
} else {
0
};
let one_line_budget = context
.config
.max_width()
.saturating_sub(constr_shape.used_width() + offset + brace_overhead);
let force_newline_brace = (pat_expr_string.contains('\n')
|| pat_expr_string.len() > one_line_budget)
&& (!last_line_extendable(&pat_expr_string)
|| last_line_offsetted(shape.used_width(), &pat_expr_string));
// Try to format if-else on single line.
if self.allow_single_line
&& context
.config
.width_heuristics()
.single_line_if_else_max_width
> 0
{
let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
if let Some(cond_str) = trial {
if cond_str.len()
<= context
.config
.width_heuristics()
.single_line_if_else_max_width
{
return Some((cond_str, 0));
}
}
}
let cond_span = if let Some(cond) = self.cond {
cond.span
} else {
mk_sp(self.block.span.lo(), self.block.span.lo())
};
// `for event in event`
// Do not include label in the span.
let lo = self
.label
.map_or(self.span.lo(), |label| label.ident.span.hi());
let between_kwd_cond = mk_sp(
context
.snippet_provider
.span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
if self.pat.is_none() {
cond_span.lo()
} else if self.matcher.is_empty() {
self.pat.unwrap().span.lo()
} else {
context
.snippet_provider
.span_before(self.span, self.matcher.trim())
},
);
let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
let after_cond_comment =
extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
""
} else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
|| force_newline_brace
{
alt_block_sep
} else {
" "
};
let used_width = if pat_expr_string.contains('\n') {
last_line_width(&pat_expr_string)
} else {
// 2 = spaces after keyword and condition.
label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
};
Some((
format!(
"{}{}{}{}{}",
label_string,
self.keyword,
between_kwd_cond_comment.as_ref().map_or(
if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
""
} else {
" "
},
|s| &**s,
),
pat_expr_string,
after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
),
used_width,
))
}
}
impl<'a> Rewrite for ControlFlow<'a> {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
// If `used_width` is 0, it indicates that whole control flow is written in a single line.
if used_width == 0 {
return Some(cond_str);
}
let block_width = shape.width.saturating_sub(used_width);
// This is used only for the empty block case: `{}`. So, we use 1 if we know
// we should avoid the single line case.
let block_width = if self.else_block.is_some() || self.nested_if {
min(1, block_width)
} else {
block_width
};
let block_shape = Shape {
width: block_width,
..shape
};
let block_str = {
let old_val = context.is_if_else_block.replace(self.else_block.is_some());
let result =
rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
context.is_if_else_block.replace(old_val);
result?
};
let mut result = format!("{}{}", cond_str, block_str);
if let Some(else_block) = self.else_block {
let shape = Shape::indented(shape.indent, context.config);
let mut last_in_chain = false;
let rewrite = match else_block.kind {
// If the else expression is another if-else expression, prevent it
// from being formatted on a single line.
// Note how we're passing the original shape, as the
// cost of "else" should not cascade.
ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
let (pats, cond) = extract_pats_and_cond(cond);
ControlFlow::new_if(
cond,
pats,
if_block,
next_else_block.as_ref().map(|e| &**e),
false,
true,
mk_sp(else_block.span.lo(), self.span.hi()),
)
.rewrite(context, shape)
}
_ => {
last_in_chain = true;
// When rewriting a block, the width is only used for single line
// blocks, passing 1 lets us avoid that.
let else_shape = Shape {
width: min(1, shape.width),
..shape
};
format_expr(else_block, ExprType::Statement, context, else_shape)
}
};
let between_kwd_else_block = mk_sp(
self.block.span.hi(),
context
.snippet_provider
.span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
);
let between_kwd_else_block_comment =
extract_comment(between_kwd_else_block, context, shape);
let after_else = mk_sp(
context
.snippet_provider
.span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
else_block.span.lo(),
);
let after_else_comment = extract_comment(after_else, context, shape);
let between_sep = match context.config.control_brace_style() {
ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
&*alt_block_sep
}
ControlBraceStyle::AlwaysSameLine => " ",
};
let after_sep = match context.config.control_brace_style() {
ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
_ => " ",
};
result.push_str(&format!(
"{}else{}",
between_kwd_else_block_comment
.as_ref()
.map_or(between_sep, |s| &**s),
after_else_comment.as_ref().map_or(after_sep, |s| &**s),
));
result.push_str(&rewrite?);
}
Some(result)
}
}
fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
match opt_label {
Some(label) => Cow::from(format!("{}: ", label.ident)),
None => Cow::from(""),
}
}
fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
match rewrite_missing_comment(span, shape, context) {
Some(ref comment) if !comment.is_empty() => Some(format!(
"{indent}{}{indent}",
comment,
indent = shape.indent.to_string_with_newline(context.config)
)),
_ => None,
}
}
pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
contains_comment(context.snippet(block.span))
}
// Checks that a block contains no statements, an expression and no comments or
// attributes.
// FIXME: incorrectly returns false when comment is contained completely within
// the expression.
pub(crate) fn is_simple_block(
context: &RewriteContext<'_>,
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
) -> bool {
(block.stmts.len() == 1
&& stmt_is_expr(&block.stmts[0])
&& !block_contains_comment(context, block)
&& attrs.map_or(true, |a| a.is_empty()))
}
/// Checks whether a block contains at most one statement or expression, and no
/// comments or attributes.
pub(crate) fn is_simple_block_stmt(
context: &RewriteContext<'_>,
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
) -> bool {
block.stmts.len() <= 1
&& !block_contains_comment(context, block)
&& attrs.map_or(true, |a| a.is_empty())
}
fn block_has_statements(block: &ast::Block) -> bool {
block.stmts.iter().any(|stmt| {
if let ast::StmtKind::Semi(ref expr) = stmt.kind {
if let ast::ExprKind::Tup(ref tup_exprs) = expr.kind {
if tup_exprs.is_empty() {
return false;
}
}
}
true
})
}
/// Checks whether a block contains no statements, expressions, comments, or
/// inner attributes.
pub(crate) fn is_empty_block(
context: &RewriteContext<'_>,
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
) -> bool {
!block_has_statements(&block)
&& !block_contains_comment(context, block)
&& attrs.map_or(true, |a| inner_attributes(a).is_empty())
}
pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
match stmt.kind {
ast::StmtKind::Expr(..) => true,
_ => false,
}
}
pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
if let ast::BlockCheckMode::Unsafe(..) = block.rules {
true
} else {
false
}
}
pub(crate) fn rewrite_literal(
context: &RewriteContext<'_>,
l: &ast::Lit,
shape: Shape,
) -> Option<String> {
match l.kind {
ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
_ => wrap_str(
context.snippet(l.span).to_owned(),
context.config.max_width(),
shape,
),
}
}
fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
let string_lit = context.snippet(span);
if !context.config.format_strings() {
if string_lit
.lines()
.dropping_back(1)
.all(|line| line.ends_with('\\'))
{
return Some(string_lit.to_owned());
} else {
return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
}
}
// Remove the quote characters.
let str_lit = &string_lit[1..string_lit.len() - 1];
rewrite_string(
str_lit,
&StringFormat::new(shape.visual_indent(0), context.config),
shape.width.saturating_sub(2),
)
}
fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
if context.inside_macro() {
if span_ends_with_comma(context, span) {
Some(SeparatorTactic::Always)
} else {
Some(SeparatorTactic::Never)
}
} else {
None
}
}
pub(crate) fn rewrite_call(
context: &RewriteContext<'_>,
callee: &str,
args: &[ptr::P<ast::Expr>],
span: Span,
shape: Shape,
) -> Option<String> {
overflow::rewrite_with_parens(
context,
callee,
args.iter(),
shape,
span,
context.config.width_heuristics().fn_call_width,
choose_separator_tactic(context, span),
)
}
pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
match expr.kind {
ast::ExprKind::Lit(..) => true,
ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
ast::ExprKind::AddrOf(_, ref expr)
| ast::ExprKind::Box(ref expr)
| ast::ExprKind::Cast(ref expr, _)
| ast::ExprKind::Field(ref expr, _)
| ast::ExprKind::Try(ref expr)
| ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
ast::ExprKind::Repeat(ref lhs, ref rhs) => {
is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
}
_ => false,
}
}
pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
lists.iter().all(OverflowableItem::is_simple)
}
pub(crate) fn can_be_overflowed_expr(
context: &RewriteContext<'_>,
expr: &ast::Expr,
args_len: usize,
) -> bool {
match expr.kind {
_ if !expr.attrs.is_empty() => false,
ast::ExprKind::Match(..) => {
(context.use_block_indent() && args_len == 1)
|| (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
|| context.config.overflow_delimited_expr()
}
ast::ExprKind::If(..)
| ast::ExprKind::ForLoop(..)
| ast::ExprKind::Loop(..)
| ast::ExprKind::While(..) => {
context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
}
// Handle always block-like expressions
ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
// Handle `[]` and `{}`-like expressions
ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
context.config.overflow_delimited_expr()
|| (context.use_block_indent() && args_len == 1)
}
ast::ExprKind::Mac(ref mac) => {
match (mac.delim, context.config.overflow_delimited_expr()) {
(ast::MacDelimiter::Bracket, true) | (ast::MacDelimiter::Brace, true) => true,
_ => context.use_block_indent() && args_len == 1,
}
}
// Handle parenthetical expressions
ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
context.use_block_indent() && args_len == 1
}
// Handle unary-like expressions
ast::ExprKind::AddrOf(_, ref expr)
| ast::ExprKind::Box(ref expr)
| ast::ExprKind::Try(ref expr)
| ast::ExprKind::Unary(_, ref expr)
| ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
_ => false,
}
}
pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
match expr.kind {
ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
ast::ExprKind::AddrOf(_, ref expr)
| ast::ExprKind::Box(ref expr)
| ast::ExprKind::Try(ref expr)
| ast::ExprKind::Unary(_, ref expr)
| ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
_ => false,
}
}
/// Returns `true` if a function call or a method call represented by the given span ends with a
/// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
/// comma from macro can potentially break the code.
pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
let mut result: bool = Default::default();
let mut prev_char: char = Default::default();
let closing_delimiters = &[')', '}', ']'];
for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
match c {
_ if kind.is_comment() || c.is_whitespace() => continue,
c if closing_delimiters.contains(&c) => {
result &= !closing_delimiters.contains(&prev_char);
}
',' => result = true,
_ => result = false,
}
prev_char = c;
}
result
}
fn rewrite_paren(
context: &RewriteContext<'_>,
mut subexpr: &ast::Expr,
shape: Shape,
mut span: Span,
) -> Option<String> {
debug!("rewrite_paren, shape: {:?}", shape);
// Extract comments within parens.
let mut pre_span;
let mut post_span;
let mut pre_comment;
let mut post_comment;
let remove_nested_parens = context.config.remove_nested_parens();
loop {
// 1 = "(" or ")"
pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
post_comment = rewrite_missing_comment(post_span, shape, context)?;
// Remove nested parens if there are no comments.
if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
span = subexpr.span;
subexpr = subsubexpr;
continue;
}
}
break;
}
// 1 = `(` and `)`
let sub_shape = shape.offset_left(1)?.sub_width(1)?;
let subexpr_str = subexpr.rewrite(context, sub_shape)?;
let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
if fits_single_line {
Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
} else {
rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
}
}
fn rewrite_paren_in_multi_line(
context: &RewriteContext<'_>,
subexpr: &ast::Expr,
shape: Shape,
pre_span: Span,
post_span: Span,
) -> Option<String> {
let nested_indent = shape.indent.block_indent(context.config);
let nested_shape = Shape::indented(nested_indent, context.config);
let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
let subexpr_str = subexpr.rewrite(context, nested_shape)?;
let mut result = String::with_capacity(subexpr_str.len() * 2);
result.push('(');
if !pre_comment.is_empty() {
result.push_str(&nested_indent.to_string_with_newline(context.config));
result.push_str(&pre_comment);
}
result.push_str(&nested_indent.to_string_with_newline(context.config));
result.push_str(&subexpr_str);
if !post_comment.is_empty() {
result.push_str(&nested_indent.to_string_with_newline(context.config));
result.push_str(&post_comment);
}
result.push_str(&shape.indent.to_string_with_newline(context.config));
result.push(')');
Some(result)
}
fn rewrite_index(
expr: &ast::Expr,
index: &ast::Expr,
context: &RewriteContext<'_>,
shape: Shape,
) -> Option<String> {
let expr_str = expr.rewrite(context, shape)?;
let offset = last_line_width(&expr_str) + 1;
let rhs_overhead = shape.rhs_overhead(context.config);
let index_shape = if expr_str.contains('\n') {
Shape::legacy(context.config.max_width(), shape.indent)
.offset_left(offset)
.and_then(|shape| shape.sub_width(1 + rhs_overhead))
} else {
match context.config.indent_style() {
IndentStyle::Block => shape
.offset_left(offset)
.and_then(|shape| shape.sub_width(1)),
IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
}
};
let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
// Return if index fits in a single line.
match orig_index_rw {
Some(ref index_str) if !index_str.contains('\n') => {
return Some(format!("{}[{}]", expr_str, index_str));
}
_ => (),
}
// Try putting index on the next line and see if it fits in a single line.
let indent = shape.indent.block_indent(context.config);
let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
let new_index_rw = index.rewrite(context, index_shape);
match (orig_index_rw, new_index_rw) {
(_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
"{}{}[{}]",
expr_str,
indent.to_string_with_newline(context.config),
new_index_str,
)),
(None, Some(ref new_index_str)) => Some(format!(
"{}{}[{}]",
expr_str,
indent.to_string_with_newline(context.config),
new_index_str,
)),
(Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
_ => None,
}
}
fn struct_lit_can_be_aligned(fields: &[ast::Field], base: Option<&ast::Expr>) -> bool {
if base.is_some() {
return false;
}
fields.iter().all(|field| !field.is_shorthand)
}
fn rewrite_struct_lit<'a>(
context: &RewriteContext<'_>,
path: &ast::Path,
fields: &'a [ast::Field],
base: Option<&'a ast::Expr>,
attrs: &[ast::Attribute],
span: Span,
shape: Shape,
) -> Option<String> {
debug!("rewrite_struct_lit: shape {:?}", shape);
enum StructLitField<'a> {
Regular(&'a ast::Field),
Base(&'a ast::Expr),
}
// 2 = " {".len()
let path_shape = shape.sub_width(2)?;
let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
if fields.is_empty() && base.is_none() {
return Some(format!("{} {{}}", path_str));
}
// Foo { a: Foo } - indent is +3, width is -5.
let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
let one_line_width = h_shape.map_or(0, |shape| shape.width);
let body_lo = context.snippet_provider.span_after(span, "{");
let fields_str = if struct_lit_can_be_aligned(fields, base)
&& context.config.struct_field_align_threshold() > 0
{
rewrite_with_alignment(
fields,
context,
v_shape,
mk_sp(body_lo, span.hi()),
one_line_width,
)?
} else {
let field_iter = fields
.iter()
.map(StructLitField::Regular)
.chain(base.into_iter().map(StructLitField::Base));
let span_lo = |item: &StructLitField<'_>| match *item {
StructLitField::Regular(field) => field.span().lo(),
StructLitField::Base(expr) => {
let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
let pos = snippet.find_uncommented("..").unwrap();
last_field_hi + BytePos(pos as u32)
}
};
let span_hi = |item: &StructLitField<'_>| match *item {
StructLitField::Regular(field) => field.span().hi(),
StructLitField::Base(expr) => expr.span.hi(),
};
let rewrite = |item: &StructLitField<'_>| match *item {
StructLitField::Regular(field) => {
// The 1 taken from the v_budget is for the comma.
rewrite_field(context, field, v_shape.sub_width(1)?, 0)
}
StructLitField::Base(expr) => {
// 2 = ..
expr.rewrite(context, v_shape.offset_left(2)?)
.map(|s| format!("..{}", s))
}
};
let items = itemize_list(
context.snippet_provider,
field_iter,
"}",
",",
span_lo,
span_hi,
rewrite,
body_lo,
span.hi(),
false,
);
let item_vec = items.collect::<Vec<_>>();
let tactic = struct_lit_tactic(h_shape, context, &item_vec);
let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
let ends_with_comma = span_ends_with_comma(context, span);
let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
let fmt = struct_lit_formatting(
nested_shape,
tactic,
context,
force_no_trailing_comma || base.is_some() || !context.use_block_indent(),
);
write_list(&item_vec, &fmt)?
};
let fields_str =
wrap_struct_field(context, &attrs, &fields_str, shape, v_shape, one_line_width)?;
Some(format!("{} {{{}}}", path_str, fields_str))
// FIXME if context.config.indent_style() == Visual, but we run out
// of space, we should fall back to BlockIndent.
}
pub(crate) fn wrap_struct_field(
context: &RewriteContext<'_>,
attrs: &[ast::Attribute],
fields_str: &str,
shape: Shape,
nested_shape: Shape,
one_line_width: usize,
) -> Option<String> {
let should_vertical = context.config.indent_style() == IndentStyle::Block
&& (fields_str.contains('\n')
|| !context.config.struct_lit_single_line()
|| fields_str.len() > one_line_width);
let inner_attrs = &inner_attributes(attrs);
if inner_attrs.is_empty() {
if should_vertical {
Some(format!(
"{}{}{}",
nested_shape.indent.to_string_with_newline(context.config),
fields_str,
shape.indent.to_string_with_newline(context.config)
))
} else {
// One liner or visual indent.
Some(format!(" {} ", fields_str))
}
} else {
Some(format!(
"{}{}{}{}{}",
nested_shape.indent.to_string_with_newline(context.config),
inner_attrs.rewrite(context, shape)?,
nested_shape.indent.to_string_with_newline(context.config),
fields_str,
shape.indent.to_string_with_newline(context.config)
))
}
}
pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
colon_spaces(config)
}
pub(crate) fn rewrite_field(
context: &RewriteContext<'_>,
field: &ast::Field,
shape: Shape,
prefix_max_width: usize,
) -> Option<String> {
if contains_skip(&field.attrs) {
return Some(context.snippet(field.span()).to_owned());
}
let mut attrs_str = field.attrs.rewrite(context, shape)?;
if !attrs_str.is_empty() {
attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
};
let name = context.snippet(field.ident.span);
if field.is_shorthand {
Some(attrs_str + name)
} else {
let mut separator = String::from(struct_lit_field_separator(context.config));
for _ in 0..prefix_max_width.saturating_sub(name.len()) {
separator.push(' ');
}
let overhead = name.len() + separator.len();
let expr_shape = shape.offset_left(overhead)?;
let expr = field.expr.rewrite(context, expr_shape);
match expr {
Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
Some(attrs_str + name)
}
Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
None => {
let expr_offset = shape.indent.block_indent(context.config);
let expr = field
.expr
.rewrite(context, Shape::indented(expr_offset, context.config));
expr.map(|s| {
format!(
"{}{}:\n{}{}",
attrs_str,
name,
expr_offset.to_string(context.config),
s
)
})
}
}
}
}
fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
context: &RewriteContext<'_>,
mut items: impl Iterator<Item = &'a T>,
span: Span,
shape: Shape,
is_singleton_tuple: bool,
) -> Option<String> {
// In case of length 1, need a trailing comma
debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
if is_singleton_tuple {
// 3 = "(" + ",)"
let nested_shape = shape.sub_width(3)?.visual_indent(1);
return items
.next()
.unwrap()
.rewrite(context, nested_shape)
.map(|s| format!("({},)", s));
}
let list_lo = context.snippet_provider.span_after(span, "(");
let nested_shape = shape.sub_width(2)?.visual_indent(1);
let items = itemize_list(
context.snippet_provider,
items,
")",
",",
|item| item.span().lo(),
|item| item.span().hi(),
|item| item.rewrite(context, nested_shape),
list_lo,
span.hi() - BytePos(1),
false,
);
let item_vec: Vec<_> = items.collect();
let tactic = definitive_tactic(
&item_vec,
ListTactic::HorizontalVertical,
Separator::Comma,
nested_shape.width,
);
let fmt = ListFormatting::new(nested_shape, context.config)
.tactic(tactic)
.ends_with_newline(false);
let list_str = write_list(&item_vec, &fmt)?;
Some(format!("({})", list_str))
}
pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
context: &'a RewriteContext<'_>,
items: impl Iterator<Item = &'a T>,
span: Span,
shape: Shape,
is_singleton_tuple: bool,
) -> Option<String> {
debug!("rewrite_tuple {:?}", shape);
if context.use_block_indent() {
// We use the same rule as function calls for rewriting tuples.
let force_tactic = if context.inside_macro() {
if span_ends_with_comma(context, span) {
Some(SeparatorTactic::Always)
} else {
Some(SeparatorTactic::Never)
}
} else if is_singleton_tuple {
Some(SeparatorTactic::Always)
} else {
None
};
overflow::rewrite_with_parens(
context,
"",
items,
shape,
span,
context.config.width_heuristics().fn_call_width,
force_tactic,
)
} else {
rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
}
}
pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
context: &RewriteContext<'_>,
prefix: &str,
rewrite: &R,
shape: Shape,
) -> Option<String> {
rewrite
.rewrite(context, shape.offset_left(prefix.len())?)
.map(|r| format!("{}{}", prefix, r))
}
// FIXME: this is probably not correct for multi-line Rewrites. we should
// subtract suffix.len() from the last line budget, not the first!
pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
context: &RewriteContext<'_>,
suffix: &str,
rewrite: &R,
shape: Shape,
) -> Option<String> {
rewrite
.rewrite(context, shape.sub_width(suffix.len())?)
.map(|mut r| {
r.push_str(suffix);
r
})
}
fn rewrite_unary_op(
context: &RewriteContext<'_>,
op: ast::UnOp,
expr: &ast::Expr,
shape: Shape,
) -> Option<String> {
// For some reason, an UnOp is not spanned like BinOp!
rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
}
fn rewrite_assignment(
context: &RewriteContext<'_>,
lhs: &ast::Expr,
rhs: &ast::Expr,
op: Option<&ast::BinOp>,
shape: Shape,
) -> Option<String> {
let operator_str = match op {
Some(op) => context.snippet(op.span),
None => "=",
};
// 1 = space between lhs and operator.
let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
rewrite_assign_rhs(context, lhs_str, rhs, shape)
}
/// Controls where to put the rhs.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum RhsTactics {
/// Use heuristics.
Default,
/// Put the rhs on the next line if it uses multiple line, without extra indentation.
ForceNextLineWithoutIndent,
/// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
/// did not work.
AllowOverflow,
}
// The left hand side must contain everything up to, and including, the
// assignment operator.
pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
context: &RewriteContext<'_>,
lhs: S,
ex: &R,
shape: Shape,
) -> Option<String> {
rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
}
pub(crate) fn rewrite_assign_rhs_expr<R: Rewrite>(
context: &RewriteContext<'_>,
lhs: &str,
ex: &R,
shape: Shape,
rhs_tactics: RhsTactics,
) -> Option<String> {
let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
shape.indent.width()
} else {
0
});
// 1 = space between operator and rhs.
let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
width: 0,
offset: shape.offset + last_line_width + 1,
..shape
});
let has_rhs_comment = if let Some(offset) = lhs.find_last_uncommented("=") {
lhs.trim_end().len() > offset + 1
} else {
false
};
choose_rhs(
context,
ex,
orig_shape,
ex.rewrite(context, orig_shape),
rhs_tactics,
has_rhs_comment,
)
}
pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
context: &RewriteContext<'_>,
lhs: S,
ex: &R,
shape: Shape,
rhs_tactics: RhsTactics,
) -> Option<String> {
let lhs = lhs.into();
let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_tactics)?;
Some(lhs + &rhs)
}
fn choose_rhs<R: Rewrite>(
context: &RewriteContext<'_>,
expr: &R,
shape: Shape,
orig_rhs: Option<String>,
rhs_tactics: RhsTactics,
has_rhs_comment: bool,
) -> Option<String> {
match orig_rhs {
Some(ref new_str)
if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
{
Some(format!(" {}", new_str))
}
_ => {
// Expression did not fit on the same line as the identifier.
// Try splitting the line and see if that works better.
let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
let new_rhs = expr.rewrite(context, new_shape);
let new_indent_str = &shape
.indent
.block_indent(context.config)
.to_string_with_newline(context.config);
let before_space_str = if has_rhs_comment { "" } else { " " };
match (orig_rhs, new_rhs) {
(Some(ref orig_rhs), Some(ref new_rhs))
if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
.is_none() =>
{
Some(format!("{}{}", before_space_str, orig_rhs))
}
(Some(ref orig_rhs), Some(ref new_rhs))
if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
{
Some(format!("{}{}", new_indent_str, new_rhs))
}
(None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
(None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
let shape = shape.infinite_width();
expr.rewrite(context, shape)
.map(|s| format!("{}{}", before_space_str, s))
}
(None, None) => None,
(Some(orig_rhs), _) => Some(format!("{}{}", before_space_str, orig_rhs)),
}
}
}
}
fn shape_from_rhs_tactic(
context: &RewriteContext<'_>,
shape: Shape,
rhs_tactic: RhsTactics,
) -> Option<Shape> {
match rhs_tactic {
RhsTactics::ForceNextLineWithoutIndent => shape
.with_max_width(context.config)
.sub_width(shape.indent.width()),
RhsTactics::Default | RhsTactics::AllowOverflow => {
Shape::indented(shape.indent.block_indent(context.config), context.config)
.sub_width(shape.rhs_overhead(context.config))
}
}
}
/// Returns true if formatting next_line_rhs is better on a new line when compared to the
/// original's line formatting.
///
/// It is considered better if:
/// 1. the tactic is ForceNextLineWithoutIndent
/// 2. next_line_rhs doesn't have newlines
/// 3. the original line has more newlines than next_line_rhs
/// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
/// doesn't
pub(crate) fn prefer_next_line(
orig_rhs: &str,
next_line_rhs: &str,
rhs_tactics: RhsTactics,
) -> bool {
rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
|| !next_line_rhs.contains('\n')
|| count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
|| first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
|| first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
|| first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
}
fn rewrite_expr_addrof(
context: &RewriteContext<'_>,
mutability: ast::Mutability,
expr: &ast::Expr,
shape: Shape,
) -> Option<String> {
let operator_str = match mutability {
ast::Mutability::Immutable => "&",
ast::Mutability::Mutable => "&mut ",
};
rewrite_unary_prefix(context, operator_str, expr, shape)
}
pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
match expr.kind {
ast::ExprKind::MethodCall(..) => true,
ast::ExprKind::AddrOf(_, ref expr)
| ast::ExprKind::Box(ref expr)
| ast::ExprKind::Cast(ref expr, _)
| ast::ExprKind::Try(ref expr)
| ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
_ => false,
}
}
#[cfg(test)]
mod test {
use super::last_line_offsetted;
#[test]
fn test_last_line_offsetted() {
let lines = "one\n two";
assert_eq!(last_line_offsetted(2, lines), true);
assert_eq!(last_line_offsetted(4, lines), false);
assert_eq!(last_line_offsetted(6, lines), false);
let lines = "one two";
assert_eq!(last_line_offsetted(2, lines), false);
assert_eq!(last_line_offsetted(0, lines), false);
let lines = "\ntwo";
assert_eq!(last_line_offsetted(2, lines), false);
assert_eq!(last_line_offsetted(0, lines), false);
let lines = "one\n two three";
assert_eq!(last_line_offsetted(2, lines), true);
let lines = "one\n two three";
assert_eq!(last_line_offsetted(2, lines), false);
}
}
| 34.49013 | 100 | 0.536881 |
61976b232376a40bb060fd9f6130644e7800faec | 10,481 | use crate::{
errors::{HealthchecksApiError, HealthchecksConfigError},
model::{Channel, Check, Flip, NewCheck, Ping, UpdatedCheck},
util::default_user_agent,
};
use std::result::Result;
use ureq::{delete, get, post, Error, Request};
const HEALTHCHECK_API_URL: &str = "https://healthchecks.io/api/v1/";
/// Typealias to prevent some repetitiveness in function definitions
pub type ApiResult<T> = Result<T, HealthchecksApiError>;
/// Struct that encapsulates the API key used to communicate with the healthchecks.io
/// management API. Instances of this struct expose methods to query the API.
pub struct ManageClient {
pub(crate) api_key: String,
pub(crate) user_agent: String,
}
/// Create an instance of [`ManageClient`] from a given API key. No validation
/// is performed.
pub fn get_client(
api_key: String,
user_agent: Option<String>,
) -> Result<ManageClient, HealthchecksConfigError> {
if api_key.is_empty() {
Err(HealthchecksConfigError::EmptyApiKey)
} else if let Some(ua) = user_agent {
if ua.is_empty() {
Err(HealthchecksConfigError::EmptyUserAgent)
} else {
Ok(ManageClient {
api_key,
user_agent: ua,
})
}
} else {
Ok(ManageClient {
api_key,
user_agent: default_user_agent().to_owned(),
})
}
}
impl ManageClient {
fn ureq_get(&self, path: String) -> Request {
get(&path)
.set("X-Api-Key", &self.api_key)
.set("User-Agent", &self.user_agent)
}
fn ureq_post(&self, path: String) -> Request {
post(&path)
.set("X-Api-Key", &self.api_key)
.set("User-Agent", &self.user_agent)
}
fn ureq_delete(&self, path: String) -> Request {
delete(&path)
.set("X-Api-Key", &self.api_key)
.set("User-Agent", &self.user_agent)
}
/// Get a list of [`Check`]s.
pub fn get_checks(&self) -> ApiResult<Vec<Check>> {
#[derive(serde::Deserialize)]
struct ChecksResult {
pub checks: Vec<Check>,
}
let r = self.ureq_get(format!("{}/{}", HEALTHCHECK_API_URL, "checks"));
match r.call() {
Ok(response) => Ok(response.into_json::<ChecksResult>()?.checks),
Err(Error::Status(401, _)) => Err(HealthchecksApiError::InvalidApiKey),
Err(Error::Status(_, response)) => Err(HealthchecksApiError::UnexpectedError(
response.into_string()?,
)),
Err(Error::Transport(err)) => Err(HealthchecksApiError::TransportError(Box::new(err))),
}
}
/// Get a [`Check`] with the given UUID or unique key.
pub fn get_check(&self, check_id: &str) -> ApiResult<Check> {
let r = self.ureq_get(format!("{}/{}/{}", HEALTHCHECK_API_URL, "checks", check_id));
match r.call() {
Ok(response) => Ok(response.into_json::<Check>()?),
Err(Error::Status(401, _)) => Err(HealthchecksApiError::InvalidApiKey),
Err(Error::Status(403, _)) => Err(HealthchecksApiError::AccessDenied),
Err(Error::Status(404, _)) => {
Err(HealthchecksApiError::NoCheckFound(check_id.to_string()))
}
Err(Error::Status(_, response)) => Err(HealthchecksApiError::UnexpectedError(
response.into_string()?,
)),
Err(Error::Transport(err)) => Err(HealthchecksApiError::TransportError(Box::new(err))),
}
}
/// Returns a list of [`Channel`]s belonging to the project.
pub fn get_channels(&self) -> ApiResult<Vec<Channel>> {
#[derive(serde::Deserialize)]
struct ChannelsResult {
pub channels: Vec<Channel>,
}
let r = self.ureq_get(format!("{}/{}", HEALTHCHECK_API_URL, "channels"));
match r.call() {
Ok(response) => Ok(response.into_json::<ChannelsResult>()?.channels),
Err(Error::Status(401, _)) => Err(HealthchecksApiError::PossibleReadOnlyKey),
Err(Error::Status(_, response)) => Err(HealthchecksApiError::UnexpectedError(
response.into_string()?,
)),
Err(Error::Transport(err)) => Err(HealthchecksApiError::TransportError(Box::new(err))),
}
}
/// Pauses the [`Check`] with the given UUID or unique key.
pub fn pause(&self, check_id: &str) -> ApiResult<Check> {
let r = self.ureq_post(format!("{}/checks/{}/pause", HEALTHCHECK_API_URL, check_id));
match r.call() {
Ok(response) => Ok(response.into_json::<Check>()?),
Err(Error::Status(401, _)) => Err(HealthchecksApiError::PossibleReadOnlyKey),
Err(Error::Status(403, _)) => Err(HealthchecksApiError::AccessDenied),
Err(Error::Status(404, _)) => {
Err(HealthchecksApiError::NoCheckFound(check_id.to_string()))
}
Err(Error::Status(_, response)) => Err(HealthchecksApiError::UnexpectedError(
response.into_string()?,
)),
Err(Error::Transport(err)) => Err(HealthchecksApiError::TransportError(Box::new(err))),
}
}
/// Get a list of check's logged pings with the given UUID or unique key.
pub fn list_logged_pings(&self, check_id: &str) -> ApiResult<Vec<Ping>> {
#[derive(serde::Deserialize)]
struct PingsResult {
pub pings: Vec<Ping>,
}
let r = self.ureq_post(format!("{}/checks/{}/pings", HEALTHCHECK_API_URL, check_id));
match r.send_string("") {
Ok(response) => Ok(response.into_json::<PingsResult>()?.pings),
Err(Error::Status(401, _)) => Err(HealthchecksApiError::InvalidApiKey),
Err(Error::Status(403, _)) => Err(HealthchecksApiError::AccessDenied),
Err(Error::Status(404, _)) => {
Err(HealthchecksApiError::NoCheckFound(check_id.to_string()))
}
Err(Error::Status(_, response)) => Err(HealthchecksApiError::UnexpectedError(
response.into_string()?,
)),
Err(Error::Transport(err)) => Err(HealthchecksApiError::TransportError(Box::new(err))),
}
}
/// Get a list of check's status changes with the given UUID or unique key.
pub fn list_status_changes(&self, check_id: &str) -> ApiResult<Vec<Flip>> {
let r = self.ureq_post(format!("{}/checks/{}/flips", HEALTHCHECK_API_URL, check_id));
match r.call() {
Ok(response) => Ok(response.into_json::<Vec<Flip>>()?),
Err(Error::Status(401, _)) => Err(HealthchecksApiError::InvalidApiKey),
Err(Error::Status(403, _)) => Err(HealthchecksApiError::AccessDenied),
Err(Error::Status(404, _)) => {
Err(HealthchecksApiError::NoCheckFound(check_id.to_string()))
}
Err(Error::Status(_, response)) => Err(HealthchecksApiError::UnexpectedError(
response.into_string()?,
)),
Err(Error::Transport(err)) => Err(HealthchecksApiError::TransportError(Box::new(err))),
}
}
/// Deletes the [`Check`] with the given UUID or unique key.
pub fn delete(&self, check_id: &str) -> ApiResult<Check> {
let r = self.ureq_delete(format!("{}/{}/{}", HEALTHCHECK_API_URL, "checks", check_id));
match r.call() {
Ok(response) => Ok(response.into_json::<Check>()?),
Err(Error::Status(401, _)) => Err(HealthchecksApiError::InvalidApiKey),
Err(Error::Status(403, _)) => Err(HealthchecksApiError::AccessDenied),
Err(Error::Status(404, _)) => {
Err(HealthchecksApiError::NoCheckFound(check_id.to_string()))
}
Err(Error::Status(_, response)) => Err(HealthchecksApiError::UnexpectedError(
response.into_string()?,
)),
Err(Error::Transport(err)) => Err(HealthchecksApiError::TransportError(Box::new(err))),
}
}
/// Creates a new check with the given [`NewCheck`] configuration.
pub fn create_check(&self, check: NewCheck) -> ApiResult<Check> {
let check_json = serde_json::to_value(check)?;
let r = self.ureq_post(format!("{}/{}/", HEALTHCHECK_API_URL, "checks"));
match r
.set("Content-Type", "application/json")
.send_json(check_json)
{
Ok(response) => match response.status() {
201 => Ok(response.into_json::<Check>()?),
200 => Err(HealthchecksApiError::ExistingCheckMatched),
_ => Err(HealthchecksApiError::UnexpectedError(format!(
"Invalid result code: {}",
response.status()
))),
},
Err(Error::Status(400, _)) => Err(HealthchecksApiError::NotWellFormed),
Err(Error::Status(401, _)) => Err(HealthchecksApiError::InvalidApiKey),
Err(Error::Status(403, _)) => Err(HealthchecksApiError::CheckLimitReached),
Err(Error::Status(_, response)) => Err(HealthchecksApiError::UnexpectedError(
response.into_string()?,
)),
Err(Error::Transport(err)) => Err(HealthchecksApiError::TransportError(Box::new(err))),
}
}
/// Update the check with the given `check_id` with the data from `check`.
pub fn update_check(&self, check: UpdatedCheck, check_id: &str) -> ApiResult<Check> {
let check_json = serde_json::to_value(check)?;
let r = self.ureq_post(format!("{}/{}/{}", HEALTHCHECK_API_URL, "checks", check_id));
match r
.set("Content-Type", "application/json")
.send_json(check_json)
{
Ok(response) => Ok(response.into_json::<Check>()?),
Err(Error::Status(400, _)) => Err(HealthchecksApiError::NotWellFormed),
Err(Error::Status(401, _)) => Err(HealthchecksApiError::InvalidApiKey),
Err(Error::Status(403, _)) => Err(HealthchecksApiError::AccessDenied),
Err(Error::Status(404, _)) => {
Err(HealthchecksApiError::NoCheckFound(check_id.to_string()))
}
Err(Error::Status(_, response)) => Err(HealthchecksApiError::UnexpectedError(
response.into_string()?,
)),
Err(Error::Transport(err)) => Err(HealthchecksApiError::TransportError(Box::new(err))),
}
}
}
| 44.411017 | 99 | 0.585154 |
0efb47197ad3726900894d2c693c946b2992b319 | 3,776 | use serde::de::{self, Deserialize, Deserializer, Error as DeError};
use serde::ser::{Serialize, Serializer};
use ::overlay::{Color as OverlayColor, Outline as OverlayOutline};
use ::utils::RGB;
impl Serialize for Color {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(format!("#{:02X}{:02X}{:02X}",self.red,self.green,self.blue).as_str())
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
enum JsonColor {
Hex(String),
Struct{
red: u8,
green: u8,
blue: u8,
}
}
impl<'de> Deserialize<'de> for Color {
fn deserialize<D>(deserializer: D) -> Result<Color, D::Error>
where D: Deserializer<'de>
{
let json_color : JsonColor = JsonColor::deserialize(deserializer)?;
match json_color {
JsonColor::Hex(string) => {
let mut chars_iter = string.trim().chars();
if chars_iter.next() == Some('#') {
match ::read_color::rgb(&mut chars_iter) {
None => Err(D::Error::custom(format!("Color {} is not valid", string.trim()))),
Some(answer) => {
Ok(Color {
red: answer[0],
green: answer[1],
blue: answer[2],
})
}
}
} else {
Err(D::Error::custom(format!("Color must be of the format #RRGGBB; found {}", string.trim())))
}
},
JsonColor::Struct{red, green, blue} => Ok(Color {red, green, blue})
}
}
}
#[derive(Debug,Clone,Copy,PartialEq)]
pub struct Color {
pub red: u8,
pub green: u8,
pub blue: u8,
}
impl Default for Color {
fn default() -> Color {
Color {
red: 0,
green: 0,
blue: 0,
}
}
}
impl From<OverlayColor> for Color {
fn from(c: OverlayColor) -> Color {
Color {
red: c.red,
green: c.green,
blue: c.blue,
}
}
}
impl From<Color> for OverlayColor {
fn from(c: Color) -> OverlayColor {
OverlayColor {
red: c.red,
green: c.green,
blue: c.blue,
}
}
}
impl RGB for Color {
fn r(&self) -> u8 {
self.red
}
fn g(&self) -> u8 {
self.green
}
fn b(&self) -> u8 {
self.blue
}
fn new(r: u8, g: u8, b: u8) -> Color {
Color {
red: r,
green: g,
blue: b,
}
}
}
#[derive(Debug,Clone,Copy,Serialize,Deserialize)]
pub struct Outline {
pub color: Color,
pub size: u8,
}
impl From<OverlayOutline> for Outline {
fn from(o: OverlayOutline) -> Outline {
match o {
OverlayOutline::None => {
Outline {
color: Color::default(),
size: 0,
}
}
OverlayOutline::Light(color) => {
Outline {
color: Color::from(color),
size: 1,
}
}
OverlayOutline::Bold(color) => {
Outline {
color: Color::from(color),
size: 2,
}
}
}
}
}
impl From<Outline> for OverlayOutline {
fn from(o: Outline) -> OverlayOutline {
match o.size {
0 => OverlayOutline::None,
1 => OverlayOutline::Light(OverlayColor::from(o.color)),
_ => OverlayOutline::Bold(OverlayColor::from(o.color)),
}
}
}
| 25.342282 | 114 | 0.458157 |
e8a12247cbffaeafac328712981dee90af3741b6 | 1,657 | // Copyright 2013-2014 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// 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.
extern crate cgmath;
use cgmath::{Angle, Rad, Deg, rad, deg};
use cgmath::{ToRad, ToDeg};
use cgmath::ApproxEq;
#[test]
fn conv() {
assert!(deg(-5.0f64).to_rad().to_deg().approx_eq(°(-5.0f64)));
assert!(deg(30.0f64).to_rad().to_deg().approx_eq(°(30.0f64)));
assert!(rad(-5.0f64).to_deg().to_rad().approx_eq(&rad(-5.0f64)));
assert!(rad(30.0f64).to_deg().to_rad().approx_eq(&rad(30.0f64)));
}
#[test]
fn equiv() {
assert!(Deg::<f32>::full_turn().equiv(&-Deg::<f32>::full_turn()));
assert!(Deg::<f32>::turn_div_2().equiv(&-Deg::<f32>::turn_div_2()));
assert!(Deg::<f32>::turn_div_3().sub_a(Deg::<f32>::full_turn()).equiv(&Deg::<f32>::turn_div_3()));
assert!(Rad::<f32>::full_turn().equiv(&-Rad::<f32>::full_turn()));
assert!(Rad::<f32>::turn_div_2().equiv(&-Rad::<f32>::turn_div_2()));
assert!(Rad::<f32>::turn_div_3().sub_a(Rad::<f32>::full_turn()).equiv(&Rad::<f32>::turn_div_3()));
}
| 40.414634 | 102 | 0.671092 |
f4ee1ef77a018e19bb7b1b54c79caa59a6442400 | 5,060 | use super::{Map, TileType};
use rltk::{FontCharType, RGB};
pub fn tile_glyph(idx: usize, map: &Map) -> (FontCharType, RGB, RGB) {
let (glyph, mut fg, mut bg) = match map.depth {
2 => get_forest_glyph(idx, map),
_ => get_tile_glyph_default(idx, map),
};
if map.visible_tiles[idx] {
if map.bloodstains.contains(&idx) {
bg = RGB::from_f32(0.75, 0.0, 0.0);
}
} else {
fg = fg.to_greyscale()
}
(glyph, fg, bg)
}
fn get_tile_glyph_default(idx: usize, map: &Map) -> (FontCharType, RGB, RGB) {
let glyph;
let fg;
let bg = RGB::from_f32(0.0, 0.0, 0.0);
match map.tiles[idx] {
TileType::Floor => {
glyph = rltk::to_cp437('.');
fg = RGB::from_f32(0.0, 0.5, 0.5);
}
TileType::WoodFloor => {
glyph = rltk::to_cp437('░');
fg = RGB::named(rltk::CHOCOLATE);
}
TileType::Wall => {
let x = idx as i32 % map.width;
let y = idx as i32 / map.width;
glyph = wall_glyph(&map, x, y);
fg = RGB::from_f32(0.0, 1.0, 0.0);
}
TileType::DownStairs => {
glyph = rltk::to_cp437('>');
fg = RGB::from_f32(0.0, 1.0, 1.0);
}
TileType::UpStairs => {
glyph = rltk::to_cp437('<');
fg = RGB::from_f32(0.0, 1.0, 1.0);
}
TileType::Bridge => {
glyph = rltk::to_cp437('▒');
fg = RGB::named(rltk::CHOCOLATE);
}
TileType::Road => {
glyph = rltk::to_cp437('≡');
fg = RGB::named(rltk::GRAY);
}
TileType::Grass => {
glyph = rltk::to_cp437('"');
fg = RGB::named(rltk::GREEN);
}
TileType::ShallowWater => {
glyph = rltk::to_cp437('~');
fg = RGB::named(rltk::CYAN);
}
TileType::DeepWater => {
glyph = rltk::to_cp437('~');
fg = RGB::named(rltk::BLUE);
}
TileType::Gravel => {
glyph = rltk::to_cp437(';');
fg = RGB::named(rltk::GRAY);
}
}
(glyph, fg, bg)
}
fn wall_glyph(map: &Map, x: i32, y: i32) -> FontCharType {
if x < 0 || x >= map.width || y < 0 || y >= map.height {
return 35;
}
let mut mask: u8 = 0;
if is_revealed_and_wall(map, x, y - 1) {
mask += 1;
}
if is_revealed_and_wall(map, x, y + 1) {
mask += 2;
}
if is_revealed_and_wall(map, x - 1, y) {
mask += 4;
}
if is_revealed_and_wall(map, x + 1, y) {
mask += 8;
}
match mask {
0 => 9, // Pillar because we can't see neighbors
1 => 186, // Wall only to the north
2 => 186, // Wall only to the south
3 => 186, // Wall to the north and south
4 => 205, // Wall only to the west
5 => 188, // Wall to the north and west
6 => 187, // Wall to the south and west
7 => 185, // Wall to the north, south and west
8 => 205, // Wall only to the east
9 => 200, // Wall to the north and east
10 => 201, // Wall to the south and east
11 => 204, // Wall to the north, south and east
12 => 205, // Wall to the east and west
13 => 202, // Wall to the east, west, and south
14 => 203, // Wall to the east, west, and north
15 => 206, // ╬ Wall on all sides
_ => 35, // We missed one?
}
}
fn is_revealed_and_wall(map: &Map, x: i32, y: i32) -> bool {
if x < 0 || x >= map.width || y < 0 || y >= map.height {
return false;
}
let idx = map.xy_idx(x, y);
map.tiles[idx] == TileType::Wall && map.revealed_tiles[idx]
}
fn get_forest_glyph(idx: usize, map: &Map) -> (FontCharType, RGB, RGB) {
let glyph;
let fg;
let bg = RGB::from_f32(0.0, 0.0, 0.0);
match map.tiles[idx] {
TileType::Wall => {
glyph = rltk::to_cp437('♣');
fg = RGB::from_f32(0.0, 0.6, 0.0);
}
TileType::Bridge => {
glyph = rltk::to_cp437('.');
fg = RGB::named(rltk::CHOCOLATE);
}
TileType::Road => {
glyph = rltk::to_cp437('≡');
fg = RGB::named(rltk::YELLOW);
}
TileType::Grass => {
glyph = rltk::to_cp437('"');
fg = RGB::named(rltk::GREEN);
}
TileType::ShallowWater => {
glyph = rltk::to_cp437('~');
fg = RGB::named(rltk::CYAN);
}
TileType::DeepWater => {
glyph = rltk::to_cp437('~');
fg = RGB::named(rltk::BLUE);
}
TileType::Gravel => {
glyph = rltk::to_cp437(';');
fg = RGB::from_f32(0.5, 0.5, 0.5);
}
TileType::DownStairs => {
glyph = rltk::to_cp437('>');
fg = RGB::from_f32(0.0, 1.0, 1.0);
}
_ => {
glyph = rltk::to_cp437('"');
fg = RGB::from_f32(0.0, 0.6, 0.0);
}
}
(glyph, fg, bg)
}
| 29.418605 | 78 | 0.461858 |
38ff5a82bcfe8d68ef40c9a497e9112d1d3c09cb | 2,009 | use chromiumoxide_cdp::cdp::browser_protocol::emulation::{
ScreenOrientation, ScreenOrientationType, SetDeviceMetricsOverrideParams,
SetTouchEmulationEnabledParams,
};
use chromiumoxide_types::Method;
use crate::cmd::CommandChain;
use crate::handler::viewport::Viewport;
use std::time::Duration;
#[derive(Debug)]
pub struct EmulationManager {
pub emulating_mobile: bool,
pub has_touch: bool,
pub needs_reload: bool,
pub request_timeout: Duration,
}
impl EmulationManager {
pub fn new(request_timeout: Duration) -> Self {
Self {
emulating_mobile: false,
has_touch: false,
needs_reload: false,
request_timeout,
}
}
pub fn init_commands(&mut self, viewport: &Viewport) -> CommandChain {
let orientation = if viewport.is_landscape {
ScreenOrientation::new(ScreenOrientationType::LandscapePrimary, 90)
} else {
ScreenOrientation::new(ScreenOrientationType::PortraitPrimary, 0)
};
let set_device = SetDeviceMetricsOverrideParams::builder()
.mobile(viewport.emulating_mobile)
.width(viewport.width)
.height(viewport.height)
.device_scale_factor(viewport.device_scale_factor.unwrap_or(1.))
.screen_orientation(orientation)
.build()
.unwrap();
let set_touch = SetTouchEmulationEnabledParams::new(true);
let chain = CommandChain::new(
vec![
(
set_device.identifier(),
serde_json::to_value(set_device).unwrap(),
),
(
set_touch.identifier(),
serde_json::to_value(set_touch).unwrap(),
),
],
self.request_timeout,
);
self.needs_reload = self.emulating_mobile != viewport.emulating_mobile
|| self.has_touch != viewport.has_touch;
chain
}
}
| 30.439394 | 79 | 0.60229 |
7986191f858067daf4394bee09e5b7a0eb1f3438 | 567 | use reqwest::Certificate;
use crate::core::Result;
use std::io::Read;
use std::{fs::File, path::Path};
pub fn load<P: AsRef<Path>>(path: P) -> Result<Certificate> {
let mut buf = Vec::new();
File::open(&path)?.read_to_end(&mut buf)?;
let cert = certificate(path, &buf)?;
Ok(cert)
}
fn certificate<P: AsRef<Path>>(path: P, buf: &[u8]) -> Result<Certificate> {
let cert = if Some(std::ffi::OsStr::new("der")) == path.as_ref().extension() {
Certificate::from_der(buf)
} else {
Certificate::from_pem(buf)
}?;
Ok(cert)
}
| 25.772727 | 82 | 0.599647 |
4878005268dc77d5325496dc3b5f2f62847c238a | 13,780 | use crate::numbers::*;
#[cfg(all(feature = "use_simd"))]
use packed_simd::*;
use std;
use std::mem;
use std::ops::*;
mod simd_partition;
pub use self::simd_partition::{EdgeIteratorMut, IndexedEdgeIteratorMut, SimdPartition};
/// SIMD methods which have `f32` or `f64` specific implementation.
pub trait Simd<T>: Sized
where
T: Sized + Sync + Send,
{
/// The type of real valued array which matches a SIMD register.
type Array;
/// SIMD register to array.
fn to_array(self) -> Self::Array;
/// The type of complex valued array which matches a SIMD register.
type ComplexArray;
/// Number of elements in a SIMD register.
const LEN: usize;
/// Creates a SIMD register loaded with a complex value.
fn from_complex(value: Complex<T>) -> Self;
/// Add a real number to the register.
fn add_real(self, value: T) -> Self;
/// Add a complex number to the register.
fn add_complex(self, value: Complex<T>) -> Self;
/// Scale the register by a real number.
fn scale_real(self, value: T) -> Self;
/// Scale the register by a complex number.
fn scale_complex(self, value: Complex<T>) -> Self;
/// Store the complex norm squared in the first half of the vector.
fn complex_abs_squared(self) -> Self;
/// Store the complex norm in the first half of the vector.
fn complex_abs(self) -> Self;
/// Calculates the square root of the register.
fn sqrt(self) -> Self;
/// Stores the first half of the vector in an array.
/// Useful e.g. in combination with `complex_abs_squared`.
fn store_half(self, target: &mut [T], index: usize);
/// Multiplies the register with a complex value.
fn mul_complex(self, value: Self) -> Self;
/// Divides the register by a complex value.
fn div_complex(self, value: Self) -> Self;
/// Calculates the sum of all register elements, assuming that they
/// are real valued.
fn sum_real(&self) -> T;
/// Calculates the sum of all register elements, assuming that they
/// are complex valued.
fn sum_complex(&self) -> Complex<T>;
fn max(self, other: Self) -> Self;
fn min(self, other: Self) -> Self;
// Swaps I and Q (or Real and Imag) of a complex vector
fn swap_iq(self) -> Self;
}
/// Dirty workaround since the stdsimd doesn't implement conversion traits (yet?).
pub trait SimdFrom<T> {
fn regfrom(src: T) -> Self;
}
/// SIMD methods which share their implementation independent if it's a `f32` or `f64` register.
pub trait SimdGeneric<T>:
Simd<T>
+ SimdApproximations<T>
+ Add<Self, Output = Self>
+ Sub<Self, Output = Self>
+ Mul<Self, Output = Self>
+ Div<Self, Output = Self>
+ Copy
+ Clone
+ Sync
+ Send
+ Sized
+ Zero
where
T: Sized + Sync + Send,
{
/// On some CPU architectures memory access needs to be aligned or otherwise
/// the process will crash. This method takes a vector an divides it in three ranges:
/// beginning, center, end. Beginning and end may not be loaded directly as SIMD registers.
/// Center will contain most of the data.
fn calc_data_alignment_reqs(array: &[T]) -> SimdPartition<T>;
/// Converts a real valued array which has exactly the size of a SIMD register
/// into a SIMD register.
fn from_array(array: Self::Array) -> Self;
/// Converts the SIMD register into a complex valued array.
fn to_complex_array(self) -> Self::ComplexArray;
/// Converts a complex valued array which has exactly the size of a SIMD register
/// into a SIMD register.
fn from_complex_array(array: Self::ComplexArray) -> Self;
/// Executed the given function on each element of the register.
/// Register elements are assumed to be real valued.
fn iter_over_vector<F>(self, op: F) -> Self
where
F: FnMut(T) -> T;
/// Executed the given function on each element of the register.
/// Register elements are assumed to be complex valued.
fn iter_over_complex_vector<F>(self, op: F) -> Self
where
F: FnMut(Complex<T>) -> Complex<T>;
/// Converts an array slice into a slice of SIMD registers.
///
/// WARNING: `calc_data_alignment_reqs` must have been used before to ensure that
/// data is loaded with the proper memory alignment. Code will panic otherwise.
fn array_to_regs(array: &[T]) -> &[Self];
/// Converts a mutable array slice into a slice of mutable SIMD registers.
///
/// WARNING: `calc_data_alignment_reqs` must have been used before to ensure that
/// data is loaded with the proper memory alignment. Code will panic otherwise.
fn array_to_regs_mut(array: &mut [T]) -> &mut [Self];
/// Loads a SIMD register from an array without any bound checks.
fn load(array: &[T], idx: usize) -> Self;
/// Stores a SIMD register into an array.
fn store(self, array: &mut [T], index: usize);
/// Returns one element from the register.
fn extract(self, idx: usize) -> T;
/// Creates a new SIMD register where every element equals `value`.
fn splat(value: T) -> Self;
}
/// Approximated and faster implementation of some numeric standard function.
/// The approximations are implemented based on SIMD registers.
/// Refer to the documentation of the `ApproximatedOps` trait (which is part of
/// the public API of this lib) for some information about accuracy and speed.
pub trait SimdApproximations<T> {
/// Returns the natural logarithm of the number.
fn ln_approx(self) -> Self;
/// Returns `e^(self)`, (the exponential function).
fn exp_approx(self) -> Self;
/// Computes the sine of a number (in radians).
fn sin_approx(self) -> Self;
/// Computes the cosine of a number (in radians).
fn cos_approx(self) -> Self;
/// An implementation detail which leaked into the trait defintion
/// for convenience. Use `sin_approx` or `cos_approx` instead of this
/// function.
///
/// Since the implementation of sine and cosine is almost identical
/// the implementation is easier with a boolean `is_sin` flag which
/// determines if the sine or cosine is requried.
fn sin_cos_approx(self, is_sin: bool) -> Self;
}
fn get_alignment_offset(addr: usize, reg_len: usize) -> usize {
addr % reg_len
}
macro_rules! simd_generic_impl {
($data_type:ident, $mod: ident::$reg:ident) => {
impl Zero for $mod::$reg {
fn zero() -> Self {
Self::splat(0.0)
}
}
impl SimdGeneric<$data_type> for $mod::$reg {
#[inline]
fn calc_data_alignment_reqs(array: &[$data_type]) -> SimdPartition<$data_type> {
let data_length = array.len();
let addr = array.as_ptr();
let left = get_alignment_offset(addr as usize, mem::size_of::<Self>());
assert!(left % mem::size_of::<$data_type>() == 0);
let left = left / mem::size_of::<$data_type>();
if left + Self::LEN > data_length {
SimdPartition::new_all_scalar(data_length)
} else {
let right = (data_length - left) % Self::LEN;
SimdPartition::new_simd(left, right, data_length)
}
}
#[inline]
fn from_array(array: Self::Array) -> Self {
Self::load(&array, 0)
}
#[inline]
fn to_complex_array(self) -> Self::ComplexArray {
unsafe { mem::transmute(self.to_array()) }
}
#[inline]
fn from_complex_array(array: Self::ComplexArray) -> Self {
Self::from_array(unsafe { mem::transmute(array) })
}
#[inline]
fn iter_over_vector<F>(self, mut op: F) -> Self
where
F: FnMut($data_type) -> $data_type,
{
let mut array = self.to_array();
for n in &mut array {
*n = op(*n);
}
Self::from_array(array)
}
#[inline]
fn iter_over_complex_vector<F>(self, mut op: F) -> Self
where
F: FnMut(Complex<$data_type>) -> Complex<$data_type>,
{
let mut array = self.to_complex_array();
for n in &mut array[0..Self::LEN / 2] {
*n = op(*n);
}
Self::from_complex_array(array)
}
#[inline]
fn array_to_regs(array: &[$data_type]) -> &[Self] {
if array.is_empty() {
return &[];
}
assert_eq!(
get_alignment_offset(array.as_ptr() as usize, mem::size_of::<Self>()),
0
);
super::transmute_slice(array)
}
#[inline]
fn array_to_regs_mut(array: &mut [$data_type]) -> &mut [Self] {
if array.is_empty() {
return &mut [];
}
assert_eq!(
get_alignment_offset(array.as_ptr() as usize, mem::size_of::<Self>()),
0
);
super::transmute_slice_mut(array)
}
#[inline]
fn load(array: &[$data_type], idx: usize) -> Self {
Self::from_slice_unaligned(&array[idx..idx + Self::LEN])
}
#[inline]
fn store(self, array: &mut [$data_type], index: usize) {
self.write_to_slice_unaligned(&mut array[index..index + Self::LEN])
}
#[inline]
fn extract(self, idx: usize) -> $data_type {
$mod::$reg::extract(self, idx)
}
#[inline]
fn splat(value: $data_type) -> Self {
Self::splat(value)
}
}
};
}
#[cfg(feature = "use_avx512")]
pub mod avx512;
#[cfg(feature = "use_avx512")]
simd_generic_impl!(f32, avx512::f32x16); // Type isn't implemented in simd
#[cfg(feature = "use_avx512")]
simd_generic_impl!(f64, avx512::f64x8); // Type isn't implemented in simd
#[cfg(all(feature = "use_avx2", target_feature = "avx2"))]
pub mod avx;
#[cfg(all(feature = "use_avx2", target_feature = "avx2"))]
simd_generic_impl!(f32, avx::f32x8);
#[cfg(all(feature = "use_avx2", target_feature = "avx2"))]
simd_generic_impl!(f64, avx::f64x4);
#[cfg(feature = "use_sse2")]
pub mod sse;
#[cfg(all(feature = "use_sse2", target_feature = "sse2"))]
simd_generic_impl!(f32, sse::f32x4);
#[cfg(all(feature = "use_sse2", target_feature = "sse2"))]
simd_generic_impl!(f64, sse::f64x2);
#[cfg(feature = "use_simd")]
mod approximations;
mod approx_fallback;
pub mod fallback;
simd_generic_impl!(f32, fallback::f32x4);
simd_generic_impl!(f64, fallback::f64x2);
pub struct RegType<Reg> {
_type: std::marker::PhantomData<Reg>,
}
impl<Reg> RegType<Reg> {
pub fn new() -> Self {
RegType {
_type: std::marker::PhantomData,
}
}
}
/// Selects a SIMD register type and passes it as 2nd argument to a function.
/// The macro tries to mimic the Rust syntax of a method call.
macro_rules! sel_reg(
($self_:ident.$method: ident::<$type: ident>($($args: expr),*)) => {
if is_x86_feature_detected!("avx512vl") && cfg!(feature="use_avx512") {
$self_.$method(RegType::<<$type as ToSimd>::RegAvx512>::new(), $($args),*)
} else if is_x86_feature_detected!("avx2") && cfg!(feature="use_avx2") {
$self_.$method(RegType::<<$type as ToSimd>::RegAvx>::new(), $($args),*)
} else if is_x86_feature_detected!("sse2") && cfg!(feature="use_sse2") {
$self_.$method(RegType::<<$type as ToSimd>::RegSse>::new(), $($args),*)
} else {
$self_.$method(RegType::<<$type as ToSimd>::RegFallback>::new(), $($args),*)
}
};
($method: ident::<$type: ident>($($args: expr),*)) => {
if is_x86_feature_detected!("avx512vl") && cfg!(feature="use_avx512") {
$method(RegType::<<$type as ToSimd>::RegAvx512>::new(), $($args),*)
} else if is_x86_feature_detected!("avx2") && cfg!(feature="use_avx2") && cfg!(target_feature="avx2") {
$method(RegType::<<$type as ToSimd>::RegAvx>::new(), $($args),*)
} else if is_x86_feature_detected!("sse2") && cfg!(feature="use_sse2")&& cfg!(target_feature="sse2") {
$method(RegType::<<$type as ToSimd>::RegSse>::new(), $($args),*)
} else {
$method(RegType::<<$type as ToSimd>::RegFallback>::new(), $($args),*)
}
};
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_alignment_offset_test() {
let reg_len = mem::size_of::<fallback::f64x2>();
assert_eq!(reg_len, 16);
assert_eq!(get_alignment_offset(0, reg_len), 0);
assert_eq!(get_alignment_offset(8, reg_len), 8);
assert_eq!(get_alignment_offset(16, reg_len), 0);
assert_eq!(get_alignment_offset(24, reg_len), 8);
}
#[cfg(all(feature = "use_avx2", target_feature = "avx2"))]
mod avx {
use super::super::*;
#[test]
fn get_alignment_offset_test() {
let reg_len = mem::size_of::<f64x4>();
assert_eq!(reg_len, 32);
assert_eq!(get_alignment_offset(0, reg_len), 0);
assert_eq!(get_alignment_offset(8, reg_len), 8);
assert_eq!(get_alignment_offset(16, reg_len), 16);
assert_eq!(get_alignment_offset(24, reg_len), 24);
assert_eq!(get_alignment_offset(32, reg_len), 0);
assert_eq!(get_alignment_offset(40, reg_len), 8);
}
}
}
| 34.886076 | 111 | 0.58643 |
9b9e25326f9663b11e84984b0acb71e59ffc1cfa | 12,440 | use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::higher;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{path_to_local, usage::is_potentially_mutated};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, Visitor};
use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, PathSegment, UnOp};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::nested_filter;
use rustc_middle::lint::in_external_macro;
use rustc_middle::ty::Ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// Checks for calls of `unwrap[_err]()` that cannot fail.
///
/// ### Why is this bad?
/// Using `if let` or `match` is more idiomatic.
///
/// ### Example
/// ```rust
/// # let option = Some(0);
/// # fn do_something_with(_x: usize) {}
/// if option.is_some() {
/// do_something_with(option.unwrap())
/// }
/// ```
///
/// Could be written:
///
/// ```rust
/// # let option = Some(0);
/// # fn do_something_with(_x: usize) {}
/// if let Some(value) = option {
/// do_something_with(value)
/// }
/// ```
#[clippy::version = "pre 1.29.0"]
pub UNNECESSARY_UNWRAP,
complexity,
"checks for calls of `unwrap[_err]()` that cannot fail"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for calls of `unwrap[_err]()` that will always fail.
///
/// ### Why is this bad?
/// If panicking is desired, an explicit `panic!()` should be used.
///
/// ### Known problems
/// This lint only checks `if` conditions not assignments.
/// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
///
/// ### Example
/// ```rust
/// # let option = Some(0);
/// # fn do_something_with(_x: usize) {}
/// if option.is_none() {
/// do_something_with(option.unwrap())
/// }
/// ```
///
/// This code will always panic. The if condition should probably be inverted.
#[clippy::version = "pre 1.29.0"]
pub PANICKING_UNWRAP,
correctness,
"checks for calls of `unwrap[_err]()` that will always fail"
}
/// Visitor that keeps track of which variables are unwrappable.
struct UnwrappableVariablesVisitor<'a, 'tcx> {
unwrappables: Vec<UnwrapInfo<'tcx>>,
cx: &'a LateContext<'tcx>,
}
/// What kind of unwrappable this is.
#[derive(Copy, Clone, Debug)]
enum UnwrappableKind {
Option,
Result,
}
impl UnwrappableKind {
fn success_variant_pattern(self) -> &'static str {
match self {
UnwrappableKind::Option => "Some(..)",
UnwrappableKind::Result => "Ok(..)",
}
}
fn error_variant_pattern(self) -> &'static str {
match self {
UnwrappableKind::Option => "None",
UnwrappableKind::Result => "Err(..)",
}
}
}
/// Contains information about whether a variable can be unwrapped.
#[derive(Copy, Clone, Debug)]
struct UnwrapInfo<'tcx> {
/// The variable that is checked
local_id: HirId,
/// The if itself
if_expr: &'tcx Expr<'tcx>,
/// The check, like `x.is_ok()`
check: &'tcx Expr<'tcx>,
/// The check's name, like `is_ok`
check_name: &'tcx PathSegment<'tcx>,
/// The branch where the check takes place, like `if x.is_ok() { .. }`
branch: &'tcx Expr<'tcx>,
/// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
safe_to_unwrap: bool,
/// What kind of unwrappable this is.
kind: UnwrappableKind,
/// If the check is the entire condition (`if x.is_ok()`) or only a part of it (`foo() &&
/// x.is_ok()`)
is_entire_condition: bool,
}
/// Collects the information about unwrappable variables from an if condition
/// The `invert` argument tells us whether the condition is negated.
fn collect_unwrap_info<'tcx>(
cx: &LateContext<'tcx>,
if_expr: &'tcx Expr<'_>,
expr: &'tcx Expr<'_>,
branch: &'tcx Expr<'_>,
invert: bool,
is_entire_condition: bool,
) -> Vec<UnwrapInfo<'tcx>> {
fn is_relevant_option_call(cx: &LateContext<'_>, ty: Ty<'_>, method_name: &str) -> bool {
is_type_diagnostic_item(cx, ty, sym::Option) && ["is_some", "is_none"].contains(&method_name)
}
fn is_relevant_result_call(cx: &LateContext<'_>, ty: Ty<'_>, method_name: &str) -> bool {
is_type_diagnostic_item(cx, ty, sym::Result) && ["is_ok", "is_err"].contains(&method_name)
}
if let ExprKind::Binary(op, left, right) = &expr.kind {
match (invert, op.node) {
(false, BinOpKind::And | BinOpKind::BitAnd) | (true, BinOpKind::Or | BinOpKind::BitOr) => {
let mut unwrap_info = collect_unwrap_info(cx, if_expr, left, branch, invert, false);
unwrap_info.append(&mut collect_unwrap_info(cx, if_expr, right, branch, invert, false));
return unwrap_info;
},
_ => (),
}
} else if let ExprKind::Unary(UnOp::Not, expr) = &expr.kind {
return collect_unwrap_info(cx, if_expr, expr, branch, !invert, false);
} else {
if_chain! {
if let ExprKind::MethodCall(method_name, args, _) = &expr.kind;
if let Some(local_id) = path_to_local(&args[0]);
let ty = cx.typeck_results().expr_ty(&args[0]);
let name = method_name.ident.as_str();
if is_relevant_option_call(cx, ty, name) || is_relevant_result_call(cx, ty, name);
then {
assert!(args.len() == 1);
let unwrappable = match name {
"is_some" | "is_ok" => true,
"is_err" | "is_none" => false,
_ => unreachable!(),
};
let safe_to_unwrap = unwrappable != invert;
let kind = if is_type_diagnostic_item(cx, ty, sym::Option) {
UnwrappableKind::Option
} else {
UnwrappableKind::Result
};
return vec![
UnwrapInfo {
local_id,
if_expr,
check: expr,
check_name: method_name,
branch,
safe_to_unwrap,
kind,
is_entire_condition,
}
]
}
}
}
Vec::new()
}
impl<'a, 'tcx> UnwrappableVariablesVisitor<'a, 'tcx> {
fn visit_branch(
&mut self,
if_expr: &'tcx Expr<'_>,
cond: &'tcx Expr<'_>,
branch: &'tcx Expr<'_>,
else_branch: bool,
) {
let prev_len = self.unwrappables.len();
for unwrap_info in collect_unwrap_info(self.cx, if_expr, cond, branch, else_branch, true) {
if is_potentially_mutated(unwrap_info.local_id, cond, self.cx)
|| is_potentially_mutated(unwrap_info.local_id, branch, self.cx)
{
// if the variable is mutated, we don't know whether it can be unwrapped:
continue;
}
self.unwrappables.push(unwrap_info);
}
walk_expr(self, branch);
self.unwrappables.truncate(prev_len);
}
}
impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
type NestedFilter = nested_filter::OnlyBodies;
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
// Shouldn't lint when `expr` is in macro.
if in_external_macro(self.cx.tcx.sess, expr.span) {
return;
}
if let Some(higher::If { cond, then, r#else }) = higher::If::hir(expr) {
walk_expr(self, cond);
self.visit_branch(expr, cond, then, false);
if let Some(else_inner) = r#else {
self.visit_branch(expr, cond, else_inner, true);
}
} else {
// find `unwrap[_err]()` calls:
if_chain! {
if let ExprKind::MethodCall(method_name, [self_arg, ..], _) = expr.kind;
if let Some(id) = path_to_local(self_arg);
if [sym::unwrap, sym::expect, sym!(unwrap_err)].contains(&method_name.ident.name);
let call_to_unwrap = [sym::unwrap, sym::expect].contains(&method_name.ident.name);
if let Some(unwrappable) = self.unwrappables.iter()
.find(|u| u.local_id == id);
// Span contexts should not differ with the conditional branch
let span_ctxt = expr.span.ctxt();
if unwrappable.branch.span.ctxt() == span_ctxt;
if unwrappable.check.span.ctxt() == span_ctxt;
then {
if call_to_unwrap == unwrappable.safe_to_unwrap {
let is_entire_condition = unwrappable.is_entire_condition;
let unwrappable_variable_name = self.cx.tcx.hir().name(unwrappable.local_id);
let suggested_pattern = if call_to_unwrap {
unwrappable.kind.success_variant_pattern()
} else {
unwrappable.kind.error_variant_pattern()
};
span_lint_and_then(
self.cx,
UNNECESSARY_UNWRAP,
expr.span,
&format!(
"called `{}` on `{}` after checking its variant with `{}`",
method_name.ident.name,
unwrappable_variable_name,
unwrappable.check_name.ident.as_str(),
),
|diag| {
if is_entire_condition {
diag.span_suggestion(
unwrappable.check.span.with_lo(unwrappable.if_expr.span.lo()),
"try",
format!(
"if let {} = {}",
suggested_pattern,
unwrappable_variable_name,
),
// We don't track how the unwrapped value is used inside the
// block or suggest deleting the unwrap, so we can't offer a
// fixable solution.
Applicability::Unspecified,
);
} else {
diag.span_label(unwrappable.check.span, "the check is happening here");
diag.help("try using `if let` or `match`");
}
},
);
} else {
span_lint_and_then(
self.cx,
PANICKING_UNWRAP,
expr.span,
&format!("this call to `{}()` will always panic",
method_name.ident.name),
|diag| { diag.span_label(unwrappable.check.span, "because of this check"); },
);
}
}
}
walk_expr(self, expr);
}
}
fn nested_visit_map(&mut self) -> Self::Map {
self.cx.tcx.hir()
}
}
declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
impl<'tcx> LateLintPass<'tcx> for Unwrap {
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
kind: FnKind<'tcx>,
decl: &'tcx FnDecl<'_>,
body: &'tcx Body<'_>,
span: Span,
fn_id: HirId,
) {
if span.from_expansion() {
return;
}
let mut v = UnwrappableVariablesVisitor {
cx,
unwrappables: Vec::new(),
};
walk_fn(&mut v, kind, decl, body.id(), span, fn_id);
}
}
| 37.69697 | 107 | 0.511013 |
e6712bc78f450001db0288cbaad2a9f0bae87398 | 52,491 | use std::mem;
use std::slice;
use std::i32;
use std::collections::{BTreeMap, HashMap};
use std::marker::PhantomData;
use std::hash::Hash;
use webcore::ffi;
use webcore::callfn::{CallOnce, CallMut};
use webcore::newtype::Newtype;
use webcore::try_from::{TryFrom, TryInto};
use webcore::number::Number;
use webcore::type_name::type_name;
use webcore::symbol::Symbol;
use webcore::unsafe_typed_array::UnsafeTypedArray;
use webcore::mutfn::Mut;
use webcore::once::Once;
use webcore::global_arena;
use webcore::value::{
Null,
Undefined,
Reference,
Value,
ConversionError
};
use webapi::error::TypeError;
#[repr(u8)]
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Tag {
Undefined = 0,
Null = 1,
I32 = 2,
F64 = 3,
Str = 4,
False = 5,
True = 6,
Array = 7,
Object = 8,
Reference = 9,
Function = 10,
FunctionMut = 12,
FunctionOnce = 13,
UnsafeTypedArray = 14,
Symbol = 15
}
impl Default for Tag {
#[inline]
fn default() -> Self {
Tag::Undefined
}
}
#[doc(hidden)]
pub trait JsSerializeOwned: Sized {
fn into_js_owned< 'a >( value: &'a mut Option< Self > ) -> SerializedValue< 'a >;
}
/// A trait for types which can be serialized through the `js!` macro.
///
/// Do **not** try to implement this trait yourself! It's only meant
/// to be used inside generic code for specifying trait bounds.
pub trait JsSerialize {
#[doc(hidden)]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a >;
}
// This is a generic structure for serializing every JavaScript value.
#[doc(hidden)]
#[repr(C)]
#[derive(Default, Debug)]
pub struct SerializedValue< 'a > {
data_1: u64,
data_2: u32,
tag: Tag,
phantom: PhantomData< &'a () >
}
#[test]
fn test_serialized_value_size() {
assert_eq!( mem::size_of::< SerializedValue< 'static > >(), 16 );
}
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedUndefined;
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedNull;
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedI32 {
value: i32
}
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedF64 {
value: f64
}
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedTrue {}
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedFalse {}
#[repr(C)]
#[derive(Clone, Debug)]
struct SerializedUntaggedString {
pointer: u32,
length: u32
}
#[repr(C)]
#[derive(Clone, Debug)]
struct SerializedUntaggedArray {
pointer: u32,
length: u32
}
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedObject {
value_pointer: u32,
length: u32,
key_pointer: u32
}
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedSymbol {
id: i32
}
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedReference {
refid: i32
}
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedFunction {
adapter_pointer: u32,
pointer: u32,
deallocator_pointer: u32
}
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedFunctionMut {
adapter_pointer: u32,
pointer: u32,
deallocator_pointer: u32
}
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedFunctionOnce {
adapter_pointer: u32,
pointer: u32,
deallocator_pointer: u32
}
#[repr(C)]
#[derive(Debug)]
struct SerializedUntaggedUnsafeTypedArray {
pointer: u32,
length: u32,
kind: u32
}
impl SerializedUntaggedString {
#[inline]
fn deserialize( &self ) -> String {
let pointer = self.pointer as *mut u8;
let length = self.length as usize;
if length == 0 {
return String::new();
}
unsafe {
let vector = Vec::from_raw_parts( pointer, length, length + 1 );
String::from_utf8_unchecked( vector )
}
}
}
impl SerializedUntaggedArray {
#[inline]
fn deserialize( &self ) -> Vec< Value > {
let pointer = self.pointer as *const SerializedValue;
let length = self.length as usize;
let slice = unsafe {
slice::from_raw_parts( pointer, length )
};
let vector = slice.iter().map( |value| value.deserialize() ).collect();
unsafe {
ffi::dealloc( pointer as *mut u8, length * mem::size_of::< SerializedValue >() );
}
vector
}
}
pub struct ObjectDeserializer< 'a > {
key_slice: &'a [SerializedUntaggedString],
value_slice: &'a [SerializedValue< 'a >],
index: usize
}
impl< 'a > Iterator for ObjectDeserializer< 'a > {
type Item = (String, Value);
fn next( &mut self ) -> Option< Self::Item > {
if self.index >= self.key_slice.len() {
None
} else {
let key = self.key_slice[ self.index ].deserialize();
let value = self.value_slice[ self.index ].deserialize();
self.index += 1;
Some( (key, value) )
}
}
#[inline]
fn size_hint( &self ) -> (usize, Option< usize >) {
let remaining = self.key_slice.len() - self.index;
(remaining, Some( remaining ))
}
}
impl< 'a > ExactSizeIterator for ObjectDeserializer< 'a > {}
pub fn deserialize_object< R, F: FnOnce( &mut ObjectDeserializer ) -> R >( reference: &Reference, callback: F ) -> R {
let mut result: SerializedValue = Default::default();
__js_raw_asm!( "\
var object = Module.STDWEB_PRIVATE.acquire_js_reference( $0 );\
Module.STDWEB_PRIVATE.serialize_object( $1, object );",
reference.as_raw(),
&mut result as *mut _
);
assert_eq!( result.tag, Tag::Object );
let result = result.as_object();
let length = result.length as usize;
let key_pointer = result.key_pointer as *const SerializedUntaggedString;
let value_pointer = result.value_pointer as *const SerializedValue;
let key_slice = unsafe { slice::from_raw_parts( key_pointer, length ) };
let value_slice = unsafe { slice::from_raw_parts( value_pointer, length ) };
let mut iter = ObjectDeserializer {
key_slice,
value_slice,
index: 0
};
let output = callback( &mut iter );
// TODO: Panic-safety.
unsafe {
ffi::dealloc( key_pointer as *mut u8, length * mem::size_of::< SerializedUntaggedString >() );
ffi::dealloc( value_pointer as *mut u8, length * mem::size_of::< SerializedValue >() );
}
output
}
pub struct ArrayDeserializer< 'a > {
slice: &'a [SerializedValue< 'a >],
index: usize
}
impl< 'a > Iterator for ArrayDeserializer< 'a > {
type Item = Value;
fn next( &mut self ) -> Option< Self::Item > {
if self.index >= self.slice.len() {
None
} else {
let value = self.slice[ self.index ].deserialize();
self.index += 1;
Some( value )
}
}
#[inline]
fn size_hint( &self ) -> (usize, Option< usize >) {
let remaining = self.slice.len() - self.index;
(remaining, Some( remaining ))
}
}
impl< 'a > ExactSizeIterator for ArrayDeserializer< 'a > {}
pub fn deserialize_array< R, F: FnOnce( &mut ArrayDeserializer ) -> R >( reference: &Reference, callback: F ) -> R {
let mut result: SerializedValue = Default::default();
__js_raw_asm!( "\
var array = Module.STDWEB_PRIVATE.acquire_js_reference( $0 );\
Module.STDWEB_PRIVATE.serialize_array( $1, array );",
reference.as_raw(),
&mut result as *mut _
);
assert_eq!( result.tag, Tag::Array );
let result = result.as_array();
let length = result.length as usize;
let pointer = result.pointer as *const SerializedValue;
let slice = unsafe { slice::from_raw_parts( pointer, length ) };
let mut iter = ArrayDeserializer {
slice,
index: 0
};
let output = callback( &mut iter );
// TODO: Panic-safety.
unsafe {
ffi::dealloc( pointer as *mut u8, length * mem::size_of::< SerializedValue >() );
}
output
}
impl SerializedUntaggedSymbol {
#[inline]
fn deserialize( &self ) -> Symbol {
Symbol( self.id )
}
}
impl SerializedUntaggedReference {
#[inline]
fn deserialize( &self ) -> Reference {
unsafe { Reference::from_raw_unchecked_noref( self.refid ) }
}
}
macro_rules! untagged_boilerplate {
($tests_namespace:ident, $reader_name:ident, $tag:expr, $untagged_type:ident) => {
impl< 'a > SerializedValue< 'a > {
#[allow(dead_code)]
#[inline]
fn $reader_name( &self ) -> &$untagged_type {
debug_assert_eq!( self.tag, $tag );
unsafe {
&*(self as *const _ as *const $untagged_type)
}
}
}
impl< 'a > From< $untagged_type > for SerializedValue< 'a > {
#[inline]
fn from( untagged: $untagged_type ) -> Self {
unsafe {
let mut value: SerializedValue = mem::uninitialized();
*(&mut value as *mut SerializedValue as *mut $untagged_type) = untagged;
value.tag = $tag;
value
}
}
}
#[cfg(test)]
mod $tests_namespace {
use super::*;
#[test]
fn does_not_overlap_with_the_tag() {
let size = mem::size_of::< $untagged_type >();
let tag_offset = unsafe { &(&*(0 as *const SerializedValue< 'static >)).tag as *const _ as usize };
assert!( size <= tag_offset );
}
}
}
}
untagged_boilerplate!( test_undefined, as_undefined, Tag::Undefined, SerializedUntaggedUndefined );
untagged_boilerplate!( test_null, as_null, Tag::Null, SerializedUntaggedNull );
untagged_boilerplate!( test_i32, as_i32, Tag::I32, SerializedUntaggedI32 );
untagged_boilerplate!( test_f64, as_f64, Tag::F64, SerializedUntaggedF64 );
untagged_boilerplate!( test_true, as_true, Tag::True, SerializedUntaggedTrue );
untagged_boilerplate!( test_false, as_false, Tag::False, SerializedUntaggedFalse );
untagged_boilerplate!( test_object, as_object, Tag::Object, SerializedUntaggedObject );
untagged_boilerplate!( test_string, as_string, Tag::Str, SerializedUntaggedString );
untagged_boilerplate!( test_array, as_array, Tag::Array, SerializedUntaggedArray );
untagged_boilerplate!( test_symbol, as_symbol, Tag::Symbol, SerializedUntaggedSymbol );
untagged_boilerplate!( test_reference, as_reference, Tag::Reference, SerializedUntaggedReference );
untagged_boilerplate!( test_function, as_function, Tag::Function, SerializedUntaggedFunction );
untagged_boilerplate!( test_function_mut, as_function_mut, Tag::FunctionMut, SerializedUntaggedFunctionMut );
untagged_boilerplate!( test_function_once, as_function_once, Tag::FunctionOnce, SerializedUntaggedFunctionOnce );
untagged_boilerplate!( test_unsafe_typed_array, as_unsafe_typed_array, Tag::UnsafeTypedArray, SerializedUntaggedUnsafeTypedArray );
impl< 'a > SerializedValue< 'a > {
#[doc(hidden)]
#[inline]
pub fn deserialize( &self ) -> Value {
match self.tag {
Tag::Undefined => Value::Undefined,
Tag::Null => Value::Null,
Tag::I32 => self.as_i32().value.into(),
Tag::F64 => self.as_f64().value.into(),
Tag::Str => Value::String( self.as_string().deserialize() ),
Tag::False => Value::Bool( false ),
Tag::True => Value::Bool( true ),
Tag::Reference => self.as_reference().deserialize().into(),
Tag::Symbol => self.as_symbol().deserialize().into(),
Tag::Function |
Tag::FunctionMut |
Tag::FunctionOnce |
Tag::Object |
Tag::Array |
Tag::UnsafeTypedArray => unreachable!()
}
}
}
impl JsSerialize for () {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedUndefined.into()
}
}
__js_serializable_boilerplate!( () );
impl JsSerialize for Undefined {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedUndefined.into()
}
}
__js_serializable_boilerplate!( Undefined );
impl JsSerialize for Null {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedNull.into()
}
}
__js_serializable_boilerplate!( Null );
impl JsSerialize for Symbol {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedSymbol {
id: self.0
}.into()
}
}
__js_serializable_boilerplate!( Symbol );
impl JsSerialize for Reference {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedReference {
refid: self.as_raw()
}.into()
}
}
__js_serializable_boilerplate!( Reference );
impl JsSerialize for bool {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
if *self {
SerializedUntaggedTrue {}.into()
} else {
SerializedUntaggedFalse {}.into()
}
}
}
__js_serializable_boilerplate!( bool );
impl JsSerialize for str {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedString {
pointer: self.as_ptr() as u32,
length: self.len() as u32
}.into()
}
}
__js_serializable_boilerplate!( impl< 'a > for &'a str );
impl JsSerialize for String {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
self.as_str()._into_js()
}
}
__js_serializable_boilerplate!( String );
impl JsSerialize for i8 {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedI32 {
value: *self as i32
}.into()
}
}
__js_serializable_boilerplate!( i8 );
impl JsSerialize for i16 {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedI32 {
value: *self as i32
}.into()
}
}
__js_serializable_boilerplate!( i16 );
impl JsSerialize for i32 {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedI32 {
value: *self
}.into()
}
}
__js_serializable_boilerplate!( i32 );
impl JsSerialize for u8 {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedI32 {
value: *self as i32
}.into()
}
}
__js_serializable_boilerplate!( u8 );
impl JsSerialize for u16 {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedI32 {
value: *self as i32
}.into()
}
}
__js_serializable_boilerplate!( u16 );
impl JsSerialize for u32 {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedF64 {
value: *self as f64
}.into()
}
}
__js_serializable_boilerplate!( u32 );
impl JsSerialize for f32 {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedF64 {
value: *self as f64
}.into()
}
}
__js_serializable_boilerplate!( f32 );
impl JsSerialize for f64 {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedF64 {
value: *self
}.into()
}
}
__js_serializable_boilerplate!( f64 );
impl JsSerialize for Number {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
use webcore::number::{Storage, get_storage};
match *get_storage( self ) {
Storage::I32( ref value ) => value._into_js(),
Storage::F64( ref value ) => value._into_js()
}
}
}
__js_serializable_boilerplate!( Number );
impl< T: JsSerialize > JsSerialize for Option< T > {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
if let Some( value ) = self.as_ref() {
value._into_js()
} else {
SerializedUntaggedNull.into()
}
}
}
__js_serializable_boilerplate!( impl< T > for Option< T > where T: JsSerialize );
impl< T: JsSerialize > JsSerialize for [T] {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
let mut output = global_arena::reserve( self.len() );
for value in self {
unsafe {
output.append( value._into_js() );
}
}
SerializedUntaggedArray {
pointer: output.offset() as u32,
length: output.len() as u32
}.into()
}
}
__js_serializable_boilerplate!( impl< 'a, T > for &'a [T] where T: JsSerialize );
impl< T: JsSerialize > JsSerialize for Vec< T > {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
self.as_slice()._into_js()
}
}
__js_serializable_boilerplate!( impl< T > for Vec< T > where T: JsSerialize );
fn object_into_js< 'a, K: AsRef< str >, V: 'a + JsSerialize, I: Iterator< Item = (K, &'a V) > + ExactSizeIterator >( iter: I ) -> SerializedValue< 'a > {
let mut keys = global_arena::reserve( iter.len() );
let mut values = global_arena::reserve( iter.len() );
for (key, value) in iter {
unsafe {
keys.append( key.as_ref()._into_js().as_string().clone() );
values.append( value._into_js() );
}
}
SerializedUntaggedObject {
key_pointer: keys.offset() as u32,
value_pointer: values.offset() as u32,
length: keys.len() as u32
}.into()
}
impl< K: AsRef< str >, V: JsSerialize > JsSerialize for BTreeMap< K, V > {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
object_into_js( self.iter() )
}
}
__js_serializable_boilerplate!( impl< K, V > for BTreeMap< K, V > where K: AsRef< str >, V: JsSerialize );
impl< K: AsRef< str > + Eq + Hash, V: JsSerialize > JsSerialize for HashMap< K, V > {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
object_into_js( self.iter() )
}
}
__js_serializable_boilerplate!( impl< K, V > for HashMap< K, V > where K: AsRef< str > + Eq + Hash, V: JsSerialize );
impl JsSerialize for Value {
#[doc(hidden)]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
match *self {
Value::Undefined => SerializedUntaggedUndefined.into(),
Value::Null => SerializedUntaggedNull.into(),
Value::Bool( ref value ) => value._into_js(),
Value::Number( ref value ) => value._into_js(),
Value::Symbol( ref value ) => value._into_js(),
Value::String( ref value ) => value._into_js(),
Value::Reference( ref value ) => value._into_js()
}
}
}
__js_serializable_boilerplate!( Value );
macro_rules! impl_for_unsafe_typed_array {
($ty:ty, $kind:expr) => {
impl< 'r > JsSerialize for UnsafeTypedArray< 'r, $ty > {
#[doc(hidden)]
#[inline]
fn _into_js< 'a >( &'a self ) -> SerializedValue< 'a > {
SerializedUntaggedUnsafeTypedArray {
pointer: self.0.as_ptr() as u32 / mem::size_of::< $ty >() as u32,
length: self.0.len() as u32,
kind: $kind
}.into()
}
}
__js_serializable_boilerplate!( impl< 'a > for UnsafeTypedArray< 'a, $ty > );
}
}
impl_for_unsafe_typed_array!( u8, 0 );
impl_for_unsafe_typed_array!( i8, 1 );
impl_for_unsafe_typed_array!( u16, 2 );
impl_for_unsafe_typed_array!( i16, 3 );
impl_for_unsafe_typed_array!( u32, 4 );
impl_for_unsafe_typed_array!( i32, 5 );
impl_for_unsafe_typed_array!( f32, 6 );
impl_for_unsafe_typed_array!( f64, 7 );
#[derive(Debug)]
pub struct FunctionTag;
#[derive(Debug)]
pub struct NonFunctionTag;
impl< T: JsSerialize > JsSerializeOwned for Newtype< (NonFunctionTag, ()), T > {
#[inline]
fn into_js_owned< 'x >( value: &'x mut Option< Self > ) -> SerializedValue< 'x > {
JsSerialize::_into_js( value.as_ref().unwrap().as_ref() )
}
}
trait FuncallAdapter< F > {
extern fn funcall_adapter( callback: *mut F, raw_arguments: *mut SerializedUntaggedArray );
extern fn deallocator( callback: *mut F );
}
macro_rules! impl_for_fn_and_modifier {
(
args: ($($kind:ident),*),
trait: $trait:ident,
wrapped type: $wrappedtype:ty,
unwrap: $wrapped:ident => $unwrap:expr,
serialized to: $serialized_to:tt,
call: $callback:ident => $call:expr
) => {
impl< $($kind: TryFrom< Value >,)* F > FuncallAdapter< F > for Newtype< (FunctionTag, ($($kind,)*)), $wrappedtype >
where F: $trait< ($($kind,)*) > + 'static, F::Output: JsSerializeOwned
{
#[allow(unused_mut, unused_variables, non_snake_case)]
extern fn funcall_adapter(
$callback: *mut F,
raw_arguments: *mut SerializedUntaggedArray
)
{
let mut arguments = unsafe { &*raw_arguments }.deserialize();
unsafe {
ffi::dealloc( raw_arguments as *mut u8, mem::size_of::< SerializedValue >() );
}
if arguments.len() != F::expected_argument_count() {
// TODO: Should probably throw an exception into the JS world or something like that.
panic!( "Expected {} arguments, got {}", F::expected_argument_count(), arguments.len() );
}
let mut arguments = arguments.drain( .. );
let mut nth_argument = 0;
$(
let $kind = match arguments.next().unwrap().try_into() {
Ok( value ) => value,
Err( _ ) => {
panic!(
"Argument #{} is not convertible to '{}'",
nth_argument + 1,
type_name::< $kind >()
);
}
};
nth_argument += 1;
)*
$crate::private::noop( &mut nth_argument );
let result = $call;
let mut result = Some( result );
let result = JsSerializeOwned::into_js_owned( &mut result );
let result = &result as *const _;
// This is kinda hacky but I'm not sure how else to do it at the moment.
__js_raw_asm!( "Module.STDWEB_PRIVATE.tmp = Module.STDWEB_PRIVATE.to_js( $0 );", result );
}
extern fn deallocator( callback: *mut F ) {
let callback = unsafe {
Box::from_raw( callback )
};
drop( callback );
}
}
impl< $($kind: TryFrom< Value >,)* F > JsSerializeOwned for Newtype< (FunctionTag, ($($kind,)*)), $wrappedtype >
where F: $trait< ($($kind,)*) > + 'static, F::Output: JsSerializeOwned
{
#[inline]
fn into_js_owned< 'a >( value: &'a mut Option< Self > ) -> SerializedValue< 'a > {
let $wrapped = value.take().unwrap().unwrap_newtype();
let callback: *mut F = Box::into_raw( Box::new( $unwrap ) );
let adapter_pointer = <Self as FuncallAdapter< F > >::funcall_adapter;
let deallocator_pointer = <Self as FuncallAdapter< F > >::deallocator;
$serialized_to {
adapter_pointer: adapter_pointer as u32,
pointer: callback as u32,
deallocator_pointer: deallocator_pointer as u32
}.into()
}
}
impl< $($kind: TryFrom< Value >,)* F > JsSerializeOwned for Newtype< (FunctionTag, ($($kind,)*)), Option< $wrappedtype > >
where F: $trait< ($($kind,)*) > + 'static, F::Output: JsSerializeOwned
{
#[inline]
fn into_js_owned< 'a >( value: &'a mut Option< Self > ) -> SerializedValue< 'a > {
if let Some( $wrapped ) = value.take().unwrap().unwrap_newtype() {
let callback: *mut F = Box::into_raw( Box::new( $unwrap ) );
let adapter_pointer = <Newtype< (FunctionTag, ($($kind,)*)), $wrappedtype > as FuncallAdapter< F > >::funcall_adapter;
let deallocator_pointer = <Newtype< (FunctionTag, ($($kind,)*)), $wrappedtype > as FuncallAdapter< F > >::deallocator;
$serialized_to {
adapter_pointer: adapter_pointer as u32,
pointer: callback as u32,
deallocator_pointer: deallocator_pointer as u32
}.into()
} else {
SerializedUntaggedNull.into()
}
}
}
}
}
macro_rules! impl_for_fn {
($next:tt => $($kind:ident),*) => {
impl_for_fn_and_modifier!(
args: ($($kind),*),
trait: CallMut,
wrapped type: F,
unwrap: f => f,
serialized to: SerializedUntaggedFunction,
call: f => { unsafe { &mut *f }.call_mut( ($($kind,)*) ) }
);
impl_for_fn_and_modifier!(
args: ($($kind),*),
trait: CallMut,
wrapped type: Mut<F>,
unwrap: f => {f.0},
serialized to: SerializedUntaggedFunctionMut,
call: f => { unsafe { &mut *f }.call_mut( ($($kind,)*) ) }
);
impl_for_fn_and_modifier!(
args: ($($kind),*),
trait: CallOnce,
wrapped type: Once<F>,
unwrap: f => {f.0},
serialized to: SerializedUntaggedFunctionOnce,
call: f => { unsafe { Box::from_raw( f ) }.call_once( ($($kind,)*) ) }
);
next! { $next }
}
}
loop_through_identifiers!( impl_for_fn );
impl< 'a, T: ?Sized + JsSerialize > JsSerialize for &'a T {
#[doc(hidden)]
#[inline]
fn _into_js< 'x >( &'x self ) -> SerializedValue< 'x > {
T::_into_js( *self )
}
}
impl JsSerialize for ConversionError {
#[doc(hidden)]
fn _into_js< 'x >( &'x self ) -> SerializedValue< 'x > {
let type_error: TypeError = self.into();
let reference: Reference = type_error.into();
let value: Value = reference.into();
global_arena::serialize_value( value )
}
}
#[cfg(test)]
mod test_deserialization {
use std::rc::Rc;
use std::cell::{Cell, RefCell};
use super::*;
#[test]
fn i32() {
assert_eq!( js! { return 100; }, Value::Number( 100_i32.into() ) );
}
#[test]
fn f64() {
assert_eq!( js! { return 100.5; }, Value::Number( 100.5_f64.into() ) );
}
#[test]
fn bool_true() {
assert_eq!( js! { return true; }, Value::Bool( true ) );
}
#[test]
fn bool_false() {
assert_eq!( js! { return false; }, Value::Bool( false ) );
}
#[test]
fn undefined() {
assert_eq!( js! { return undefined; }, Value::Undefined );
}
#[test]
fn null() {
assert_eq!( js! { return null; }, Value::Null );
}
#[test]
fn string() {
assert_eq!( js! { return "Dog"; }, Value::String( "Dog".to_string() ) );
}
#[test]
fn empty_string() {
assert_eq!( js! { return ""; }, Value::String( "".to_string() ) );
}
#[test]
fn symbol() {
let value = js! { return Symbol(); };
assert!( value.is_symbol() );
}
#[test]
fn array() {
assert_eq!( js! { return [1, 2]; }.is_array(), true );
}
#[test]
fn object() {
assert_eq!( js! { return {"one": 1, "two": 2}; }.is_object(), true );
}
#[test]
fn object_into_btreemap() {
let object = js! { return {"one": 1, "two": 2}; }.into_object().unwrap();
let object: BTreeMap< String, Value > = object.into();
assert_eq!( object, [
("one".to_string(), Value::Number(1.into())),
("two".to_string(), Value::Number(2.into()))
].iter().cloned().collect() );
}
#[test]
fn object_into_hashmap() {
let object = js! { return {"one": 1, "two": 2}; }.into_object().unwrap();
let object: HashMap< String, Value > = object.into();
assert_eq!( object, [
("one".to_string(), Value::Number(1.into())),
("two".to_string(), Value::Number(2.into()))
].iter().cloned().collect() );
}
#[test]
fn array_into_vector() {
let array = js! { return ["one", 1]; }.into_array().unwrap();
let array: Vec< Value > = array.into();
assert_eq!( array, &[
Value::String( "one".to_string() ),
Value::Number( 1.into() )
]);
}
#[test]
fn reference() {
assert_eq!( js! { return new Date(); }.is_reference(), true );
}
#[test]
fn bad_reference() {
assert_eq!( js! {
var WeakMapProto = WeakMap.prototype;
if (WeakMapProto.BAD_REFERENCE === undefined) {
WeakMapProto.BAD_REFERENCE = {};
WeakMapProto.oldSet = WeakMapProto.set;
WeakMapProto.set = function(key, value) {
if (key === WeakMapProto.BAD_REFERENCE) {
throw new TypeError("BAD_REFERENCE");
} else {
return this.oldSet(key, value);
}
};
}
return WeakMapProto.BAD_REFERENCE;
}.is_reference(), true );
}
#[test]
fn arguments() {
let value = js! {
return (function() {
return arguments;
})( 1, 2 );
};
assert_eq!( value.is_array(), false );
}
#[test]
fn function() {
let value = Rc::new( Cell::new( 0 ) );
let fn_value = value.clone();
js! {
var callback = @{move || { fn_value.set( 1 ); }};
callback();
callback.drop();
};
assert_eq!( value.get(), 1 );
}
#[test]
fn function_returning_bool() {
let result = js! {
var callback = @{move || { return true }};
var result = callback();
callback.drop();
return result;
};
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn function_with_single_bool_argument() {
let value = Rc::new( Cell::new( false ) );
let fn_value = value.clone();
js! {
var callback = @{move |value: bool| { fn_value.set( value ); }};
callback( true );
callback.drop();
};
assert_eq!( value.get(), true );
}
#[test]
fn function_inside_an_option() {
let value = Rc::new( Cell::new( 0 ) );
let fn_value = value.clone();
js! {
var callback = @{Some( move || { fn_value.set( 1 ); } )};
callback();
callback.drop();
};
assert_eq!( value.get(), 1 );
}
#[test]
#[allow(unused_assignments)]
fn function_inside_an_empty_option() {
let mut callback = Some( move || () );
callback = None;
let result = js! {
var callback = @{callback};
return callback === null;
};
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn function_once() {
fn call< F: FnOnce( String ) -> String + 'static >( callback: F ) -> Value {
js!(
var callback = @{Once( callback )};
return callback( "Dog" );
)
}
let suffix = "!".to_owned();
let result = call( move |value| { return value + suffix.as_str() } );
assert_eq!( result, Value::String( "Dog!".to_owned() ) );
}
#[test]
fn function_mut() {
let mut count = 0;
let callback = move || -> i32 {
count += 1;
count
};
let callback = js! { return @{Mut(callback)}; };
assert_eq!({ let x : i32 = js!{ return @{&callback}(); }.try_into().unwrap(); x }, 1);
assert_eq!({ let x : i32 = js!{ return @{&callback}(); }.try_into().unwrap(); x }, 2);
assert_eq!({ let x : i32 = js!{ return @{&callback}(); }.try_into().unwrap(); x }, 3);
js!{ @{callback}.drop(); };
}
#[test]
fn function_once_cannot_be_called_twice() {
fn call< F: FnOnce() + 'static >( callback: F ) -> Value {
js!(
var callback = @{Once( callback )};
callback();
try {
callback();
} catch( error ) {
if( error instanceof ReferenceError ) {
return true;
}
}
return false;
)
}
let result = call( move || {} );
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn function_once_cannot_be_called_after_being_dropped() {
fn call< F: FnOnce() + 'static >( callback: F ) -> Value {
js!(
var callback = @{Once( callback )};
callback.drop();
try {
callback();
} catch( error ) {
if( error instanceof ReferenceError ) {
return true;
}
}
return false;
)
}
let result = call( move || {} );
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn function_once_calling_drop_after_being_called_does_not_do_anything() {
fn call< F: FnOnce() + 'static >( callback: F ) -> Value {
js!(
var callback = @{Once( callback )};
callback();
callback.drop();
return true;
)
}
let result = call( move || {} );
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn function_once_calling_drop_twice_does_not_do_anything() {
fn call< F: FnOnce() + 'static >( callback: F ) -> Value {
js!(
var callback = @{Once( callback )};
callback.drop();
callback.drop();
return true;
)
}
let result = call( move || {} );
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn issue_273() {
let mut count = 0;
let f = move |callback: ::stdweb::Value| {
count += 1;
js! {
@{callback}();
};
};
let result = js! {
let f = @{Mut(f)};
let caught = false;
try {
f(function () {
f(function() {});
});
} catch ( error ) {
if( error instanceof ReferenceError ) {
caught = true;
}
}
f.drop();
return caught;
};
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn issue_277() {
struct MyStruct {
was_dropped: bool
}
impl MyStruct {
fn consume(self) {}
}
impl Drop for MyStruct {
fn drop(&mut self) {
assert_eq!(self.was_dropped, false);
self.was_dropped = true;
}
}
let s = MyStruct { was_dropped: false };
let f = move || -> () {
s.consume();
unreachable!(); // never actually called
};
js! {
let f = @{Once(f)};
let drop = f.drop;
drop();
drop();
};
}
#[test]
fn test_closure_dropped_while_being_called_is_dropped_after_it_returns() {
struct MarkTrueOnDrop( Rc< Cell< bool > > );
impl Drop for MarkTrueOnDrop {
fn drop( &mut self ) {
self.0.set( true );
}
}
let was_dropped = Rc::new( Cell::new( false ) );
let was_dropped_clone = was_dropped.clone();
let callback = move |itself: Value, check_if_dropped: Value| {
let _mark_true_on_drop = MarkTrueOnDrop( was_dropped_clone.clone() );
js!(
@{itself}.drop();
@{check_if_dropped}();
);
};
let check_if_dropped = move || {
assert_eq!( was_dropped.get(), false );
};
js!(
var callback = @{callback};
callback( callback, @{Once( check_if_dropped )} );
);
}
#[test]
fn test_dropping_the_closure_while_it_is_being_called_will_make_future_calls_throw() {
#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
#[reference(instance_of = "ReferenceError")]
pub struct ReferenceError( Reference );
let counter = Rc::new( Cell::new( 0 ) );
let counter_clone = counter.clone();
let caught_value = Rc::new( RefCell::new( Value::Null ) );
let caught_value_clone = caught_value.clone();
let callback = move |itself: Value| {
let value = counter_clone.get();
counter_clone.set( value + 1 );
if value == 0 {
let caught = js!(
var callback = @{itself};
callback.drop();
var caught = null;
try {
callback( callback );
} catch( error ) {
caught = error;
}
return caught;
);
*caught_value_clone.borrow_mut() = caught;
}
};
js!(
var callback = @{callback};
callback( callback );
);
assert_eq!( counter.get(), 1 );
let reference_error: Result< ReferenceError, _ > = caught_value.borrow().clone().try_into();
assert!( reference_error.is_ok() );
}
}
#[cfg(test)]
mod test_serialization {
use super::*;
use std::borrow::Cow;
#[test]
fn object_from_btreemap() {
let object: BTreeMap< _, _ > = [
("number".to_string(), Value::Number( 123.into() )),
("string".to_string(), Value::String( "Hello!".into() ))
].iter().cloned().collect();
let result = js! {
var object = @{object};
return object.number === 123 && object.string === "Hello!" && Object.keys( object ).length === 2;
};
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn object_from_borrowed_btreemap() {
let object: BTreeMap< _, _ > = [
("number".to_string(), Value::Number( 123.into() ))
].iter().cloned().collect();
let result = js! {
var object = @{&object};
return object.number === 123 && Object.keys( object ).length === 1;
};
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn object_from_btreemap_with_convertible_key_and_value() {
let key: Cow< str > = "number".into();
let object: BTreeMap< _, _ > = [
(key, 123)
].iter().cloned().collect();
let result = js! {
var object = @{object};
return object.number === 123 && Object.keys( object ).length === 1;
};
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn object_from_hashmap() {
let object: HashMap< _, _ > = [
("number".to_string(), Value::Number( 123.into() )),
("string".to_string(), Value::String( "Hello!".into() ))
].iter().cloned().collect();
let result = js! {
var object = @{object};
return object.number === 123 && object.string === "Hello!" && Object.keys( object ).length === 2;
};
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn vector_of_strings() {
let vec: Vec< _ > = vec![
"one".to_string(),
"two".to_string()
];
let result = js! {
var vec = @{vec};
return vec[0] === "one" && vec[1] === "two" && vec.length === 2;
};
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn multiple() {
let reference: Reference = js! {
return new Date();
}.try_into().unwrap();
let result = js! {
var callback = @{|| {}};
var reference = @{&reference};
var string = @{"Hello!"};
return Object.prototype.toString.call( callback ) === "[object Function]" &&
Object.prototype.toString.call( reference ) === "[object Date]" &&
Object.prototype.toString.call( string ) === "[object String]"
};
assert_eq!( result, Value::Bool( true ) );
}
#[test]
fn serialize_0() {
assert_eq!(
js! { return 0; },
0
);
}
#[test]
fn serialize_1() {
assert_eq!(
js! { return @{1}; },
1
);
}
#[test]
fn serialize_2() {
assert_eq!(
js! { return @{1} + @{2}; },
1 + 2
);
}
#[test]
fn serialize_3() {
assert_eq!(
js! { return @{1} + @{2} + @{3}; },
1 + 2 + 3
);
}
#[test]
fn serialize_4() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4}; },
1 + 2 + 3 + 4
);
}
#[test]
fn serialize_5() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4} + @{5}; },
1 + 2 + 3 + 4 + 5
);
}
#[test]
fn serialize_6() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4} + @{5} + @{6}; },
1 + 2 + 3 + 4 + 5 + 6
);
}
#[test]
fn serialize_7() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4} + @{5} + @{6} + @{7}; },
1 + 2 + 3 + 4 + 5 + 6 + 7
);
}
#[test]
fn serialize_8() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4} + @{5} + @{6} + @{7} + @{8}; },
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
);
}
#[test]
fn serialize_9() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4} + @{5} + @{6} + @{7} + @{8} + @{9}; },
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9
);
}
#[test]
fn serialize_10() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4} + @{5} + @{6} + @{7} + @{8} + @{9} + @{10}; },
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
);
}
#[test]
fn serialize_11() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4} + @{5} + @{6} + @{7} + @{8} + @{9} + @{10} + @{11}; },
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11
);
}
#[test]
fn serialize_12() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4} + @{5} + @{6} + @{7} + @{8} + @{9} + @{10} + @{11} + @{12}; },
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12
);
}
#[test]
fn serialize_13() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4} + @{5} + @{6} + @{7} + @{8} + @{9} + @{10} + @{11} + @{12} + @{13}; },
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13
);
}
#[test]
fn serialize_14() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4} + @{5} + @{6} + @{7} + @{8} + @{9} + @{10} + @{11} + @{12} + @{13} + @{14}; },
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14
);
}
#[test]
fn serialize_15() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4} + @{5} + @{6} + @{7} + @{8} + @{9} + @{10} + @{11} + @{12} + @{13} + @{14} + @{15}; },
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15
);
}
#[test]
fn serialize_16() {
assert_eq!(
js! { return @{1} + @{2} + @{3} + @{4} + @{5} + @{6} + @{7} + @{8} + @{9} + @{10} + @{11} + @{12} + @{13} + @{14} + @{15} + @{16}; },
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16
);
}
#[test]
fn interpolated_args_are_converted_at_the_start() {
let mut string = "1".to_owned();
let callback = js! {
return function() {
return @{&string};
}
};
unsafe {
string.as_bytes_mut()[0] = b'2';
}
let result = js! {
return @{callback}();
};
assert_eq!( result, "1" );
}
macro_rules! test_unsafe_typed_array {
($test_name:ident, $ty:ty, $js_type_name:ident) => {
#[allow(trivial_numeric_casts)]
#[test]
fn $test_name() {
let slice: &[$ty] = &[1 as $ty, 2 as $ty, 3 as $ty];
let slice = unsafe { UnsafeTypedArray::new( slice ) };
let result: Vec< Value > = js!(
var slice = @{slice};
var sum = slice[0] + slice[1] + slice[2];
var name = slice.constructor.name;
var length = slice.length;
return [name, sum, length]
).try_into().unwrap();
let mut result = result.into_iter();
let name: String = result.next().unwrap().try_into().unwrap();
let sum: f64 = result.next().unwrap().try_into().unwrap();
let length: usize = result.next().unwrap().try_into().unwrap();
assert_eq!( name, stringify!( $js_type_name ) );
assert_eq!( sum as u64, 6 );
assert_eq!( length, 3 );
}
}
}
test_unsafe_typed_array!( test_unsafe_typed_array_u8, u8, Uint8Array );
test_unsafe_typed_array!( test_unsafe_typed_array_i8, i8, Int8Array );
test_unsafe_typed_array!( test_unsafe_typed_array_u16, u16, Uint16Array );
test_unsafe_typed_array!( test_unsafe_typed_array_i16, i16, Int16Array );
test_unsafe_typed_array!( test_unsafe_typed_array_u32, u32, Uint32Array );
test_unsafe_typed_array!( test_unsafe_typed_array_i32, i32, Int32Array );
test_unsafe_typed_array!( test_unsafe_typed_array_f32, f32, Float32Array );
test_unsafe_typed_array!( test_unsafe_typed_array_f64, f64, Float64Array );
}
// TODO: Move this back inside the test module.
//
// This had to be temporarily moved here due to a bug in Rust
// where the following error is generated if it's defined under
// the module:
//
// error: cannot determine resolution for the attribute macro `reference`
//
#[cfg(test)]
#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
#[reference(instance_of = "Error")]
pub struct TestError( Reference );
#[cfg(test)]
mod test_reserialization {
use super::*;
use webcore::array::Array;
#[test]
fn i32() {
assert_eq!( js! { return @{100}; }, Value::Number( 100_i32.into() ) );
}
#[test]
fn f64() {
assert_eq!( js! { return @{100.5}; }, Value::Number( 100.5_f64.into() ) );
}
#[test]
fn bool_true() {
assert_eq!( js! { return @{true}; }, Value::Bool( true ) );
}
#[test]
fn bool_false() {
assert_eq!( js! { return @{false}; }, Value::Bool( false ) );
}
#[test]
fn undefined() {
assert_eq!( js! { return @{Undefined}; }, Value::Undefined );
}
#[test]
fn null() {
assert_eq!( js! { return @{Null}; }, Value::Null );
}
#[test]
fn string() {
assert_eq!( js! { return @{"Dog"}; }, Value::String( "Dog".to_string() ) );
}
#[test]
fn empty_string() {
assert_eq!( js! { return @{""}; }, Value::String( "".to_string() ) );
}
#[test]
fn string_with_non_bmp_character() {
assert_eq!( js! { return @{"😐"} + ", 😐"; }, Value::String( "😐, 😐".to_string() ) );
}
#[test]
fn array() {
let array: Array = vec![ Value::Number( 1.into() ), Value::Number( 2.into() ) ].into();
assert_eq!( js! { return @{&array}; }.into_reference().unwrap(), *array.as_ref() );
}
#[test]
fn array_values_are_not_compared_by_value() {
let array: Array = vec![ Value::Number( 1.into() ), Value::Number( 2.into() ) ].into();
assert_ne!( js! { return @{&[1, 2][..]}; }.into_reference().unwrap(), *array.as_ref() );
}
#[test]
fn object() {
let object: BTreeMap< _, _ > = [
("one".to_string(), Value::Number( 1.into() )),
("two".to_string(), Value::Number( 2.into() ))
].iter().cloned().collect();
let object: Value = object.into();
assert_eq!( js! { return @{&object} }, object );
}
#[test]
fn symbol() {
let value_1: Symbol = js! { return Symbol(); }.try_into().unwrap();
let value_2: Symbol = js! { return @{&value_1}; }.try_into().unwrap();
assert_eq!( value_1, value_2 );
assert_eq!( js! { return @{value_1} === @{value_2}; }, true );
}
#[test]
fn cloned_symbol() {
let value_1: Symbol = js! { return Symbol(); }.try_into().unwrap();
let value_2 = value_1.clone();
assert_eq!( value_1, value_2 );
assert_eq!( js! { return @{value_1} === @{value_2}; }, true );
}
#[test]
fn different_symbols() {
let value_1: Symbol = js! { return Symbol(); }.try_into().unwrap();
let value_2: Symbol = js! { return Symbol(); }.try_into().unwrap();
assert_ne!( value_1, value_2 );
assert_eq!( js! { return @{value_1} !== @{value_2}; }, true );
}
#[test]
fn reference() {
let date = js! { return new Date(); };
assert_eq!( js! { return Object.prototype.toString.call( @{date} ) }, "[object Date]" );
}
#[test]
fn reference_by_ref() {
let date = js! { return new Date(); };
assert_eq!( js! { return Object.prototype.toString.call( @{&date} ) }, "[object Date]" );
}
#[test]
fn option_some() {
assert_eq!( js! { return @{Some( true )}; }, Value::Bool( true ) );
}
#[test]
fn option_none() {
let boolean_none: Option< bool > = None;
assert_eq!( js! { return @{boolean_none}; }, Value::Null );
}
#[test]
fn value() {
assert_eq!( js! { return @{Value::String( "Dog".to_string() )}; }, Value::String( "Dog".to_string() ) );
}
#[test]
fn closure_context() {
let constant: u32 = 0x12345678;
let callback = move || {
let value: Value = constant.into();
value
};
let value = js! {
return @{callback}();
};
assert_eq!( value, Value::Number( 0x12345678_i32.into() ) );
}
#[test]
fn string_identity_function() {
fn identity( string: String ) -> String {
string
}
let empty = js! {
var identity = @{identity};
return identity( "" );
};
assert_eq!( empty, Value::String( "".to_string() ) );
let non_empty = js! {
var identity = @{identity};
return identity( "死神はりんごしか食べない!" );
};
assert_eq!( non_empty, Value::String( "死神はりんごしか食べない!".to_string() ) );
}
type Error = TestError;
#[test]
fn closure_returning_reference_object() {
fn identity( error: Error ) -> Error {
error
}
let value = js! {
var identity = @{identity};
return identity( new ReferenceError() );
};
assert!( instanceof!( value, Error ) );
}
}
| 28.465835 | 153 | 0.513174 |
501147ed4593ba6748c724eba77a70016a42a8ff | 41,829 | //! HTML formatting module
//!
//! This module contains a large number of `fmt::Display` implementations for
//! various types in `rustdoc::clean`. These implementations all currently
//! assume that HTML output is desired, although it may be possible to redesign
//! them in the future to instead emit any format desired.
use std::borrow::Cow;
use std::cell::Cell;
use std::fmt;
use rustc::hir::def_id::DefId;
use rustc::util::nodemap::FxHashSet;
use rustc_target::spec::abi::Abi;
use rustc::hir;
use crate::clean::{self, PrimitiveType};
use crate::html::item_type::ItemType;
use crate::html::render::{self, cache, CURRENT_DEPTH};
pub trait Print {
fn print(self, buffer: &mut Buffer);
}
impl<F> Print for F
where F: FnOnce(&mut Buffer),
{
fn print(self, buffer: &mut Buffer) {
(self)(buffer)
}
}
impl Print for String {
fn print(self, buffer: &mut Buffer) {
buffer.write_str(&self);
}
}
impl Print for &'_ str {
fn print(self, buffer: &mut Buffer) {
buffer.write_str(self);
}
}
#[derive(Debug, Clone)]
pub struct Buffer {
for_html: bool,
buffer: String,
}
impl Buffer {
crate fn empty_from(v: &Buffer) -> Buffer {
Buffer {
for_html: v.for_html,
buffer: String::new(),
}
}
crate fn html() -> Buffer {
Buffer {
for_html: true,
buffer: String::new(),
}
}
crate fn new() -> Buffer {
Buffer {
for_html: false,
buffer: String::new(),
}
}
crate fn is_empty(&self) -> bool {
self.buffer.is_empty()
}
crate fn into_inner(self) -> String {
self.buffer
}
crate fn insert_str(&mut self, idx: usize, s: &str) {
self.buffer.insert_str(idx, s);
}
crate fn push_str(&mut self, s: &str) {
self.buffer.push_str(s);
}
// Intended for consumption by write! and writeln! (std::fmt) but without
// the fmt::Result return type imposed by fmt::Write (and avoiding the trait
// import).
crate fn write_str(&mut self, s: &str) {
self.buffer.push_str(s);
}
// Intended for consumption by write! and writeln! (std::fmt) but without
// the fmt::Result return type imposed by fmt::Write (and avoiding the trait
// import).
crate fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
use fmt::Write;
self.buffer.write_fmt(v).unwrap();
}
crate fn to_display<T: Print>(mut self, t: T) -> String {
t.print(&mut self);
self.into_inner()
}
crate fn from_display<T: std::fmt::Display>(&mut self, t: T) {
if self.for_html {
write!(self, "{}", t);
} else {
write!(self, "{:#}", t);
}
}
crate fn is_for_html(&self) -> bool {
self.for_html
}
}
/// Wrapper struct for properly emitting a function or method declaration.
pub struct Function<'a> {
/// The declaration to emit.
pub decl: &'a clean::FnDecl,
/// The length of the function header and name. In other words, the number of characters in the
/// function declaration up to but not including the parentheses.
///
/// Used to determine line-wrapping.
pub header_len: usize,
/// The number of spaces to indent each successive line with, if line-wrapping is necessary.
pub indent: usize,
/// Whether the function is async or not.
pub asyncness: hir::IsAsync,
}
/// Wrapper struct for emitting a where-clause from Generics.
pub struct WhereClause<'a>{
/// The Generics from which to emit a where-clause.
pub gens: &'a clean::Generics,
/// The number of spaces to indent each line with.
pub indent: usize,
/// Whether the where-clause needs to add a comma and newline after the last bound.
pub end_newline: bool,
}
fn comma_sep<T: fmt::Display>(items: impl Iterator<Item=T>) -> impl fmt::Display {
display_fn(move |f| {
for (i, item) in items.enumerate() {
if i != 0 { write!(f, ", ")?; }
fmt::Display::fmt(&item, f)?;
}
Ok(())
})
}
crate fn print_generic_bounds(bounds: &[clean::GenericBound]) -> impl fmt::Display + '_ {
display_fn(move |f| {
let mut bounds_dup = FxHashSet::default();
for (i, bound) in bounds.iter().filter(|b| {
bounds_dup.insert(b.print().to_string())
}).enumerate() {
if i > 0 {
f.write_str(" + ")?;
}
fmt::Display::fmt(&bound.print(), f)?;
}
Ok(())
})
}
impl clean::GenericParamDef {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
match self.kind {
clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
f.write_str(&self.name)?;
if !bounds.is_empty() {
if f.alternate() {
write!(f, ": {:#}", print_generic_bounds(bounds))?;
} else {
write!(f, ": {}", print_generic_bounds(bounds))?;
}
}
if let Some(ref ty) = default {
if f.alternate() {
write!(f, " = {:#}", ty.print())?;
} else {
write!(f, " = {}", ty.print())?;
}
}
Ok(())
}
clean::GenericParamDefKind::Const { ref ty, .. } => {
f.write_str("const ")?;
f.write_str(&self.name)?;
if f.alternate() {
write!(f, ": {:#}", ty.print())
} else {
write!(f, ": {}", ty.print())
}
}
}
})
}
}
impl clean::Generics {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
let real_params = self.params
.iter()
.filter(|p| !p.is_synthetic_type_param())
.collect::<Vec<_>>();
if real_params.is_empty() {
return Ok(());
}
if f.alternate() {
write!(f, "<{:#}>", comma_sep(real_params.iter().map(|g| g.print())))
} else {
write!(f, "<{}>", comma_sep(real_params.iter().map(|g| g.print())))
}
})
}
}
impl<'a> fmt::Display for WhereClause<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let &WhereClause { gens, indent, end_newline } = self;
if gens.where_predicates.is_empty() {
return Ok(());
}
let mut clause = String::new();
if f.alternate() {
clause.push_str(" where");
} else {
if end_newline {
clause.push_str(" <span class=\"where fmt-newline\">where");
} else {
clause.push_str(" <span class=\"where\">where");
}
}
for (i, pred) in gens.where_predicates.iter().enumerate() {
if f.alternate() {
clause.push(' ');
} else {
clause.push_str("<br>");
}
match pred {
&clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
let bounds = bounds;
if f.alternate() {
clause.push_str(&format!("{:#}: {:#}",
ty.print(), print_generic_bounds(bounds)));
} else {
clause.push_str(&format!("{}: {}",
ty.print(), print_generic_bounds(bounds)));
}
}
&clean::WherePredicate::RegionPredicate { ref lifetime, ref bounds } => {
clause.push_str(&format!("{}: {}",
lifetime.print(),
bounds.iter()
.map(|b| b.print().to_string())
.collect::<Vec<_>>()
.join(" + ")));
}
&clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
if f.alternate() {
clause.push_str(&format!("{:#} == {:#}", lhs.print(), rhs.print()));
} else {
clause.push_str(&format!("{} == {}", lhs.print(), rhs.print()));
}
}
}
if i < gens.where_predicates.len() - 1 || end_newline {
clause.push(',');
}
}
if end_newline {
// add a space so stripping <br> tags and breaking spaces still renders properly
if f.alternate() {
clause.push(' ');
} else {
clause.push_str(" ");
}
}
if !f.alternate() {
clause.push_str("</span>");
let padding = " ".repeat(indent + 4);
clause = clause.replace("<br>", &format!("<br>{}", padding));
clause.insert_str(0, &" ".repeat(indent.saturating_sub(1)));
if !end_newline {
clause.insert_str(0, "<br>");
}
}
write!(f, "{}", clause)
}
}
impl clean::Lifetime {
crate fn print(&self) -> &str {
self.get_ref()
}
}
impl clean::Constant {
crate fn print(&self) -> &str {
&self.expr
}
}
impl clean::PolyTrait {
fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
if !self.generic_params.is_empty() {
if f.alternate() {
write!(f, "for<{:#}> ",
comma_sep(self.generic_params.iter().map(|g| g.print())))?;
} else {
write!(f, "for<{}> ",
comma_sep(self.generic_params.iter().map(|g| g.print())))?;
}
}
if f.alternate() {
write!(f, "{:#}", self.trait_.print())
} else {
write!(f, "{}", self.trait_.print())
}
})
}
}
impl clean::GenericBound {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
match self {
clean::GenericBound::Outlives(lt) => {
write!(f, "{}", lt.print())
}
clean::GenericBound::TraitBound(ty, modifier) => {
let modifier_str = match modifier {
hir::TraitBoundModifier::None => "",
hir::TraitBoundModifier::Maybe => "?",
};
if f.alternate() {
write!(f, "{}{:#}", modifier_str, ty.print())
} else {
write!(f, "{}{}", modifier_str, ty.print())
}
}
}
})
}
}
impl clean::GenericArgs {
fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
match *self {
clean::GenericArgs::AngleBracketed { ref args, ref bindings } => {
if !args.is_empty() || !bindings.is_empty() {
if f.alternate() {
f.write_str("<")?;
} else {
f.write_str("<")?;
}
let mut comma = false;
for arg in args {
if comma {
f.write_str(", ")?;
}
comma = true;
if f.alternate() {
write!(f, "{:#}", arg.print())?;
} else {
write!(f, "{}", arg.print())?;
}
}
for binding in bindings {
if comma {
f.write_str(", ")?;
}
comma = true;
if f.alternate() {
write!(f, "{:#}", binding.print())?;
} else {
write!(f, "{}", binding.print())?;
}
}
if f.alternate() {
f.write_str(">")?;
} else {
f.write_str(">")?;
}
}
}
clean::GenericArgs::Parenthesized { ref inputs, ref output } => {
f.write_str("(")?;
let mut comma = false;
for ty in inputs {
if comma {
f.write_str(", ")?;
}
comma = true;
if f.alternate() {
write!(f, "{:#}", ty.print())?;
} else {
write!(f, "{}", ty.print())?;
}
}
f.write_str(")")?;
if let Some(ref ty) = *output {
if f.alternate() {
write!(f, " -> {:#}", ty.print())?;
} else {
write!(f, " -> {}", ty.print())?;
}
}
}
}
Ok(())
})
}
}
impl clean::PathSegment {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
f.write_str(&self.name)?;
if f.alternate() {
write!(f, "{:#}", self.args.print())
} else {
write!(f, "{}", self.args.print())
}
})
}
}
impl clean::Path {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
if self.global {
f.write_str("::")?
}
for (i, seg) in self.segments.iter().enumerate() {
if i > 0 {
f.write_str("::")?
}
if f.alternate() {
write!(f, "{:#}", seg.print())?;
} else {
write!(f, "{}", seg.print())?;
}
}
Ok(())
})
}
}
pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
let cache = cache();
if !did.is_local() && !cache.access_levels.is_public(did) {
return None
}
let depth = CURRENT_DEPTH.with(|l| l.get());
let (fqp, shortty, mut url) = match cache.paths.get(&did) {
Some(&(ref fqp, shortty)) => {
(fqp, shortty, "../".repeat(depth))
}
None => {
let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
(fqp, shortty, match cache.extern_locations[&did.krate] {
(.., render::Remote(ref s)) => s.to_string(),
(.., render::Local) => "../".repeat(depth),
(.., render::Unknown) => return None,
})
}
};
for component in &fqp[..fqp.len() - 1] {
url.push_str(component);
url.push_str("/");
}
match shortty {
ItemType::Module => {
url.push_str(fqp.last().unwrap());
url.push_str("/index.html");
}
_ => {
url.push_str(shortty.as_str());
url.push_str(".");
url.push_str(fqp.last().unwrap());
url.push_str(".html");
}
}
Some((url, shortty, fqp.to_vec()))
}
/// Used when rendering a `ResolvedPath` structure. This invokes the `path`
/// rendering function with the necessary arguments for linking to a local path.
fn resolved_path(w: &mut fmt::Formatter<'_>, did: DefId, path: &clean::Path,
print_all: bool, use_absolute: bool) -> fmt::Result {
let last = path.segments.last().unwrap();
if print_all {
for seg in &path.segments[..path.segments.len() - 1] {
write!(w, "{}::", seg.name)?;
}
}
if w.alternate() {
write!(w, "{}{:#}", &last.name, last.args.print())?;
} else {
let path = if use_absolute {
if let Some((_, _, fqp)) = href(did) {
format!("{}::{}",
fqp[..fqp.len() - 1].join("::"),
anchor(did, fqp.last().unwrap()))
} else {
last.name.to_string()
}
} else {
anchor(did, &last.name).to_string()
};
write!(w, "{}{}", path, last.args.print())?;
}
Ok(())
}
fn primitive_link(f: &mut fmt::Formatter<'_>,
prim: clean::PrimitiveType,
name: &str) -> fmt::Result {
let m = cache();
let mut needs_termination = false;
if !f.alternate() {
match m.primitive_locations.get(&prim) {
Some(&def_id) if def_id.is_local() => {
let len = CURRENT_DEPTH.with(|s| s.get());
let len = if len == 0 {0} else {len - 1};
write!(f, "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
"../".repeat(len),
prim.to_url_str())?;
needs_termination = true;
}
Some(&def_id) => {
let loc = match m.extern_locations[&def_id.krate] {
(ref cname, _, render::Remote(ref s)) => {
Some((cname, s.to_string()))
}
(ref cname, _, render::Local) => {
let len = CURRENT_DEPTH.with(|s| s.get());
Some((cname, "../".repeat(len)))
}
(.., render::Unknown) => None,
};
if let Some((cname, root)) = loc {
write!(f, "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
root,
cname,
prim.to_url_str())?;
needs_termination = true;
}
}
None => {}
}
}
write!(f, "{}", name)?;
if needs_termination {
write!(f, "</a>")?;
}
Ok(())
}
/// Helper to render type parameters
fn tybounds(param_names: &Option<Vec<clean::GenericBound>>) -> impl fmt::Display + '_ {
display_fn(move |f| {
match *param_names {
Some(ref params) => {
for param in params {
write!(f, " + ")?;
fmt::Display::fmt(¶m.print(), f)?;
}
Ok(())
}
None => Ok(())
}
})
}
pub fn anchor(did: DefId, text: &str) -> impl fmt::Display + '_ {
display_fn(move |f| {
if let Some((url, short_ty, fqp)) = href(did) {
write!(f, r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
short_ty, url, short_ty, fqp.join("::"), text)
} else {
write!(f, "{}", text)
}
})
}
fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter<'_>, use_absolute: bool) -> fmt::Result {
match *t {
clean::Generic(ref name) => {
f.write_str(name)
}
clean::ResolvedPath{ did, ref param_names, ref path, is_generic } => {
if param_names.is_some() {
f.write_str("dyn ")?;
}
// Paths like `T::Output` and `Self::Output` should be rendered with all segments.
resolved_path(f, did, path, is_generic, use_absolute)?;
fmt::Display::fmt(&tybounds(param_names), f)
}
clean::Infer => write!(f, "_"),
clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()),
clean::BareFunction(ref decl) => {
if f.alternate() {
write!(f, "{}{:#}fn{:#}{:#}",
decl.unsafety.print_with_space(),
print_abi_with_space(decl.abi),
decl.print_generic_params(),
decl.decl.print())
} else {
write!(f, "{}{}",
decl.unsafety.print_with_space(), print_abi_with_space(decl.abi))?;
primitive_link(f, PrimitiveType::Fn, "fn")?;
write!(f, "{}{}", decl.print_generic_params(), decl.decl.print())
}
}
clean::Tuple(ref typs) => {
match &typs[..] {
&[] => primitive_link(f, PrimitiveType::Unit, "()"),
&[ref one] => {
primitive_link(f, PrimitiveType::Tuple, "(")?;
// Carry `f.alternate()` into this display w/o branching manually.
fmt::Display::fmt(&one.print(), f)?;
primitive_link(f, PrimitiveType::Tuple, ",)")
}
many => {
primitive_link(f, PrimitiveType::Tuple, "(")?;
for (i, item) in many.iter().enumerate() {
if i != 0 { write!(f, ", ")?; }
fmt::Display::fmt(&item.print(), f)?;
}
primitive_link(f, PrimitiveType::Tuple, ")")
}
}
}
clean::Slice(ref t) => {
primitive_link(f, PrimitiveType::Slice, "[")?;
fmt::Display::fmt(&t.print(), f)?;
primitive_link(f, PrimitiveType::Slice, "]")
}
clean::Array(ref t, ref n) => {
primitive_link(f, PrimitiveType::Array, "[")?;
fmt::Display::fmt(&t.print(), f)?;
primitive_link(f, PrimitiveType::Array, &format!("; {}]", n))
}
clean::Never => primitive_link(f, PrimitiveType::Never, "!"),
clean::RawPointer(m, ref t) => {
let m = match m {
hir::Mutability::Mut => "mut",
hir::Mutability::Not => "const",
};
match **t {
clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
if f.alternate() {
primitive_link(f, clean::PrimitiveType::RawPointer,
&format!("*{} {:#}", m, t.print()))
} else {
primitive_link(f, clean::PrimitiveType::RawPointer,
&format!("*{} {}", m, t.print()))
}
}
_ => {
primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m))?;
fmt::Display::fmt(&t.print(), f)
}
}
}
clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
let lt = match l {
Some(l) => format!("{} ", l.print()),
_ => String::new()
};
let m = mutability.print_with_space();
let amp = if f.alternate() {
"&".to_string()
} else {
"&".to_string()
};
match **ty {
clean::Slice(ref bt) => { // `BorrowedRef{ ... Slice(T) }` is `&[T]`
match **bt {
clean::Generic(_) => {
if f.alternate() {
primitive_link(f, PrimitiveType::Slice,
&format!("{}{}{}[{:#}]", amp, lt, m, bt.print()))
} else {
primitive_link(f, PrimitiveType::Slice,
&format!("{}{}{}[{}]", amp, lt, m, bt.print()))
}
}
_ => {
primitive_link(f, PrimitiveType::Slice,
&format!("{}{}{}[", amp, lt, m))?;
if f.alternate() {
write!(f, "{:#}", bt.print())?;
} else {
write!(f, "{}", bt.print())?;
}
primitive_link(f, PrimitiveType::Slice, "]")
}
}
}
clean::ResolvedPath { param_names: Some(ref v), .. } if !v.is_empty() => {
write!(f, "{}{}{}(", amp, lt, m)?;
fmt_type(&ty, f, use_absolute)?;
write!(f, ")")
}
clean::Generic(..) => {
primitive_link(f, PrimitiveType::Reference,
&format!("{}{}{}", amp, lt, m))?;
fmt_type(&ty, f, use_absolute)
}
_ => {
write!(f, "{}{}{}", amp, lt, m)?;
fmt_type(&ty, f, use_absolute)
}
}
}
clean::ImplTrait(ref bounds) => {
if f.alternate() {
write!(f, "impl {:#}", print_generic_bounds(bounds))
} else {
write!(f, "impl {}", print_generic_bounds(bounds))
}
}
clean::QPath { ref name, ref self_type, ref trait_ } => {
let should_show_cast = match *trait_ {
box clean::ResolvedPath { ref path, .. } => {
!path.segments.is_empty() && !self_type.is_self_type()
}
_ => true,
};
if f.alternate() {
if should_show_cast {
write!(f, "<{:#} as {:#}>::", self_type.print(), trait_.print())?
} else {
write!(f, "{:#}::", self_type.print())?
}
} else {
if should_show_cast {
write!(f, "<{} as {}>::", self_type.print(), trait_.print())?
} else {
write!(f, "{}::", self_type.print())?
}
};
match *trait_ {
// It's pretty unsightly to look at `<A as B>::C` in output, and
// we've got hyperlinking on our side, so try to avoid longer
// notation as much as possible by making `C` a hyperlink to trait
// `B` to disambiguate.
//
// FIXME: this is still a lossy conversion and there should probably
// be a better way of representing this in general? Most of
// the ugliness comes from inlining across crates where
// everything comes in as a fully resolved QPath (hard to
// look at).
box clean::ResolvedPath { did, ref param_names, .. } => {
match href(did) {
Some((ref url, _, ref path)) if !f.alternate() => {
write!(f,
"<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
title=\"type {path}::{name}\">{name}</a>",
url = url,
shortty = ItemType::AssocType,
name = name,
path = path.join("::"))?;
}
_ => write!(f, "{}", name)?,
}
// FIXME: `param_names` are not rendered, and this seems bad?
drop(param_names);
Ok(())
}
_ => {
write!(f, "{}", name)
}
}
}
}
}
impl clean::Type {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
fmt_type(self, f, false)
})
}
}
impl clean::Impl {
crate fn print(&self) -> impl fmt::Display + '_ {
self.print_inner(true, false)
}
fn print_inner(
&self,
link_trait: bool,
use_absolute: bool,
) -> impl fmt::Display + '_ {
display_fn(move |f| {
if f.alternate() {
write!(f, "impl{:#} ", self.generics.print())?;
} else {
write!(f, "impl{} ", self.generics.print())?;
}
if let Some(ref ty) = self.trait_ {
if self.polarity == Some(clean::ImplPolarity::Negative) {
write!(f, "!")?;
}
if link_trait {
fmt::Display::fmt(&ty.print(), f)?;
} else {
match ty {
clean::ResolvedPath { param_names: None, path, is_generic: false, .. } => {
let last = path.segments.last().unwrap();
fmt::Display::fmt(&last.name, f)?;
fmt::Display::fmt(&last.args.print(), f)?;
}
_ => unreachable!(),
}
}
write!(f, " for ")?;
}
if let Some(ref ty) = self.blanket_impl {
fmt_type(ty, f, use_absolute)?;
} else {
fmt_type(&self.for_, f, use_absolute)?;
}
fmt::Display::fmt(&WhereClause {
gens: &self.generics,
indent: 0,
end_newline: true,
}, f)?;
Ok(())
})
}
}
// The difference from above is that trait is not hyperlinked.
pub fn fmt_impl_for_trait_page(i: &clean::Impl,
f: &mut Buffer,
use_absolute: bool) {
f.from_display(i.print_inner(false, use_absolute))
}
impl clean::Arguments {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
for (i, input) in self.values.iter().enumerate() {
if !input.name.is_empty() {
write!(f, "{}: ", input.name)?;
}
if f.alternate() {
write!(f, "{:#}", input.type_.print())?;
} else {
write!(f, "{}", input.type_.print())?;
}
if i + 1 < self.values.len() { write!(f, ", ")?; }
}
Ok(())
})
}
}
impl clean::FunctionRetTy {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
match self {
clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
clean::Return(ty) if f.alternate() => write!(f, " -> {:#}", ty.print()),
clean::Return(ty) => write!(f, " -> {}", ty.print()),
clean::DefaultReturn => Ok(()),
}
})
}
}
impl clean::BareFunctionDecl {
fn print_generic_params(&self) -> impl fmt::Display + '_ {
comma_sep(self.generic_params.iter().map(|g| g.print()))
}
}
impl clean::FnDecl {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
let ellipsis = if self.c_variadic { ", ..." } else { "" };
if f.alternate() {
write!(f,
"({args:#}{ellipsis}){arrow:#}",
args = self.inputs.print(), ellipsis = ellipsis, arrow = self.output.print())
} else {
write!(f,
"({args}{ellipsis}){arrow}",
args = self.inputs.print(), ellipsis = ellipsis, arrow = self.output.print())
}
})
}
}
impl Function<'_> {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
let &Function { decl, header_len, indent, asyncness } = self;
let amp = if f.alternate() { "&" } else { "&" };
let mut args = String::new();
let mut args_plain = String::new();
for (i, input) in decl.inputs.values.iter().enumerate() {
if i == 0 {
args.push_str("<br>");
}
if let Some(selfty) = input.to_self() {
match selfty {
clean::SelfValue => {
args.push_str("self");
args_plain.push_str("self");
}
clean::SelfBorrowed(Some(ref lt), mtbl) => {
args.push_str(
&format!("{}{} {}self", amp, lt.print(), mtbl.print_with_space()));
args_plain.push_str(
&format!("&{} {}self", lt.print(), mtbl.print_with_space()));
}
clean::SelfBorrowed(None, mtbl) => {
args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
}
clean::SelfExplicit(ref typ) => {
if f.alternate() {
args.push_str(&format!("self: {:#}", typ.print()));
} else {
args.push_str(&format!("self: {}", typ.print()));
}
args_plain.push_str(&format!("self: {:#}", typ.print()));
}
}
} else {
if i > 0 {
args.push_str(" <br>");
args_plain.push_str(" ");
}
if !input.name.is_empty() {
args.push_str(&format!("{}: ", input.name));
args_plain.push_str(&format!("{}: ", input.name));
}
if f.alternate() {
args.push_str(&format!("{:#}", input.type_.print()));
} else {
args.push_str(&input.type_.print().to_string());
}
args_plain.push_str(&format!("{:#}", input.type_.print()));
}
if i + 1 < decl.inputs.values.len() {
args.push(',');
args_plain.push(',');
}
}
let mut args_plain = format!("({})", args_plain);
if decl.c_variadic {
args.push_str(",<br> ...");
args_plain.push_str(", ...");
}
let output = if let hir::IsAsync::Async = asyncness {
Cow::Owned(decl.sugared_async_return_type())
} else {
Cow::Borrowed(&decl.output)
};
let arrow_plain = format!("{:#}", &output.print());
let arrow = if f.alternate() {
format!("{:#}", &output.print())
} else {
output.print().to_string()
};
let declaration_len = header_len + args_plain.len() + arrow_plain.len();
let output = if declaration_len > 80 {
let full_pad = format!("<br>{}", " ".repeat(indent + 4));
let close_pad = format!("<br>{}", " ".repeat(indent));
format!("({args}{close}){arrow}",
args = args.replace("<br>", &full_pad),
close = close_pad,
arrow = arrow)
} else {
format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
};
if f.alternate() {
write!(f, "{}", output.replace("<br>", "\n"))
} else {
write!(f, "{}", output)
}
})
}
}
impl clean::Visibility {
crate fn print_with_space(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
match *self {
clean::Public => f.write_str("pub "),
clean::Inherited => Ok(()),
clean::Visibility::Crate => write!(f, "pub(crate) "),
clean::Visibility::Restricted(did, ref path) => {
f.write_str("pub(")?;
if path.segments.len() != 1
|| (path.segments[0].name != "self" && path.segments[0].name != "super")
{
f.write_str("in ")?;
}
resolved_path(f, did, path, true, false)?;
f.write_str(") ")
}
}
})
}
}
crate trait PrintWithSpace {
fn print_with_space(&self) -> &str;
}
impl PrintWithSpace for hir::Unsafety {
fn print_with_space(&self) -> &str {
match self {
hir::Unsafety::Unsafe => "unsafe ",
hir::Unsafety::Normal => ""
}
}
}
impl PrintWithSpace for hir::Constness {
fn print_with_space(&self) -> &str {
match self {
hir::Constness::Const => "const ",
hir::Constness::NotConst => ""
}
}
}
impl PrintWithSpace for hir::IsAsync {
fn print_with_space(&self) -> &str {
match self {
hir::IsAsync::Async => "async ",
hir::IsAsync::NotAsync => "",
}
}
}
impl PrintWithSpace for hir::Mutability {
fn print_with_space(&self) -> &str {
match self {
hir::Mutability::Not => "",
hir::Mutability::Mut => "mut ",
}
}
}
impl clean::Import {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
match *self {
clean::Import::Simple(ref name, ref src) => {
if *name == src.path.last_name() {
write!(f, "use {};", src.print())
} else {
write!(f, "use {} as {};", src.print(), *name)
}
}
clean::Import::Glob(ref src) => {
if src.path.segments.is_empty() {
write!(f, "use *;")
} else {
write!(f, "use {}::*;", src.print())
}
}
}
})
}
}
impl clean::ImportSource {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
match self.did {
Some(did) => resolved_path(f, did, &self.path, true, false),
_ => {
for (i, seg) in self.path.segments.iter().enumerate() {
if i > 0 {
write!(f, "::")?
}
write!(f, "{}", seg.name)?;
}
Ok(())
}
}
})
}
}
impl clean::TypeBinding {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
f.write_str(&self.name)?;
match self.kind {
clean::TypeBindingKind::Equality { ref ty } => {
if f.alternate() {
write!(f, " = {:#}", ty.print())?;
} else {
write!(f, " = {}", ty.print())?;
}
}
clean::TypeBindingKind::Constraint { ref bounds } => {
if !bounds.is_empty() {
if f.alternate() {
write!(f, ": {:#}", print_generic_bounds(bounds))?;
} else {
write!(f, ": {}", print_generic_bounds(bounds))?;
}
}
}
}
Ok(())
})
}
}
crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
display_fn(move |f| {
let quot = if f.alternate() { "\"" } else { """ };
match abi {
Abi::Rust => Ok(()),
abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
}
})
}
crate fn print_default_space<'a>(v: bool) -> &'a str {
if v {
"default "
} else {
""
}
}
impl clean::GenericArg {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
match self {
clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(), f),
clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(), f),
}
})
}
}
crate fn display_fn(
f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
) -> impl fmt::Display {
WithFormatter(Cell::new(Some(f)))
}
struct WithFormatter<F>(Cell<Option<F>>);
impl<F> fmt::Display for WithFormatter<F>
where F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(self.0.take()).unwrap()(f)
}
}
| 34.626656 | 99 | 0.406417 |
29eb4ea451fea76fc37fc9045a0f72fa9f1493e3 | 1,851 | // Copyright 2018 The Chromium OS 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 std::ops::Deref;
use crate::bindings::libusb_endpoint_descriptor;
use crate::types::{EndpointDirection, EndpointType};
/// EndpointDescriptor wraps libusb_endpoint_descriptor.
pub struct EndpointDescriptor<'a>(&'a libusb_endpoint_descriptor);
const ENDPOINT_DESCRIPTOR_DIRECTION_MASK: u8 = 1 << 7;
const ENDPOINT_DESCRIPTOR_NUMBER_MASK: u8 = 0xf;
const ENDPOINT_DESCRIPTOR_ATTRIBUTES_TYPE_MASK: u8 = 0x3;
impl<'a> EndpointDescriptor<'a> {
// Create new endpoint descriptor.
pub fn new(descriptor: &libusb_endpoint_descriptor) -> EndpointDescriptor {
EndpointDescriptor(descriptor)
}
// Get direction of this endpoint.
pub fn get_direction(&self) -> EndpointDirection {
let direction = self.0.bEndpointAddress & ENDPOINT_DESCRIPTOR_DIRECTION_MASK;
if direction > 0 {
EndpointDirection::DeviceToHost
} else {
EndpointDirection::HostToDevice
}
}
// Get endpoint number.
pub fn get_endpoint_number(&self) -> u8 {
self.0.bEndpointAddress & ENDPOINT_DESCRIPTOR_NUMBER_MASK
}
// Get endpoint type.
pub fn get_endpoint_type(&self) -> Option<EndpointType> {
let ep_type = self.0.bmAttributes & ENDPOINT_DESCRIPTOR_ATTRIBUTES_TYPE_MASK;
match ep_type {
0 => Some(EndpointType::Control),
1 => Some(EndpointType::Isochronous),
2 => Some(EndpointType::Bulk),
3 => Some(EndpointType::Interrupt),
_ => None,
}
}
}
impl<'a> Deref for EndpointDescriptor<'a> {
type Target = libusb_endpoint_descriptor;
fn deref(&self) -> &libusb_endpoint_descriptor {
self.0
}
}
| 31.913793 | 85 | 0.681253 |
09a70c3a686078c2c6b10aa208abe6fa1fc3d50d | 343 | pub trait ResultFn {
type Result;
fn result(self) -> Self::Result;
}
impl ResultFn for () {
type Result = ();
fn result(self) {}
}
pub struct Id<T>(T);
impl<T> ResultFn for Id<T> {
type Result = T;
fn result(self) -> T {
self.0
}
}
impl<T> Id<T> {
pub fn new(v: T) -> Self {
Self(v)
}
}
| 13.72 | 36 | 0.504373 |
3883d86520fee7334b17a63cc7e732ea30198d34 | 45,561 | //! An "interner" is a data structure that associates values with usize tags and
//! allows bidirectional lookup; i.e., given a value, one can easily find the
//! type, and vice versa.
use rustc_arena::DroplessArena;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
use rustc_macros::HashStable_Generic;
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
use std::cmp::{Ord, PartialEq, PartialOrd};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::str;
use crate::{Span, DUMMY_SP, SESSION_GLOBALS};
#[cfg(test)]
mod tests;
// The proc macro code for this is in `src/librustc_macros/src/symbols.rs`.
symbols! {
// After modifying this list adjust `is_special`, `is_used_keyword`/`is_unused_keyword`,
// this should be rarely necessary though if the keywords are kept in alphabetic order.
Keywords {
// Special reserved identifiers used internally for elided lifetimes,
// unnamed method parameters, crate root module, error recovery etc.
Invalid: "",
PathRoot: "{{root}}",
DollarCrate: "$crate",
Underscore: "_",
// Keywords that are used in stable Rust.
As: "as",
Break: "break",
Const: "const",
Continue: "continue",
Crate: "crate",
Else: "else",
Enum: "enum",
Extern: "extern",
False: "false",
Fn: "fn",
For: "for",
If: "if",
Impl: "impl",
In: "in",
Let: "let",
Loop: "loop",
Match: "match",
Mod: "mod",
Move: "move",
Mut: "mut",
Pub: "pub",
Ref: "ref",
Return: "return",
SelfLower: "self",
SelfUpper: "Self",
Static: "static",
Struct: "struct",
Super: "super",
Trait: "trait",
True: "true",
Type: "type",
Unsafe: "unsafe",
Use: "use",
Where: "where",
While: "while",
// Keywords that are used in unstable Rust or reserved for future use.
Abstract: "abstract",
Become: "become",
Box: "box",
Do: "do",
Final: "final",
Macro: "macro",
Override: "override",
Priv: "priv",
Typeof: "typeof",
Unsized: "unsized",
Virtual: "virtual",
Yield: "yield",
// Edition-specific keywords that are used in stable Rust.
Async: "async", // >= 2018 Edition only
Await: "await", // >= 2018 Edition only
Dyn: "dyn", // >= 2018 Edition only
// Edition-specific keywords that are used in unstable Rust or reserved for future use.
Try: "try", // >= 2018 Edition only
// Special lifetime names
UnderscoreLifetime: "'_",
StaticLifetime: "'static",
// Weak keywords, have special meaning only in specific contexts.
Auto: "auto",
Catch: "catch",
Default: "default",
MacroRules: "macro_rules",
Raw: "raw",
Union: "union",
}
// Pre-interned symbols that can be referred to with `rustc_span::sym::*`.
//
// The symbol is the stringified identifier unless otherwise specified, in
// which case the name should mention the non-identifier punctuation.
// E.g. `sym::proc_dash_macro` represents "proc-macro", and it shouldn't be
// called `sym::proc_macro` because then it's easy to mistakenly think it
// represents "proc_macro".
//
// As well as the symbols listed, there are symbols for the the strings
// "0", "1", ..., "9", which are accessible via `sym::integer`.
//
// The proc macro will abort if symbols are not in alphabetical order (as
// defined by `impl Ord for str`) or if any symbols are duplicated. Vim
// users can sort the list by selecting it and executing the command
// `:'<,'>!LC_ALL=C sort`.
//
// There is currently no checking that all symbols are used; that would be
// nice to have.
Symbols {
Alignment,
Arc,
Argument,
ArgumentV1,
Arguments,
C,
Center,
Clone,
Copy,
Count,
Debug,
Decodable,
Decoder,
Default,
Encodable,
Encoder,
Eq,
Equal,
Err,
Error,
FormatSpec,
Formatter,
From,
Future,
FxHashMap,
FxHashSet,
GlobalAlloc,
Hash,
HashMap,
HashSet,
Hasher,
Implied,
Input,
IntoIterator,
Is,
ItemContext,
Iterator,
Layout,
Left,
LintPass,
None,
Ok,
Option,
Ord,
Ordering,
Output,
Param,
PartialEq,
PartialOrd,
Pending,
Pin,
Poll,
ProcMacro,
ProcMacroHack,
ProceduralMasqueradeDummyType,
Range,
RangeFrom,
RangeFull,
RangeInclusive,
RangeTo,
RangeToInclusive,
Rc,
Ready,
Result,
Return,
Right,
RustcDecodable,
RustcEncodable,
Send,
Some,
StructuralEq,
StructuralPartialEq,
Sync,
Target,
Try,
Ty,
TyCtxt,
TyKind,
Unknown,
Vec,
Yield,
_DECLS,
_Self,
__D,
__H,
__S,
__next,
__try_var,
_d,
_e,
_task_context,
aarch64_target_feature,
abi,
abi_amdgpu_kernel,
abi_avr_interrupt,
abi_efiapi,
abi_msp430_interrupt,
abi_ptx,
abi_sysv64,
abi_thiscall,
abi_unadjusted,
abi_vectorcall,
abi_x86_interrupt,
abort,
aborts,
add,
add_assign,
add_with_overflow,
address,
advanced_slice_patterns,
adx_target_feature,
alias,
align,
align_offset,
alignstack,
all,
alloc,
alloc_error_handler,
alloc_layout,
alloc_zeroed,
allocator,
allocator_internals,
allow,
allow_fail,
allow_internal_unsafe,
allow_internal_unstable,
allow_internal_unstable_backcompat_hack,
allowed,
always,
and,
and_then,
any,
arbitrary_enum_discriminant,
arbitrary_self_types,
arith_offset,
arm_target_feature,
array,
as_str,
asm,
assert,
assert_inhabited,
assert_receiver_is_total_eq,
assert_uninit_valid,
assert_zero_valid,
associated_consts,
associated_type_bounds,
associated_type_defaults,
associated_types,
assume,
assume_init,
async_await,
async_closure,
atomics,
att_syntax,
attr,
attr_literals,
attributes,
augmented_assignments,
automatically_derived,
avx512_target_feature,
await_macro,
bang,
begin_panic,
bench,
bin,
bind_by_move_pattern_guards,
bindings_after_at,
bitand,
bitand_assign,
bitor,
bitor_assign,
bitreverse,
bitxor,
bitxor_assign,
block,
bool,
borrowck_graphviz_format,
borrowck_graphviz_postflow,
borrowck_graphviz_preflow,
box_free,
box_patterns,
box_syntax,
braced_empty_structs,
breakpoint,
bridge,
bswap,
c_variadic,
call,
call_mut,
call_once,
caller_location,
cdylib,
ceilf32,
ceilf64,
cfg,
cfg_accessible,
cfg_attr,
cfg_attr_multi,
cfg_doctest,
cfg_sanitize,
cfg_target_feature,
cfg_target_has_atomic,
cfg_target_thread_local,
cfg_target_vendor,
cfg_version,
char,
client,
clippy,
clone,
clone_closures,
clone_from,
closure_to_fn_coercion,
cmp,
cmpxchg16b_target_feature,
coerce_unsized,
cold,
column,
compile_error,
compiler_builtins,
concat,
concat_idents,
conservative_impl_trait,
console,
const_compare_raw_pointers,
const_constructor,
const_eval_limit,
const_extern_fn,
const_fn,
const_fn_transmute,
const_fn_union,
const_generics,
const_if_match,
const_in_array_repeat_expressions,
const_indexing,
const_let,
const_loop,
const_mut_refs,
const_panic,
const_precise_live_drops,
const_ptr,
const_raw_ptr_deref,
const_raw_ptr_to_usize_cast,
const_slice_ptr,
const_trait_bound_opt_out,
const_trait_impl,
const_transmute,
contents,
context,
convert,
copy,
copy_closures,
copy_nonoverlapping,
copysignf32,
copysignf64,
core,
core_intrinsics,
cosf32,
cosf64,
crate_id,
crate_in_paths,
crate_local,
crate_name,
crate_type,
crate_visibility_modifier,
crt_dash_static: "crt-static",
ctlz,
ctlz_nonzero,
ctpop,
cttz,
cttz_nonzero,
custom_attribute,
custom_derive,
custom_inner_attributes,
custom_test_frameworks,
d,
dead_code,
dealloc,
debug,
debug_assertions,
debug_struct,
debug_trait,
debug_trait_builder,
debug_tuple,
decl_macro,
declare_lint_pass,
decode,
default_lib_allocator,
default_type_parameter_fallback,
default_type_params,
delay_span_bug_from_inside_query,
deny,
deprecated,
deref,
deref_mut,
derive,
diagnostic,
direct,
discriminant_kind,
discriminant_type,
discriminant_value,
dispatch_from_dyn,
div,
div_assign,
doc,
doc_alias,
doc_cfg,
doc_keyword,
doc_masked,
doc_spotlight,
doctest,
document_private_items,
dotdot_in_tuple_patterns,
dotdoteq_in_patterns,
double_braced_closure: "{{closure}}",
double_braced_constant: "{{constant}}",
double_braced_constructor: "{{constructor}}",
double_braced_crate: "{{crate}}",
double_braced_impl: "{{impl}}",
double_braced_misc: "{{misc}}",
double_braced_opaque: "{{opaque}}",
drop,
drop_in_place,
drop_types_in_const,
dropck_eyepatch,
dropck_parametricity,
dylib,
dyn_trait,
eh_catch_typeinfo,
eh_personality,
emit_enum,
emit_enum_variant,
emit_enum_variant_arg,
emit_struct,
emit_struct_field,
enable,
enclosing_scope,
encode,
env,
eq,
err,
exact_div,
except,
exchange_malloc,
exclusive_range_pattern,
exhaustive_integer_patterns,
exhaustive_patterns,
existential_type,
exp2f32,
exp2f64,
expected,
expf32,
expf64,
export_name,
expr,
extern_absolute_paths,
extern_crate_item_prelude,
extern_crate_self,
extern_in_paths,
extern_prelude,
extern_types,
external_doc,
f,
f16c_target_feature,
f32,
f32_runtime,
f64,
f64_runtime,
fabsf32,
fabsf64,
fadd_fast,
fdiv_fast,
feature,
ffi_const,
ffi_pure,
ffi_returns_twice,
field,
field_init_shorthand,
file,
fill,
finish,
flags,
float_to_int_unchecked,
floorf32,
floorf64,
fmaf32,
fmaf64,
fmt,
fmt_internals,
fmul_fast,
fn_must_use,
fn_mut,
fn_once,
fn_once_output,
forbid,
forget,
format,
format_args,
format_args_capture,
format_args_nl,
freeze,
frem_fast,
from,
from_desugaring,
from_error,
from_generator,
from_method,
from_ok,
from_size_align_unchecked,
from_trait,
from_usize,
fsub_fast,
fundamental,
future,
future_trait,
ge,
gen_future,
gen_kill,
generator,
generator_state,
generators,
generic_associated_types,
generic_param_attrs,
get_context,
global_allocator,
global_asm,
globs,
gt,
half_open_range_patterns,
hash,
hexagon_target_feature,
hidden,
homogeneous_aggregate,
html_favicon_url,
html_logo_url,
html_no_source,
html_playground_url,
html_root_url,
i,
i128,
i128_type,
i16,
i32,
i64,
i8,
ident,
if_let,
if_while_or_patterns,
ignore,
impl_header_lifetime_elision,
impl_lint_pass,
impl_trait_in_bindings,
import_shadowing,
in_band_lifetimes,
include,
include_bytes,
include_str,
inclusive_range_syntax,
index,
index_mut,
infer_outlives_requirements,
infer_static_outlives_requirements,
inlateout,
inline,
inout,
intel,
into_iter,
into_result,
intrinsics,
irrefutable_let_patterns,
isize,
issue,
issue_5723_bootstrap,
issue_tracker_base_url,
item,
item_like_imports,
iter,
keyword,
kind,
label,
label_break_value,
lang,
lang_items,
lateout,
lazy_normalization_consts,
le,
let_chains,
lhs,
lib,
libc,
lifetime,
likely,
line,
link,
link_args,
link_cfg,
link_llvm_intrinsics,
link_name,
link_ordinal,
link_section,
linkage,
lint_reasons,
literal,
llvm_asm,
local_inner_macros,
log10f32,
log10f64,
log2f32,
log2f64,
log_syntax,
logf32,
logf64,
loop_break_value,
lt,
macro_at_most_once_rep,
macro_escape,
macro_export,
macro_lifetime_matcher,
macro_literal_matcher,
macro_reexport,
macro_use,
macro_vis_matcher,
macros_in_extern,
main,
managed_boxes,
manually_drop,
map,
marker,
marker_trait_attr,
masked,
match_beginning_vert,
match_default_bindings,
maxnumf32,
maxnumf64,
may_dangle,
maybe_uninit,
maybe_uninit_uninit,
maybe_uninit_zeroed,
mem_uninitialized,
mem_zeroed,
member_constraints,
memory,
message,
meta,
min_align_of,
min_align_of_val,
min_const_fn,
min_const_generics,
min_const_unsafe_fn,
min_specialization,
minnumf32,
minnumf64,
mips_target_feature,
mmx_target_feature,
module,
module_path,
more_struct_aliases,
movbe_target_feature,
move_ref_pattern,
move_val_init,
mul,
mul_assign,
mul_with_overflow,
must_use,
mut_ptr,
mut_slice_ptr,
naked,
naked_functions,
name,
ne,
nearbyintf32,
nearbyintf64,
needs_allocator,
needs_drop,
needs_panic_runtime,
neg,
negate_unsigned,
negative_impls,
never,
never_type,
never_type_fallback,
new,
new_unchecked,
next,
nll,
no,
no_builtins,
no_core,
no_crate_inject,
no_debug,
no_default_passes,
no_implicit_prelude,
no_inline,
no_link,
no_main,
no_mangle,
no_niche,
no_sanitize,
no_stack_check,
no_start,
no_std,
nomem,
non_ascii_idents,
non_exhaustive,
non_modrs_mods,
none_error,
nontemporal_store,
nontrapping_dash_fptoint: "nontrapping-fptoint",
noreturn,
nostack,
not,
note,
object_safe_for_dispatch,
of,
offset,
omit_gdb_pretty_printer_section,
on,
on_unimplemented,
oom,
opaque,
ops,
opt_out_copy,
optimize,
optimize_attribute,
optin_builtin_traits,
option,
option_env,
option_type,
options,
or,
or_patterns,
other,
out,
overlapping_marker_traits,
owned_box,
packed,
panic,
panic_abort,
panic_bounds_check,
panic_handler,
panic_impl,
panic_implementation,
panic_info,
panic_location,
panic_runtime,
panic_unwind,
param_attrs,
parent_trait,
partial_cmp,
partial_ord,
passes,
pat,
path,
pattern_parentheses,
phantom_data,
pin,
pinned,
platform_intrinsics,
plugin,
plugin_registrar,
plugins,
pointer,
poll,
position,
post_dash_lto: "post-lto",
powerpc_target_feature,
powf32,
powf64,
powif32,
powif64,
pre_dash_lto: "pre-lto",
precise_pointer_size_matching,
precision,
pref_align_of,
prefetch_read_data,
prefetch_read_instruction,
prefetch_write_data,
prefetch_write_instruction,
prelude,
prelude_import,
preserves_flags,
primitive,
proc_dash_macro: "proc-macro",
proc_macro,
proc_macro_attribute,
proc_macro_def_site,
proc_macro_derive,
proc_macro_expr,
proc_macro_gen,
proc_macro_hygiene,
proc_macro_internals,
proc_macro_mod,
proc_macro_non_items,
proc_macro_path_invoc,
profiler_builtins,
profiler_runtime,
ptr_guaranteed_eq,
ptr_guaranteed_ne,
ptr_offset_from,
pub_restricted,
pure,
pushpop_unsafe,
quad_precision_float,
question_mark,
quote,
range_inclusive_new,
raw_dylib,
raw_identifiers,
raw_ref_op,
re_rebalance_coherence,
read_enum,
read_enum_variant,
read_enum_variant_arg,
read_struct,
read_struct_field,
readonly,
realloc,
reason,
receiver,
recursion_limit,
reexport_test_harness_main,
reference,
reflect,
register_attr,
register_tool,
relaxed_adts,
rem,
rem_assign,
repr,
repr128,
repr_align,
repr_align_enum,
repr_no_niche,
repr_packed,
repr_simd,
repr_transparent,
result,
result_type,
rhs,
rintf32,
rintf64,
riscv_target_feature,
rlib,
rotate_left,
rotate_right,
roundf32,
roundf64,
rt,
rtm_target_feature,
rust,
rust_2015_preview,
rust_2018_preview,
rust_begin_unwind,
rust_eh_personality,
rust_eh_register_frames,
rust_eh_unregister_frames,
rust_oom,
rustc,
rustc_allocator,
rustc_allocator_nounwind,
rustc_allow_const_fn_ptr,
rustc_args_required_const,
rustc_attrs,
rustc_builtin_macro,
rustc_clean,
rustc_const_stable,
rustc_const_unstable,
rustc_conversion_suggestion,
rustc_def_path,
rustc_deprecated,
rustc_diagnostic_item,
rustc_diagnostic_macros,
rustc_dirty,
rustc_dummy,
rustc_dump_env_program_clauses,
rustc_dump_program_clauses,
rustc_dump_user_substs,
rustc_error,
rustc_expected_cgu_reuse,
rustc_if_this_changed,
rustc_inherit_overflow_checks,
rustc_layout,
rustc_layout_scalar_valid_range_end,
rustc_layout_scalar_valid_range_start,
rustc_macro_transparency,
rustc_mir,
rustc_nonnull_optimization_guaranteed,
rustc_object_lifetime_default,
rustc_on_unimplemented,
rustc_outlives,
rustc_paren_sugar,
rustc_partition_codegened,
rustc_partition_reused,
rustc_peek,
rustc_peek_definite_init,
rustc_peek_indirectly_mutable,
rustc_peek_liveness,
rustc_peek_maybe_init,
rustc_peek_maybe_uninit,
rustc_polymorphize_error,
rustc_private,
rustc_proc_macro_decls,
rustc_promotable,
rustc_regions,
rustc_reservation_impl,
rustc_serialize,
rustc_specialization_trait,
rustc_stable,
rustc_std_internal_symbol,
rustc_symbol_name,
rustc_synthetic,
rustc_test_marker,
rustc_then_this_would_need,
rustc_unsafe_specialization_marker,
rustc_variance,
rustfmt,
rvalue_static_promotion,
sanitize,
sanitizer_runtime,
saturating_add,
saturating_sub,
self_in_typedefs,
self_struct_ctor,
semitransparent,
send_trait,
shl,
shl_assign,
should_panic,
shr,
shr_assign,
simd,
simd_add,
simd_and,
simd_bitmask,
simd_cast,
simd_ceil,
simd_div,
simd_eq,
simd_extract,
simd_fabs,
simd_fcos,
simd_fexp,
simd_fexp2,
simd_ffi,
simd_flog,
simd_flog10,
simd_flog2,
simd_floor,
simd_fma,
simd_fmax,
simd_fmin,
simd_fpow,
simd_fpowi,
simd_fsin,
simd_fsqrt,
simd_gather,
simd_ge,
simd_gt,
simd_insert,
simd_le,
simd_lt,
simd_mul,
simd_ne,
simd_or,
simd_reduce_add_ordered,
simd_reduce_add_unordered,
simd_reduce_all,
simd_reduce_and,
simd_reduce_any,
simd_reduce_max,
simd_reduce_max_nanless,
simd_reduce_min,
simd_reduce_min_nanless,
simd_reduce_mul_ordered,
simd_reduce_mul_unordered,
simd_reduce_or,
simd_reduce_xor,
simd_rem,
simd_saturating_add,
simd_saturating_sub,
simd_scatter,
simd_select,
simd_select_bitmask,
simd_shl,
simd_shr,
simd_sub,
simd_xor,
since,
sinf32,
sinf64,
size,
size_of,
size_of_val,
sized,
slice,
slice_alloc,
slice_patterns,
slice_u8,
slice_u8_alloc,
slicing_syntax,
soft,
specialization,
speed,
spotlight,
sqrtf32,
sqrtf64,
sse4a_target_feature,
stable,
staged_api,
start,
state,
static_in_const,
static_nobundle,
static_recursion,
staticlib,
std,
std_inject,
stmt,
stmt_expr_attributes,
stop_after_dataflow,
str,
str_alloc,
string_type,
stringify,
struct_field_attributes,
struct_inherit,
struct_variant,
structural_match,
structural_peq,
structural_teq,
sty,
sub,
sub_assign,
sub_with_overflow,
suggestion,
sym,
sync,
sync_trait,
target_arch,
target_endian,
target_env,
target_family,
target_feature,
target_feature_11,
target_has_atomic,
target_has_atomic_load_store,
target_os,
target_pointer_width,
target_target_vendor,
target_thread_local,
target_vendor,
task,
tbm_target_feature,
termination,
termination_trait,
termination_trait_test,
test,
test_2018_feature,
test_accepted_feature,
test_case,
test_removed_feature,
test_runner,
then_with,
thread,
thread_local,
tool_attributes,
tool_lints,
trace_macros,
track_caller,
trait_alias,
transmute,
transparent,
transparent_enums,
transparent_unions,
trivial_bounds,
truncf32,
truncf64,
try_blocks,
try_trait,
tt,
tuple,
tuple_indexing,
two_phase,
ty,
type_alias_enum_variants,
type_alias_impl_trait,
type_ascription,
type_id,
type_length_limit,
type_macros,
type_name,
u128,
u16,
u32,
u64,
u8,
unaligned_volatile_load,
unaligned_volatile_store,
unboxed_closures,
unchecked_add,
unchecked_div,
unchecked_mul,
unchecked_rem,
unchecked_shl,
unchecked_shr,
unchecked_sub,
underscore_const_names,
underscore_imports,
underscore_lifetimes,
uniform_paths,
unit,
universal_impl_trait,
unix,
unlikely,
unmarked_api,
unpin,
unreachable,
unreachable_code,
unrestricted_attribute_tokens,
unsafe_block_in_unsafe_fn,
unsafe_cell,
unsafe_no_drop_flag,
unsize,
unsized_locals,
unsized_tuple_coercion,
unstable,
untagged_unions,
unused_qualifications,
unwind,
unwind_attributes,
unwrap_or,
use_extern_macros,
use_nested_groups,
used,
usize,
v1,
va_arg,
va_copy,
va_end,
va_list,
va_start,
val,
var,
variant_count,
vec,
vec_type,
version,
vis,
visible_private_types,
volatile,
volatile_copy_memory,
volatile_copy_nonoverlapping_memory,
volatile_load,
volatile_set_memory,
volatile_store,
warn,
wasm_import_module,
wasm_target_feature,
while_let,
width,
windows,
windows_subsystem,
wrapping_add,
wrapping_mul,
wrapping_sub,
write_bytes,
}
}
#[derive(Copy, Clone, Eq, HashStable_Generic, Encodable, Decodable)]
pub struct Ident {
pub name: Symbol,
pub span: Span,
}
impl Ident {
#[inline]
/// Constructs a new identifier from a symbol and a span.
pub const fn new(name: Symbol, span: Span) -> Ident {
Ident { name, span }
}
/// Constructs a new identifier with a dummy span.
#[inline]
pub const fn with_dummy_span(name: Symbol) -> Ident {
Ident::new(name, DUMMY_SP)
}
#[inline]
pub fn invalid() -> Ident {
Ident::with_dummy_span(kw::Invalid)
}
/// Maps a string to an identifier with a dummy span.
pub fn from_str(string: &str) -> Ident {
Ident::with_dummy_span(Symbol::intern(string))
}
/// Maps a string and a span to an identifier.
pub fn from_str_and_span(string: &str, span: Span) -> Ident {
Ident::new(Symbol::intern(string), span)
}
/// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
pub fn with_span_pos(self, span: Span) -> Ident {
Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
}
pub fn without_first_quote(self) -> Ident {
Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
}
/// "Normalize" ident for use in comparisons using "item hygiene".
/// Identifiers with same string value become same if they came from the same macro 2.0 macro
/// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
/// different macro 2.0 macros.
/// Technically, this operation strips all non-opaque marks from ident's syntactic context.
pub fn normalize_to_macros_2_0(self) -> Ident {
Ident::new(self.name, self.span.normalize_to_macros_2_0())
}
/// "Normalize" ident for use in comparisons using "local variable hygiene".
/// Identifiers with same string value become same if they came from the same non-transparent
/// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
/// non-transparent macros.
/// Technically, this operation strips all transparent marks from ident's syntactic context.
pub fn normalize_to_macro_rules(self) -> Ident {
Ident::new(self.name, self.span.normalize_to_macro_rules())
}
/// Convert the name to a `SymbolStr`. This is a slowish operation because
/// it requires locking the symbol interner.
pub fn as_str(self) -> SymbolStr {
self.name.as_str()
}
}
impl PartialEq for Ident {
fn eq(&self, rhs: &Self) -> bool {
self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
}
}
impl Hash for Ident {
fn hash<H: Hasher>(&self, state: &mut H) {
self.name.hash(state);
self.span.ctxt().hash(state);
}
}
impl fmt::Debug for Ident {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)?;
fmt::Debug::fmt(&self.span.ctxt(), f)
}
}
/// This implementation is supposed to be used in error messages, so it's expected to be identical
/// to printing the original identifier token written in source code (`token_to_string`),
/// except that AST identifiers don't keep the rawness flag, so we have to guess it.
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f)
}
}
/// This is the most general way to print identifiers.
/// AST pretty-printer is used as a fallback for turning AST structures into token streams for
/// proc macros. Additionally, proc macros may stringify their input and expect it survive the
/// stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
/// So we need to somehow pretty-print `$crate` in a way preserving at least some of its
/// hygiene data, most importantly name of the crate it refers to.
/// As a result we print `$crate` as `crate` if it refers to the local crate
/// and as `::other_crate_name` if it refers to some other crate.
/// Note, that this is only done if the ident token is printed from inside of AST pretty-pringing,
/// but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
/// so we should not perform this lossy conversion if the top level call to the pretty-printer was
/// done for a token stream or a single token.
pub struct IdentPrinter {
symbol: Symbol,
is_raw: bool,
/// Span used for retrieving the crate name to which `$crate` refers to,
/// if this field is `None` then the `$crate` conversion doesn't happen.
convert_dollar_crate: Option<Span>,
}
impl IdentPrinter {
/// The most general `IdentPrinter` constructor. Do not use this.
pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option<Span>) -> IdentPrinter {
IdentPrinter { symbol, is_raw, convert_dollar_crate }
}
/// This implementation is supposed to be used when printing identifiers
/// as a part of pretty-printing for larger AST pieces.
/// Do not use this either.
pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter {
IdentPrinter::new(ident.name, is_raw, Some(ident.span))
}
}
impl fmt::Display for IdentPrinter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_raw {
f.write_str("r#")?;
} else {
if self.symbol == kw::DollarCrate {
if let Some(span) = self.convert_dollar_crate {
let converted = span.ctxt().dollar_crate_name();
if !converted.is_path_segment_keyword() {
f.write_str("::")?;
}
return fmt::Display::fmt(&converted, f);
}
}
}
fmt::Display::fmt(&self.symbol, f)
}
}
/// An newtype around `Ident` that calls [Ident::normalize_to_macro_rules] on
/// construction.
// FIXME(matthewj, petrochenkov) Use this more often, add a similar
// `ModernIdent` struct and use that as well.
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct MacroRulesNormalizedIdent(Ident);
impl MacroRulesNormalizedIdent {
pub fn new(ident: Ident) -> Self {
Self(ident.normalize_to_macro_rules())
}
}
impl fmt::Debug for MacroRulesNormalizedIdent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl fmt::Display for MacroRulesNormalizedIdent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
/// An interned string.
///
/// Internally, a `Symbol` is implemented as an index, and all operations
/// (including hashing, equality, and ordering) operate on that index. The use
/// of `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
/// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
///
/// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it
/// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Symbol(SymbolIndex);
rustc_index::newtype_index! {
pub struct SymbolIndex { .. }
}
impl Symbol {
const fn new(n: u32) -> Self {
Symbol(SymbolIndex::from_u32(n))
}
/// Maps a string to its interned representation.
pub fn intern(string: &str) -> Self {
with_interner(|interner| interner.intern(string))
}
/// Access the symbol's chars. This is a slowish operation because it
/// requires locking the symbol interner.
pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
with_interner(|interner| f(interner.get(self)))
}
/// Convert to a `SymbolStr`. This is a slowish operation because it
/// requires locking the symbol interner.
pub fn as_str(self) -> SymbolStr {
with_interner(|interner| unsafe {
SymbolStr { string: std::mem::transmute::<&str, &str>(interner.get(self)) }
})
}
pub fn as_u32(self) -> u32 {
self.0.as_u32()
}
/// This method is supposed to be used in error messages, so it's expected to be
/// identical to printing the original identifier token written in source code
/// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag
/// or edition, so we have to guess the rawness using the global edition.
pub fn to_ident_string(self) -> String {
Ident::with_dummy_span(self).to_string()
}
}
impl fmt::Debug for Symbol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.with(|str| fmt::Debug::fmt(&str, f))
}
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.with(|str| fmt::Display::fmt(&str, f))
}
}
impl<S: Encoder> Encodable<S> for Symbol {
fn encode(&self, s: &mut S) -> Result<(), S::Error> {
self.with(|string| s.emit_str(string))
}
}
impl<D: Decoder> Decodable<D> for Symbol {
#[inline]
fn decode(d: &mut D) -> Result<Symbol, D::Error> {
Ok(Symbol::intern(&d.read_str()?))
}
}
impl<CTX> HashStable<CTX> for Symbol {
#[inline]
fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
self.as_str().hash_stable(hcx, hasher);
}
}
impl<CTX> ToStableHashKey<CTX> for Symbol {
type KeyType = SymbolStr;
#[inline]
fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
self.as_str()
}
}
// The `&'static str`s in this type actually point into the arena.
//
// The `FxHashMap`+`Vec` pair could be replaced by `FxIndexSet`, but #75278
// found that to regress performance up to 2% in some cases. This might be
// revisited after further improvements to `indexmap`.
#[derive(Default)]
pub struct Interner {
arena: DroplessArena,
names: FxHashMap<&'static str, Symbol>,
strings: Vec<&'static str>,
}
impl Interner {
fn prefill(init: &[&'static str]) -> Self {
Interner {
strings: init.into(),
names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
..Default::default()
}
}
#[inline]
pub fn intern(&mut self, string: &str) -> Symbol {
if let Some(&name) = self.names.get(string) {
return name;
}
let name = Symbol::new(self.strings.len() as u32);
// `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
// UTF-8.
let string: &str =
unsafe { str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
// It is safe to extend the arena allocation to `'static` because we only access
// these while the arena is still alive.
let string: &'static str = unsafe { &*(string as *const str) };
self.strings.push(string);
self.names.insert(string, name);
name
}
// Get the symbol as a string. `Symbol::as_str()` should be used in
// preference to this function.
pub fn get(&self, symbol: Symbol) -> &str {
self.strings[symbol.0.as_usize()]
}
}
// This module has a very short name because it's used a lot.
/// This module contains all the defined keyword `Symbol`s.
///
/// Given that `kw` is imported, use them like `kw::keyword_name`.
/// For example `kw::Loop` or `kw::Break`.
pub mod kw {
use super::Symbol;
keywords!();
}
// This module has a very short name because it's used a lot.
/// This module contains all the defined non-keyword `Symbol`s.
///
/// Given that `sym` is imported, use them like `sym::symbol_name`.
/// For example `sym::rustfmt` or `sym::u8`.
#[allow(rustc::default_hash_types)]
pub mod sym {
use super::Symbol;
use std::convert::TryInto;
define_symbols!();
// Used from a macro in `librustc_feature/accepted.rs`
pub use super::kw::MacroRules as macro_rules;
// Get the symbol for an integer. The first few non-negative integers each
// have a static symbol and therefore are fast.
pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
if let Result::Ok(idx) = n.try_into() {
if let Option::Some(&sym_) = digits_array.get(idx) {
return sym_;
}
}
Symbol::intern(&n.to_string())
}
}
impl Symbol {
fn is_used_keyword_2018(self) -> bool {
self >= kw::Async && self <= kw::Dyn
}
fn is_unused_keyword_2018(self) -> bool {
self == kw::Try
}
/// Used for sanity checking rustdoc keyword sections.
pub fn is_doc_keyword(self) -> bool {
self <= kw::Union
}
/// A keyword or reserved identifier that can be used as a path segment.
pub fn is_path_segment_keyword(self) -> bool {
self == kw::Super
|| self == kw::SelfLower
|| self == kw::SelfUpper
|| self == kw::Crate
|| self == kw::PathRoot
|| self == kw::DollarCrate
}
/// Returns `true` if the symbol is `true` or `false`.
pub fn is_bool_lit(self) -> bool {
self == kw::True || self == kw::False
}
/// This symbol can be a raw identifier.
pub fn can_be_raw(self) -> bool {
self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
}
}
impl Ident {
// Returns `true` for reserved identifiers used internally for elided lifetimes,
// unnamed method parameters, crate root module, error recovery etc.
pub fn is_special(self) -> bool {
self.name <= kw::Underscore
}
/// Returns `true` if the token is a keyword used in the language.
pub fn is_used_keyword(self) -> bool {
// Note: `span.edition()` is relatively expensive, don't call it unless necessary.
self.name >= kw::As && self.name <= kw::While
|| self.name.is_used_keyword_2018() && self.span.rust_2018()
}
/// Returns `true` if the token is a keyword reserved for possible future use.
pub fn is_unused_keyword(self) -> bool {
// Note: `span.edition()` is relatively expensive, don't call it unless necessary.
self.name >= kw::Abstract && self.name <= kw::Yield
|| self.name.is_unused_keyword_2018() && self.span.rust_2018()
}
/// Returns `true` if the token is either a special identifier or a keyword.
pub fn is_reserved(self) -> bool {
self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
}
/// A keyword or reserved identifier that can be used as a path segment.
pub fn is_path_segment_keyword(self) -> bool {
self.name.is_path_segment_keyword()
}
/// We see this identifier in a normal identifier position, like variable name or a type.
/// How was it written originally? Did it use the raw form? Let's try to guess.
pub fn is_raw_guess(self) -> bool {
self.name.can_be_raw() && self.is_reserved()
}
}
#[inline]
fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
SESSION_GLOBALS.with(|session_globals| f(&mut *session_globals.symbol_interner.lock()))
}
/// An alternative to `Symbol`, useful when the chars within the symbol need to
/// be accessed. It deliberately has limited functionality and should only be
/// used for temporary values.
///
/// Because the interner outlives any thread which uses this type, we can
/// safely treat `string` which points to interner data, as an immortal string,
/// as long as this type never crosses between threads.
//
// FIXME: ensure that the interner outlives any thread which uses `SymbolStr`,
// by creating a new thread right after constructing the interner.
#[derive(Clone, Eq, PartialOrd, Ord)]
pub struct SymbolStr {
string: &'static str,
}
// This impl allows a `SymbolStr` to be directly equated with a `String` or
// `&str`.
impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for SymbolStr {
fn eq(&self, other: &T) -> bool {
self.string == other.deref()
}
}
impl !Send for SymbolStr {}
impl !Sync for SymbolStr {}
/// This impl means that if `ss` is a `SymbolStr`:
/// - `*ss` is a `str`;
/// - `&*ss` is a `&str` (and `match &*ss { ... }` is a common pattern).
/// - `&ss as &str` is a `&str`, which means that `&ss` can be passed to a
/// function expecting a `&str`.
impl std::ops::Deref for SymbolStr {
type Target = str;
#[inline]
fn deref(&self) -> &str {
self.string
}
}
impl fmt::Debug for SymbolStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.string, f)
}
}
impl fmt::Display for SymbolStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self.string, f)
}
}
impl<CTX> HashStable<CTX> for SymbolStr {
#[inline]
fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
self.string.hash_stable(hcx, hasher)
}
}
impl<CTX> ToStableHashKey<CTX> for SymbolStr {
type KeyType = SymbolStr;
#[inline]
fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
self.clone()
}
}
| 26.959172 | 100 | 0.571827 |
69adb15f039374906a537fc95e6562979b191de3 | 17,202 | extern crate serde;
extern crate rltk;
use rltk::{Console, GameState, Rltk, Point};
extern crate specs;
use specs::prelude::*;
use specs::saveload::{SimpleMarker, SimpleMarkerAllocator};
#[macro_use]
extern crate specs_derive;
mod components;
pub use components::*;
mod map;
pub use map::*;
mod player;
use player::*;
mod rect;
pub use rect::Rect;
mod visibility_system;
use visibility_system::VisibilitySystem;
mod map_indexing_system;
use map_indexing_system::MapIndexingSystem;
mod melee_combat_system;
use melee_combat_system::MeleeCombatSystem;
mod damage_system;
use damage_system::DamageSystem;
mod gui;
mod gamelog;
mod spawner;
mod inventory_system;
use inventory_system::{ ItemCollectionSystem, ItemUseSystem, ItemDropSystem, ItemRemoveSystem };
pub mod saveload_system;
pub mod random_table;
pub mod particle_system;
pub mod hunger_system;
pub mod rex_assets;
pub mod trigger_system;
pub mod map_builders;
pub mod camera;
pub mod raws;
mod gamesystem;
pub use gamesystem::*;
mod lighting_system;
mod ai;
#[macro_use]
extern crate lazy_static;
const SHOW_MAPGEN_VISUALIZER : bool = false;
#[derive(PartialEq, Copy, Clone)]
pub enum RunState {
AwaitingInput,
PreRun,
Ticking,
ShowInventory,
ShowDropItem,
ShowTargeting { range : i32, item : Entity},
MainMenu { menu_selection : gui::MainMenuSelection },
SaveGame,
NextLevel,
PreviousLevel,
ShowRemoveItem,
GameOver,
MagicMapReveal { row : i32 },
MapGeneration,
ShowCheatMenu
}
pub struct State {
pub ecs: World,
mapgen_next_state : Option<RunState>,
mapgen_history : Vec<Map>,
mapgen_index : usize,
mapgen_timer : f32
}
impl State {
fn run_systems(&mut self) {
let mut mapindex = MapIndexingSystem{};
mapindex.run_now(&self.ecs);
let mut vis = VisibilitySystem{};
vis.run_now(&self.ecs);
let mut initiative = ai::InitiativeSystem{};
initiative.run_now(&self.ecs);
let mut turnstatus = ai::TurnStatusSystem{};
turnstatus.run_now(&self.ecs);
let mut quipper = ai::QuipSystem{};
quipper.run_now(&self.ecs);
let mut adjacent = ai::AdjacentAI{};
adjacent.run_now(&self.ecs);
let mut visible = ai::VisibleAI{};
visible.run_now(&self.ecs);
let mut approach = ai::ApproachAI{};
approach.run_now(&self.ecs);
let mut flee = ai::FleeAI{};
flee.run_now(&self.ecs);
let mut chase = ai::ChaseAI{};
chase.run_now(&self.ecs);
let mut defaultmove = ai::DefaultMoveAI{};
defaultmove.run_now(&self.ecs);
let mut triggers = trigger_system::TriggerSystem{};
triggers.run_now(&self.ecs);
let mut melee = MeleeCombatSystem{};
melee.run_now(&self.ecs);
let mut damage = DamageSystem{};
damage.run_now(&self.ecs);
let mut pickup = ItemCollectionSystem{};
pickup.run_now(&self.ecs);
let mut itemuse = ItemUseSystem{};
itemuse.run_now(&self.ecs);
let mut drop_items = ItemDropSystem{};
drop_items.run_now(&self.ecs);
let mut item_remove = ItemRemoveSystem{};
item_remove.run_now(&self.ecs);
let mut hunger = hunger_system::HungerSystem{};
hunger.run_now(&self.ecs);
let mut particles = particle_system::ParticleSpawnSystem{};
particles.run_now(&self.ecs);
let mut lighting = lighting_system::LightingSystem{};
lighting.run_now(&self.ecs);
self.ecs.maintain();
}
}
impl GameState for State {
fn tick(&mut self, ctx : &mut Rltk) {
let mut newrunstate;
{
let runstate = self.ecs.fetch::<RunState>();
newrunstate = *runstate;
}
ctx.cls();
particle_system::cull_dead_particles(&mut self.ecs, ctx);
match newrunstate {
RunState::MainMenu{..} => {}
RunState::GameOver{..} => {}
_ => {
camera::render_camera(&self.ecs, ctx);
gui::draw_ui(&self.ecs, ctx);
}
}
match newrunstate {
RunState::MapGeneration => {
if !SHOW_MAPGEN_VISUALIZER {
newrunstate = self.mapgen_next_state.unwrap();
} else {
ctx.cls();
if self.mapgen_index < self.mapgen_history.len() { camera::render_debug_map(&self.mapgen_history[self.mapgen_index], ctx); }
self.mapgen_timer += ctx.frame_time_ms;
if self.mapgen_timer > 500.0 {
self.mapgen_timer = 0.0;
self.mapgen_index += 1;
if self.mapgen_index >= self.mapgen_history.len() {
//self.mapgen_index -= 1;
newrunstate = self.mapgen_next_state.unwrap();
}
}
}
}
RunState::PreRun => {
self.run_systems();
self.ecs.maintain();
newrunstate = RunState::AwaitingInput;
}
RunState::AwaitingInput => {
newrunstate = player_input(self, ctx);
}
RunState::Ticking => {
while newrunstate == RunState::Ticking {
self.run_systems();
self.ecs.maintain();
match *self.ecs.fetch::<RunState>() {
RunState::AwaitingInput => newrunstate = RunState::AwaitingInput,
RunState::MagicMapReveal{ .. } => newrunstate = RunState::MagicMapReveal{ row: 0 },
_ => newrunstate = RunState::Ticking
}
}
}
RunState::ShowInventory => {
let result = gui::show_inventory(self, ctx);
match result.0 {
gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let item_entity = result.1.unwrap();
let is_ranged = self.ecs.read_storage::<Ranged>();
let is_item_ranged = is_ranged.get(item_entity);
if let Some(is_item_ranged) = is_item_ranged {
newrunstate = RunState::ShowTargeting{ range: is_item_ranged.range, item: item_entity };
} else {
let mut intent = self.ecs.write_storage::<WantsToUseItem>();
intent.insert(*self.ecs.fetch::<Entity>(), WantsToUseItem{ item: item_entity, target: None }).expect("Unable to insert intent");
newrunstate = RunState::Ticking;
}
}
}
}
RunState::ShowCheatMenu => {
let result = gui::show_cheat_mode(self, ctx);
match result {
gui::CheatMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
gui::CheatMenuResult::NoResponse => {}
gui::CheatMenuResult::TeleportToExit => {
self.goto_level(1);
self.mapgen_next_state = Some(RunState::PreRun);
newrunstate = RunState::MapGeneration;
}
}
}
RunState::ShowDropItem => {
let result = gui::drop_item_menu(self, ctx);
match result.0 {
gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let item_entity = result.1.unwrap();
let mut intent = self.ecs.write_storage::<WantsToDropItem>();
intent.insert(*self.ecs.fetch::<Entity>(), WantsToDropItem{ item: item_entity }).expect("Unable to insert intent");
newrunstate = RunState::Ticking;
}
}
}
RunState::ShowRemoveItem => {
let result = gui::remove_item_menu(self, ctx);
match result.0 {
gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let item_entity = result.1.unwrap();
let mut intent = self.ecs.write_storage::<WantsToRemoveItem>();
intent.insert(*self.ecs.fetch::<Entity>(), WantsToRemoveItem{ item: item_entity }).expect("Unable to insert intent");
newrunstate = RunState::Ticking;
}
}
}
RunState::ShowTargeting{range, item} => {
let result = gui::ranged_target(self, ctx, range);
match result.0 {
gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let mut intent = self.ecs.write_storage::<WantsToUseItem>();
intent.insert(*self.ecs.fetch::<Entity>(), WantsToUseItem{ item, target: result.1 }).expect("Unable to insert intent");
newrunstate = RunState::Ticking;
}
}
}
RunState::MainMenu{ .. } => {
let result = gui::main_menu(self, ctx);
match result {
gui::MainMenuResult::NoSelection{ selected } => newrunstate = RunState::MainMenu{ menu_selection: selected },
gui::MainMenuResult::Selected{ selected } => {
match selected {
gui::MainMenuSelection::NewGame => newrunstate = RunState::PreRun,
gui::MainMenuSelection::LoadGame => {
saveload_system::load_game(&mut self.ecs);
newrunstate = RunState::AwaitingInput;
saveload_system::delete_save();
}
gui::MainMenuSelection::Quit => { ::std::process::exit(0); }
}
}
}
}
RunState::GameOver => {
let result = gui::game_over(ctx);
match result {
gui::GameOverResult::NoSelection => {}
gui::GameOverResult::QuitToMenu => {
self.game_over_cleanup();
newrunstate = RunState::MapGeneration;
self.mapgen_next_state = Some(RunState::MainMenu{ menu_selection: gui::MainMenuSelection::NewGame });
}
}
}
RunState::SaveGame => {
saveload_system::save_game(&mut self.ecs);
newrunstate = RunState::MainMenu{ menu_selection : gui::MainMenuSelection::LoadGame };
}
RunState::NextLevel => {
self.goto_level(1);
self.mapgen_next_state = Some(RunState::PreRun);
newrunstate = RunState::MapGeneration;
}
RunState::PreviousLevel => {
self.goto_level(-1);
self.mapgen_next_state = Some(RunState::PreRun);
newrunstate = RunState::MapGeneration;
}
RunState::MagicMapReveal{row} => {
let mut map = self.ecs.fetch_mut::<Map>();
for x in 0..map.width {
let idx = map.xy_idx(x as i32,row);
map.revealed_tiles[idx] = true;
}
if row == map.height-1 {
newrunstate = RunState::Ticking;
} else {
newrunstate = RunState::MagicMapReveal{ row: row+1 };
}
}
}
{
let mut runwriter = self.ecs.write_resource::<RunState>();
*runwriter = newrunstate;
}
damage_system::delete_the_dead(&mut self.ecs);
}
}
impl State {
fn goto_level(&mut self, offset: i32) {
freeze_level_entities(&mut self.ecs);
// Build a new map and place the player
let current_depth = self.ecs.fetch::<Map>().depth;
self.generate_world_map(current_depth + offset, offset);
// Notify the player
let mut gamelog = self.ecs.fetch_mut::<gamelog::GameLog>();
gamelog.entries.push("You change level.".to_string());
}
fn game_over_cleanup(&mut self) {
// Delete everything
let mut to_delete = Vec::new();
for e in self.ecs.entities().join() {
to_delete.push(e);
}
for del in to_delete.iter() {
self.ecs.delete_entity(*del).expect("Deletion failed");
}
// Spawn a new player
{
let player_entity = spawner::player(&mut self.ecs, 0, 0);
let mut player_entity_writer = self.ecs.write_resource::<Entity>();
*player_entity_writer = player_entity;
}
// Replace the world maps
self.ecs.insert(map::MasterDungeonMap::new());
// Build a new map and place the player
self.generate_world_map(1, 0);
}
fn generate_world_map(&mut self, new_depth : i32, offset: i32) {
self.mapgen_index = 0;
self.mapgen_timer = 0.0;
self.mapgen_history.clear();
let map_building_info = map::level_transition(&mut self.ecs, new_depth, offset);
if let Some(history) = map_building_info {
self.mapgen_history = history;
} else {
map::thaw_level_entities(&mut self.ecs);
}
}
}
fn main() {
let mut context = Rltk::init_simple8x8(80, 60, "Rusty Roguelike", "resources");
context.with_post_scanlines(true);
let mut gs = State {
ecs: World::new(),
mapgen_next_state : Some(RunState::MainMenu{ menu_selection: gui::MainMenuSelection::NewGame }),
mapgen_index : 0,
mapgen_history: Vec::new(),
mapgen_timer: 0.0
};
gs.ecs.register::<Position>();
gs.ecs.register::<Renderable>();
gs.ecs.register::<Player>();
gs.ecs.register::<Viewshed>();
gs.ecs.register::<Name>();
gs.ecs.register::<BlocksTile>();
gs.ecs.register::<WantsToMelee>();
gs.ecs.register::<SufferDamage>();
gs.ecs.register::<Item>();
gs.ecs.register::<ProvidesHealing>();
gs.ecs.register::<InflictsDamage>();
gs.ecs.register::<AreaOfEffect>();
gs.ecs.register::<Consumable>();
gs.ecs.register::<Ranged>();
gs.ecs.register::<InBackpack>();
gs.ecs.register::<WantsToPickupItem>();
gs.ecs.register::<WantsToUseItem>();
gs.ecs.register::<WantsToDropItem>();
gs.ecs.register::<Confusion>();
gs.ecs.register::<SimpleMarker<SerializeMe>>();
gs.ecs.register::<SerializationHelper>();
gs.ecs.register::<DMSerializationHelper>();
gs.ecs.register::<Equippable>();
gs.ecs.register::<Equipped>();
gs.ecs.register::<MeleeWeapon>();
gs.ecs.register::<Wearable>();
gs.ecs.register::<WantsToRemoveItem>();
gs.ecs.register::<ParticleLifetime>();
gs.ecs.register::<HungerClock>();
gs.ecs.register::<ProvidesFood>();
gs.ecs.register::<MagicMapper>();
gs.ecs.register::<Hidden>();
gs.ecs.register::<EntryTrigger>();
gs.ecs.register::<EntityMoved>();
gs.ecs.register::<SingleActivation>();
gs.ecs.register::<BlocksVisibility>();
gs.ecs.register::<Door>();
gs.ecs.register::<Quips>();
gs.ecs.register::<Attributes>();
gs.ecs.register::<Skills>();
gs.ecs.register::<Pools>();
gs.ecs.register::<NaturalAttackDefense>();
gs.ecs.register::<LootTable>();
gs.ecs.register::<OtherLevelPosition>();
gs.ecs.register::<LightSource>();
gs.ecs.register::<Initiative>();
gs.ecs.register::<MyTurn>();
gs.ecs.register::<Faction>();
gs.ecs.register::<WantsToApproach>();
gs.ecs.register::<WantsToFlee>();
gs.ecs.register::<MoveMode>();
gs.ecs.register::<Chasing>();
gs.ecs.insert(SimpleMarkerAllocator::<SerializeMe>::new());
raws::load_raws();
gs.ecs.insert(map::MasterDungeonMap::new());
gs.ecs.insert(Map::new(1, 64, 64, "New Map"));
gs.ecs.insert(Point::new(0, 0));
gs.ecs.insert(rltk::RandomNumberGenerator::new());
let player_entity = spawner::player(&mut gs.ecs, 0, 0);
gs.ecs.insert(player_entity);
gs.ecs.insert(RunState::MapGeneration{} );
gs.ecs.insert(gamelog::GameLog{ entries : vec!["Welcome to Rusty Roguelike".to_string()] });
gs.ecs.insert(particle_system::ParticleBuilder::new());
gs.ecs.insert(rex_assets::RexAssets::new());
gs.generate_world_map(1, 0);
rltk::main_loop(context, gs);
}
| 38.397321 | 156 | 0.551157 |
7aeb0fc77649b4f336b0e6066c75306414596dcf | 3,877 | //! msq is a rust library implementation of the legacy [Master Server Query Protocol](https://developer.valvesoftware.com/wiki/Master_Server_Query_Protocol).
//!
//! # Usage
//! Add this to your `Cargo.toml`:
//! ```toml
//! [dependencies]
//! msq = "0.2"
//! ```
//! If you want to get straight from the latest master branch:
//! ```toml
//! [dependencies]
//! msq = { git = "https://github.com/nullsystem/msq-rs.git" }
//! ```
//!
//! To get started using msq, see the [Quick Start](#quick-start) section below.
//!
//! ## Features
//! By default, both async [`MSQClient`] and non-async/blocking [`MSQClientBlock`] are included.
//! However, if you want to include either only async or only non-async, you could do the following:
//!
//! * For async/[`MSQClient`] **only**:
//! ```toml
//! [dependencies]
//! msq = { version = "0.2", default-features = false, features = ["async"] }
//! ```
//! * For non-async/[`MSQClientBlock`] **only**:
//! ```toml
//! [dependencies]
//! msq = { version = "0.2", default-features = false, features = ["non-async"] }
//! ```
//!
//! # Quick Start
//! The following example covers the primary functionalities of this library
//! and should be quick on understanding how to use the library.
//!
//! ## Async version
//! ```rust
//! use msq::{MSQClient, Region, Filter};
//! use std::io::Result;
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//! // Startup the client
//! let mut client = MSQClient::new().await?;
//!
//! // Connect to the master server
//! client.connect("hl2master.steampowered.com:27011").await?;
//!
//! // Maximum amount of servers we wanted to query
//! client.max_servers_on_query(256);
//!
//! let servers = client
//! .query(Region::Europe, // Restrict query to Europe region
//! Filter::new() // Create a Filter builder
//! .appid(240) // appid of 240 (CS:S)
//! .nand() // Start of NAND special filter
//! .map("de_dust2") // Map is de_dust2
//! .empty(true) // Server is empty
//! .end() // End of NAND special filter
//! .gametype(&vec!["friendlyfire", "alltalk"])).await?;
//!
//! // nand filter excludes servers that has de_dust2 as
//! // its map and is empty
//!
//! // nand and nor are both special filters, both closed by
//! // using the end method
//!
//! Ok(())
//! }
//! ```
//!
//! ## Blocking/Non-Async version
//! If you don't want to use async, then a blocking version is available.
//! The methods functionalities and names should matches its async
//! counterpart.
//! ```rust
//! use msq::{MSQClientBlock, Region, Filter};
//! use std::io::Result;
//!
//! fn main() -> Result<()> {
//! let mut client = MSQClientBlock::new()?;
//! client.connect("hl2master.steampowered.com:27011")?;
//! client.max_servers_on_query(256);
//!
//! let servers = client
//! .query(Region::Europe, // Restrict query to Europe region
//! Filter::new() // Create a Filter builder
//! .appid(240) // appid of 240 (CS:S)
//! .nand() // Start of NAND special filter
//! .map("de_dust2") // Map is de_dust2
//! .empty(true) // Server is empty
//! .end() // End of NAND special filter
//! .gametype(&vec!["friendlyfire", "alltalk"]))?;
//! Ok(())
//! }
//! ```
mod filter;
mod region;
mod packet_ext;
#[cfg(feature = "async")]
mod client_async;
#[cfg(feature = "non-async")]
mod client_blocking;
pub use crate::filter::Filter;
pub use crate::region::Region;
#[cfg(feature = "async")]
pub use crate::client_async::MSQClient;
#[cfg(feature = "non-async")]
pub use crate::client_blocking::MSQClientBlock;
| 33.136752 | 157 | 0.570028 |
91a39f7b9b4ef024b92c27d9510f14edafead135 | 3,125 | // This defines a base target-configuration for native UEFI systems. The UEFI specification has
// quite detailed sections on the ABI of all the supported target architectures. In almost all
// cases it simply follows what Microsoft Windows does. Hence, whenever in doubt, see the MSDN
// documentation.
// UEFI uses COFF/PE32+ format for binaries. All binaries must be statically linked. No dynamic
// linker is supported. As native to COFF, binaries are position-dependent, but will be relocated
// by the loader if the pre-chosen memory location is already in use.
// UEFI forbids running code on anything but the boot-CPU. No interrupts are allowed other than
// the timer-interrupt. Device-drivers are required to use polling-based models. Furthermore, all
// code runs in the same environment, no process separation is supported.
use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, TargetOptions};
pub fn opts() -> TargetOptions {
let mut base = super::msvc_base::opts();
let pre_link_args_msvc = vec![
// Non-standard subsystems have no default entry-point in PE+ files. We have to define
// one. "efi_main" seems to be a common choice amongst other implementations and the
// spec.
"/entry:efi_main".to_string(),
// COFF images have a "Subsystem" field in their header, which defines what kind of
// program it is. UEFI has 3 fields reserved, which are EFI_APPLICATION,
// EFI_BOOT_SERVICE_DRIVER, and EFI_RUNTIME_DRIVER. We default to EFI_APPLICATION,
// which is very likely the most common option. Individual projects can override this
// with custom linker flags.
// The subsystem-type only has minor effects on the application. It defines the memory
// regions the application is loaded into (runtime-drivers need to be put into
// reserved areas), as well as whether a return from the entry-point is treated as
// exit (default for applications).
"/subsystem:efi_application".to_string(),
];
base.pre_link_args.get_mut(&LinkerFlavor::Msvc).unwrap().extend(pre_link_args_msvc.clone());
base.pre_link_args
.get_mut(&LinkerFlavor::Lld(LldFlavor::Link))
.unwrap()
.extend(pre_link_args_msvc);
TargetOptions {
target_os: "uefi".to_string(),
linker_flavor: LinkerFlavor::Lld(LldFlavor::Link),
disable_redzone: true,
exe_suffix: ".efi".to_string(),
allows_weak_linkage: false,
panic_strategy: PanicStrategy::Abort,
stack_probes: true,
singlethread: true,
linker: Some("rust-lld".to_string()),
// FIXME: This should likely be `true` inherited from `msvc_base`
// because UEFI follows Windows ABI and uses PE/COFF.
// The `false` is probably causing ABI bugs right now.
is_like_windows: false,
// FIXME: This should likely be `true` inherited from `msvc_base`
// because UEFI follows Windows ABI and uses PE/COFF.
// The `false` is probably causing ABI bugs right now.
is_like_msvc: false,
..base
}
}
| 51.229508 | 97 | 0.69504 |
1ea95665f0f9567975de4baf84be3a25b890526b | 1,368 | // Copyright 2015-2021 Swim Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// 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 crate::StoreError;
use serde::{Deserialize, Serialize};
pub fn serialize_then<S, F, O, E>(engine: &E, obj: &S, f: F) -> Result<O, StoreError>
where
S: Serialize,
F: Fn(&E, Vec<u8>) -> Result<O, StoreError>,
{
f(engine, serialize(obj)?).map_err(Into::into)
}
pub fn serialize<S: Serialize>(obj: &S) -> Result<Vec<u8>, StoreError> {
bincode::serialize(obj).map_err(|e| StoreError::Encoding(e.to_string()))
}
pub fn deserialize<'de, D: Deserialize<'de>>(obj: &'de [u8]) -> Result<D, StoreError> {
bincode::deserialize(obj).map_err(|e| StoreError::Decoding(e.to_string()))
}
pub fn deserialize_key<B: AsRef<[u8]>>(bytes: B) -> Result<u64, StoreError> {
bincode::deserialize::<u64>(bytes.as_ref()).map_err(|e| StoreError::Decoding(e.to_string()))
}
| 36.972973 | 96 | 0.695906 |
872eb25df95663296c4b46dcb2ea9e6c8a62a9d4 | 14,289 | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use super::traits::{FieldElement, StarkField};
use crate::errors::{ElementDecodingError, SerializationError};
use core::{
convert::{TryFrom, TryInto},
fmt::{Debug, Display, Formatter},
mem,
ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Range, Sub, SubAssign},
slice,
};
use rand::{distributions::Uniform, prelude::*};
use utils::AsBytes;
#[cfg(test)]
mod tests;
// CONSTANTS
// ================================================================================================
/// Field modulus = 2^62 - 111 * 2^39 + 1
const M: u64 = 4611624995532046337;
/// 2^128 mod M; this is used for conversion of elements into Montgomery representation.
const R2: u64 = 630444561284293700;
/// 2^192 mod M; this is used during element inversion.
const R3: u64 = 732984146687909319;
/// -M^{-1} mod 2^64; this is used during element multiplication.
const U: u128 = 4611624995532046335;
/// Number of bytes needed to represent field element
const ELEMENT_BYTES: usize = std::mem::size_of::<u64>();
// 2^39 root of unity
const G: u64 = 4421547261963328785;
const RANGE: Range<u64> = Range { start: 0, end: M };
// FIELD ELEMENT
// ================================================================================================
/// Base field element; internal values are stored in Montgomery representation and can be in
/// the range [0; 2M)
#[derive(Copy, Clone, Debug, Default)]
pub struct BaseElement(u64);
impl BaseElement {
/// Creates a new field element from the provided `value`; the value is converted into
/// Montgomery representation.
pub const fn new(value: u64) -> BaseElement {
// multiply the value with R2 to convert to Montgomery representation; this is OK because
// given the value of R2, the product of R2 and `value` is guaranteed to be in the range
// [0, 4M^2 - 4M + 1)
let z = mul(value, R2);
BaseElement(z)
}
}
impl FieldElement for BaseElement {
type PositiveInteger = u64;
type Base = Self;
const ZERO: Self = BaseElement::new(0);
const ONE: Self = BaseElement::new(1);
const ELEMENT_BYTES: usize = ELEMENT_BYTES;
fn exp(self, power: Self::PositiveInteger) -> Self {
let mut b = self;
if power == 0 {
return Self::ONE;
} else if b == Self::ZERO {
return Self::ZERO;
}
let mut r = if power & 1 == 1 { b } else { Self::ONE };
for i in 1..64 - power.leading_zeros() {
b = b.square();
if (power >> i) & 1 == 1 {
r *= b;
}
}
r
}
fn inv(self) -> Self {
BaseElement(inv(self.0))
}
fn conjugate(&self) -> Self {
BaseElement(self.0)
}
fn rand() -> Self {
let range = Uniform::from(RANGE);
let mut g = thread_rng();
BaseElement::new(g.sample(range))
}
fn from_random_bytes(bytes: &[u8]) -> Option<Self> {
Self::try_from(bytes).ok()
}
fn to_canonical_bytes(self) -> Vec<u8> {
// convert from Montgomery representation into canonical representation
self.as_int().to_le_bytes().to_vec()
}
fn elements_into_bytes(elements: Vec<Self>) -> Vec<u8> {
let mut v = std::mem::ManuallyDrop::new(elements);
let p = v.as_mut_ptr();
let len = v.len() * Self::ELEMENT_BYTES;
let cap = v.capacity() * Self::ELEMENT_BYTES;
unsafe { Vec::from_raw_parts(p as *mut u8, len, cap) }
}
fn elements_as_bytes(elements: &[Self]) -> &[u8] {
// TODO: take endianness into account
let p = elements.as_ptr();
let len = elements.len() * Self::ELEMENT_BYTES;
unsafe { slice::from_raw_parts(p as *const u8, len) }
}
unsafe fn bytes_as_elements(bytes: &[u8]) -> Result<&[Self], SerializationError> {
if bytes.len() % Self::ELEMENT_BYTES != 0 {
return Err(SerializationError::NotEnoughBytesForWholeElements(
bytes.len(),
));
}
let p = bytes.as_ptr();
let len = bytes.len() / Self::ELEMENT_BYTES;
if (p as usize) % mem::align_of::<u64>() != 0 {
return Err(SerializationError::InvalidMemoryAlignment);
}
Ok(slice::from_raw_parts(p as *const Self, len))
}
fn zeroed_vector(n: usize) -> Vec<Self> {
// this uses a specialized vector initialization code which requests zero-filled memory
// from the OS; unfortunately, this works only for built-in types and we can't use
// Self::ZERO here as much less efficient initialization procedure will be invoked.
// We also use u64 to make sure the memory is aligned correctly for our element size.
let result = vec![0u64; n];
// translate a zero-filled vector of u64s into a vector of base field elements
let mut v = std::mem::ManuallyDrop::new(result);
let p = v.as_mut_ptr();
let len = v.len();
let cap = v.capacity();
unsafe { Vec::from_raw_parts(p as *mut Self, len, cap) }
}
fn prng_vector(seed: [u8; 32], n: usize) -> Vec<Self> {
let range = Uniform::from(RANGE);
let g = StdRng::from_seed(seed);
g.sample_iter(range).take(n).map(BaseElement::new).collect()
}
}
impl StarkField for BaseElement {
/// sage: MODULUS = 2^62 - 111 * 2^39 + 1
/// sage: GF(MODULUS).is_prime_field()
/// True
/// sage: GF(MODULUS).order()
/// 4611624995532046337
const MODULUS: Self::PositiveInteger = M;
const MODULUS_BITS: u32 = 64;
/// sage: GF(MODULUS).primitive_element()
/// 3
const GENERATOR: Self = BaseElement::new(3);
/// sage: is_odd((MODULUS - 1) / 2^39)
/// True
const TWO_ADICITY: u32 = 39;
/// sage: k = (MODULUS - 1) / 2^39
/// sage: GF(MODULUS).primitive_element()^k
/// 4421547261963328785
const TWO_ADIC_ROOT_OF_UNITY: Self = BaseElement::new(G);
fn get_modulus_le_bytes() -> Vec<u8> {
Self::MODULUS.to_le_bytes().to_vec()
}
fn as_int(&self) -> Self::PositiveInteger {
// convert from Montgomery representation by multiplying by 1
let result = mul(self.0, 1);
// since the result of multiplication can be in [0, 2M), we need to normalize it
normalize(result)
}
}
impl Display for BaseElement {
fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
write!(f, "{}", self.as_int())
}
}
// EQUALITY CHECKS
// ================================================================================================
impl PartialEq for BaseElement {
fn eq(&self, other: &Self) -> bool {
// since either of the elements can be in [0, 2M) range, we normalize them first to be
// in [0, M) range and then compare them.
normalize(self.0) == normalize(other.0)
}
}
impl Eq for BaseElement {}
// OVERLOADED OPERATORS
// ================================================================================================
impl Add for BaseElement {
type Output = Self;
fn add(self, rhs: Self) -> Self {
Self(add(self.0, rhs.0))
}
}
impl AddAssign for BaseElement {
fn add_assign(&mut self, rhs: Self) {
*self = *self + rhs
}
}
impl Sub for BaseElement {
type Output = Self;
fn sub(self, rhs: Self) -> Self {
Self(sub(self.0, rhs.0))
}
}
impl SubAssign for BaseElement {
fn sub_assign(&mut self, rhs: Self) {
*self = *self - rhs;
}
}
impl Mul for BaseElement {
type Output = Self;
fn mul(self, rhs: Self) -> Self {
Self(mul(self.0, rhs.0))
}
}
impl MulAssign for BaseElement {
fn mul_assign(&mut self, rhs: Self) {
*self = *self * rhs
}
}
impl Div for BaseElement {
type Output = Self;
fn div(self, rhs: Self) -> Self {
Self(mul(self.0, inv(rhs.0)))
}
}
impl DivAssign for BaseElement {
fn div_assign(&mut self, rhs: Self) {
*self = *self / rhs
}
}
impl Neg for BaseElement {
type Output = Self;
fn neg(self) -> Self {
Self(sub(0, self.0))
}
}
// TYPE CONVERSIONS
// ================================================================================================
impl From<u128> for BaseElement {
/// Converts a 128-bit value into a filed element. If the value is greater than or equal to
/// the field modulus, modular reduction is silently preformed.
fn from(value: u128) -> Self {
// make sure the value is < 4M^2 - 4M + 1; this is overly conservative and a single
// subtraction of (M * 2^65) should be enough, but this needs to be proven
const M4: u128 = (2 * M as u128).pow(2) - 4 * (M as u128) + 1;
const Q: u128 = (2 * M as u128).pow(2) - 4 * (M as u128);
let mut v = value;
while v >= M4 {
v -= Q;
}
// apply similar reduction as during multiplication; as output we get z = v * R^{-1} mod M,
// so we need to Montgomery-multiply it be R^3 to get z = v * R mod M
let q = (((v as u64) as u128) * U) as u64;
let z = v + (q as u128) * (M as u128);
let z = mul((z >> 64) as u64, R3);
BaseElement(z)
}
}
impl From<u64> for BaseElement {
/// Converts a 64-bit value into a filed element. If the value is greater than or equal to
/// the field modulus, modular reduction is silently preformed.
fn from(value: u64) -> Self {
BaseElement::new(value)
}
}
impl From<u32> for BaseElement {
/// Converts a 32-bit value into a filed element.
fn from(value: u32) -> Self {
BaseElement::new(value as u64)
}
}
impl From<u16> for BaseElement {
/// Converts a 16-bit value into a filed element.
fn from(value: u16) -> Self {
BaseElement::new(value as u64)
}
}
impl From<u8> for BaseElement {
/// Converts an 8-bit value into a filed element.
fn from(value: u8) -> Self {
BaseElement::new(value as u64)
}
}
impl From<[u8; 8]> for BaseElement {
/// Converts the value encoded in an array of 8 bytes into a field element. The bytes are
/// assumed to encode the element in the canonical representation in little-endian byte order.
/// If the value is greater than or equal to the field modulus, modular reduction is silently
/// preformed.
fn from(bytes: [u8; 8]) -> Self {
let value = u64::from_le_bytes(bytes);
BaseElement::new(value)
}
}
impl<'a> TryFrom<&'a [u8]> for BaseElement {
type Error = ElementDecodingError;
/// Converts a slice of bytes into a field element; returns error if the value encoded in bytes
/// is not a valid field element. The bytes are assumed to encode the element in the canonical
/// representation in little-endian byte order.
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
if bytes.len() < ELEMENT_BYTES {
return Err(ElementDecodingError::NotEnoughBytes(
ELEMENT_BYTES,
bytes.len(),
));
}
if bytes.len() > ELEMENT_BYTES {
return Err(ElementDecodingError::TooManyBytes(
ELEMENT_BYTES,
bytes.len(),
));
}
let value = bytes
.try_into()
.map(u64::from_le_bytes)
.map_err(|error| ElementDecodingError::UnknownError(format!("{}", error)))?;
if value >= M {
return Err(ElementDecodingError::ValueTooLarger(format!("{}", value)));
}
Ok(BaseElement::new(value))
}
}
impl AsBytes for BaseElement {
fn as_bytes(&self) -> &[u8] {
// TODO: take endianness into account
let self_ptr: *const BaseElement = self;
unsafe { slice::from_raw_parts(self_ptr as *const u8, ELEMENT_BYTES) }
}
}
// FINITE FIELD ARITHMETIC
// ================================================================================================
/// Computes (a + b) reduced by M such that the output is in [0, 2M) range; a and b are assumed to
/// be in [0, 2M).
#[inline(always)]
fn add(a: u64, b: u64) -> u64 {
let z = a + b;
let q = (z >> 62) * M;
z - q
}
/// Computes (a - b) reduced by M such that the output is in [0, 2M) range; a and b are assumed to
/// be in [0, 2M).
#[inline(always)]
fn sub(a: u64, b: u64) -> u64 {
if a < b {
2 * M - b + a
} else {
a - b
}
}
/// Computes (a * b) reduced by M such that the output is in [0, 2M) range; a and b are assumed to
/// be in [0, 2M).
#[inline(always)]
const fn mul(a: u64, b: u64) -> u64 {
let z = (a as u128) * (b as u128);
let q = (((z as u64) as u128) * U) as u64;
let z = z + (q as u128) * (M as u128);
(z >> 64) as u64
}
/// Computes y such that (x * y) % M = 1 except for when when x = 0; in such a case, 0 is returned;
/// x is assumed to in [0, 2M) range, and the output will also be in [0, 2M) range.
#[inline(always)]
#[allow(clippy::many_single_char_names)]
fn inv(x: u64) -> u64 {
if x == 0 {
return 0;
};
let mut a: u128 = 0;
let mut u: u128 = if x & 1 == 1 {
x as u128
} else {
(x as u128) + (M as u128)
};
let mut v: u128 = M as u128;
let mut d = (M as u128) - 1;
while v != 1 {
while v < u {
u -= v;
d += a;
while u & 1 == 0 {
if d & 1 == 1 {
d += M as u128;
}
u >>= 1;
d >>= 1;
}
}
v -= u;
a += d;
while v & 1 == 0 {
if a & 1 == 1 {
a += M as u128;
}
v >>= 1;
a >>= 1;
}
}
while a > (M as u128) {
a -= M as u128;
}
mul(a as u64, R3)
}
// HELPER FUNCTIONS
// ================================================================================================
/// Reduces any value in [0, 2M) range to [0, M) range
#[inline(always)]
fn normalize(value: u64) -> u64 {
if value >= M {
value - M
} else {
value
}
}
| 29.280738 | 99 | 0.545455 |
ff11965c394f07d8febd808cb7dd1ca6aa5c5e37 | 4,071 | //! Methods for triangular matrices
use ndarray::*;
use num_traits::Zero;
use super::convert::*;
use super::error::*;
use super::lapack_traits::*;
use super::layout::*;
use super::types::*;
pub use super::lapack_traits::Diag;
/// solve a triangular system with upper triangular matrix
pub trait SolveTriangular<A, S, D>
where
A: Scalar,
S: Data<Elem = A>,
D: Dimension,
{
fn solve_triangular(&self, UPLO, Diag, &ArrayBase<S, D>) -> Result<Array<A, D>>;
}
/// solve a triangular system with upper triangular matrix
pub trait SolveTriangularInto<S, D>
where
S: DataMut,
D: Dimension,
{
fn solve_triangular_into(&self, UPLO, Diag, ArrayBase<S, D>) -> Result<ArrayBase<S, D>>;
}
/// solve a triangular system with upper triangular matrix
pub trait SolveTriangularInplace<S, D>
where
S: DataMut,
D: Dimension,
{
fn solve_triangular_inplace<'a>(&self, UPLO, Diag, &'a mut ArrayBase<S, D>) -> Result<&'a mut ArrayBase<S, D>>;
}
impl<A, Si, So> SolveTriangularInto<So, Ix2> for ArrayBase<Si, Ix2>
where
A: Scalar,
Si: Data<Elem = A>,
So: DataMut<Elem = A> + DataOwned,
{
fn solve_triangular_into(&self, uplo: UPLO, diag: Diag, mut b: ArrayBase<So, Ix2>) -> Result<ArrayBase<So, Ix2>> {
self.solve_triangular_inplace(uplo, diag, &mut b)?;
Ok(b)
}
}
impl<A, Si, So> SolveTriangularInplace<So, Ix2> for ArrayBase<Si, Ix2>
where
A: Scalar,
Si: Data<Elem = A>,
So: DataMut<Elem = A> + DataOwned,
{
fn solve_triangular_inplace<'a>(
&self,
uplo: UPLO,
diag: Diag,
b: &'a mut ArrayBase<So, Ix2>,
) -> Result<&'a mut ArrayBase<So, Ix2>> {
let la = self.layout()?;
let a_ = self.as_allocated()?;
let lb = b.layout()?;
if !la.same_order(&lb) {
transpose_data(b)?;
}
let lb = b.layout()?;
unsafe { A::solve_triangular(la, lb, uplo, diag, a_, b.as_allocated_mut()?)? };
Ok(b)
}
}
impl<A, Si, So> SolveTriangular<A, So, Ix2> for ArrayBase<Si, Ix2>
where
A: Scalar,
Si: Data<Elem = A>,
So: DataMut<Elem = A> + DataOwned,
{
fn solve_triangular(&self, uplo: UPLO, diag: Diag, b: &ArrayBase<So, Ix2>) -> Result<Array2<A>> {
let b = replicate(b);
self.solve_triangular_into(uplo, diag, b)
}
}
impl<A, Si, So> SolveTriangularInto<So, Ix1> for ArrayBase<Si, Ix2>
where
A: Scalar,
Si: Data<Elem = A>,
So: DataMut<Elem = A> + DataOwned,
{
fn solve_triangular_into(&self, uplo: UPLO, diag: Diag, b: ArrayBase<So, Ix1>) -> Result<ArrayBase<So, Ix1>> {
let b = into_col(b);
let b = self.solve_triangular_into(uplo, diag, b)?;
Ok(flatten(b))
}
}
impl<A, Si, So> SolveTriangular<A, So, Ix1> for ArrayBase<Si, Ix2>
where
A: Scalar,
Si: Data<Elem = A>,
So: DataMut<Elem = A> + DataOwned,
{
fn solve_triangular(&self, uplo: UPLO, diag: Diag, b: &ArrayBase<So, Ix1>) -> Result<Array1<A>> {
let b = b.to_owned();
self.solve_triangular_into(uplo, diag, b)
}
}
pub trait IntoTriangular<T> {
fn into_triangular(self, UPLO) -> T;
}
impl<'a, A, S> IntoTriangular<&'a mut ArrayBase<S, Ix2>> for &'a mut ArrayBase<S, Ix2>
where
A: Zero,
S: DataMut<Elem = A>,
{
fn into_triangular(self, uplo: UPLO) -> &'a mut ArrayBase<S, Ix2> {
match uplo {
UPLO::Upper => {
for ((i, j), val) in self.indexed_iter_mut() {
if i > j {
*val = A::zero();
}
}
}
UPLO::Lower => {
for ((i, j), val) in self.indexed_iter_mut() {
if i < j {
*val = A::zero();
}
}
}
}
self
}
}
impl<A, S> IntoTriangular<ArrayBase<S, Ix2>> for ArrayBase<S, Ix2>
where
A: Zero,
S: DataMut<Elem = A>,
{
fn into_triangular(mut self, uplo: UPLO) -> ArrayBase<S, Ix2> {
(&mut self).into_triangular(uplo);
self
}
}
| 26.264516 | 118 | 0.564972 |
11572a40602155fb1a446ddf471e65490213671c | 6,674 | #![recursion_limit = "1024"]
#[macro_use]
extern crate cpp;
use std::{
os::raw::c_char,
ffi::CStr,
io,
path::Path,
};
#[cfg(windows)]
mod os
{
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
pub(crate) type NodSystemChar = u16;
pub(crate) fn os_str_to_sys_char(s: &OsStr) -> Vec<NodSystemChar>
{
let mut v: Vec<_> = s.encode_wide().collect();
v.push(0);
v
}
}
#[cfg(not(windows))]
mod os
{
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
pub(crate) type NodSystemChar = u8;
pub(crate) fn os_str_to_sys_char(s: &OsStr) -> Vec<NodSystemChar>
{
let mut v: Vec<_> = s.as_bytes().to_owned();
v.push(0);
v
}
}
use os::*;
cpp! {{
#include <nod/nod.hpp>
#include <nod/DiscBase.hpp>
struct FileWrapper
{
std::shared_ptr<nod::DiscBase> disc;
nod::Node &file;
uint64_t read_bytes(uint64_t offset, uint64_t buf_length, uint8_t *buf)
{
try {
auto stream = this->file.beginReadStream(offset);
return stream->read(buf, buf_length);
} catch (...) {
return 0;
}
}
FileWrapper(std::shared_ptr<nod::DiscBase> disc_, nod::Node &file_)
: disc(std::move(disc_)), file(file_)
{ }
};
struct DiscWrapper
{
std::shared_ptr<nod::DiscBase> disc;
static DiscWrapper* create(nod::SystemChar *disc_path, const char **err_msg)
{
try {
bool is_wii;
std::unique_ptr<nod::DiscBase> disc = nod::OpenDiscFromImage(disc_path, is_wii);
if (!disc) {
*err_msg = "Failed to open disc";
return 0;
}
nod::IPartition* partition = disc->getDataPartition();
if (!partition) {
*err_msg = "Failed to find data partition";
return 0;
}
return new DiscWrapper { std::shared_ptr<nod::DiscBase>(disc.release()) };
} catch (...) {
*err_msg = "Unknown error";
return 0;
}
}
FileWrapper* open_file(const char *file_name)
{
try {
nod::IPartition* partition = this->disc->getDataPartition();
if (!partition) {
return 0;
}
nod::Node &root = partition->getFSTRoot();
nod::Node *found = nullptr;
auto it_end = root.rawEnd();
for(auto it = root.rawBegin(); it != it_end; ++it) {
if(it->getName() == file_name) {
found = &*it;
break;
}
}
if(!found) {
return 0;
}
return new FileWrapper(this->disc, *found);
} catch (...) {
return 0;
}
}
};
}}
pub struct DiscWrapper(*const ());
impl DiscWrapper
{
pub fn new<P>(disc_path: P) -> Result<DiscWrapper, String>
where P: AsRef<Path>
{
let disc_path = os_str_to_sys_char(disc_path.as_ref().as_os_str());
let disc_path = &disc_path[..] as *const [_] as *const NodSystemChar;
let mut err_msg: *const c_char = std::ptr::null();
let err_msg = &mut err_msg;
let p = cpp!(unsafe [disc_path as "nod::SystemChar*", err_msg as "const char **"]
-> *const () as "DiscWrapper*" {
return DiscWrapper::create(disc_path, err_msg);
});
if p.is_null() {
Err(if !err_msg.is_null() {
unsafe { CStr::from_ptr(*err_msg) }.to_string_lossy().into_owned()
} else {
"Unknown error".to_owned()
})?
}
Ok(DiscWrapper(p))
}
pub fn open_file(&self, file_name: &CStr) -> Result<FileWrapper, String>
{
let self_ptr = self.0;
let file_name_ptr = file_name.as_ptr();
let p = cpp!(unsafe [self_ptr as "DiscWrapper*", file_name_ptr as "const char*"]
-> *const () as "FileWrapper*" {
return self_ptr->open_file(file_name_ptr);
});
if p.is_null() {
Err(format!("Failed to find file {}", &file_name.to_string_lossy()[..]))?
}
Ok(FileWrapper(p))
}
}
impl Drop for DiscWrapper
{
fn drop(&mut self)
{
let p = self.0;
cpp!(unsafe [p as "DiscWrapper*"] {
delete p;
});
}
}
#[derive(Debug)]
pub struct FileWrapper(*const ());
impl FileWrapper
{
pub fn read_bytes(&self, offset: u64, buf: &mut [u8]) -> u64
{
let p = self.0;
let buf_len = buf.len() as u64;
let buf = buf as *mut [u8] as *mut u8;
cpp!(unsafe [p as "FileWrapper*", offset as "uint64_t", buf_len as "uint64_t",
buf as "uint8_t*"]
-> u64 as "uint64_t" {
return p->read_bytes(offset, buf_len, buf);
})
}
pub fn len(&self) -> u64
{
let p = self.0;
cpp!(unsafe [p as "FileWrapper*"] -> u64 as "uint64_t" {
return p->file.size();
})
}
}
impl Drop for FileWrapper
{
fn drop(&mut self)
{
let p = self.0;
cpp!(unsafe [p as "FileWrapper*"] {
delete p;
});
}
}
impl Clone for FileWrapper
{
fn clone(&self) -> Self
{
let p = self.0;
let p = cpp!(unsafe [p as "FileWrapper*"] -> *const () as "FileWrapper*" {
return new FileWrapper(*p);
});
FileWrapper(p)
}
}
impl reader_writer::WithRead for FileWrapper
{
fn len(&self) -> usize
{
self.len() as usize
}
fn boxed<'a>(&self) -> Box<dyn reader_writer::WithRead + 'a>
where Self: 'a
{
Box::new(self.clone())
}
fn with_read(&self, f: &mut dyn FnMut(&mut dyn io::Read) -> io::Result<u64>) -> io::Result<u64>
{
f(&mut FileWrapperRead {
fw: self,
offset: 0,
})
}
}
struct FileWrapperRead<'a>
{
fw: &'a FileWrapper,
offset: u64,
}
impl<'a> io::Read for FileWrapperRead<'a>
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>
{
let bytes_to_write = std::cmp::min(buf.len() as u64, self.fw.len() - self.offset) as usize;
let i = self.fw.read_bytes(self.offset, &mut buf[..bytes_to_write]);
self.offset += i;
Ok(i as usize)
}
}
| 24.810409 | 99 | 0.489661 |
dddaf43d653107d7f22da34f35cb88bd26a57550 | 4,377 | use std::result;
use super::BOARD_WIDTH;
pub type Result<T> = result::Result<T, String>;
const MOVEMENT_SPEED: f64 = 1.0;
pub static TETROMINOS: [Tetromino; 7] = [
Tetromino {
name: Shape::I,
blocks: [[0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]],
x_offset: (BOARD_WIDTH as f64 / 2.0) - 2.0,
y_offset: 0.0,
color: [0.0, 1.0, 1.0, 1.0]
},
Tetromino {
name: Shape::O,
blocks: [[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
x_offset: (BOARD_WIDTH as f64 / 2.0) - 1.0,
y_offset: 0.0,
color: [1.0, 1.0, 0.0, 1.0]
},
Tetromino {
name: Shape::T,
blocks: [[0, 0, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]],
x_offset: (BOARD_WIDTH as f64 / 2.0) - 2.0,
y_offset: 0.0,
color: [0.4, 0.0, 0.8, 1.0]
},
Tetromino {
name: Shape::S,
blocks: [[0, 0, 0, 0], [0, 1, 1, 0], [1, 1, 0, 0], [0, 0, 0, 0]],
x_offset: (BOARD_WIDTH as f64 / 2.0) - 2.0,
y_offset: 0.0,
color: [0.48, 1.0, 0.0, 1.0]
},
Tetromino {
name: Shape::Z,
blocks: [[0, 0, 0, 0], [1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 0]],
x_offset: (BOARD_WIDTH as f64 / 2.0) - 2.0,
y_offset: 0.0,
color: [1.0, 0.0, 0.0, 1.0]
},
Tetromino {
name: Shape::J,
blocks: [[0, 1, 0, 0], [0, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 0]],
x_offset: (BOARD_WIDTH as f64 / 2.0) - 2.0,
y_offset: 0.0,
color: [0.11, 0.56, 1.0, 1.0]
},
Tetromino {
name: Shape::L,
blocks: [[0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 0]],
x_offset: (BOARD_WIDTH as f64 / 2.0) - 2.0,
y_offset: 0.0,
color: [1.0, 0.6, 0.0, 1.0]
},
];
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum Shape {
I,
O,
T,
S,
Z,
J,
L
}
#[derive(Debug, Clone, Copy)]
pub struct Tetromino {
pub name: Shape,
pub blocks: [[u8; 4]; 4],
pub x_offset: f64, // offset (in block cell units) of the top left cell
pub y_offset: f64,
pub color: [f32; 4] // color of the block
}
impl Tetromino {
pub fn rotate_right(&mut self) {
if self.name == Shape::O {
return
}
let mut new_blocks = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];
for r in 0..self.blocks.len() {
for c in 0..self.blocks[0].len() {
new_blocks[r][c] = self.blocks[4 - c - 1][r];
}
}
self.blocks = new_blocks;
}
pub fn rotate_left(&mut self) {
if self.name == Shape::O {
return
}
let mut new_blocks = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];
for r in 0..self.blocks.len() {
for c in 0..self.blocks[0].len() {
new_blocks[r][c] = self.blocks[c][4 - r - 1];
}
}
self.blocks = new_blocks;
}
pub fn block_height(&self) -> f64 {
let mut height = 0.0;
for r in 0..self.blocks.len() {
for c in 0..self.blocks[0].len() {
if self.blocks[r][c] == 1 {
height += 1.0;
break;
}
}
}
height
}
pub fn block_width(&self) -> f64 {
let mut cols_vec: [i64; 4] = [0, 0, 0, 0];
for r in 0..self.blocks.len() {
for c in 0..self.blocks[0].len() {
if self.blocks[r][c] == 1 {
cols_vec[c] = 1;
}
}
}
let mut width = 0.0;
for x in cols_vec.iter() {
if *x == 1 {
width += 1.0;
}
}
width
}
// coordinates of leftmost point in block
pub fn leftmost(&self) -> f64 {
let mut leftmost = 3.0;
for r in 0..self.blocks.len() {
for c in 0..self.blocks[0].len() {
if self.blocks[r][c] == 1 {
if leftmost > c as f64 {
leftmost = c as f64;
}
}
}
}
leftmost + self.x_offset
}
pub fn rightmost(&self) -> f64 {
self.leftmost() + self.block_width() - 1.0
}
pub fn topmost(&self) -> f64 {
let mut topmost = 3.0;
for r in 0..self.blocks.len() {
for c in 0..self.blocks[0].len() {
if self.blocks[r][c] == 1 {
if topmost > r as f64 {
topmost = r as f64;
}
}
}
}
topmost + self.y_offset
}
pub fn bottommost(&self) -> f64 {
self.topmost() + self.block_height() - 1.0
}
pub fn move_down(&mut self) {
self.y_offset += MOVEMENT_SPEED;
}
pub fn move_left(&mut self) {
self.x_offset -= MOVEMENT_SPEED;
}
pub fn move_right(&mut self) {
self.x_offset += MOVEMENT_SPEED;
}
} | 23.532258 | 82 | 0.488005 |
64d6a01d4f5572e42a33a689f71291650efa7303 | 4,036 | #![allow(missing_docs)]
/// Derived from https://github.com/project-serum/anchor/blob/9224e0fa99093943a6190e396bccbc3387e5b230/examples/pyth/programs/pyth/src/pc.rs
use bytemuck::{
cast_slice, cast_slice_mut, from_bytes, from_bytes_mut, try_cast_slice, try_cast_slice_mut,
Pod, PodCastError, Zeroable,
};
use std::mem::size_of;
pub const MAGIC: u32 = 0xa1b2c3d4;
pub const VERSION_2: u32 = 2;
pub const VERSION: u32 = VERSION_2;
pub const MAP_TABLE_SIZE: usize = 640;
pub const PROD_ACCT_SIZE: usize = 512;
pub const PROD_HDR_SIZE: usize = 48;
pub const PROD_ATTR_SIZE: usize = PROD_ACCT_SIZE - PROD_HDR_SIZE;
pub const USE_PYTH: bool = true;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct AccKey {
pub val: [u8; 32],
}
#[derive(Copy, Clone)]
#[repr(C)]
pub enum AccountType {
Unknown,
Mapping,
Product,
Price,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub enum PriceStatus {
Unknown,
Trading,
Halted,
Auction,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub enum CorpAction {
NoCorpAct,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct PriceInfo {
pub price: i64,
pub conf: u64,
pub status: PriceStatus,
pub corp_act: CorpAction,
pub pub_slot: u64,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct PriceComp {
publisher: AccKey,
agg: PriceInfo,
latest: PriceInfo,
}
#[derive(PartialEq, Copy, Clone)]
#[repr(C)]
pub enum PriceType {
Unknown,
Price,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Price {
pub magic: u32, // pyth magic number
pub ver: u32, // program version
pub atype: u32, // account type
pub size: u32, // price account size
pub ptype: PriceType, // price or calculation type
pub expo: i32, // price exponent
pub num: u32, // number of component prices
pub unused: u32,
pub curr_slot: u64, // currently accumulating price slot
pub valid_slot: u64, // valid slot-time of agg. price
pub twap: i64, // time-weighted average price
pub avol: u64, // annualized price volatility
pub drv0: i64, // space for future derived values
pub drv1: i64, // space for future derived values
pub drv2: i64, // space for future derived values
pub drv3: i64, // space for future derived values
pub drv4: i64, // space for future derived values
pub drv5: i64, // space for future derived values
pub prod: AccKey, // product account key
pub next: AccKey, // next Price account in linked list
pub agg_pub: AccKey, // quoter who computed last aggregate price
pub agg: PriceInfo, // aggregate price info
pub comp: [PriceComp; 32], // price components one per quoter
}
#[cfg(target_endian = "little")]
unsafe impl Zeroable for Price {}
#[cfg(target_endian = "little")]
unsafe impl Pod for Price {}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Product {
pub magic: u32, // pyth magic number
pub ver: u32, // program version
pub atype: u32, // account type
pub size: u32, // price account size
pub px_acc: AccKey, // first price account in list
pub attr: [u8; PROD_ATTR_SIZE], // key/value pairs of reference attr.
}
#[cfg(target_endian = "little")]
unsafe impl Zeroable for Product {}
#[cfg(target_endian = "little")]
unsafe impl Pod for Product {}
pub fn load<T: Pod>(data: &[u8]) -> Result<&T, PodCastError> {
let size = size_of::<T>();
Ok(from_bytes(cast_slice::<u8, u8>(try_cast_slice(
&data[0..size],
)?)))
}
pub fn load_mut<T: Pod>(data: &mut [u8]) -> Result<&mut T, PodCastError> {
let size = size_of::<T>();
Ok(from_bytes_mut(cast_slice_mut::<u8, u8>(
try_cast_slice_mut(&mut data[0..size])?,
)))
}
| 29.246377 | 141 | 0.600842 |
29736f2765e9516500d0db8e08fd780b71277b62 | 431,440 | // automatically generated by the FlatBuffers compiler, do not modify
use std::cmp::Ordering;
use std::mem;
extern crate flatbuffers;
use self::flatbuffers::EndianScalar;
#[allow(unused_imports, dead_code)]
pub mod fbsemantic {
use std::cmp::Ordering;
use std::mem;
extern crate flatbuffers;
use self::flatbuffers::EndianScalar;
#[allow(non_camel_case_types)]
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum MonoType {
NONE = 0,
Basic = 1,
Var = 2,
Arr = 3,
Row = 4,
Fun = 5,
}
const ENUM_MIN_MONO_TYPE: u8 = 0;
const ENUM_MAX_MONO_TYPE: u8 = 5;
impl<'a> flatbuffers::Follow<'a> for MonoType {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::read_scalar_at::<Self>(buf, loc)
}
}
impl flatbuffers::EndianScalar for MonoType {
#[inline]
fn to_little_endian(self) -> Self {
let n = u8::to_le(self as u8);
let p = &n as *const u8 as *const MonoType;
unsafe { *p }
}
#[inline]
fn from_little_endian(self) -> Self {
let n = u8::from_le(self as u8);
let p = &n as *const u8 as *const MonoType;
unsafe { *p }
}
}
impl flatbuffers::Push for MonoType {
type Output = MonoType;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
flatbuffers::emplace_scalar::<MonoType>(dst, *self);
}
}
#[allow(non_camel_case_types)]
const ENUM_VALUES_MONO_TYPE: [MonoType; 6] = [
MonoType::NONE,
MonoType::Basic,
MonoType::Var,
MonoType::Arr,
MonoType::Row,
MonoType::Fun,
];
#[allow(non_camel_case_types)]
const ENUM_NAMES_MONO_TYPE: [&'static str; 6] = ["NONE", "Basic", "Var", "Arr", "Row", "Fun"];
pub fn enum_name_mono_type(e: MonoType) -> &'static str {
let index = e as u8;
ENUM_NAMES_MONO_TYPE[index as usize]
}
pub struct MonoTypeUnionTableOffset {}
#[allow(non_camel_case_types)]
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Type {
Bool = 0,
Int = 1,
Uint = 2,
Float = 3,
String = 4,
Duration = 5,
Time = 6,
Regexp = 7,
Bytes = 8,
}
const ENUM_MIN_TYPE: u8 = 0;
const ENUM_MAX_TYPE: u8 = 8;
impl<'a> flatbuffers::Follow<'a> for Type {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::read_scalar_at::<Self>(buf, loc)
}
}
impl flatbuffers::EndianScalar for Type {
#[inline]
fn to_little_endian(self) -> Self {
let n = u8::to_le(self as u8);
let p = &n as *const u8 as *const Type;
unsafe { *p }
}
#[inline]
fn from_little_endian(self) -> Self {
let n = u8::from_le(self as u8);
let p = &n as *const u8 as *const Type;
unsafe { *p }
}
}
impl flatbuffers::Push for Type {
type Output = Type;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
flatbuffers::emplace_scalar::<Type>(dst, *self);
}
}
#[allow(non_camel_case_types)]
const ENUM_VALUES_TYPE: [Type; 9] = [
Type::Bool,
Type::Int,
Type::Uint,
Type::Float,
Type::String,
Type::Duration,
Type::Time,
Type::Regexp,
Type::Bytes,
];
#[allow(non_camel_case_types)]
const ENUM_NAMES_TYPE: [&'static str; 9] = [
"Bool", "Int", "Uint", "Float", "String", "Duration", "Time", "Regexp", "Bytes",
];
pub fn enum_name_type(e: Type) -> &'static str {
let index = e as u8;
ENUM_NAMES_TYPE[index as usize]
}
#[allow(non_camel_case_types)]
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Kind {
Addable = 0,
Subtractable = 1,
Divisible = 2,
Numeric = 3,
Comparable = 4,
Equatable = 5,
Nullable = 6,
Row = 7,
Negatable = 8,
Timeable = 9,
}
const ENUM_MIN_KIND: u8 = 0;
const ENUM_MAX_KIND: u8 = 9;
impl<'a> flatbuffers::Follow<'a> for Kind {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::read_scalar_at::<Self>(buf, loc)
}
}
impl flatbuffers::EndianScalar for Kind {
#[inline]
fn to_little_endian(self) -> Self {
let n = u8::to_le(self as u8);
let p = &n as *const u8 as *const Kind;
unsafe { *p }
}
#[inline]
fn from_little_endian(self) -> Self {
let n = u8::from_le(self as u8);
let p = &n as *const u8 as *const Kind;
unsafe { *p }
}
}
impl flatbuffers::Push for Kind {
type Output = Kind;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
flatbuffers::emplace_scalar::<Kind>(dst, *self);
}
}
#[allow(non_camel_case_types)]
const ENUM_VALUES_KIND: [Kind; 10] = [
Kind::Addable,
Kind::Subtractable,
Kind::Divisible,
Kind::Numeric,
Kind::Comparable,
Kind::Equatable,
Kind::Nullable,
Kind::Row,
Kind::Negatable,
Kind::Timeable,
];
#[allow(non_camel_case_types)]
const ENUM_NAMES_KIND: [&'static str; 10] = [
"Addable",
"Subtractable",
"Divisible",
"Numeric",
"Comparable",
"Equatable",
"Nullable",
"Row",
"Negatable",
"Timeable",
];
pub fn enum_name_kind(e: Kind) -> &'static str {
let index = e as u8;
ENUM_NAMES_KIND[index as usize]
}
#[allow(non_camel_case_types)]
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Statement {
NONE = 0,
OptionStatement = 1,
BuiltinStatement = 2,
TestStatement = 3,
ExpressionStatement = 4,
NativeVariableAssignment = 5,
MemberAssignment = 6,
ReturnStatement = 7,
}
const ENUM_MIN_STATEMENT: u8 = 0;
const ENUM_MAX_STATEMENT: u8 = 7;
impl<'a> flatbuffers::Follow<'a> for Statement {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::read_scalar_at::<Self>(buf, loc)
}
}
impl flatbuffers::EndianScalar for Statement {
#[inline]
fn to_little_endian(self) -> Self {
let n = u8::to_le(self as u8);
let p = &n as *const u8 as *const Statement;
unsafe { *p }
}
#[inline]
fn from_little_endian(self) -> Self {
let n = u8::from_le(self as u8);
let p = &n as *const u8 as *const Statement;
unsafe { *p }
}
}
impl flatbuffers::Push for Statement {
type Output = Statement;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
flatbuffers::emplace_scalar::<Statement>(dst, *self);
}
}
#[allow(non_camel_case_types)]
const ENUM_VALUES_STATEMENT: [Statement; 8] = [
Statement::NONE,
Statement::OptionStatement,
Statement::BuiltinStatement,
Statement::TestStatement,
Statement::ExpressionStatement,
Statement::NativeVariableAssignment,
Statement::MemberAssignment,
Statement::ReturnStatement,
];
#[allow(non_camel_case_types)]
const ENUM_NAMES_STATEMENT: [&'static str; 8] = [
"NONE",
"OptionStatement",
"BuiltinStatement",
"TestStatement",
"ExpressionStatement",
"NativeVariableAssignment",
"MemberAssignment",
"ReturnStatement",
];
pub fn enum_name_statement(e: Statement) -> &'static str {
let index = e as u8;
ENUM_NAMES_STATEMENT[index as usize]
}
pub struct StatementUnionTableOffset {}
#[allow(non_camel_case_types)]
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Assignment {
NONE = 0,
MemberAssignment = 1,
NativeVariableAssignment = 2,
}
const ENUM_MIN_ASSIGNMENT: u8 = 0;
const ENUM_MAX_ASSIGNMENT: u8 = 2;
impl<'a> flatbuffers::Follow<'a> for Assignment {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::read_scalar_at::<Self>(buf, loc)
}
}
impl flatbuffers::EndianScalar for Assignment {
#[inline]
fn to_little_endian(self) -> Self {
let n = u8::to_le(self as u8);
let p = &n as *const u8 as *const Assignment;
unsafe { *p }
}
#[inline]
fn from_little_endian(self) -> Self {
let n = u8::from_le(self as u8);
let p = &n as *const u8 as *const Assignment;
unsafe { *p }
}
}
impl flatbuffers::Push for Assignment {
type Output = Assignment;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
flatbuffers::emplace_scalar::<Assignment>(dst, *self);
}
}
#[allow(non_camel_case_types)]
const ENUM_VALUES_ASSIGNMENT: [Assignment; 3] = [
Assignment::NONE,
Assignment::MemberAssignment,
Assignment::NativeVariableAssignment,
];
#[allow(non_camel_case_types)]
const ENUM_NAMES_ASSIGNMENT: [&'static str; 3] =
["NONE", "MemberAssignment", "NativeVariableAssignment"];
pub fn enum_name_assignment(e: Assignment) -> &'static str {
let index = e as u8;
ENUM_NAMES_ASSIGNMENT[index as usize]
}
pub struct AssignmentUnionTableOffset {}
#[allow(non_camel_case_types)]
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Expression {
NONE = 0,
StringExpression = 1,
ArrayExpression = 2,
FunctionExpression = 3,
BinaryExpression = 4,
CallExpression = 5,
ConditionalExpression = 6,
IdentifierExpression = 7,
LogicalExpression = 8,
MemberExpression = 9,
IndexExpression = 10,
ObjectExpression = 11,
UnaryExpression = 12,
BooleanLiteral = 13,
DateTimeLiteral = 14,
DurationLiteral = 15,
FloatLiteral = 16,
IntegerLiteral = 17,
StringLiteral = 18,
RegexpLiteral = 19,
UnsignedIntegerLiteral = 20,
}
const ENUM_MIN_EXPRESSION: u8 = 0;
const ENUM_MAX_EXPRESSION: u8 = 20;
impl<'a> flatbuffers::Follow<'a> for Expression {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::read_scalar_at::<Self>(buf, loc)
}
}
impl flatbuffers::EndianScalar for Expression {
#[inline]
fn to_little_endian(self) -> Self {
let n = u8::to_le(self as u8);
let p = &n as *const u8 as *const Expression;
unsafe { *p }
}
#[inline]
fn from_little_endian(self) -> Self {
let n = u8::from_le(self as u8);
let p = &n as *const u8 as *const Expression;
unsafe { *p }
}
}
impl flatbuffers::Push for Expression {
type Output = Expression;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
flatbuffers::emplace_scalar::<Expression>(dst, *self);
}
}
#[allow(non_camel_case_types)]
const ENUM_VALUES_EXPRESSION: [Expression; 21] = [
Expression::NONE,
Expression::StringExpression,
Expression::ArrayExpression,
Expression::FunctionExpression,
Expression::BinaryExpression,
Expression::CallExpression,
Expression::ConditionalExpression,
Expression::IdentifierExpression,
Expression::LogicalExpression,
Expression::MemberExpression,
Expression::IndexExpression,
Expression::ObjectExpression,
Expression::UnaryExpression,
Expression::BooleanLiteral,
Expression::DateTimeLiteral,
Expression::DurationLiteral,
Expression::FloatLiteral,
Expression::IntegerLiteral,
Expression::StringLiteral,
Expression::RegexpLiteral,
Expression::UnsignedIntegerLiteral,
];
#[allow(non_camel_case_types)]
const ENUM_NAMES_EXPRESSION: [&'static str; 21] = [
"NONE",
"StringExpression",
"ArrayExpression",
"FunctionExpression",
"BinaryExpression",
"CallExpression",
"ConditionalExpression",
"IdentifierExpression",
"LogicalExpression",
"MemberExpression",
"IndexExpression",
"ObjectExpression",
"UnaryExpression",
"BooleanLiteral",
"DateTimeLiteral",
"DurationLiteral",
"FloatLiteral",
"IntegerLiteral",
"StringLiteral",
"RegexpLiteral",
"UnsignedIntegerLiteral",
];
pub fn enum_name_expression(e: Expression) -> &'static str {
let index = e as u8;
ENUM_NAMES_EXPRESSION[index as usize]
}
pub struct ExpressionUnionTableOffset {}
#[allow(non_camel_case_types)]
#[repr(i8)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Operator {
MultiplicationOperator = 0,
DivisionOperator = 1,
ModuloOperator = 2,
PowerOperator = 3,
AdditionOperator = 4,
SubtractionOperator = 5,
LessThanEqualOperator = 6,
LessThanOperator = 7,
GreaterThanEqualOperator = 8,
GreaterThanOperator = 9,
StartsWithOperator = 10,
InOperator = 11,
NotOperator = 12,
ExistsOperator = 13,
NotEmptyOperator = 14,
EmptyOperator = 15,
EqualOperator = 16,
NotEqualOperator = 17,
RegexpMatchOperator = 18,
NotRegexpMatchOperator = 19,
InvalidOperator = 20,
}
const ENUM_MIN_OPERATOR: i8 = 0;
const ENUM_MAX_OPERATOR: i8 = 20;
impl<'a> flatbuffers::Follow<'a> for Operator {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::read_scalar_at::<Self>(buf, loc)
}
}
impl flatbuffers::EndianScalar for Operator {
#[inline]
fn to_little_endian(self) -> Self {
let n = i8::to_le(self as i8);
let p = &n as *const i8 as *const Operator;
unsafe { *p }
}
#[inline]
fn from_little_endian(self) -> Self {
let n = i8::from_le(self as i8);
let p = &n as *const i8 as *const Operator;
unsafe { *p }
}
}
impl flatbuffers::Push for Operator {
type Output = Operator;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
flatbuffers::emplace_scalar::<Operator>(dst, *self);
}
}
#[allow(non_camel_case_types)]
const ENUM_VALUES_OPERATOR: [Operator; 21] = [
Operator::MultiplicationOperator,
Operator::DivisionOperator,
Operator::ModuloOperator,
Operator::PowerOperator,
Operator::AdditionOperator,
Operator::SubtractionOperator,
Operator::LessThanEqualOperator,
Operator::LessThanOperator,
Operator::GreaterThanEqualOperator,
Operator::GreaterThanOperator,
Operator::StartsWithOperator,
Operator::InOperator,
Operator::NotOperator,
Operator::ExistsOperator,
Operator::NotEmptyOperator,
Operator::EmptyOperator,
Operator::EqualOperator,
Operator::NotEqualOperator,
Operator::RegexpMatchOperator,
Operator::NotRegexpMatchOperator,
Operator::InvalidOperator,
];
#[allow(non_camel_case_types)]
const ENUM_NAMES_OPERATOR: [&'static str; 21] = [
"MultiplicationOperator",
"DivisionOperator",
"ModuloOperator",
"PowerOperator",
"AdditionOperator",
"SubtractionOperator",
"LessThanEqualOperator",
"LessThanOperator",
"GreaterThanEqualOperator",
"GreaterThanOperator",
"StartsWithOperator",
"InOperator",
"NotOperator",
"ExistsOperator",
"NotEmptyOperator",
"EmptyOperator",
"EqualOperator",
"NotEqualOperator",
"RegexpMatchOperator",
"NotRegexpMatchOperator",
"InvalidOperator",
];
pub fn enum_name_operator(e: Operator) -> &'static str {
let index = e as i8;
ENUM_NAMES_OPERATOR[index as usize]
}
#[allow(non_camel_case_types)]
#[repr(i8)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum LogicalOperator {
AndOperator = 0,
OrOperator = 1,
}
const ENUM_MIN_LOGICAL_OPERATOR: i8 = 0;
const ENUM_MAX_LOGICAL_OPERATOR: i8 = 1;
impl<'a> flatbuffers::Follow<'a> for LogicalOperator {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::read_scalar_at::<Self>(buf, loc)
}
}
impl flatbuffers::EndianScalar for LogicalOperator {
#[inline]
fn to_little_endian(self) -> Self {
let n = i8::to_le(self as i8);
let p = &n as *const i8 as *const LogicalOperator;
unsafe { *p }
}
#[inline]
fn from_little_endian(self) -> Self {
let n = i8::from_le(self as i8);
let p = &n as *const i8 as *const LogicalOperator;
unsafe { *p }
}
}
impl flatbuffers::Push for LogicalOperator {
type Output = LogicalOperator;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
flatbuffers::emplace_scalar::<LogicalOperator>(dst, *self);
}
}
#[allow(non_camel_case_types)]
const ENUM_VALUES_LOGICAL_OPERATOR: [LogicalOperator; 2] =
[LogicalOperator::AndOperator, LogicalOperator::OrOperator];
#[allow(non_camel_case_types)]
const ENUM_NAMES_LOGICAL_OPERATOR: [&'static str; 2] = ["AndOperator", "OrOperator"];
pub fn enum_name_logical_operator(e: LogicalOperator) -> &'static str {
let index = e as i8;
ENUM_NAMES_LOGICAL_OPERATOR[index as usize]
}
// struct Position, aligned to 4
#[repr(C, align(4))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Position {
line_: i32,
column_: i32,
} // pub struct Position
impl flatbuffers::SafeSliceAccess for Position {}
impl<'a> flatbuffers::Follow<'a> for Position {
type Inner = &'a Position;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
<&'a Position>::follow(buf, loc)
}
}
impl<'a> flatbuffers::Follow<'a> for &'a Position {
type Inner = &'a Position;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::follow_cast_ref::<Position>(buf, loc)
}
}
impl<'b> flatbuffers::Push for Position {
type Output = Position;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
let src = unsafe {
::std::slice::from_raw_parts(self as *const Position as *const u8, Self::size())
};
dst.copy_from_slice(src);
}
}
impl<'b> flatbuffers::Push for &'b Position {
type Output = Position;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
let src = unsafe {
::std::slice::from_raw_parts(*self as *const Position as *const u8, Self::size())
};
dst.copy_from_slice(src);
}
}
impl Position {
pub fn new<'a>(_line: i32, _column: i32) -> Self {
Position {
line_: _line.to_little_endian(),
column_: _column.to_little_endian(),
}
}
pub fn line<'a>(&'a self) -> i32 {
self.line_.from_little_endian()
}
pub fn column<'a>(&'a self) -> i32 {
self.column_.from_little_endian()
}
}
pub enum FresherOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Fresher<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Fresher<'a> {
type Inner = Fresher<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Fresher<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Fresher { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args FresherArgs,
) -> flatbuffers::WIPOffset<Fresher<'bldr>> {
let mut builder = FresherBuilder::new(_fbb);
builder.add_u(args.u);
builder.finish()
}
pub const VT_U: flatbuffers::VOffsetT = 4;
#[inline]
pub fn u(&self) -> u64 {
self._tab.get::<u64>(Fresher::VT_U, Some(0)).unwrap()
}
}
pub struct FresherArgs {
pub u: u64,
}
impl<'a> Default for FresherArgs {
#[inline]
fn default() -> Self {
FresherArgs { u: 0 }
}
}
pub struct FresherBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> FresherBuilder<'a, 'b> {
#[inline]
pub fn add_u(&mut self, u: u64) {
self.fbb_.push_slot::<u64>(Fresher::VT_U, u, 0);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> FresherBuilder<'a, 'b> {
let start = _fbb.start_table();
FresherBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Fresher<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum TypeEnvironmentOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct TypeEnvironment<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for TypeEnvironment<'a> {
type Inner = TypeEnvironment<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> TypeEnvironment<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
TypeEnvironment { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args TypeEnvironmentArgs<'args>,
) -> flatbuffers::WIPOffset<TypeEnvironment<'bldr>> {
let mut builder = TypeEnvironmentBuilder::new(_fbb);
if let Some(x) = args.assignments {
builder.add_assignments(x);
}
builder.finish()
}
pub const VT_ASSIGNMENTS: flatbuffers::VOffsetT = 4;
#[inline]
pub fn assignments(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<TypeAssignment<'a>>>>
{
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<TypeAssignment<'a>>>,
>>(TypeEnvironment::VT_ASSIGNMENTS, None)
}
}
pub struct TypeEnvironmentArgs<'a> {
pub assignments: Option<
flatbuffers::WIPOffset<
flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<TypeAssignment<'a>>>,
>,
>,
}
impl<'a> Default for TypeEnvironmentArgs<'a> {
#[inline]
fn default() -> Self {
TypeEnvironmentArgs { assignments: None }
}
}
pub struct TypeEnvironmentBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> TypeEnvironmentBuilder<'a, 'b> {
#[inline]
pub fn add_assignments(
&mut self,
assignments: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<TypeAssignment<'b>>>,
>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
TypeEnvironment::VT_ASSIGNMENTS,
assignments,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> TypeEnvironmentBuilder<'a, 'b> {
let start = _fbb.start_table();
TypeEnvironmentBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<TypeEnvironment<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum TypeAssignmentOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct TypeAssignment<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for TypeAssignment<'a> {
type Inner = TypeAssignment<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> TypeAssignment<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
TypeAssignment { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args TypeAssignmentArgs<'args>,
) -> flatbuffers::WIPOffset<TypeAssignment<'bldr>> {
let mut builder = TypeAssignmentBuilder::new(_fbb);
if let Some(x) = args.ty {
builder.add_ty(x);
}
if let Some(x) = args.id {
builder.add_id(x);
}
builder.finish()
}
pub const VT_ID: flatbuffers::VOffsetT = 4;
pub const VT_TY: flatbuffers::VOffsetT = 6;
#[inline]
pub fn id(&self) -> Option<&'a str> {
self._tab
.get::<flatbuffers::ForwardsUOffset<&str>>(TypeAssignment::VT_ID, None)
}
#[inline]
pub fn ty(&self) -> Option<PolyType<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<PolyType<'a>>>(TypeAssignment::VT_TY, None)
}
}
pub struct TypeAssignmentArgs<'a> {
pub id: Option<flatbuffers::WIPOffset<&'a str>>,
pub ty: Option<flatbuffers::WIPOffset<PolyType<'a>>>,
}
impl<'a> Default for TypeAssignmentArgs<'a> {
#[inline]
fn default() -> Self {
TypeAssignmentArgs { id: None, ty: None }
}
}
pub struct TypeAssignmentBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> TypeAssignmentBuilder<'a, 'b> {
#[inline]
pub fn add_id(&mut self, id: flatbuffers::WIPOffset<&'b str>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(TypeAssignment::VT_ID, id);
}
#[inline]
pub fn add_ty(&mut self, ty: flatbuffers::WIPOffset<PolyType<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<PolyType>>(TypeAssignment::VT_TY, ty);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> TypeAssignmentBuilder<'a, 'b> {
let start = _fbb.start_table();
TypeAssignmentBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<TypeAssignment<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum VarOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Var<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Var<'a> {
type Inner = Var<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Var<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Var { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args VarArgs,
) -> flatbuffers::WIPOffset<Var<'bldr>> {
let mut builder = VarBuilder::new(_fbb);
builder.add_i(args.i);
builder.finish()
}
pub const VT_I: flatbuffers::VOffsetT = 4;
#[inline]
pub fn i(&self) -> u64 {
self._tab.get::<u64>(Var::VT_I, Some(0)).unwrap()
}
}
pub struct VarArgs {
pub i: u64,
}
impl<'a> Default for VarArgs {
#[inline]
fn default() -> Self {
VarArgs { i: 0 }
}
}
pub struct VarBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> VarBuilder<'a, 'b> {
#[inline]
pub fn add_i(&mut self, i: u64) {
self.fbb_.push_slot::<u64>(Var::VT_I, i, 0);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> VarBuilder<'a, 'b> {
let start = _fbb.start_table();
VarBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Var<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum BasicOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Basic<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Basic<'a> {
type Inner = Basic<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Basic<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Basic { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args BasicArgs,
) -> flatbuffers::WIPOffset<Basic<'bldr>> {
let mut builder = BasicBuilder::new(_fbb);
builder.add_t(args.t);
builder.finish()
}
pub const VT_T: flatbuffers::VOffsetT = 4;
#[inline]
pub fn t(&self) -> Type {
self._tab
.get::<Type>(Basic::VT_T, Some(Type::Bool))
.unwrap()
}
}
pub struct BasicArgs {
pub t: Type,
}
impl<'a> Default for BasicArgs {
#[inline]
fn default() -> Self {
BasicArgs { t: Type::Bool }
}
}
pub struct BasicBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> BasicBuilder<'a, 'b> {
#[inline]
pub fn add_t(&mut self, t: Type) {
self.fbb_.push_slot::<Type>(Basic::VT_T, t, Type::Bool);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> BasicBuilder<'a, 'b> {
let start = _fbb.start_table();
BasicBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Basic<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum ArrOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Arr<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Arr<'a> {
type Inner = Arr<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Arr<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Arr { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args ArrArgs,
) -> flatbuffers::WIPOffset<Arr<'bldr>> {
let mut builder = ArrBuilder::new(_fbb);
if let Some(x) = args.t {
builder.add_t(x);
}
builder.add_t_type(args.t_type);
builder.finish()
}
pub const VT_T_TYPE: flatbuffers::VOffsetT = 4;
pub const VT_T: flatbuffers::VOffsetT = 6;
#[inline]
pub fn t_type(&self) -> MonoType {
self._tab
.get::<MonoType>(Arr::VT_T_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn t(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Arr::VT_T, None)
}
#[inline]
#[allow(non_snake_case)]
pub fn t_as_basic(&self) -> Option<Basic<'a>> {
if self.t_type() == MonoType::Basic {
self.t().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn t_as_var(&self) -> Option<Var<'a>> {
if self.t_type() == MonoType::Var {
self.t().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn t_as_arr(&self) -> Option<Arr<'a>> {
if self.t_type() == MonoType::Arr {
self.t().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn t_as_row(&self) -> Option<Row<'a>> {
if self.t_type() == MonoType::Row {
self.t().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn t_as_fun(&self) -> Option<Fun<'a>> {
if self.t_type() == MonoType::Fun {
self.t().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct ArrArgs {
pub t_type: MonoType,
pub t: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for ArrArgs {
#[inline]
fn default() -> Self {
ArrArgs {
t_type: MonoType::NONE,
t: None,
}
}
}
pub struct ArrBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> ArrBuilder<'a, 'b> {
#[inline]
pub fn add_t_type(&mut self, t_type: MonoType) {
self.fbb_
.push_slot::<MonoType>(Arr::VT_T_TYPE, t_type, MonoType::NONE);
}
#[inline]
pub fn add_t(&mut self, t: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Arr::VT_T, t);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> ArrBuilder<'a, 'b> {
let start = _fbb.start_table();
ArrBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Arr<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum RowOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Row<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Row<'a> {
type Inner = Row<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Row<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Row { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args RowArgs<'args>,
) -> flatbuffers::WIPOffset<Row<'bldr>> {
let mut builder = RowBuilder::new(_fbb);
if let Some(x) = args.extends {
builder.add_extends(x);
}
if let Some(x) = args.props {
builder.add_props(x);
}
builder.finish()
}
pub const VT_PROPS: flatbuffers::VOffsetT = 4;
pub const VT_EXTENDS: flatbuffers::VOffsetT = 6;
#[inline]
pub fn props(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Prop<'a>>>> {
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<Prop<'a>>>,
>>(Row::VT_PROPS, None)
}
#[inline]
pub fn extends(&self) -> Option<Var<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<Var<'a>>>(Row::VT_EXTENDS, None)
}
}
pub struct RowArgs<'a> {
pub props: Option<
flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Prop<'a>>>>,
>,
pub extends: Option<flatbuffers::WIPOffset<Var<'a>>>,
}
impl<'a> Default for RowArgs<'a> {
#[inline]
fn default() -> Self {
RowArgs {
props: None,
extends: None,
}
}
}
pub struct RowBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> RowBuilder<'a, 'b> {
#[inline]
pub fn add_props(
&mut self,
props: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<Prop<'b>>>,
>,
) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Row::VT_PROPS, props);
}
#[inline]
pub fn add_extends(&mut self, extends: flatbuffers::WIPOffset<Var<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<Var>>(Row::VT_EXTENDS, extends);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> RowBuilder<'a, 'b> {
let start = _fbb.start_table();
RowBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Row<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum FunOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Fun<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Fun<'a> {
type Inner = Fun<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Fun<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Fun { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args FunArgs<'args>,
) -> flatbuffers::WIPOffset<Fun<'bldr>> {
let mut builder = FunBuilder::new(_fbb);
if let Some(x) = args.retn {
builder.add_retn(x);
}
if let Some(x) = args.args {
builder.add_args(x);
}
builder.add_retn_type(args.retn_type);
builder.finish()
}
pub const VT_ARGS: flatbuffers::VOffsetT = 4;
pub const VT_RETN_TYPE: flatbuffers::VOffsetT = 6;
pub const VT_RETN: flatbuffers::VOffsetT = 8;
#[inline]
pub fn args(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Argument<'a>>>> {
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<Argument<'a>>>,
>>(Fun::VT_ARGS, None)
}
#[inline]
pub fn retn_type(&self) -> MonoType {
self._tab
.get::<MonoType>(Fun::VT_RETN_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn retn(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Fun::VT_RETN, None)
}
#[inline]
#[allow(non_snake_case)]
pub fn retn_as_basic(&self) -> Option<Basic<'a>> {
if self.retn_type() == MonoType::Basic {
self.retn().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn retn_as_var(&self) -> Option<Var<'a>> {
if self.retn_type() == MonoType::Var {
self.retn().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn retn_as_arr(&self) -> Option<Arr<'a>> {
if self.retn_type() == MonoType::Arr {
self.retn().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn retn_as_row(&self) -> Option<Row<'a>> {
if self.retn_type() == MonoType::Row {
self.retn().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn retn_as_fun(&self) -> Option<Fun<'a>> {
if self.retn_type() == MonoType::Fun {
self.retn().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct FunArgs<'a> {
pub args: Option<
flatbuffers::WIPOffset<
flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Argument<'a>>>,
>,
>,
pub retn_type: MonoType,
pub retn: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for FunArgs<'a> {
#[inline]
fn default() -> Self {
FunArgs {
args: None,
retn_type: MonoType::NONE,
retn: None,
}
}
}
pub struct FunBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> FunBuilder<'a, 'b> {
#[inline]
pub fn add_args(
&mut self,
args: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<Argument<'b>>>,
>,
) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Fun::VT_ARGS, args);
}
#[inline]
pub fn add_retn_type(&mut self, retn_type: MonoType) {
self.fbb_
.push_slot::<MonoType>(Fun::VT_RETN_TYPE, retn_type, MonoType::NONE);
}
#[inline]
pub fn add_retn(&mut self, retn: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Fun::VT_RETN, retn);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> FunBuilder<'a, 'b> {
let start = _fbb.start_table();
FunBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Fun<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum ArgumentOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Argument<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Argument<'a> {
type Inner = Argument<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Argument<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Argument { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args ArgumentArgs<'args>,
) -> flatbuffers::WIPOffset<Argument<'bldr>> {
let mut builder = ArgumentBuilder::new(_fbb);
if let Some(x) = args.t {
builder.add_t(x);
}
if let Some(x) = args.name {
builder.add_name(x);
}
builder.add_optional(args.optional);
builder.add_pipe(args.pipe);
builder.add_t_type(args.t_type);
builder.finish()
}
pub const VT_NAME: flatbuffers::VOffsetT = 4;
pub const VT_T_TYPE: flatbuffers::VOffsetT = 6;
pub const VT_T: flatbuffers::VOffsetT = 8;
pub const VT_PIPE: flatbuffers::VOffsetT = 10;
pub const VT_OPTIONAL: flatbuffers::VOffsetT = 12;
#[inline]
pub fn name(&self) -> Option<&'a str> {
self._tab
.get::<flatbuffers::ForwardsUOffset<&str>>(Argument::VT_NAME, None)
}
#[inline]
pub fn t_type(&self) -> MonoType {
self._tab
.get::<MonoType>(Argument::VT_T_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn t(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Argument::VT_T, None)
}
#[inline]
pub fn pipe(&self) -> bool {
self._tab
.get::<bool>(Argument::VT_PIPE, Some(false))
.unwrap()
}
#[inline]
pub fn optional(&self) -> bool {
self._tab
.get::<bool>(Argument::VT_OPTIONAL, Some(false))
.unwrap()
}
#[inline]
#[allow(non_snake_case)]
pub fn t_as_basic(&self) -> Option<Basic<'a>> {
if self.t_type() == MonoType::Basic {
self.t().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn t_as_var(&self) -> Option<Var<'a>> {
if self.t_type() == MonoType::Var {
self.t().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn t_as_arr(&self) -> Option<Arr<'a>> {
if self.t_type() == MonoType::Arr {
self.t().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn t_as_row(&self) -> Option<Row<'a>> {
if self.t_type() == MonoType::Row {
self.t().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn t_as_fun(&self) -> Option<Fun<'a>> {
if self.t_type() == MonoType::Fun {
self.t().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct ArgumentArgs<'a> {
pub name: Option<flatbuffers::WIPOffset<&'a str>>,
pub t_type: MonoType,
pub t: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub pipe: bool,
pub optional: bool,
}
impl<'a> Default for ArgumentArgs<'a> {
#[inline]
fn default() -> Self {
ArgumentArgs {
name: None,
t_type: MonoType::NONE,
t: None,
pipe: false,
optional: false,
}
}
}
pub struct ArgumentBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> ArgumentBuilder<'a, 'b> {
#[inline]
pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Argument::VT_NAME, name);
}
#[inline]
pub fn add_t_type(&mut self, t_type: MonoType) {
self.fbb_
.push_slot::<MonoType>(Argument::VT_T_TYPE, t_type, MonoType::NONE);
}
#[inline]
pub fn add_t(&mut self, t: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Argument::VT_T, t);
}
#[inline]
pub fn add_pipe(&mut self, pipe: bool) {
self.fbb_.push_slot::<bool>(Argument::VT_PIPE, pipe, false);
}
#[inline]
pub fn add_optional(&mut self, optional: bool) {
self.fbb_
.push_slot::<bool>(Argument::VT_OPTIONAL, optional, false);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> ArgumentBuilder<'a, 'b> {
let start = _fbb.start_table();
ArgumentBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Argument<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum PropOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Prop<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Prop<'a> {
type Inner = Prop<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Prop<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Prop { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args PropArgs<'args>,
) -> flatbuffers::WIPOffset<Prop<'bldr>> {
let mut builder = PropBuilder::new(_fbb);
if let Some(x) = args.v {
builder.add_v(x);
}
if let Some(x) = args.k {
builder.add_k(x);
}
builder.add_v_type(args.v_type);
builder.finish()
}
pub const VT_K: flatbuffers::VOffsetT = 4;
pub const VT_V_TYPE: flatbuffers::VOffsetT = 6;
pub const VT_V: flatbuffers::VOffsetT = 8;
#[inline]
pub fn k(&self) -> Option<&'a str> {
self._tab
.get::<flatbuffers::ForwardsUOffset<&str>>(Prop::VT_K, None)
}
#[inline]
pub fn v_type(&self) -> MonoType {
self._tab
.get::<MonoType>(Prop::VT_V_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn v(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Prop::VT_V, None)
}
#[inline]
#[allow(non_snake_case)]
pub fn v_as_basic(&self) -> Option<Basic<'a>> {
if self.v_type() == MonoType::Basic {
self.v().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn v_as_var(&self) -> Option<Var<'a>> {
if self.v_type() == MonoType::Var {
self.v().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn v_as_arr(&self) -> Option<Arr<'a>> {
if self.v_type() == MonoType::Arr {
self.v().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn v_as_row(&self) -> Option<Row<'a>> {
if self.v_type() == MonoType::Row {
self.v().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn v_as_fun(&self) -> Option<Fun<'a>> {
if self.v_type() == MonoType::Fun {
self.v().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct PropArgs<'a> {
pub k: Option<flatbuffers::WIPOffset<&'a str>>,
pub v_type: MonoType,
pub v: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for PropArgs<'a> {
#[inline]
fn default() -> Self {
PropArgs {
k: None,
v_type: MonoType::NONE,
v: None,
}
}
}
pub struct PropBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> PropBuilder<'a, 'b> {
#[inline]
pub fn add_k(&mut self, k: flatbuffers::WIPOffset<&'b str>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Prop::VT_K, k);
}
#[inline]
pub fn add_v_type(&mut self, v_type: MonoType) {
self.fbb_
.push_slot::<MonoType>(Prop::VT_V_TYPE, v_type, MonoType::NONE);
}
#[inline]
pub fn add_v(&mut self, v: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Prop::VT_V, v);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> PropBuilder<'a, 'b> {
let start = _fbb.start_table();
PropBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Prop<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum PolyTypeOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct PolyType<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for PolyType<'a> {
type Inner = PolyType<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> PolyType<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
PolyType { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args PolyTypeArgs<'args>,
) -> flatbuffers::WIPOffset<PolyType<'bldr>> {
let mut builder = PolyTypeBuilder::new(_fbb);
if let Some(x) = args.expr {
builder.add_expr(x);
}
if let Some(x) = args.cons {
builder.add_cons(x);
}
if let Some(x) = args.vars {
builder.add_vars(x);
}
builder.add_expr_type(args.expr_type);
builder.finish()
}
pub const VT_VARS: flatbuffers::VOffsetT = 4;
pub const VT_CONS: flatbuffers::VOffsetT = 6;
pub const VT_EXPR_TYPE: flatbuffers::VOffsetT = 8;
pub const VT_EXPR: flatbuffers::VOffsetT = 10;
#[inline]
pub fn vars(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Var<'a>>>> {
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<Var<'a>>>,
>>(PolyType::VT_VARS, None)
}
#[inline]
pub fn cons(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Constraint<'a>>>> {
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<Constraint<'a>>>,
>>(PolyType::VT_CONS, None)
}
#[inline]
pub fn expr_type(&self) -> MonoType {
self._tab
.get::<MonoType>(PolyType::VT_EXPR_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn expr(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
PolyType::VT_EXPR,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn expr_as_basic(&self) -> Option<Basic<'a>> {
if self.expr_type() == MonoType::Basic {
self.expr().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expr_as_var(&self) -> Option<Var<'a>> {
if self.expr_type() == MonoType::Var {
self.expr().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expr_as_arr(&self) -> Option<Arr<'a>> {
if self.expr_type() == MonoType::Arr {
self.expr().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expr_as_row(&self) -> Option<Row<'a>> {
if self.expr_type() == MonoType::Row {
self.expr().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expr_as_fun(&self) -> Option<Fun<'a>> {
if self.expr_type() == MonoType::Fun {
self.expr().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct PolyTypeArgs<'a> {
pub vars: Option<
flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Var<'a>>>>,
>,
pub cons: Option<
flatbuffers::WIPOffset<
flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Constraint<'a>>>,
>,
>,
pub expr_type: MonoType,
pub expr: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for PolyTypeArgs<'a> {
#[inline]
fn default() -> Self {
PolyTypeArgs {
vars: None,
cons: None,
expr_type: MonoType::NONE,
expr: None,
}
}
}
pub struct PolyTypeBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> PolyTypeBuilder<'a, 'b> {
#[inline]
pub fn add_vars(
&mut self,
vars: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<Var<'b>>>,
>,
) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(PolyType::VT_VARS, vars);
}
#[inline]
pub fn add_cons(
&mut self,
cons: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<Constraint<'b>>>,
>,
) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(PolyType::VT_CONS, cons);
}
#[inline]
pub fn add_expr_type(&mut self, expr_type: MonoType) {
self.fbb_
.push_slot::<MonoType>(PolyType::VT_EXPR_TYPE, expr_type, MonoType::NONE);
}
#[inline]
pub fn add_expr(&mut self, expr: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(PolyType::VT_EXPR, expr);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> PolyTypeBuilder<'a, 'b> {
let start = _fbb.start_table();
PolyTypeBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<PolyType<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum ConstraintOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Constraint<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Constraint<'a> {
type Inner = Constraint<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Constraint<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Constraint { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args ConstraintArgs<'args>,
) -> flatbuffers::WIPOffset<Constraint<'bldr>> {
let mut builder = ConstraintBuilder::new(_fbb);
if let Some(x) = args.tvar {
builder.add_tvar(x);
}
builder.add_kind(args.kind);
builder.finish()
}
pub const VT_TVAR: flatbuffers::VOffsetT = 4;
pub const VT_KIND: flatbuffers::VOffsetT = 6;
#[inline]
pub fn tvar(&self) -> Option<Var<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<Var<'a>>>(Constraint::VT_TVAR, None)
}
#[inline]
pub fn kind(&self) -> Kind {
self._tab
.get::<Kind>(Constraint::VT_KIND, Some(Kind::Addable))
.unwrap()
}
}
pub struct ConstraintArgs<'a> {
pub tvar: Option<flatbuffers::WIPOffset<Var<'a>>>,
pub kind: Kind,
}
impl<'a> Default for ConstraintArgs<'a> {
#[inline]
fn default() -> Self {
ConstraintArgs {
tvar: None,
kind: Kind::Addable,
}
}
}
pub struct ConstraintBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> ConstraintBuilder<'a, 'b> {
#[inline]
pub fn add_tvar(&mut self, tvar: flatbuffers::WIPOffset<Var<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<Var>>(Constraint::VT_TVAR, tvar);
}
#[inline]
pub fn add_kind(&mut self, kind: Kind) {
self.fbb_
.push_slot::<Kind>(Constraint::VT_KIND, kind, Kind::Addable);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> ConstraintBuilder<'a, 'b> {
let start = _fbb.start_table();
ConstraintBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Constraint<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum PackageOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Package<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Package<'a> {
type Inner = Package<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Package<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Package { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args PackageArgs<'args>,
) -> flatbuffers::WIPOffset<Package<'bldr>> {
let mut builder = PackageBuilder::new(_fbb);
if let Some(x) = args.files {
builder.add_files(x);
}
if let Some(x) = args.package {
builder.add_package(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_PACKAGE: flatbuffers::VOffsetT = 6;
pub const VT_FILES: flatbuffers::VOffsetT = 8;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(Package::VT_LOC, None)
}
#[inline]
pub fn package(&self) -> Option<&'a str> {
self._tab
.get::<flatbuffers::ForwardsUOffset<&str>>(Package::VT_PACKAGE, None)
}
#[inline]
pub fn files(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<File<'a>>>> {
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<File<'a>>>,
>>(Package::VT_FILES, None)
}
}
pub struct PackageArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub package: Option<flatbuffers::WIPOffset<&'a str>>,
pub files: Option<
flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<File<'a>>>>,
>,
}
impl<'a> Default for PackageArgs<'a> {
#[inline]
fn default() -> Self {
PackageArgs {
loc: None,
package: None,
files: None,
}
}
}
pub struct PackageBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> PackageBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(Package::VT_LOC, loc);
}
#[inline]
pub fn add_package(&mut self, package: flatbuffers::WIPOffset<&'b str>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Package::VT_PACKAGE, package);
}
#[inline]
pub fn add_files(
&mut self,
files: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<File<'b>>>,
>,
) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Package::VT_FILES, files);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> PackageBuilder<'a, 'b> {
let start = _fbb.start_table();
PackageBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Package<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum FileOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct File<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for File<'a> {
type Inner = File<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> File<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
File { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args FileArgs<'args>,
) -> flatbuffers::WIPOffset<File<'bldr>> {
let mut builder = FileBuilder::new(_fbb);
if let Some(x) = args.body {
builder.add_body(x);
}
if let Some(x) = args.imports {
builder.add_imports(x);
}
if let Some(x) = args.package {
builder.add_package(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_PACKAGE: flatbuffers::VOffsetT = 6;
pub const VT_IMPORTS: flatbuffers::VOffsetT = 8;
pub const VT_BODY: flatbuffers::VOffsetT = 10;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(File::VT_LOC, None)
}
#[inline]
pub fn package(&self) -> Option<PackageClause<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<PackageClause<'a>>>(File::VT_PACKAGE, None)
}
#[inline]
pub fn imports(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<ImportDeclaration<'a>>>>
{
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<ImportDeclaration<'a>>>,
>>(File::VT_IMPORTS, None)
}
#[inline]
pub fn body(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<WrappedStatement<'a>>>>
{
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<WrappedStatement<'a>>>,
>>(File::VT_BODY, None)
}
}
pub struct FileArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub package: Option<flatbuffers::WIPOffset<PackageClause<'a>>>,
pub imports: Option<
flatbuffers::WIPOffset<
flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<ImportDeclaration<'a>>>,
>,
>,
pub body: Option<
flatbuffers::WIPOffset<
flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<WrappedStatement<'a>>>,
>,
>,
}
impl<'a> Default for FileArgs<'a> {
#[inline]
fn default() -> Self {
FileArgs {
loc: None,
package: None,
imports: None,
body: None,
}
}
}
pub struct FileBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> FileBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(File::VT_LOC, loc);
}
#[inline]
pub fn add_package(&mut self, package: flatbuffers::WIPOffset<PackageClause<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<PackageClause>>(
File::VT_PACKAGE,
package,
);
}
#[inline]
pub fn add_imports(
&mut self,
imports: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<ImportDeclaration<'b>>>,
>,
) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(File::VT_IMPORTS, imports);
}
#[inline]
pub fn add_body(
&mut self,
body: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<WrappedStatement<'b>>>,
>,
) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(File::VT_BODY, body);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> FileBuilder<'a, 'b> {
let start = _fbb.start_table();
FileBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<File<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum PackageClauseOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct PackageClause<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for PackageClause<'a> {
type Inner = PackageClause<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> PackageClause<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
PackageClause { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args PackageClauseArgs<'args>,
) -> flatbuffers::WIPOffset<PackageClause<'bldr>> {
let mut builder = PackageClauseBuilder::new(_fbb);
if let Some(x) = args.name {
builder.add_name(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_NAME: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
PackageClause::VT_LOC,
None,
)
}
#[inline]
pub fn name(&self) -> Option<Identifier<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<Identifier<'a>>>(PackageClause::VT_NAME, None)
}
}
pub struct PackageClauseArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub name: Option<flatbuffers::WIPOffset<Identifier<'a>>>,
}
impl<'a> Default for PackageClauseArgs<'a> {
#[inline]
fn default() -> Self {
PackageClauseArgs {
loc: None,
name: None,
}
}
}
pub struct PackageClauseBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> PackageClauseBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
PackageClause::VT_LOC,
loc,
);
}
#[inline]
pub fn add_name(&mut self, name: flatbuffers::WIPOffset<Identifier<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<Identifier>>(
PackageClause::VT_NAME,
name,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> PackageClauseBuilder<'a, 'b> {
let start = _fbb.start_table();
PackageClauseBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<PackageClause<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum ImportDeclarationOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ImportDeclaration<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for ImportDeclaration<'a> {
type Inner = ImportDeclaration<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> ImportDeclaration<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
ImportDeclaration { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args ImportDeclarationArgs<'args>,
) -> flatbuffers::WIPOffset<ImportDeclaration<'bldr>> {
let mut builder = ImportDeclarationBuilder::new(_fbb);
if let Some(x) = args.path {
builder.add_path(x);
}
if let Some(x) = args.alias {
builder.add_alias(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_ALIAS: flatbuffers::VOffsetT = 6;
pub const VT_PATH: flatbuffers::VOffsetT = 8;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
ImportDeclaration::VT_LOC,
None,
)
}
#[inline]
pub fn alias(&self) -> Option<Identifier<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<Identifier<'a>>>(
ImportDeclaration::VT_ALIAS,
None,
)
}
#[inline]
pub fn path(&self) -> Option<StringLiteral<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<StringLiteral<'a>>>(
ImportDeclaration::VT_PATH,
None,
)
}
}
pub struct ImportDeclarationArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub alias: Option<flatbuffers::WIPOffset<Identifier<'a>>>,
pub path: Option<flatbuffers::WIPOffset<StringLiteral<'a>>>,
}
impl<'a> Default for ImportDeclarationArgs<'a> {
#[inline]
fn default() -> Self {
ImportDeclarationArgs {
loc: None,
alias: None,
path: None,
}
}
}
pub struct ImportDeclarationBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> ImportDeclarationBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
ImportDeclaration::VT_LOC,
loc,
);
}
#[inline]
pub fn add_alias(&mut self, alias: flatbuffers::WIPOffset<Identifier<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<Identifier>>(
ImportDeclaration::VT_ALIAS,
alias,
);
}
#[inline]
pub fn add_path(&mut self, path: flatbuffers::WIPOffset<StringLiteral<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<StringLiteral>>(
ImportDeclaration::VT_PATH,
path,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> ImportDeclarationBuilder<'a, 'b> {
let start = _fbb.start_table();
ImportDeclarationBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<ImportDeclaration<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum SourceLocationOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SourceLocation<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for SourceLocation<'a> {
type Inner = SourceLocation<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> SourceLocation<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
SourceLocation { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args SourceLocationArgs<'args>,
) -> flatbuffers::WIPOffset<SourceLocation<'bldr>> {
let mut builder = SourceLocationBuilder::new(_fbb);
if let Some(x) = args.source {
builder.add_source(x);
}
if let Some(x) = args.end {
builder.add_end(x);
}
if let Some(x) = args.start {
builder.add_start(x);
}
if let Some(x) = args.file {
builder.add_file(x);
}
builder.finish()
}
pub const VT_FILE: flatbuffers::VOffsetT = 4;
pub const VT_START: flatbuffers::VOffsetT = 6;
pub const VT_END: flatbuffers::VOffsetT = 8;
pub const VT_SOURCE: flatbuffers::VOffsetT = 10;
#[inline]
pub fn file(&self) -> Option<&'a str> {
self._tab
.get::<flatbuffers::ForwardsUOffset<&str>>(SourceLocation::VT_FILE, None)
}
#[inline]
pub fn start(&self) -> Option<&'a Position> {
self._tab.get::<Position>(SourceLocation::VT_START, None)
}
#[inline]
pub fn end(&self) -> Option<&'a Position> {
self._tab.get::<Position>(SourceLocation::VT_END, None)
}
#[inline]
pub fn source(&self) -> Option<&'a str> {
self._tab
.get::<flatbuffers::ForwardsUOffset<&str>>(SourceLocation::VT_SOURCE, None)
}
}
pub struct SourceLocationArgs<'a> {
pub file: Option<flatbuffers::WIPOffset<&'a str>>,
pub start: Option<&'a Position>,
pub end: Option<&'a Position>,
pub source: Option<flatbuffers::WIPOffset<&'a str>>,
}
impl<'a> Default for SourceLocationArgs<'a> {
#[inline]
fn default() -> Self {
SourceLocationArgs {
file: None,
start: None,
end: None,
source: None,
}
}
}
pub struct SourceLocationBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> SourceLocationBuilder<'a, 'b> {
#[inline]
pub fn add_file(&mut self, file: flatbuffers::WIPOffset<&'b str>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(SourceLocation::VT_FILE, file);
}
#[inline]
pub fn add_start(&mut self, start: &'b Position) {
self.fbb_
.push_slot_always::<&Position>(SourceLocation::VT_START, start);
}
#[inline]
pub fn add_end(&mut self, end: &'b Position) {
self.fbb_
.push_slot_always::<&Position>(SourceLocation::VT_END, end);
}
#[inline]
pub fn add_source(&mut self, source: flatbuffers::WIPOffset<&'b str>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(SourceLocation::VT_SOURCE, source);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> SourceLocationBuilder<'a, 'b> {
let start = _fbb.start_table();
SourceLocationBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<SourceLocation<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum WrappedStatementOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct WrappedStatement<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for WrappedStatement<'a> {
type Inner = WrappedStatement<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> WrappedStatement<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
WrappedStatement { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args WrappedStatementArgs,
) -> flatbuffers::WIPOffset<WrappedStatement<'bldr>> {
let mut builder = WrappedStatementBuilder::new(_fbb);
if let Some(x) = args.statement {
builder.add_statement(x);
}
builder.add_statement_type(args.statement_type);
builder.finish()
}
pub const VT_STATEMENT_TYPE: flatbuffers::VOffsetT = 4;
pub const VT_STATEMENT: flatbuffers::VOffsetT = 6;
#[inline]
pub fn statement_type(&self) -> Statement {
self._tab
.get::<Statement>(WrappedStatement::VT_STATEMENT_TYPE, Some(Statement::NONE))
.unwrap()
}
#[inline]
pub fn statement(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
WrappedStatement::VT_STATEMENT,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn statement_as_option_statement(&self) -> Option<OptionStatement<'a>> {
if self.statement_type() == Statement::OptionStatement {
self.statement()
.map(|u| OptionStatement::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn statement_as_builtin_statement(&self) -> Option<BuiltinStatement<'a>> {
if self.statement_type() == Statement::BuiltinStatement {
self.statement()
.map(|u| BuiltinStatement::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn statement_as_test_statement(&self) -> Option<TestStatement<'a>> {
if self.statement_type() == Statement::TestStatement {
self.statement().map(|u| TestStatement::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn statement_as_expression_statement(&self) -> Option<ExpressionStatement<'a>> {
if self.statement_type() == Statement::ExpressionStatement {
self.statement()
.map(|u| ExpressionStatement::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn statement_as_native_variable_assignment(
&self,
) -> Option<NativeVariableAssignment<'a>> {
if self.statement_type() == Statement::NativeVariableAssignment {
self.statement()
.map(|u| NativeVariableAssignment::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn statement_as_member_assignment(&self) -> Option<MemberAssignment<'a>> {
if self.statement_type() == Statement::MemberAssignment {
self.statement()
.map(|u| MemberAssignment::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn statement_as_return_statement(&self) -> Option<ReturnStatement<'a>> {
if self.statement_type() == Statement::ReturnStatement {
self.statement()
.map(|u| ReturnStatement::init_from_table(u))
} else {
None
}
}
}
pub struct WrappedStatementArgs {
pub statement_type: Statement,
pub statement: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for WrappedStatementArgs {
#[inline]
fn default() -> Self {
WrappedStatementArgs {
statement_type: Statement::NONE,
statement: None,
}
}
}
pub struct WrappedStatementBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> WrappedStatementBuilder<'a, 'b> {
#[inline]
pub fn add_statement_type(&mut self, statement_type: Statement) {
self.fbb_.push_slot::<Statement>(
WrappedStatement::VT_STATEMENT_TYPE,
statement_type,
Statement::NONE,
);
}
#[inline]
pub fn add_statement(
&mut self,
statement: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
WrappedStatement::VT_STATEMENT,
statement,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> WrappedStatementBuilder<'a, 'b> {
let start = _fbb.start_table();
WrappedStatementBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<WrappedStatement<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum OptionStatementOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct OptionStatement<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for OptionStatement<'a> {
type Inner = OptionStatement<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> OptionStatement<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
OptionStatement { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args OptionStatementArgs<'args>,
) -> flatbuffers::WIPOffset<OptionStatement<'bldr>> {
let mut builder = OptionStatementBuilder::new(_fbb);
if let Some(x) = args.assignment {
builder.add_assignment(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_assignment_type(args.assignment_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_ASSIGNMENT_TYPE: flatbuffers::VOffsetT = 6;
pub const VT_ASSIGNMENT: flatbuffers::VOffsetT = 8;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
OptionStatement::VT_LOC,
None,
)
}
#[inline]
pub fn assignment_type(&self) -> Assignment {
self._tab
.get::<Assignment>(OptionStatement::VT_ASSIGNMENT_TYPE, Some(Assignment::NONE))
.unwrap()
}
#[inline]
pub fn assignment(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
OptionStatement::VT_ASSIGNMENT,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn assignment_as_member_assignment(&self) -> Option<MemberAssignment<'a>> {
if self.assignment_type() == Assignment::MemberAssignment {
self.assignment()
.map(|u| MemberAssignment::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn assignment_as_native_variable_assignment(
&self,
) -> Option<NativeVariableAssignment<'a>> {
if self.assignment_type() == Assignment::NativeVariableAssignment {
self.assignment()
.map(|u| NativeVariableAssignment::init_from_table(u))
} else {
None
}
}
}
pub struct OptionStatementArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub assignment_type: Assignment,
pub assignment: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for OptionStatementArgs<'a> {
#[inline]
fn default() -> Self {
OptionStatementArgs {
loc: None,
assignment_type: Assignment::NONE,
assignment: None,
}
}
}
pub struct OptionStatementBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> OptionStatementBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
OptionStatement::VT_LOC,
loc,
);
}
#[inline]
pub fn add_assignment_type(&mut self, assignment_type: Assignment) {
self.fbb_.push_slot::<Assignment>(
OptionStatement::VT_ASSIGNMENT_TYPE,
assignment_type,
Assignment::NONE,
);
}
#[inline]
pub fn add_assignment(
&mut self,
assignment: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
OptionStatement::VT_ASSIGNMENT,
assignment,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> OptionStatementBuilder<'a, 'b> {
let start = _fbb.start_table();
OptionStatementBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<OptionStatement<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum BuiltinStatementOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct BuiltinStatement<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for BuiltinStatement<'a> {
type Inner = BuiltinStatement<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> BuiltinStatement<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
BuiltinStatement { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args BuiltinStatementArgs<'args>,
) -> flatbuffers::WIPOffset<BuiltinStatement<'bldr>> {
let mut builder = BuiltinStatementBuilder::new(_fbb);
if let Some(x) = args.id {
builder.add_id(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_ID: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
BuiltinStatement::VT_LOC,
None,
)
}
#[inline]
pub fn id(&self) -> Option<Identifier<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<Identifier<'a>>>(BuiltinStatement::VT_ID, None)
}
}
pub struct BuiltinStatementArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub id: Option<flatbuffers::WIPOffset<Identifier<'a>>>,
}
impl<'a> Default for BuiltinStatementArgs<'a> {
#[inline]
fn default() -> Self {
BuiltinStatementArgs {
loc: None,
id: None,
}
}
}
pub struct BuiltinStatementBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> BuiltinStatementBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
BuiltinStatement::VT_LOC,
loc,
);
}
#[inline]
pub fn add_id(&mut self, id: flatbuffers::WIPOffset<Identifier<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<Identifier>>(
BuiltinStatement::VT_ID,
id,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> BuiltinStatementBuilder<'a, 'b> {
let start = _fbb.start_table();
BuiltinStatementBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<BuiltinStatement<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum TestStatementOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct TestStatement<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for TestStatement<'a> {
type Inner = TestStatement<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> TestStatement<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
TestStatement { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args TestStatementArgs<'args>,
) -> flatbuffers::WIPOffset<TestStatement<'bldr>> {
let mut builder = TestStatementBuilder::new(_fbb);
if let Some(x) = args.assignment {
builder.add_assignment(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_ASSIGNMENT: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
TestStatement::VT_LOC,
None,
)
}
#[inline]
pub fn assignment(&self) -> Option<NativeVariableAssignment<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<NativeVariableAssignment<'a>>>(
TestStatement::VT_ASSIGNMENT,
None,
)
}
}
pub struct TestStatementArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub assignment: Option<flatbuffers::WIPOffset<NativeVariableAssignment<'a>>>,
}
impl<'a> Default for TestStatementArgs<'a> {
#[inline]
fn default() -> Self {
TestStatementArgs {
loc: None,
assignment: None,
}
}
}
pub struct TestStatementBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> TestStatementBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
TestStatement::VT_LOC,
loc,
);
}
#[inline]
pub fn add_assignment(
&mut self,
assignment: flatbuffers::WIPOffset<NativeVariableAssignment<'b>>,
) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<NativeVariableAssignment>>(
TestStatement::VT_ASSIGNMENT,
assignment,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> TestStatementBuilder<'a, 'b> {
let start = _fbb.start_table();
TestStatementBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<TestStatement<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum ExpressionStatementOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ExpressionStatement<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for ExpressionStatement<'a> {
type Inner = ExpressionStatement<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> ExpressionStatement<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
ExpressionStatement { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args ExpressionStatementArgs<'args>,
) -> flatbuffers::WIPOffset<ExpressionStatement<'bldr>> {
let mut builder = ExpressionStatementBuilder::new(_fbb);
if let Some(x) = args.expression {
builder.add_expression(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_expression_type(args.expression_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_EXPRESSION_TYPE: flatbuffers::VOffsetT = 6;
pub const VT_EXPRESSION: flatbuffers::VOffsetT = 8;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
ExpressionStatement::VT_LOC,
None,
)
}
#[inline]
pub fn expression_type(&self) -> Expression {
self._tab
.get::<Expression>(
ExpressionStatement::VT_EXPRESSION_TYPE,
Some(Expression::NONE),
)
.unwrap()
}
#[inline]
pub fn expression(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
ExpressionStatement::VT_EXPRESSION,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.expression_type() == Expression::StringExpression {
self.expression()
.map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.expression_type() == Expression::ArrayExpression {
self.expression()
.map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.expression_type() == Expression::FunctionExpression {
self.expression()
.map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.expression_type() == Expression::BinaryExpression {
self.expression()
.map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.expression_type() == Expression::CallExpression {
self.expression()
.map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.expression_type() == Expression::ConditionalExpression {
self.expression()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.expression_type() == Expression::IdentifierExpression {
self.expression()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.expression_type() == Expression::LogicalExpression {
self.expression()
.map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.expression_type() == Expression::MemberExpression {
self.expression()
.map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.expression_type() == Expression::IndexExpression {
self.expression()
.map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.expression_type() == Expression::ObjectExpression {
self.expression()
.map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.expression_type() == Expression::UnaryExpression {
self.expression()
.map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.expression_type() == Expression::BooleanLiteral {
self.expression()
.map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.expression_type() == Expression::DateTimeLiteral {
self.expression()
.map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.expression_type() == Expression::DurationLiteral {
self.expression()
.map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.expression_type() == Expression::FloatLiteral {
self.expression().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.expression_type() == Expression::IntegerLiteral {
self.expression()
.map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.expression_type() == Expression::StringLiteral {
self.expression().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.expression_type() == Expression::RegexpLiteral {
self.expression().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.expression_type() == Expression::UnsignedIntegerLiteral {
self.expression()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
}
pub struct ExpressionStatementArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub expression_type: Expression,
pub expression: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for ExpressionStatementArgs<'a> {
#[inline]
fn default() -> Self {
ExpressionStatementArgs {
loc: None,
expression_type: Expression::NONE,
expression: None,
}
}
}
pub struct ExpressionStatementBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> ExpressionStatementBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
ExpressionStatement::VT_LOC,
loc,
);
}
#[inline]
pub fn add_expression_type(&mut self, expression_type: Expression) {
self.fbb_.push_slot::<Expression>(
ExpressionStatement::VT_EXPRESSION_TYPE,
expression_type,
Expression::NONE,
);
}
#[inline]
pub fn add_expression(
&mut self,
expression: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
ExpressionStatement::VT_EXPRESSION,
expression,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> ExpressionStatementBuilder<'a, 'b> {
let start = _fbb.start_table();
ExpressionStatementBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<ExpressionStatement<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum ReturnStatementOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ReturnStatement<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for ReturnStatement<'a> {
type Inner = ReturnStatement<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> ReturnStatement<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
ReturnStatement { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args ReturnStatementArgs<'args>,
) -> flatbuffers::WIPOffset<ReturnStatement<'bldr>> {
let mut builder = ReturnStatementBuilder::new(_fbb);
if let Some(x) = args.argument {
builder.add_argument(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_argument_type(args.argument_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_ARGUMENT_TYPE: flatbuffers::VOffsetT = 6;
pub const VT_ARGUMENT: flatbuffers::VOffsetT = 8;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
ReturnStatement::VT_LOC,
None,
)
}
#[inline]
pub fn argument_type(&self) -> Expression {
self._tab
.get::<Expression>(ReturnStatement::VT_ARGUMENT_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn argument(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
ReturnStatement::VT_ARGUMENT,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.argument_type() == Expression::StringExpression {
self.argument()
.map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.argument_type() == Expression::ArrayExpression {
self.argument().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.argument_type() == Expression::FunctionExpression {
self.argument()
.map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.argument_type() == Expression::BinaryExpression {
self.argument()
.map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.argument_type() == Expression::CallExpression {
self.argument().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.argument_type() == Expression::ConditionalExpression {
self.argument()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.argument_type() == Expression::IdentifierExpression {
self.argument()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.argument_type() == Expression::LogicalExpression {
self.argument()
.map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.argument_type() == Expression::MemberExpression {
self.argument()
.map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.argument_type() == Expression::IndexExpression {
self.argument().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.argument_type() == Expression::ObjectExpression {
self.argument()
.map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.argument_type() == Expression::UnaryExpression {
self.argument().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.argument_type() == Expression::BooleanLiteral {
self.argument().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.argument_type() == Expression::DateTimeLiteral {
self.argument().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.argument_type() == Expression::DurationLiteral {
self.argument().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.argument_type() == Expression::FloatLiteral {
self.argument().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.argument_type() == Expression::IntegerLiteral {
self.argument().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.argument_type() == Expression::StringLiteral {
self.argument().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.argument_type() == Expression::RegexpLiteral {
self.argument().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.argument_type() == Expression::UnsignedIntegerLiteral {
self.argument()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
}
pub struct ReturnStatementArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub argument_type: Expression,
pub argument: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for ReturnStatementArgs<'a> {
#[inline]
fn default() -> Self {
ReturnStatementArgs {
loc: None,
argument_type: Expression::NONE,
argument: None,
}
}
}
pub struct ReturnStatementBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> ReturnStatementBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
ReturnStatement::VT_LOC,
loc,
);
}
#[inline]
pub fn add_argument_type(&mut self, argument_type: Expression) {
self.fbb_.push_slot::<Expression>(
ReturnStatement::VT_ARGUMENT_TYPE,
argument_type,
Expression::NONE,
);
}
#[inline]
pub fn add_argument(
&mut self,
argument: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
ReturnStatement::VT_ARGUMENT,
argument,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> ReturnStatementBuilder<'a, 'b> {
let start = _fbb.start_table();
ReturnStatementBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<ReturnStatement<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum NativeVariableAssignmentOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct NativeVariableAssignment<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for NativeVariableAssignment<'a> {
type Inner = NativeVariableAssignment<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> NativeVariableAssignment<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
NativeVariableAssignment { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args NativeVariableAssignmentArgs<'args>,
) -> flatbuffers::WIPOffset<NativeVariableAssignment<'bldr>> {
let mut builder = NativeVariableAssignmentBuilder::new(_fbb);
if let Some(x) = args.typ {
builder.add_typ(x);
}
if let Some(x) = args.init_ {
builder.add_init_(x);
}
if let Some(x) = args.identifier {
builder.add_identifier(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_init__type(args.init__type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_IDENTIFIER: flatbuffers::VOffsetT = 6;
pub const VT_INIT__TYPE: flatbuffers::VOffsetT = 8;
pub const VT_INIT_: flatbuffers::VOffsetT = 10;
pub const VT_TYP: flatbuffers::VOffsetT = 12;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
NativeVariableAssignment::VT_LOC,
None,
)
}
#[inline]
pub fn identifier(&self) -> Option<Identifier<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<Identifier<'a>>>(
NativeVariableAssignment::VT_IDENTIFIER,
None,
)
}
#[inline]
pub fn init__type(&self) -> Expression {
self._tab
.get::<Expression>(
NativeVariableAssignment::VT_INIT__TYPE,
Some(Expression::NONE),
)
.unwrap()
}
#[inline]
pub fn init_(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
NativeVariableAssignment::VT_INIT_,
None,
)
}
#[inline]
pub fn typ(&self) -> Option<PolyType<'a>> {
self._tab.get::<flatbuffers::ForwardsUOffset<PolyType<'a>>>(
NativeVariableAssignment::VT_TYP,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.init__type() == Expression::StringExpression {
self.init_().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.init__type() == Expression::ArrayExpression {
self.init_().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.init__type() == Expression::FunctionExpression {
self.init_().map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.init__type() == Expression::BinaryExpression {
self.init_().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.init__type() == Expression::CallExpression {
self.init_().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.init__type() == Expression::ConditionalExpression {
self.init_()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.init__type() == Expression::IdentifierExpression {
self.init_()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.init__type() == Expression::LogicalExpression {
self.init_().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.init__type() == Expression::MemberExpression {
self.init_().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.init__type() == Expression::IndexExpression {
self.init_().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.init__type() == Expression::ObjectExpression {
self.init_().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.init__type() == Expression::UnaryExpression {
self.init_().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.init__type() == Expression::BooleanLiteral {
self.init_().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.init__type() == Expression::DateTimeLiteral {
self.init_().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.init__type() == Expression::DurationLiteral {
self.init_().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.init__type() == Expression::FloatLiteral {
self.init_().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.init__type() == Expression::IntegerLiteral {
self.init_().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.init__type() == Expression::StringLiteral {
self.init_().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.init__type() == Expression::RegexpLiteral {
self.init_().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.init__type() == Expression::UnsignedIntegerLiteral {
self.init_()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
}
pub struct NativeVariableAssignmentArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub identifier: Option<flatbuffers::WIPOffset<Identifier<'a>>>,
pub init__type: Expression,
pub init_: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub typ: Option<flatbuffers::WIPOffset<PolyType<'a>>>,
}
impl<'a> Default for NativeVariableAssignmentArgs<'a> {
#[inline]
fn default() -> Self {
NativeVariableAssignmentArgs {
loc: None,
identifier: None,
init__type: Expression::NONE,
init_: None,
typ: None,
}
}
}
pub struct NativeVariableAssignmentBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> NativeVariableAssignmentBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
NativeVariableAssignment::VT_LOC,
loc,
);
}
#[inline]
pub fn add_identifier(&mut self, identifier: flatbuffers::WIPOffset<Identifier<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<Identifier>>(
NativeVariableAssignment::VT_IDENTIFIER,
identifier,
);
}
#[inline]
pub fn add_init__type(&mut self, init__type: Expression) {
self.fbb_.push_slot::<Expression>(
NativeVariableAssignment::VT_INIT__TYPE,
init__type,
Expression::NONE,
);
}
#[inline]
pub fn add_init_(&mut self, init_: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
NativeVariableAssignment::VT_INIT_,
init_,
);
}
#[inline]
pub fn add_typ(&mut self, typ: flatbuffers::WIPOffset<PolyType<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<PolyType>>(
NativeVariableAssignment::VT_TYP,
typ,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> NativeVariableAssignmentBuilder<'a, 'b> {
let start = _fbb.start_table();
NativeVariableAssignmentBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<NativeVariableAssignment<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum MemberAssignmentOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct MemberAssignment<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for MemberAssignment<'a> {
type Inner = MemberAssignment<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> MemberAssignment<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
MemberAssignment { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args MemberAssignmentArgs<'args>,
) -> flatbuffers::WIPOffset<MemberAssignment<'bldr>> {
let mut builder = MemberAssignmentBuilder::new(_fbb);
if let Some(x) = args.init_ {
builder.add_init_(x);
}
if let Some(x) = args.member {
builder.add_member(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_init__type(args.init__type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_MEMBER: flatbuffers::VOffsetT = 6;
pub const VT_INIT__TYPE: flatbuffers::VOffsetT = 8;
pub const VT_INIT_: flatbuffers::VOffsetT = 10;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
MemberAssignment::VT_LOC,
None,
)
}
#[inline]
pub fn member(&self) -> Option<MemberExpression<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<MemberExpression<'a>>>(
MemberAssignment::VT_MEMBER,
None,
)
}
#[inline]
pub fn init__type(&self) -> Expression {
self._tab
.get::<Expression>(MemberAssignment::VT_INIT__TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn init_(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
MemberAssignment::VT_INIT_,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.init__type() == Expression::StringExpression {
self.init_().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.init__type() == Expression::ArrayExpression {
self.init_().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.init__type() == Expression::FunctionExpression {
self.init_().map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.init__type() == Expression::BinaryExpression {
self.init_().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.init__type() == Expression::CallExpression {
self.init_().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.init__type() == Expression::ConditionalExpression {
self.init_()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.init__type() == Expression::IdentifierExpression {
self.init_()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.init__type() == Expression::LogicalExpression {
self.init_().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.init__type() == Expression::MemberExpression {
self.init_().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.init__type() == Expression::IndexExpression {
self.init_().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.init__type() == Expression::ObjectExpression {
self.init_().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.init__type() == Expression::UnaryExpression {
self.init_().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.init__type() == Expression::BooleanLiteral {
self.init_().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.init__type() == Expression::DateTimeLiteral {
self.init_().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.init__type() == Expression::DurationLiteral {
self.init_().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.init__type() == Expression::FloatLiteral {
self.init_().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.init__type() == Expression::IntegerLiteral {
self.init_().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.init__type() == Expression::StringLiteral {
self.init_().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.init__type() == Expression::RegexpLiteral {
self.init_().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn init__as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.init__type() == Expression::UnsignedIntegerLiteral {
self.init_()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
}
pub struct MemberAssignmentArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub member: Option<flatbuffers::WIPOffset<MemberExpression<'a>>>,
pub init__type: Expression,
pub init_: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for MemberAssignmentArgs<'a> {
#[inline]
fn default() -> Self {
MemberAssignmentArgs {
loc: None,
member: None,
init__type: Expression::NONE,
init_: None,
}
}
}
pub struct MemberAssignmentBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> MemberAssignmentBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
MemberAssignment::VT_LOC,
loc,
);
}
#[inline]
pub fn add_member(&mut self, member: flatbuffers::WIPOffset<MemberExpression<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<MemberExpression>>(
MemberAssignment::VT_MEMBER,
member,
);
}
#[inline]
pub fn add_init__type(&mut self, init__type: Expression) {
self.fbb_.push_slot::<Expression>(
MemberAssignment::VT_INIT__TYPE,
init__type,
Expression::NONE,
);
}
#[inline]
pub fn add_init_(&mut self, init_: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(MemberAssignment::VT_INIT_, init_);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> MemberAssignmentBuilder<'a, 'b> {
let start = _fbb.start_table();
MemberAssignmentBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<MemberAssignment<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum WrappedExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct WrappedExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for WrappedExpression<'a> {
type Inner = WrappedExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> WrappedExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
WrappedExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args WrappedExpressionArgs,
) -> flatbuffers::WIPOffset<WrappedExpression<'bldr>> {
let mut builder = WrappedExpressionBuilder::new(_fbb);
if let Some(x) = args.expression {
builder.add_expression(x);
}
builder.add_expression_type(args.expression_type);
builder.finish()
}
pub const VT_EXPRESSION_TYPE: flatbuffers::VOffsetT = 4;
pub const VT_EXPRESSION: flatbuffers::VOffsetT = 6;
#[inline]
pub fn expression_type(&self) -> Expression {
self._tab
.get::<Expression>(
WrappedExpression::VT_EXPRESSION_TYPE,
Some(Expression::NONE),
)
.unwrap()
}
#[inline]
pub fn expression(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
WrappedExpression::VT_EXPRESSION,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.expression_type() == Expression::StringExpression {
self.expression()
.map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.expression_type() == Expression::ArrayExpression {
self.expression()
.map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.expression_type() == Expression::FunctionExpression {
self.expression()
.map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.expression_type() == Expression::BinaryExpression {
self.expression()
.map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.expression_type() == Expression::CallExpression {
self.expression()
.map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.expression_type() == Expression::ConditionalExpression {
self.expression()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.expression_type() == Expression::IdentifierExpression {
self.expression()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.expression_type() == Expression::LogicalExpression {
self.expression()
.map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.expression_type() == Expression::MemberExpression {
self.expression()
.map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.expression_type() == Expression::IndexExpression {
self.expression()
.map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.expression_type() == Expression::ObjectExpression {
self.expression()
.map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.expression_type() == Expression::UnaryExpression {
self.expression()
.map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.expression_type() == Expression::BooleanLiteral {
self.expression()
.map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.expression_type() == Expression::DateTimeLiteral {
self.expression()
.map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.expression_type() == Expression::DurationLiteral {
self.expression()
.map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.expression_type() == Expression::FloatLiteral {
self.expression().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.expression_type() == Expression::IntegerLiteral {
self.expression()
.map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.expression_type() == Expression::StringLiteral {
self.expression().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.expression_type() == Expression::RegexpLiteral {
self.expression().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn expression_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.expression_type() == Expression::UnsignedIntegerLiteral {
self.expression()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
}
pub struct WrappedExpressionArgs {
pub expression_type: Expression,
pub expression: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for WrappedExpressionArgs {
#[inline]
fn default() -> Self {
WrappedExpressionArgs {
expression_type: Expression::NONE,
expression: None,
}
}
}
pub struct WrappedExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> WrappedExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_expression_type(&mut self, expression_type: Expression) {
self.fbb_.push_slot::<Expression>(
WrappedExpression::VT_EXPRESSION_TYPE,
expression_type,
Expression::NONE,
);
}
#[inline]
pub fn add_expression(
&mut self,
expression: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
WrappedExpression::VT_EXPRESSION,
expression,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> WrappedExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
WrappedExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<WrappedExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum StringExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct StringExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for StringExpression<'a> {
type Inner = StringExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> StringExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
StringExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args StringExpressionArgs<'args>,
) -> flatbuffers::WIPOffset<StringExpression<'bldr>> {
let mut builder = StringExpressionBuilder::new(_fbb);
if let Some(x) = args.parts {
builder.add_parts(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_PARTS: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
StringExpression::VT_LOC,
None,
)
}
#[inline]
pub fn parts(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<StringExpressionPart<'a>>>>
{
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<StringExpressionPart<'a>>>,
>>(StringExpression::VT_PARTS, None)
}
}
pub struct StringExpressionArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub parts: Option<
flatbuffers::WIPOffset<
flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<StringExpressionPart<'a>>>,
>,
>,
}
impl<'a> Default for StringExpressionArgs<'a> {
#[inline]
fn default() -> Self {
StringExpressionArgs {
loc: None,
parts: None,
}
}
}
pub struct StringExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> StringExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
StringExpression::VT_LOC,
loc,
);
}
#[inline]
pub fn add_parts(
&mut self,
parts: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<StringExpressionPart<'b>>>,
>,
) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(StringExpression::VT_PARTS, parts);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> StringExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
StringExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<StringExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum StringExpressionPartOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct StringExpressionPart<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for StringExpressionPart<'a> {
type Inner = StringExpressionPart<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> StringExpressionPart<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
StringExpressionPart { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args StringExpressionPartArgs<'args>,
) -> flatbuffers::WIPOffset<StringExpressionPart<'bldr>> {
let mut builder = StringExpressionPartBuilder::new(_fbb);
if let Some(x) = args.interpolated_expression {
builder.add_interpolated_expression(x);
}
if let Some(x) = args.text_value {
builder.add_text_value(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_interpolated_expression_type(args.interpolated_expression_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_TEXT_VALUE: flatbuffers::VOffsetT = 6;
pub const VT_INTERPOLATED_EXPRESSION_TYPE: flatbuffers::VOffsetT = 8;
pub const VT_INTERPOLATED_EXPRESSION: flatbuffers::VOffsetT = 10;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
StringExpressionPart::VT_LOC,
None,
)
}
#[inline]
pub fn text_value(&self) -> Option<&'a str> {
self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(
StringExpressionPart::VT_TEXT_VALUE,
None,
)
}
#[inline]
pub fn interpolated_expression_type(&self) -> Expression {
self._tab
.get::<Expression>(
StringExpressionPart::VT_INTERPOLATED_EXPRESSION_TYPE,
Some(Expression::NONE),
)
.unwrap()
}
#[inline]
pub fn interpolated_expression(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
StringExpressionPart::VT_INTERPOLATED_EXPRESSION,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.interpolated_expression_type() == Expression::StringExpression {
self.interpolated_expression()
.map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.interpolated_expression_type() == Expression::ArrayExpression {
self.interpolated_expression()
.map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_function_expression(
&self,
) -> Option<FunctionExpression<'a>> {
if self.interpolated_expression_type() == Expression::FunctionExpression {
self.interpolated_expression()
.map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.interpolated_expression_type() == Expression::BinaryExpression {
self.interpolated_expression()
.map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.interpolated_expression_type() == Expression::CallExpression {
self.interpolated_expression()
.map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_conditional_expression(
&self,
) -> Option<ConditionalExpression<'a>> {
if self.interpolated_expression_type() == Expression::ConditionalExpression {
self.interpolated_expression()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_identifier_expression(
&self,
) -> Option<IdentifierExpression<'a>> {
if self.interpolated_expression_type() == Expression::IdentifierExpression {
self.interpolated_expression()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_logical_expression(
&self,
) -> Option<LogicalExpression<'a>> {
if self.interpolated_expression_type() == Expression::LogicalExpression {
self.interpolated_expression()
.map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.interpolated_expression_type() == Expression::MemberExpression {
self.interpolated_expression()
.map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.interpolated_expression_type() == Expression::IndexExpression {
self.interpolated_expression()
.map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.interpolated_expression_type() == Expression::ObjectExpression {
self.interpolated_expression()
.map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.interpolated_expression_type() == Expression::UnaryExpression {
self.interpolated_expression()
.map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.interpolated_expression_type() == Expression::BooleanLiteral {
self.interpolated_expression()
.map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.interpolated_expression_type() == Expression::DateTimeLiteral {
self.interpolated_expression()
.map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.interpolated_expression_type() == Expression::DurationLiteral {
self.interpolated_expression()
.map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.interpolated_expression_type() == Expression::FloatLiteral {
self.interpolated_expression()
.map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.interpolated_expression_type() == Expression::IntegerLiteral {
self.interpolated_expression()
.map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.interpolated_expression_type() == Expression::StringLiteral {
self.interpolated_expression()
.map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.interpolated_expression_type() == Expression::RegexpLiteral {
self.interpolated_expression()
.map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn interpolated_expression_as_unsigned_integer_literal(
&self,
) -> Option<UnsignedIntegerLiteral<'a>> {
if self.interpolated_expression_type() == Expression::UnsignedIntegerLiteral {
self.interpolated_expression()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
}
pub struct StringExpressionPartArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub text_value: Option<flatbuffers::WIPOffset<&'a str>>,
pub interpolated_expression_type: Expression,
pub interpolated_expression: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for StringExpressionPartArgs<'a> {
#[inline]
fn default() -> Self {
StringExpressionPartArgs {
loc: None,
text_value: None,
interpolated_expression_type: Expression::NONE,
interpolated_expression: None,
}
}
}
pub struct StringExpressionPartBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> StringExpressionPartBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
StringExpressionPart::VT_LOC,
loc,
);
}
#[inline]
pub fn add_text_value(&mut self, text_value: flatbuffers::WIPOffset<&'b str>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
StringExpressionPart::VT_TEXT_VALUE,
text_value,
);
}
#[inline]
pub fn add_interpolated_expression_type(
&mut self,
interpolated_expression_type: Expression,
) {
self.fbb_.push_slot::<Expression>(
StringExpressionPart::VT_INTERPOLATED_EXPRESSION_TYPE,
interpolated_expression_type,
Expression::NONE,
);
}
#[inline]
pub fn add_interpolated_expression(
&mut self,
interpolated_expression: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
StringExpressionPart::VT_INTERPOLATED_EXPRESSION,
interpolated_expression,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> StringExpressionPartBuilder<'a, 'b> {
let start = _fbb.start_table();
StringExpressionPartBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<StringExpressionPart<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum ArrayExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ArrayExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for ArrayExpression<'a> {
type Inner = ArrayExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> ArrayExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
ArrayExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args ArrayExpressionArgs<'args>,
) -> flatbuffers::WIPOffset<ArrayExpression<'bldr>> {
let mut builder = ArrayExpressionBuilder::new(_fbb);
if let Some(x) = args.typ {
builder.add_typ(x);
}
if let Some(x) = args.elements {
builder.add_elements(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_typ_type(args.typ_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_ELEMENTS: flatbuffers::VOffsetT = 6;
pub const VT_TYP_TYPE: flatbuffers::VOffsetT = 8;
pub const VT_TYP: flatbuffers::VOffsetT = 10;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
ArrayExpression::VT_LOC,
None,
)
}
#[inline]
pub fn elements(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<WrappedExpression<'a>>>>
{
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<WrappedExpression<'a>>>,
>>(ArrayExpression::VT_ELEMENTS, None)
}
#[inline]
pub fn typ_type(&self) -> MonoType {
self._tab
.get::<MonoType>(ArrayExpression::VT_TYP_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn typ(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
ArrayExpression::VT_TYP,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_basic(&self) -> Option<Basic<'a>> {
if self.typ_type() == MonoType::Basic {
self.typ().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_var(&self) -> Option<Var<'a>> {
if self.typ_type() == MonoType::Var {
self.typ().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_arr(&self) -> Option<Arr<'a>> {
if self.typ_type() == MonoType::Arr {
self.typ().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_row(&self) -> Option<Row<'a>> {
if self.typ_type() == MonoType::Row {
self.typ().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_fun(&self) -> Option<Fun<'a>> {
if self.typ_type() == MonoType::Fun {
self.typ().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct ArrayExpressionArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub elements: Option<
flatbuffers::WIPOffset<
flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<WrappedExpression<'a>>>,
>,
>,
pub typ_type: MonoType,
pub typ: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for ArrayExpressionArgs<'a> {
#[inline]
fn default() -> Self {
ArrayExpressionArgs {
loc: None,
elements: None,
typ_type: MonoType::NONE,
typ: None,
}
}
}
pub struct ArrayExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> ArrayExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
ArrayExpression::VT_LOC,
loc,
);
}
#[inline]
pub fn add_elements(
&mut self,
elements: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<WrappedExpression<'b>>>,
>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
ArrayExpression::VT_ELEMENTS,
elements,
);
}
#[inline]
pub fn add_typ_type(&mut self, typ_type: MonoType) {
self.fbb_
.push_slot::<MonoType>(ArrayExpression::VT_TYP_TYPE, typ_type, MonoType::NONE);
}
#[inline]
pub fn add_typ(&mut self, typ: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(ArrayExpression::VT_TYP, typ);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> ArrayExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
ArrayExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<ArrayExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum FunctionExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct FunctionExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for FunctionExpression<'a> {
type Inner = FunctionExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> FunctionExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
FunctionExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args FunctionExpressionArgs<'args>,
) -> flatbuffers::WIPOffset<FunctionExpression<'bldr>> {
let mut builder = FunctionExpressionBuilder::new(_fbb);
if let Some(x) = args.typ {
builder.add_typ(x);
}
if let Some(x) = args.body {
builder.add_body(x);
}
if let Some(x) = args.params {
builder.add_params(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_typ_type(args.typ_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_PARAMS: flatbuffers::VOffsetT = 6;
pub const VT_BODY: flatbuffers::VOffsetT = 8;
pub const VT_TYP_TYPE: flatbuffers::VOffsetT = 10;
pub const VT_TYP: flatbuffers::VOffsetT = 12;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
FunctionExpression::VT_LOC,
None,
)
}
#[inline]
pub fn params(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<FunctionParameter<'a>>>>
{
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<FunctionParameter<'a>>>,
>>(FunctionExpression::VT_PARAMS, None)
}
#[inline]
pub fn body(&self) -> Option<Block<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<Block<'a>>>(FunctionExpression::VT_BODY, None)
}
#[inline]
pub fn typ_type(&self) -> MonoType {
self._tab
.get::<MonoType>(FunctionExpression::VT_TYP_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn typ(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
FunctionExpression::VT_TYP,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_basic(&self) -> Option<Basic<'a>> {
if self.typ_type() == MonoType::Basic {
self.typ().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_var(&self) -> Option<Var<'a>> {
if self.typ_type() == MonoType::Var {
self.typ().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_arr(&self) -> Option<Arr<'a>> {
if self.typ_type() == MonoType::Arr {
self.typ().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_row(&self) -> Option<Row<'a>> {
if self.typ_type() == MonoType::Row {
self.typ().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_fun(&self) -> Option<Fun<'a>> {
if self.typ_type() == MonoType::Fun {
self.typ().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct FunctionExpressionArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub params: Option<
flatbuffers::WIPOffset<
flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<FunctionParameter<'a>>>,
>,
>,
pub body: Option<flatbuffers::WIPOffset<Block<'a>>>,
pub typ_type: MonoType,
pub typ: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for FunctionExpressionArgs<'a> {
#[inline]
fn default() -> Self {
FunctionExpressionArgs {
loc: None,
params: None,
body: None,
typ_type: MonoType::NONE,
typ: None,
}
}
}
pub struct FunctionExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> FunctionExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
FunctionExpression::VT_LOC,
loc,
);
}
#[inline]
pub fn add_params(
&mut self,
params: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<FunctionParameter<'b>>>,
>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
FunctionExpression::VT_PARAMS,
params,
);
}
#[inline]
pub fn add_body(&mut self, body: flatbuffers::WIPOffset<Block<'b>>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<Block>>(
FunctionExpression::VT_BODY,
body,
);
}
#[inline]
pub fn add_typ_type(&mut self, typ_type: MonoType) {
self.fbb_.push_slot::<MonoType>(
FunctionExpression::VT_TYP_TYPE,
typ_type,
MonoType::NONE,
);
}
#[inline]
pub fn add_typ(&mut self, typ: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(FunctionExpression::VT_TYP, typ);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> FunctionExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
FunctionExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<FunctionExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum FunctionParameterOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct FunctionParameter<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for FunctionParameter<'a> {
type Inner = FunctionParameter<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> FunctionParameter<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
FunctionParameter { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args FunctionParameterArgs<'args>,
) -> flatbuffers::WIPOffset<FunctionParameter<'bldr>> {
let mut builder = FunctionParameterBuilder::new(_fbb);
if let Some(x) = args.default {
builder.add_default(x);
}
if let Some(x) = args.key {
builder.add_key(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_default_type(args.default_type);
builder.add_is_pipe(args.is_pipe);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_IS_PIPE: flatbuffers::VOffsetT = 6;
pub const VT_KEY: flatbuffers::VOffsetT = 8;
pub const VT_DEFAULT_TYPE: flatbuffers::VOffsetT = 10;
pub const VT_DEFAULT: flatbuffers::VOffsetT = 12;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
FunctionParameter::VT_LOC,
None,
)
}
#[inline]
pub fn is_pipe(&self) -> bool {
self._tab
.get::<bool>(FunctionParameter::VT_IS_PIPE, Some(false))
.unwrap()
}
#[inline]
pub fn key(&self) -> Option<Identifier<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<Identifier<'a>>>(
FunctionParameter::VT_KEY,
None,
)
}
#[inline]
pub fn default_type(&self) -> Expression {
self._tab
.get::<Expression>(FunctionParameter::VT_DEFAULT_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn default(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
FunctionParameter::VT_DEFAULT,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.default_type() == Expression::StringExpression {
self.default().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.default_type() == Expression::ArrayExpression {
self.default().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.default_type() == Expression::FunctionExpression {
self.default()
.map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.default_type() == Expression::BinaryExpression {
self.default().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.default_type() == Expression::CallExpression {
self.default().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.default_type() == Expression::ConditionalExpression {
self.default()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.default_type() == Expression::IdentifierExpression {
self.default()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.default_type() == Expression::LogicalExpression {
self.default()
.map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.default_type() == Expression::MemberExpression {
self.default().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.default_type() == Expression::IndexExpression {
self.default().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.default_type() == Expression::ObjectExpression {
self.default().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.default_type() == Expression::UnaryExpression {
self.default().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.default_type() == Expression::BooleanLiteral {
self.default().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.default_type() == Expression::DateTimeLiteral {
self.default().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.default_type() == Expression::DurationLiteral {
self.default().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.default_type() == Expression::FloatLiteral {
self.default().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.default_type() == Expression::IntegerLiteral {
self.default().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.default_type() == Expression::StringLiteral {
self.default().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.default_type() == Expression::RegexpLiteral {
self.default().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn default_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.default_type() == Expression::UnsignedIntegerLiteral {
self.default()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
}
pub struct FunctionParameterArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub is_pipe: bool,
pub key: Option<flatbuffers::WIPOffset<Identifier<'a>>>,
pub default_type: Expression,
pub default: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for FunctionParameterArgs<'a> {
#[inline]
fn default() -> Self {
FunctionParameterArgs {
loc: None,
is_pipe: false,
key: None,
default_type: Expression::NONE,
default: None,
}
}
}
pub struct FunctionParameterBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> FunctionParameterBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
FunctionParameter::VT_LOC,
loc,
);
}
#[inline]
pub fn add_is_pipe(&mut self, is_pipe: bool) {
self.fbb_
.push_slot::<bool>(FunctionParameter::VT_IS_PIPE, is_pipe, false);
}
#[inline]
pub fn add_key(&mut self, key: flatbuffers::WIPOffset<Identifier<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<Identifier>>(
FunctionParameter::VT_KEY,
key,
);
}
#[inline]
pub fn add_default_type(&mut self, default_type: Expression) {
self.fbb_.push_slot::<Expression>(
FunctionParameter::VT_DEFAULT_TYPE,
default_type,
Expression::NONE,
);
}
#[inline]
pub fn add_default(
&mut self,
default: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
FunctionParameter::VT_DEFAULT,
default,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> FunctionParameterBuilder<'a, 'b> {
let start = _fbb.start_table();
FunctionParameterBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<FunctionParameter<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum BlockOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Block<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Block<'a> {
type Inner = Block<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Block<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Block { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args BlockArgs<'args>,
) -> flatbuffers::WIPOffset<Block<'bldr>> {
let mut builder = BlockBuilder::new(_fbb);
if let Some(x) = args.body {
builder.add_body(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_BODY: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(Block::VT_LOC, None)
}
#[inline]
pub fn body(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<WrappedStatement<'a>>>>
{
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<WrappedStatement<'a>>>,
>>(Block::VT_BODY, None)
}
}
pub struct BlockArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub body: Option<
flatbuffers::WIPOffset<
flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<WrappedStatement<'a>>>,
>,
>,
}
impl<'a> Default for BlockArgs<'a> {
#[inline]
fn default() -> Self {
BlockArgs {
loc: None,
body: None,
}
}
}
pub struct BlockBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> BlockBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(Block::VT_LOC, loc);
}
#[inline]
pub fn add_body(
&mut self,
body: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<WrappedStatement<'b>>>,
>,
) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Block::VT_BODY, body);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> BlockBuilder<'a, 'b> {
let start = _fbb.start_table();
BlockBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Block<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum BinaryExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct BinaryExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for BinaryExpression<'a> {
type Inner = BinaryExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> BinaryExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
BinaryExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args BinaryExpressionArgs<'args>,
) -> flatbuffers::WIPOffset<BinaryExpression<'bldr>> {
let mut builder = BinaryExpressionBuilder::new(_fbb);
if let Some(x) = args.typ {
builder.add_typ(x);
}
if let Some(x) = args.right {
builder.add_right(x);
}
if let Some(x) = args.left {
builder.add_left(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_typ_type(args.typ_type);
builder.add_right_type(args.right_type);
builder.add_left_type(args.left_type);
builder.add_operator(args.operator);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_OPERATOR: flatbuffers::VOffsetT = 6;
pub const VT_LEFT_TYPE: flatbuffers::VOffsetT = 8;
pub const VT_LEFT: flatbuffers::VOffsetT = 10;
pub const VT_RIGHT_TYPE: flatbuffers::VOffsetT = 12;
pub const VT_RIGHT: flatbuffers::VOffsetT = 14;
pub const VT_TYP_TYPE: flatbuffers::VOffsetT = 16;
pub const VT_TYP: flatbuffers::VOffsetT = 18;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
BinaryExpression::VT_LOC,
None,
)
}
#[inline]
pub fn operator(&self) -> Operator {
self._tab
.get::<Operator>(
BinaryExpression::VT_OPERATOR,
Some(Operator::MultiplicationOperator),
)
.unwrap()
}
#[inline]
pub fn left_type(&self) -> Expression {
self._tab
.get::<Expression>(BinaryExpression::VT_LEFT_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn left(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
BinaryExpression::VT_LEFT,
None,
)
}
#[inline]
pub fn right_type(&self) -> Expression {
self._tab
.get::<Expression>(BinaryExpression::VT_RIGHT_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn right(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
BinaryExpression::VT_RIGHT,
None,
)
}
#[inline]
pub fn typ_type(&self) -> MonoType {
self._tab
.get::<MonoType>(BinaryExpression::VT_TYP_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn typ(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
BinaryExpression::VT_TYP,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.left_type() == Expression::StringExpression {
self.left().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.left_type() == Expression::ArrayExpression {
self.left().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.left_type() == Expression::FunctionExpression {
self.left().map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.left_type() == Expression::BinaryExpression {
self.left().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.left_type() == Expression::CallExpression {
self.left().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.left_type() == Expression::ConditionalExpression {
self.left()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.left_type() == Expression::IdentifierExpression {
self.left()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.left_type() == Expression::LogicalExpression {
self.left().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.left_type() == Expression::MemberExpression {
self.left().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.left_type() == Expression::IndexExpression {
self.left().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.left_type() == Expression::ObjectExpression {
self.left().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.left_type() == Expression::UnaryExpression {
self.left().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.left_type() == Expression::BooleanLiteral {
self.left().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.left_type() == Expression::DateTimeLiteral {
self.left().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.left_type() == Expression::DurationLiteral {
self.left().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.left_type() == Expression::FloatLiteral {
self.left().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.left_type() == Expression::IntegerLiteral {
self.left().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.left_type() == Expression::StringLiteral {
self.left().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.left_type() == Expression::RegexpLiteral {
self.left().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.left_type() == Expression::UnsignedIntegerLiteral {
self.left()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.right_type() == Expression::StringExpression {
self.right().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.right_type() == Expression::ArrayExpression {
self.right().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.right_type() == Expression::FunctionExpression {
self.right().map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.right_type() == Expression::BinaryExpression {
self.right().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.right_type() == Expression::CallExpression {
self.right().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.right_type() == Expression::ConditionalExpression {
self.right()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.right_type() == Expression::IdentifierExpression {
self.right()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.right_type() == Expression::LogicalExpression {
self.right().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.right_type() == Expression::MemberExpression {
self.right().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.right_type() == Expression::IndexExpression {
self.right().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.right_type() == Expression::ObjectExpression {
self.right().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.right_type() == Expression::UnaryExpression {
self.right().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.right_type() == Expression::BooleanLiteral {
self.right().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.right_type() == Expression::DateTimeLiteral {
self.right().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.right_type() == Expression::DurationLiteral {
self.right().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.right_type() == Expression::FloatLiteral {
self.right().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.right_type() == Expression::IntegerLiteral {
self.right().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.right_type() == Expression::StringLiteral {
self.right().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.right_type() == Expression::RegexpLiteral {
self.right().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.right_type() == Expression::UnsignedIntegerLiteral {
self.right()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_basic(&self) -> Option<Basic<'a>> {
if self.typ_type() == MonoType::Basic {
self.typ().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_var(&self) -> Option<Var<'a>> {
if self.typ_type() == MonoType::Var {
self.typ().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_arr(&self) -> Option<Arr<'a>> {
if self.typ_type() == MonoType::Arr {
self.typ().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_row(&self) -> Option<Row<'a>> {
if self.typ_type() == MonoType::Row {
self.typ().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_fun(&self) -> Option<Fun<'a>> {
if self.typ_type() == MonoType::Fun {
self.typ().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct BinaryExpressionArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub operator: Operator,
pub left_type: Expression,
pub left: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub right_type: Expression,
pub right: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub typ_type: MonoType,
pub typ: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for BinaryExpressionArgs<'a> {
#[inline]
fn default() -> Self {
BinaryExpressionArgs {
loc: None,
operator: Operator::MultiplicationOperator,
left_type: Expression::NONE,
left: None,
right_type: Expression::NONE,
right: None,
typ_type: MonoType::NONE,
typ: None,
}
}
}
pub struct BinaryExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> BinaryExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
BinaryExpression::VT_LOC,
loc,
);
}
#[inline]
pub fn add_operator(&mut self, operator: Operator) {
self.fbb_.push_slot::<Operator>(
BinaryExpression::VT_OPERATOR,
operator,
Operator::MultiplicationOperator,
);
}
#[inline]
pub fn add_left_type(&mut self, left_type: Expression) {
self.fbb_.push_slot::<Expression>(
BinaryExpression::VT_LEFT_TYPE,
left_type,
Expression::NONE,
);
}
#[inline]
pub fn add_left(&mut self, left: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(BinaryExpression::VT_LEFT, left);
}
#[inline]
pub fn add_right_type(&mut self, right_type: Expression) {
self.fbb_.push_slot::<Expression>(
BinaryExpression::VT_RIGHT_TYPE,
right_type,
Expression::NONE,
);
}
#[inline]
pub fn add_right(&mut self, right: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(BinaryExpression::VT_RIGHT, right);
}
#[inline]
pub fn add_typ_type(&mut self, typ_type: MonoType) {
self.fbb_.push_slot::<MonoType>(
BinaryExpression::VT_TYP_TYPE,
typ_type,
MonoType::NONE,
);
}
#[inline]
pub fn add_typ(&mut self, typ: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(BinaryExpression::VT_TYP, typ);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> BinaryExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
BinaryExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<BinaryExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum CallExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct CallExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for CallExpression<'a> {
type Inner = CallExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> CallExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
CallExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args CallExpressionArgs<'args>,
) -> flatbuffers::WIPOffset<CallExpression<'bldr>> {
let mut builder = CallExpressionBuilder::new(_fbb);
if let Some(x) = args.typ {
builder.add_typ(x);
}
if let Some(x) = args.pipe {
builder.add_pipe(x);
}
if let Some(x) = args.arguments {
builder.add_arguments(x);
}
if let Some(x) = args.callee {
builder.add_callee(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_typ_type(args.typ_type);
builder.add_pipe_type(args.pipe_type);
builder.add_callee_type(args.callee_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_CALLEE_TYPE: flatbuffers::VOffsetT = 6;
pub const VT_CALLEE: flatbuffers::VOffsetT = 8;
pub const VT_ARGUMENTS: flatbuffers::VOffsetT = 10;
pub const VT_PIPE_TYPE: flatbuffers::VOffsetT = 12;
pub const VT_PIPE: flatbuffers::VOffsetT = 14;
pub const VT_TYP_TYPE: flatbuffers::VOffsetT = 16;
pub const VT_TYP: flatbuffers::VOffsetT = 18;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
CallExpression::VT_LOC,
None,
)
}
#[inline]
pub fn callee_type(&self) -> Expression {
self._tab
.get::<Expression>(CallExpression::VT_CALLEE_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn callee(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
CallExpression::VT_CALLEE,
None,
)
}
#[inline]
pub fn arguments(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Property<'a>>>> {
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<Property<'a>>>,
>>(CallExpression::VT_ARGUMENTS, None)
}
#[inline]
pub fn pipe_type(&self) -> Expression {
self._tab
.get::<Expression>(CallExpression::VT_PIPE_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn pipe(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
CallExpression::VT_PIPE,
None,
)
}
#[inline]
pub fn typ_type(&self) -> MonoType {
self._tab
.get::<MonoType>(CallExpression::VT_TYP_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn typ(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
CallExpression::VT_TYP,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.callee_type() == Expression::StringExpression {
self.callee().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.callee_type() == Expression::ArrayExpression {
self.callee().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.callee_type() == Expression::FunctionExpression {
self.callee()
.map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.callee_type() == Expression::BinaryExpression {
self.callee().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.callee_type() == Expression::CallExpression {
self.callee().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.callee_type() == Expression::ConditionalExpression {
self.callee()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.callee_type() == Expression::IdentifierExpression {
self.callee()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.callee_type() == Expression::LogicalExpression {
self.callee().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.callee_type() == Expression::MemberExpression {
self.callee().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.callee_type() == Expression::IndexExpression {
self.callee().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.callee_type() == Expression::ObjectExpression {
self.callee().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.callee_type() == Expression::UnaryExpression {
self.callee().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.callee_type() == Expression::BooleanLiteral {
self.callee().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.callee_type() == Expression::DateTimeLiteral {
self.callee().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.callee_type() == Expression::DurationLiteral {
self.callee().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.callee_type() == Expression::FloatLiteral {
self.callee().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.callee_type() == Expression::IntegerLiteral {
self.callee().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.callee_type() == Expression::StringLiteral {
self.callee().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.callee_type() == Expression::RegexpLiteral {
self.callee().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn callee_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.callee_type() == Expression::UnsignedIntegerLiteral {
self.callee()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.pipe_type() == Expression::StringExpression {
self.pipe().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.pipe_type() == Expression::ArrayExpression {
self.pipe().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.pipe_type() == Expression::FunctionExpression {
self.pipe().map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.pipe_type() == Expression::BinaryExpression {
self.pipe().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.pipe_type() == Expression::CallExpression {
self.pipe().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.pipe_type() == Expression::ConditionalExpression {
self.pipe()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.pipe_type() == Expression::IdentifierExpression {
self.pipe()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.pipe_type() == Expression::LogicalExpression {
self.pipe().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.pipe_type() == Expression::MemberExpression {
self.pipe().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.pipe_type() == Expression::IndexExpression {
self.pipe().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.pipe_type() == Expression::ObjectExpression {
self.pipe().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.pipe_type() == Expression::UnaryExpression {
self.pipe().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.pipe_type() == Expression::BooleanLiteral {
self.pipe().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.pipe_type() == Expression::DateTimeLiteral {
self.pipe().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.pipe_type() == Expression::DurationLiteral {
self.pipe().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.pipe_type() == Expression::FloatLiteral {
self.pipe().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.pipe_type() == Expression::IntegerLiteral {
self.pipe().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.pipe_type() == Expression::StringLiteral {
self.pipe().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.pipe_type() == Expression::RegexpLiteral {
self.pipe().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn pipe_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.pipe_type() == Expression::UnsignedIntegerLiteral {
self.pipe()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_basic(&self) -> Option<Basic<'a>> {
if self.typ_type() == MonoType::Basic {
self.typ().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_var(&self) -> Option<Var<'a>> {
if self.typ_type() == MonoType::Var {
self.typ().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_arr(&self) -> Option<Arr<'a>> {
if self.typ_type() == MonoType::Arr {
self.typ().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_row(&self) -> Option<Row<'a>> {
if self.typ_type() == MonoType::Row {
self.typ().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_fun(&self) -> Option<Fun<'a>> {
if self.typ_type() == MonoType::Fun {
self.typ().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct CallExpressionArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub callee_type: Expression,
pub callee: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub arguments: Option<
flatbuffers::WIPOffset<
flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Property<'a>>>,
>,
>,
pub pipe_type: Expression,
pub pipe: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub typ_type: MonoType,
pub typ: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for CallExpressionArgs<'a> {
#[inline]
fn default() -> Self {
CallExpressionArgs {
loc: None,
callee_type: Expression::NONE,
callee: None,
arguments: None,
pipe_type: Expression::NONE,
pipe: None,
typ_type: MonoType::NONE,
typ: None,
}
}
}
pub struct CallExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> CallExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
CallExpression::VT_LOC,
loc,
);
}
#[inline]
pub fn add_callee_type(&mut self, callee_type: Expression) {
self.fbb_.push_slot::<Expression>(
CallExpression::VT_CALLEE_TYPE,
callee_type,
Expression::NONE,
);
}
#[inline]
pub fn add_callee(&mut self, callee: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(CallExpression::VT_CALLEE, callee);
}
#[inline]
pub fn add_arguments(
&mut self,
arguments: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<Property<'b>>>,
>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
CallExpression::VT_ARGUMENTS,
arguments,
);
}
#[inline]
pub fn add_pipe_type(&mut self, pipe_type: Expression) {
self.fbb_.push_slot::<Expression>(
CallExpression::VT_PIPE_TYPE,
pipe_type,
Expression::NONE,
);
}
#[inline]
pub fn add_pipe(&mut self, pipe: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(CallExpression::VT_PIPE, pipe);
}
#[inline]
pub fn add_typ_type(&mut self, typ_type: MonoType) {
self.fbb_
.push_slot::<MonoType>(CallExpression::VT_TYP_TYPE, typ_type, MonoType::NONE);
}
#[inline]
pub fn add_typ(&mut self, typ: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(CallExpression::VT_TYP, typ);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> CallExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
CallExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<CallExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum ConditionalExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ConditionalExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for ConditionalExpression<'a> {
type Inner = ConditionalExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> ConditionalExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
ConditionalExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args ConditionalExpressionArgs<'args>,
) -> flatbuffers::WIPOffset<ConditionalExpression<'bldr>> {
let mut builder = ConditionalExpressionBuilder::new(_fbb);
if let Some(x) = args.consequent {
builder.add_consequent(x);
}
if let Some(x) = args.alternate {
builder.add_alternate(x);
}
if let Some(x) = args.test {
builder.add_test(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_consequent_type(args.consequent_type);
builder.add_alternate_type(args.alternate_type);
builder.add_test_type(args.test_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_TEST_TYPE: flatbuffers::VOffsetT = 6;
pub const VT_TEST: flatbuffers::VOffsetT = 8;
pub const VT_ALTERNATE_TYPE: flatbuffers::VOffsetT = 10;
pub const VT_ALTERNATE: flatbuffers::VOffsetT = 12;
pub const VT_CONSEQUENT_TYPE: flatbuffers::VOffsetT = 14;
pub const VT_CONSEQUENT: flatbuffers::VOffsetT = 16;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
ConditionalExpression::VT_LOC,
None,
)
}
#[inline]
pub fn test_type(&self) -> Expression {
self._tab
.get::<Expression>(ConditionalExpression::VT_TEST_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn test(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
ConditionalExpression::VT_TEST,
None,
)
}
#[inline]
pub fn alternate_type(&self) -> Expression {
self._tab
.get::<Expression>(
ConditionalExpression::VT_ALTERNATE_TYPE,
Some(Expression::NONE),
)
.unwrap()
}
#[inline]
pub fn alternate(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
ConditionalExpression::VT_ALTERNATE,
None,
)
}
#[inline]
pub fn consequent_type(&self) -> Expression {
self._tab
.get::<Expression>(
ConditionalExpression::VT_CONSEQUENT_TYPE,
Some(Expression::NONE),
)
.unwrap()
}
#[inline]
pub fn consequent(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
ConditionalExpression::VT_CONSEQUENT,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.test_type() == Expression::StringExpression {
self.test().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.test_type() == Expression::ArrayExpression {
self.test().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.test_type() == Expression::FunctionExpression {
self.test().map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.test_type() == Expression::BinaryExpression {
self.test().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.test_type() == Expression::CallExpression {
self.test().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.test_type() == Expression::ConditionalExpression {
self.test()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.test_type() == Expression::IdentifierExpression {
self.test()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.test_type() == Expression::LogicalExpression {
self.test().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.test_type() == Expression::MemberExpression {
self.test().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.test_type() == Expression::IndexExpression {
self.test().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.test_type() == Expression::ObjectExpression {
self.test().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.test_type() == Expression::UnaryExpression {
self.test().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.test_type() == Expression::BooleanLiteral {
self.test().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.test_type() == Expression::DateTimeLiteral {
self.test().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.test_type() == Expression::DurationLiteral {
self.test().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.test_type() == Expression::FloatLiteral {
self.test().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.test_type() == Expression::IntegerLiteral {
self.test().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.test_type() == Expression::StringLiteral {
self.test().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.test_type() == Expression::RegexpLiteral {
self.test().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn test_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.test_type() == Expression::UnsignedIntegerLiteral {
self.test()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.alternate_type() == Expression::StringExpression {
self.alternate()
.map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.alternate_type() == Expression::ArrayExpression {
self.alternate()
.map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.alternate_type() == Expression::FunctionExpression {
self.alternate()
.map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.alternate_type() == Expression::BinaryExpression {
self.alternate()
.map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.alternate_type() == Expression::CallExpression {
self.alternate().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.alternate_type() == Expression::ConditionalExpression {
self.alternate()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.alternate_type() == Expression::IdentifierExpression {
self.alternate()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.alternate_type() == Expression::LogicalExpression {
self.alternate()
.map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.alternate_type() == Expression::MemberExpression {
self.alternate()
.map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.alternate_type() == Expression::IndexExpression {
self.alternate()
.map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.alternate_type() == Expression::ObjectExpression {
self.alternate()
.map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.alternate_type() == Expression::UnaryExpression {
self.alternate()
.map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.alternate_type() == Expression::BooleanLiteral {
self.alternate().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.alternate_type() == Expression::DateTimeLiteral {
self.alternate()
.map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.alternate_type() == Expression::DurationLiteral {
self.alternate()
.map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.alternate_type() == Expression::FloatLiteral {
self.alternate().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.alternate_type() == Expression::IntegerLiteral {
self.alternate().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.alternate_type() == Expression::StringLiteral {
self.alternate().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.alternate_type() == Expression::RegexpLiteral {
self.alternate().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn alternate_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.alternate_type() == Expression::UnsignedIntegerLiteral {
self.alternate()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.consequent_type() == Expression::StringExpression {
self.consequent()
.map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.consequent_type() == Expression::ArrayExpression {
self.consequent()
.map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.consequent_type() == Expression::FunctionExpression {
self.consequent()
.map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.consequent_type() == Expression::BinaryExpression {
self.consequent()
.map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.consequent_type() == Expression::CallExpression {
self.consequent()
.map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.consequent_type() == Expression::ConditionalExpression {
self.consequent()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.consequent_type() == Expression::IdentifierExpression {
self.consequent()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.consequent_type() == Expression::LogicalExpression {
self.consequent()
.map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.consequent_type() == Expression::MemberExpression {
self.consequent()
.map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.consequent_type() == Expression::IndexExpression {
self.consequent()
.map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.consequent_type() == Expression::ObjectExpression {
self.consequent()
.map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.consequent_type() == Expression::UnaryExpression {
self.consequent()
.map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.consequent_type() == Expression::BooleanLiteral {
self.consequent()
.map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.consequent_type() == Expression::DateTimeLiteral {
self.consequent()
.map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.consequent_type() == Expression::DurationLiteral {
self.consequent()
.map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.consequent_type() == Expression::FloatLiteral {
self.consequent().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.consequent_type() == Expression::IntegerLiteral {
self.consequent()
.map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.consequent_type() == Expression::StringLiteral {
self.consequent().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.consequent_type() == Expression::RegexpLiteral {
self.consequent().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn consequent_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.consequent_type() == Expression::UnsignedIntegerLiteral {
self.consequent()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
}
pub struct ConditionalExpressionArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub test_type: Expression,
pub test: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub alternate_type: Expression,
pub alternate: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub consequent_type: Expression,
pub consequent: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for ConditionalExpressionArgs<'a> {
#[inline]
fn default() -> Self {
ConditionalExpressionArgs {
loc: None,
test_type: Expression::NONE,
test: None,
alternate_type: Expression::NONE,
alternate: None,
consequent_type: Expression::NONE,
consequent: None,
}
}
}
pub struct ConditionalExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> ConditionalExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
ConditionalExpression::VT_LOC,
loc,
);
}
#[inline]
pub fn add_test_type(&mut self, test_type: Expression) {
self.fbb_.push_slot::<Expression>(
ConditionalExpression::VT_TEST_TYPE,
test_type,
Expression::NONE,
);
}
#[inline]
pub fn add_test(&mut self, test: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
ConditionalExpression::VT_TEST,
test,
);
}
#[inline]
pub fn add_alternate_type(&mut self, alternate_type: Expression) {
self.fbb_.push_slot::<Expression>(
ConditionalExpression::VT_ALTERNATE_TYPE,
alternate_type,
Expression::NONE,
);
}
#[inline]
pub fn add_alternate(
&mut self,
alternate: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
ConditionalExpression::VT_ALTERNATE,
alternate,
);
}
#[inline]
pub fn add_consequent_type(&mut self, consequent_type: Expression) {
self.fbb_.push_slot::<Expression>(
ConditionalExpression::VT_CONSEQUENT_TYPE,
consequent_type,
Expression::NONE,
);
}
#[inline]
pub fn add_consequent(
&mut self,
consequent: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
ConditionalExpression::VT_CONSEQUENT,
consequent,
);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> ConditionalExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
ConditionalExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<ConditionalExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum LogicalExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct LogicalExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for LogicalExpression<'a> {
type Inner = LogicalExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> LogicalExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
LogicalExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args LogicalExpressionArgs<'args>,
) -> flatbuffers::WIPOffset<LogicalExpression<'bldr>> {
let mut builder = LogicalExpressionBuilder::new(_fbb);
if let Some(x) = args.right {
builder.add_right(x);
}
if let Some(x) = args.left {
builder.add_left(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_right_type(args.right_type);
builder.add_left_type(args.left_type);
builder.add_operator(args.operator);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_OPERATOR: flatbuffers::VOffsetT = 6;
pub const VT_LEFT_TYPE: flatbuffers::VOffsetT = 8;
pub const VT_LEFT: flatbuffers::VOffsetT = 10;
pub const VT_RIGHT_TYPE: flatbuffers::VOffsetT = 12;
pub const VT_RIGHT: flatbuffers::VOffsetT = 14;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
LogicalExpression::VT_LOC,
None,
)
}
#[inline]
pub fn operator(&self) -> LogicalOperator {
self._tab
.get::<LogicalOperator>(
LogicalExpression::VT_OPERATOR,
Some(LogicalOperator::AndOperator),
)
.unwrap()
}
#[inline]
pub fn left_type(&self) -> Expression {
self._tab
.get::<Expression>(LogicalExpression::VT_LEFT_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn left(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
LogicalExpression::VT_LEFT,
None,
)
}
#[inline]
pub fn right_type(&self) -> Expression {
self._tab
.get::<Expression>(LogicalExpression::VT_RIGHT_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn right(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
LogicalExpression::VT_RIGHT,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.left_type() == Expression::StringExpression {
self.left().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.left_type() == Expression::ArrayExpression {
self.left().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.left_type() == Expression::FunctionExpression {
self.left().map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.left_type() == Expression::BinaryExpression {
self.left().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.left_type() == Expression::CallExpression {
self.left().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.left_type() == Expression::ConditionalExpression {
self.left()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.left_type() == Expression::IdentifierExpression {
self.left()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.left_type() == Expression::LogicalExpression {
self.left().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.left_type() == Expression::MemberExpression {
self.left().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.left_type() == Expression::IndexExpression {
self.left().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.left_type() == Expression::ObjectExpression {
self.left().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.left_type() == Expression::UnaryExpression {
self.left().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.left_type() == Expression::BooleanLiteral {
self.left().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.left_type() == Expression::DateTimeLiteral {
self.left().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.left_type() == Expression::DurationLiteral {
self.left().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.left_type() == Expression::FloatLiteral {
self.left().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.left_type() == Expression::IntegerLiteral {
self.left().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.left_type() == Expression::StringLiteral {
self.left().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.left_type() == Expression::RegexpLiteral {
self.left().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn left_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.left_type() == Expression::UnsignedIntegerLiteral {
self.left()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.right_type() == Expression::StringExpression {
self.right().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.right_type() == Expression::ArrayExpression {
self.right().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.right_type() == Expression::FunctionExpression {
self.right().map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.right_type() == Expression::BinaryExpression {
self.right().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.right_type() == Expression::CallExpression {
self.right().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.right_type() == Expression::ConditionalExpression {
self.right()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.right_type() == Expression::IdentifierExpression {
self.right()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.right_type() == Expression::LogicalExpression {
self.right().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.right_type() == Expression::MemberExpression {
self.right().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.right_type() == Expression::IndexExpression {
self.right().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.right_type() == Expression::ObjectExpression {
self.right().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.right_type() == Expression::UnaryExpression {
self.right().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.right_type() == Expression::BooleanLiteral {
self.right().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.right_type() == Expression::DateTimeLiteral {
self.right().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.right_type() == Expression::DurationLiteral {
self.right().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.right_type() == Expression::FloatLiteral {
self.right().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.right_type() == Expression::IntegerLiteral {
self.right().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.right_type() == Expression::StringLiteral {
self.right().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.right_type() == Expression::RegexpLiteral {
self.right().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn right_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.right_type() == Expression::UnsignedIntegerLiteral {
self.right()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
}
pub struct LogicalExpressionArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub operator: LogicalOperator,
pub left_type: Expression,
pub left: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub right_type: Expression,
pub right: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for LogicalExpressionArgs<'a> {
#[inline]
fn default() -> Self {
LogicalExpressionArgs {
loc: None,
operator: LogicalOperator::AndOperator,
left_type: Expression::NONE,
left: None,
right_type: Expression::NONE,
right: None,
}
}
}
pub struct LogicalExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> LogicalExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
LogicalExpression::VT_LOC,
loc,
);
}
#[inline]
pub fn add_operator(&mut self, operator: LogicalOperator) {
self.fbb_.push_slot::<LogicalOperator>(
LogicalExpression::VT_OPERATOR,
operator,
LogicalOperator::AndOperator,
);
}
#[inline]
pub fn add_left_type(&mut self, left_type: Expression) {
self.fbb_.push_slot::<Expression>(
LogicalExpression::VT_LEFT_TYPE,
left_type,
Expression::NONE,
);
}
#[inline]
pub fn add_left(&mut self, left: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(LogicalExpression::VT_LEFT, left);
}
#[inline]
pub fn add_right_type(&mut self, right_type: Expression) {
self.fbb_.push_slot::<Expression>(
LogicalExpression::VT_RIGHT_TYPE,
right_type,
Expression::NONE,
);
}
#[inline]
pub fn add_right(&mut self, right: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(LogicalExpression::VT_RIGHT, right);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> LogicalExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
LogicalExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<LogicalExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum MemberExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct MemberExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for MemberExpression<'a> {
type Inner = MemberExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> MemberExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
MemberExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args MemberExpressionArgs<'args>,
) -> flatbuffers::WIPOffset<MemberExpression<'bldr>> {
let mut builder = MemberExpressionBuilder::new(_fbb);
if let Some(x) = args.typ {
builder.add_typ(x);
}
if let Some(x) = args.property {
builder.add_property(x);
}
if let Some(x) = args.object {
builder.add_object(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_typ_type(args.typ_type);
builder.add_object_type(args.object_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_OBJECT_TYPE: flatbuffers::VOffsetT = 6;
pub const VT_OBJECT: flatbuffers::VOffsetT = 8;
pub const VT_PROPERTY: flatbuffers::VOffsetT = 10;
pub const VT_TYP_TYPE: flatbuffers::VOffsetT = 12;
pub const VT_TYP: flatbuffers::VOffsetT = 14;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
MemberExpression::VT_LOC,
None,
)
}
#[inline]
pub fn object_type(&self) -> Expression {
self._tab
.get::<Expression>(MemberExpression::VT_OBJECT_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn object(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
MemberExpression::VT_OBJECT,
None,
)
}
#[inline]
pub fn property(&self) -> Option<&'a str> {
self._tab
.get::<flatbuffers::ForwardsUOffset<&str>>(MemberExpression::VT_PROPERTY, None)
}
#[inline]
pub fn typ_type(&self) -> MonoType {
self._tab
.get::<MonoType>(MemberExpression::VT_TYP_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn typ(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
MemberExpression::VT_TYP,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.object_type() == Expression::StringExpression {
self.object().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.object_type() == Expression::ArrayExpression {
self.object().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.object_type() == Expression::FunctionExpression {
self.object()
.map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.object_type() == Expression::BinaryExpression {
self.object().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.object_type() == Expression::CallExpression {
self.object().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.object_type() == Expression::ConditionalExpression {
self.object()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.object_type() == Expression::IdentifierExpression {
self.object()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.object_type() == Expression::LogicalExpression {
self.object().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.object_type() == Expression::MemberExpression {
self.object().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.object_type() == Expression::IndexExpression {
self.object().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.object_type() == Expression::ObjectExpression {
self.object().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.object_type() == Expression::UnaryExpression {
self.object().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.object_type() == Expression::BooleanLiteral {
self.object().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.object_type() == Expression::DateTimeLiteral {
self.object().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.object_type() == Expression::DurationLiteral {
self.object().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.object_type() == Expression::FloatLiteral {
self.object().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.object_type() == Expression::IntegerLiteral {
self.object().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.object_type() == Expression::StringLiteral {
self.object().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.object_type() == Expression::RegexpLiteral {
self.object().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn object_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.object_type() == Expression::UnsignedIntegerLiteral {
self.object()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_basic(&self) -> Option<Basic<'a>> {
if self.typ_type() == MonoType::Basic {
self.typ().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_var(&self) -> Option<Var<'a>> {
if self.typ_type() == MonoType::Var {
self.typ().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_arr(&self) -> Option<Arr<'a>> {
if self.typ_type() == MonoType::Arr {
self.typ().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_row(&self) -> Option<Row<'a>> {
if self.typ_type() == MonoType::Row {
self.typ().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_fun(&self) -> Option<Fun<'a>> {
if self.typ_type() == MonoType::Fun {
self.typ().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct MemberExpressionArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub object_type: Expression,
pub object: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub property: Option<flatbuffers::WIPOffset<&'a str>>,
pub typ_type: MonoType,
pub typ: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for MemberExpressionArgs<'a> {
#[inline]
fn default() -> Self {
MemberExpressionArgs {
loc: None,
object_type: Expression::NONE,
object: None,
property: None,
typ_type: MonoType::NONE,
typ: None,
}
}
}
pub struct MemberExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> MemberExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
MemberExpression::VT_LOC,
loc,
);
}
#[inline]
pub fn add_object_type(&mut self, object_type: Expression) {
self.fbb_.push_slot::<Expression>(
MemberExpression::VT_OBJECT_TYPE,
object_type,
Expression::NONE,
);
}
#[inline]
pub fn add_object(&mut self, object: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(MemberExpression::VT_OBJECT, object);
}
#[inline]
pub fn add_property(&mut self, property: flatbuffers::WIPOffset<&'b str>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
MemberExpression::VT_PROPERTY,
property,
);
}
#[inline]
pub fn add_typ_type(&mut self, typ_type: MonoType) {
self.fbb_.push_slot::<MonoType>(
MemberExpression::VT_TYP_TYPE,
typ_type,
MonoType::NONE,
);
}
#[inline]
pub fn add_typ(&mut self, typ: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(MemberExpression::VT_TYP, typ);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> MemberExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
MemberExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<MemberExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum IndexExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct IndexExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for IndexExpression<'a> {
type Inner = IndexExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> IndexExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
IndexExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args IndexExpressionArgs<'args>,
) -> flatbuffers::WIPOffset<IndexExpression<'bldr>> {
let mut builder = IndexExpressionBuilder::new(_fbb);
if let Some(x) = args.typ {
builder.add_typ(x);
}
if let Some(x) = args.index {
builder.add_index(x);
}
if let Some(x) = args.array {
builder.add_array(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_typ_type(args.typ_type);
builder.add_index_type(args.index_type);
builder.add_array_type(args.array_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_ARRAY_TYPE: flatbuffers::VOffsetT = 6;
pub const VT_ARRAY: flatbuffers::VOffsetT = 8;
pub const VT_INDEX_TYPE: flatbuffers::VOffsetT = 10;
pub const VT_INDEX: flatbuffers::VOffsetT = 12;
pub const VT_TYP_TYPE: flatbuffers::VOffsetT = 14;
pub const VT_TYP: flatbuffers::VOffsetT = 16;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
IndexExpression::VT_LOC,
None,
)
}
#[inline]
pub fn array_type(&self) -> Expression {
self._tab
.get::<Expression>(IndexExpression::VT_ARRAY_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn array(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
IndexExpression::VT_ARRAY,
None,
)
}
#[inline]
pub fn index_type(&self) -> Expression {
self._tab
.get::<Expression>(IndexExpression::VT_INDEX_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn index(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
IndexExpression::VT_INDEX,
None,
)
}
#[inline]
pub fn typ_type(&self) -> MonoType {
self._tab
.get::<MonoType>(IndexExpression::VT_TYP_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn typ(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
IndexExpression::VT_TYP,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.array_type() == Expression::StringExpression {
self.array().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.array_type() == Expression::ArrayExpression {
self.array().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.array_type() == Expression::FunctionExpression {
self.array().map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.array_type() == Expression::BinaryExpression {
self.array().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.array_type() == Expression::CallExpression {
self.array().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.array_type() == Expression::ConditionalExpression {
self.array()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.array_type() == Expression::IdentifierExpression {
self.array()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.array_type() == Expression::LogicalExpression {
self.array().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.array_type() == Expression::MemberExpression {
self.array().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.array_type() == Expression::IndexExpression {
self.array().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.array_type() == Expression::ObjectExpression {
self.array().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.array_type() == Expression::UnaryExpression {
self.array().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.array_type() == Expression::BooleanLiteral {
self.array().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.array_type() == Expression::DateTimeLiteral {
self.array().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.array_type() == Expression::DurationLiteral {
self.array().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.array_type() == Expression::FloatLiteral {
self.array().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.array_type() == Expression::IntegerLiteral {
self.array().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.array_type() == Expression::StringLiteral {
self.array().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.array_type() == Expression::RegexpLiteral {
self.array().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn array_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.array_type() == Expression::UnsignedIntegerLiteral {
self.array()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.index_type() == Expression::StringExpression {
self.index().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.index_type() == Expression::ArrayExpression {
self.index().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.index_type() == Expression::FunctionExpression {
self.index().map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.index_type() == Expression::BinaryExpression {
self.index().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.index_type() == Expression::CallExpression {
self.index().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.index_type() == Expression::ConditionalExpression {
self.index()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.index_type() == Expression::IdentifierExpression {
self.index()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.index_type() == Expression::LogicalExpression {
self.index().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.index_type() == Expression::MemberExpression {
self.index().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.index_type() == Expression::IndexExpression {
self.index().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.index_type() == Expression::ObjectExpression {
self.index().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.index_type() == Expression::UnaryExpression {
self.index().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.index_type() == Expression::BooleanLiteral {
self.index().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.index_type() == Expression::DateTimeLiteral {
self.index().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.index_type() == Expression::DurationLiteral {
self.index().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.index_type() == Expression::FloatLiteral {
self.index().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.index_type() == Expression::IntegerLiteral {
self.index().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.index_type() == Expression::StringLiteral {
self.index().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.index_type() == Expression::RegexpLiteral {
self.index().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn index_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.index_type() == Expression::UnsignedIntegerLiteral {
self.index()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_basic(&self) -> Option<Basic<'a>> {
if self.typ_type() == MonoType::Basic {
self.typ().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_var(&self) -> Option<Var<'a>> {
if self.typ_type() == MonoType::Var {
self.typ().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_arr(&self) -> Option<Arr<'a>> {
if self.typ_type() == MonoType::Arr {
self.typ().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_row(&self) -> Option<Row<'a>> {
if self.typ_type() == MonoType::Row {
self.typ().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_fun(&self) -> Option<Fun<'a>> {
if self.typ_type() == MonoType::Fun {
self.typ().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct IndexExpressionArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub array_type: Expression,
pub array: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub index_type: Expression,
pub index: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub typ_type: MonoType,
pub typ: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for IndexExpressionArgs<'a> {
#[inline]
fn default() -> Self {
IndexExpressionArgs {
loc: None,
array_type: Expression::NONE,
array: None,
index_type: Expression::NONE,
index: None,
typ_type: MonoType::NONE,
typ: None,
}
}
}
pub struct IndexExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> IndexExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
IndexExpression::VT_LOC,
loc,
);
}
#[inline]
pub fn add_array_type(&mut self, array_type: Expression) {
self.fbb_.push_slot::<Expression>(
IndexExpression::VT_ARRAY_TYPE,
array_type,
Expression::NONE,
);
}
#[inline]
pub fn add_array(&mut self, array: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(IndexExpression::VT_ARRAY, array);
}
#[inline]
pub fn add_index_type(&mut self, index_type: Expression) {
self.fbb_.push_slot::<Expression>(
IndexExpression::VT_INDEX_TYPE,
index_type,
Expression::NONE,
);
}
#[inline]
pub fn add_index(&mut self, index: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(IndexExpression::VT_INDEX, index);
}
#[inline]
pub fn add_typ_type(&mut self, typ_type: MonoType) {
self.fbb_
.push_slot::<MonoType>(IndexExpression::VT_TYP_TYPE, typ_type, MonoType::NONE);
}
#[inline]
pub fn add_typ(&mut self, typ: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(IndexExpression::VT_TYP, typ);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> IndexExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
IndexExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<IndexExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum ObjectExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ObjectExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for ObjectExpression<'a> {
type Inner = ObjectExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> ObjectExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
ObjectExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args ObjectExpressionArgs<'args>,
) -> flatbuffers::WIPOffset<ObjectExpression<'bldr>> {
let mut builder = ObjectExpressionBuilder::new(_fbb);
if let Some(x) = args.typ {
builder.add_typ(x);
}
if let Some(x) = args.properties {
builder.add_properties(x);
}
if let Some(x) = args.with {
builder.add_with(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_typ_type(args.typ_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_WITH: flatbuffers::VOffsetT = 6;
pub const VT_PROPERTIES: flatbuffers::VOffsetT = 8;
pub const VT_TYP_TYPE: flatbuffers::VOffsetT = 10;
pub const VT_TYP: flatbuffers::VOffsetT = 12;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
ObjectExpression::VT_LOC,
None,
)
}
#[inline]
pub fn with(&self) -> Option<IdentifierExpression<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<IdentifierExpression<'a>>>(
ObjectExpression::VT_WITH,
None,
)
}
#[inline]
pub fn properties(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Property<'a>>>> {
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<Property<'a>>>,
>>(ObjectExpression::VT_PROPERTIES, None)
}
#[inline]
pub fn typ_type(&self) -> MonoType {
self._tab
.get::<MonoType>(ObjectExpression::VT_TYP_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn typ(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
ObjectExpression::VT_TYP,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_basic(&self) -> Option<Basic<'a>> {
if self.typ_type() == MonoType::Basic {
self.typ().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_var(&self) -> Option<Var<'a>> {
if self.typ_type() == MonoType::Var {
self.typ().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_arr(&self) -> Option<Arr<'a>> {
if self.typ_type() == MonoType::Arr {
self.typ().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_row(&self) -> Option<Row<'a>> {
if self.typ_type() == MonoType::Row {
self.typ().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_fun(&self) -> Option<Fun<'a>> {
if self.typ_type() == MonoType::Fun {
self.typ().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct ObjectExpressionArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub with: Option<flatbuffers::WIPOffset<IdentifierExpression<'a>>>,
pub properties: Option<
flatbuffers::WIPOffset<
flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Property<'a>>>,
>,
>,
pub typ_type: MonoType,
pub typ: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for ObjectExpressionArgs<'a> {
#[inline]
fn default() -> Self {
ObjectExpressionArgs {
loc: None,
with: None,
properties: None,
typ_type: MonoType::NONE,
typ: None,
}
}
}
pub struct ObjectExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> ObjectExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
ObjectExpression::VT_LOC,
loc,
);
}
#[inline]
pub fn add_with(&mut self, with: flatbuffers::WIPOffset<IdentifierExpression<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<IdentifierExpression>>(
ObjectExpression::VT_WITH,
with,
);
}
#[inline]
pub fn add_properties(
&mut self,
properties: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<Property<'b>>>,
>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
ObjectExpression::VT_PROPERTIES,
properties,
);
}
#[inline]
pub fn add_typ_type(&mut self, typ_type: MonoType) {
self.fbb_.push_slot::<MonoType>(
ObjectExpression::VT_TYP_TYPE,
typ_type,
MonoType::NONE,
);
}
#[inline]
pub fn add_typ(&mut self, typ: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(ObjectExpression::VT_TYP, typ);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> ObjectExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
ObjectExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<ObjectExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum UnaryExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct UnaryExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for UnaryExpression<'a> {
type Inner = UnaryExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> UnaryExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
UnaryExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args UnaryExpressionArgs<'args>,
) -> flatbuffers::WIPOffset<UnaryExpression<'bldr>> {
let mut builder = UnaryExpressionBuilder::new(_fbb);
if let Some(x) = args.typ {
builder.add_typ(x);
}
if let Some(x) = args.argument {
builder.add_argument(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_typ_type(args.typ_type);
builder.add_argument_type(args.argument_type);
builder.add_operator(args.operator);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_OPERATOR: flatbuffers::VOffsetT = 6;
pub const VT_ARGUMENT_TYPE: flatbuffers::VOffsetT = 8;
pub const VT_ARGUMENT: flatbuffers::VOffsetT = 10;
pub const VT_TYP_TYPE: flatbuffers::VOffsetT = 12;
pub const VT_TYP: flatbuffers::VOffsetT = 14;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
UnaryExpression::VT_LOC,
None,
)
}
#[inline]
pub fn operator(&self) -> Operator {
self._tab
.get::<Operator>(
UnaryExpression::VT_OPERATOR,
Some(Operator::MultiplicationOperator),
)
.unwrap()
}
#[inline]
pub fn argument_type(&self) -> Expression {
self._tab
.get::<Expression>(UnaryExpression::VT_ARGUMENT_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn argument(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
UnaryExpression::VT_ARGUMENT,
None,
)
}
#[inline]
pub fn typ_type(&self) -> MonoType {
self._tab
.get::<MonoType>(UnaryExpression::VT_TYP_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn typ(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
UnaryExpression::VT_TYP,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.argument_type() == Expression::StringExpression {
self.argument()
.map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.argument_type() == Expression::ArrayExpression {
self.argument().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.argument_type() == Expression::FunctionExpression {
self.argument()
.map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.argument_type() == Expression::BinaryExpression {
self.argument()
.map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.argument_type() == Expression::CallExpression {
self.argument().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.argument_type() == Expression::ConditionalExpression {
self.argument()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.argument_type() == Expression::IdentifierExpression {
self.argument()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.argument_type() == Expression::LogicalExpression {
self.argument()
.map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.argument_type() == Expression::MemberExpression {
self.argument()
.map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.argument_type() == Expression::IndexExpression {
self.argument().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.argument_type() == Expression::ObjectExpression {
self.argument()
.map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.argument_type() == Expression::UnaryExpression {
self.argument().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.argument_type() == Expression::BooleanLiteral {
self.argument().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.argument_type() == Expression::DateTimeLiteral {
self.argument().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.argument_type() == Expression::DurationLiteral {
self.argument().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.argument_type() == Expression::FloatLiteral {
self.argument().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.argument_type() == Expression::IntegerLiteral {
self.argument().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.argument_type() == Expression::StringLiteral {
self.argument().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.argument_type() == Expression::RegexpLiteral {
self.argument().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn argument_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.argument_type() == Expression::UnsignedIntegerLiteral {
self.argument()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_basic(&self) -> Option<Basic<'a>> {
if self.typ_type() == MonoType::Basic {
self.typ().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_var(&self) -> Option<Var<'a>> {
if self.typ_type() == MonoType::Var {
self.typ().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_arr(&self) -> Option<Arr<'a>> {
if self.typ_type() == MonoType::Arr {
self.typ().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_row(&self) -> Option<Row<'a>> {
if self.typ_type() == MonoType::Row {
self.typ().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_fun(&self) -> Option<Fun<'a>> {
if self.typ_type() == MonoType::Fun {
self.typ().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct UnaryExpressionArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub operator: Operator,
pub argument_type: Expression,
pub argument: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub typ_type: MonoType,
pub typ: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for UnaryExpressionArgs<'a> {
#[inline]
fn default() -> Self {
UnaryExpressionArgs {
loc: None,
operator: Operator::MultiplicationOperator,
argument_type: Expression::NONE,
argument: None,
typ_type: MonoType::NONE,
typ: None,
}
}
}
pub struct UnaryExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> UnaryExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
UnaryExpression::VT_LOC,
loc,
);
}
#[inline]
pub fn add_operator(&mut self, operator: Operator) {
self.fbb_.push_slot::<Operator>(
UnaryExpression::VT_OPERATOR,
operator,
Operator::MultiplicationOperator,
);
}
#[inline]
pub fn add_argument_type(&mut self, argument_type: Expression) {
self.fbb_.push_slot::<Expression>(
UnaryExpression::VT_ARGUMENT_TYPE,
argument_type,
Expression::NONE,
);
}
#[inline]
pub fn add_argument(
&mut self,
argument: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
UnaryExpression::VT_ARGUMENT,
argument,
);
}
#[inline]
pub fn add_typ_type(&mut self, typ_type: MonoType) {
self.fbb_
.push_slot::<MonoType>(UnaryExpression::VT_TYP_TYPE, typ_type, MonoType::NONE);
}
#[inline]
pub fn add_typ(&mut self, typ: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(UnaryExpression::VT_TYP, typ);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> UnaryExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
UnaryExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<UnaryExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum PropertyOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Property<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Property<'a> {
type Inner = Property<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Property<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Property { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args PropertyArgs<'args>,
) -> flatbuffers::WIPOffset<Property<'bldr>> {
let mut builder = PropertyBuilder::new(_fbb);
if let Some(x) = args.value {
builder.add_value(x);
}
if let Some(x) = args.key {
builder.add_key(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_value_type(args.value_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_KEY: flatbuffers::VOffsetT = 6;
pub const VT_VALUE_TYPE: flatbuffers::VOffsetT = 8;
pub const VT_VALUE: flatbuffers::VOffsetT = 10;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(Property::VT_LOC, None)
}
#[inline]
pub fn key(&self) -> Option<Identifier<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<Identifier<'a>>>(Property::VT_KEY, None)
}
#[inline]
pub fn value_type(&self) -> Expression {
self._tab
.get::<Expression>(Property::VT_VALUE_TYPE, Some(Expression::NONE))
.unwrap()
}
#[inline]
pub fn value(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
Property::VT_VALUE,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_string_expression(&self) -> Option<StringExpression<'a>> {
if self.value_type() == Expression::StringExpression {
self.value().map(|u| StringExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_array_expression(&self) -> Option<ArrayExpression<'a>> {
if self.value_type() == Expression::ArrayExpression {
self.value().map(|u| ArrayExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_function_expression(&self) -> Option<FunctionExpression<'a>> {
if self.value_type() == Expression::FunctionExpression {
self.value().map(|u| FunctionExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_binary_expression(&self) -> Option<BinaryExpression<'a>> {
if self.value_type() == Expression::BinaryExpression {
self.value().map(|u| BinaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_call_expression(&self) -> Option<CallExpression<'a>> {
if self.value_type() == Expression::CallExpression {
self.value().map(|u| CallExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_conditional_expression(&self) -> Option<ConditionalExpression<'a>> {
if self.value_type() == Expression::ConditionalExpression {
self.value()
.map(|u| ConditionalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_identifier_expression(&self) -> Option<IdentifierExpression<'a>> {
if self.value_type() == Expression::IdentifierExpression {
self.value()
.map(|u| IdentifierExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_logical_expression(&self) -> Option<LogicalExpression<'a>> {
if self.value_type() == Expression::LogicalExpression {
self.value().map(|u| LogicalExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_member_expression(&self) -> Option<MemberExpression<'a>> {
if self.value_type() == Expression::MemberExpression {
self.value().map(|u| MemberExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_index_expression(&self) -> Option<IndexExpression<'a>> {
if self.value_type() == Expression::IndexExpression {
self.value().map(|u| IndexExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_object_expression(&self) -> Option<ObjectExpression<'a>> {
if self.value_type() == Expression::ObjectExpression {
self.value().map(|u| ObjectExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_unary_expression(&self) -> Option<UnaryExpression<'a>> {
if self.value_type() == Expression::UnaryExpression {
self.value().map(|u| UnaryExpression::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_boolean_literal(&self) -> Option<BooleanLiteral<'a>> {
if self.value_type() == Expression::BooleanLiteral {
self.value().map(|u| BooleanLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_date_time_literal(&self) -> Option<DateTimeLiteral<'a>> {
if self.value_type() == Expression::DateTimeLiteral {
self.value().map(|u| DateTimeLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_duration_literal(&self) -> Option<DurationLiteral<'a>> {
if self.value_type() == Expression::DurationLiteral {
self.value().map(|u| DurationLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_float_literal(&self) -> Option<FloatLiteral<'a>> {
if self.value_type() == Expression::FloatLiteral {
self.value().map(|u| FloatLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_integer_literal(&self) -> Option<IntegerLiteral<'a>> {
if self.value_type() == Expression::IntegerLiteral {
self.value().map(|u| IntegerLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_string_literal(&self) -> Option<StringLiteral<'a>> {
if self.value_type() == Expression::StringLiteral {
self.value().map(|u| StringLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_regexp_literal(&self) -> Option<RegexpLiteral<'a>> {
if self.value_type() == Expression::RegexpLiteral {
self.value().map(|u| RegexpLiteral::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn value_as_unsigned_integer_literal(&self) -> Option<UnsignedIntegerLiteral<'a>> {
if self.value_type() == Expression::UnsignedIntegerLiteral {
self.value()
.map(|u| UnsignedIntegerLiteral::init_from_table(u))
} else {
None
}
}
}
pub struct PropertyArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub key: Option<flatbuffers::WIPOffset<Identifier<'a>>>,
pub value_type: Expression,
pub value: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for PropertyArgs<'a> {
#[inline]
fn default() -> Self {
PropertyArgs {
loc: None,
key: None,
value_type: Expression::NONE,
value: None,
}
}
}
pub struct PropertyBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> PropertyBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(Property::VT_LOC, loc);
}
#[inline]
pub fn add_key(&mut self, key: flatbuffers::WIPOffset<Identifier<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<Identifier>>(Property::VT_KEY, key);
}
#[inline]
pub fn add_value_type(&mut self, value_type: Expression) {
self.fbb_.push_slot::<Expression>(
Property::VT_VALUE_TYPE,
value_type,
Expression::NONE,
);
}
#[inline]
pub fn add_value(&mut self, value: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Property::VT_VALUE, value);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> PropertyBuilder<'a, 'b> {
let start = _fbb.start_table();
PropertyBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Property<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum IdentifierExpressionOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct IdentifierExpression<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for IdentifierExpression<'a> {
type Inner = IdentifierExpression<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> IdentifierExpression<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
IdentifierExpression { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args IdentifierExpressionArgs<'args>,
) -> flatbuffers::WIPOffset<IdentifierExpression<'bldr>> {
let mut builder = IdentifierExpressionBuilder::new(_fbb);
if let Some(x) = args.typ {
builder.add_typ(x);
}
if let Some(x) = args.name {
builder.add_name(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_typ_type(args.typ_type);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_NAME: flatbuffers::VOffsetT = 6;
pub const VT_TYP_TYPE: flatbuffers::VOffsetT = 8;
pub const VT_TYP: flatbuffers::VOffsetT = 10;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
IdentifierExpression::VT_LOC,
None,
)
}
#[inline]
pub fn name(&self) -> Option<&'a str> {
self._tab
.get::<flatbuffers::ForwardsUOffset<&str>>(IdentifierExpression::VT_NAME, None)
}
#[inline]
pub fn typ_type(&self) -> MonoType {
self._tab
.get::<MonoType>(IdentifierExpression::VT_TYP_TYPE, Some(MonoType::NONE))
.unwrap()
}
#[inline]
pub fn typ(&self) -> Option<flatbuffers::Table<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(
IdentifierExpression::VT_TYP,
None,
)
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_basic(&self) -> Option<Basic<'a>> {
if self.typ_type() == MonoType::Basic {
self.typ().map(|u| Basic::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_var(&self) -> Option<Var<'a>> {
if self.typ_type() == MonoType::Var {
self.typ().map(|u| Var::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_arr(&self) -> Option<Arr<'a>> {
if self.typ_type() == MonoType::Arr {
self.typ().map(|u| Arr::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_row(&self) -> Option<Row<'a>> {
if self.typ_type() == MonoType::Row {
self.typ().map(|u| Row::init_from_table(u))
} else {
None
}
}
#[inline]
#[allow(non_snake_case)]
pub fn typ_as_fun(&self) -> Option<Fun<'a>> {
if self.typ_type() == MonoType::Fun {
self.typ().map(|u| Fun::init_from_table(u))
} else {
None
}
}
}
pub struct IdentifierExpressionArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub name: Option<flatbuffers::WIPOffset<&'a str>>,
pub typ_type: MonoType,
pub typ: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
}
impl<'a> Default for IdentifierExpressionArgs<'a> {
#[inline]
fn default() -> Self {
IdentifierExpressionArgs {
loc: None,
name: None,
typ_type: MonoType::NONE,
typ: None,
}
}
}
pub struct IdentifierExpressionBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> IdentifierExpressionBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
IdentifierExpression::VT_LOC,
loc,
);
}
#[inline]
pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(IdentifierExpression::VT_NAME, name);
}
#[inline]
pub fn add_typ_type(&mut self, typ_type: MonoType) {
self.fbb_.push_slot::<MonoType>(
IdentifierExpression::VT_TYP_TYPE,
typ_type,
MonoType::NONE,
);
}
#[inline]
pub fn add_typ(&mut self, typ: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(IdentifierExpression::VT_TYP, typ);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> IdentifierExpressionBuilder<'a, 'b> {
let start = _fbb.start_table();
IdentifierExpressionBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<IdentifierExpression<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum IdentifierOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Identifier<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Identifier<'a> {
type Inner = Identifier<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Identifier<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Identifier { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args IdentifierArgs<'args>,
) -> flatbuffers::WIPOffset<Identifier<'bldr>> {
let mut builder = IdentifierBuilder::new(_fbb);
if let Some(x) = args.name {
builder.add_name(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_NAME: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(Identifier::VT_LOC, None)
}
#[inline]
pub fn name(&self) -> Option<&'a str> {
self._tab
.get::<flatbuffers::ForwardsUOffset<&str>>(Identifier::VT_NAME, None)
}
}
pub struct IdentifierArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub name: Option<flatbuffers::WIPOffset<&'a str>>,
}
impl<'a> Default for IdentifierArgs<'a> {
#[inline]
fn default() -> Self {
IdentifierArgs {
loc: None,
name: None,
}
}
}
pub struct IdentifierBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> IdentifierBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
Identifier::VT_LOC,
loc,
);
}
#[inline]
pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(Identifier::VT_NAME, name);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> IdentifierBuilder<'a, 'b> {
let start = _fbb.start_table();
IdentifierBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Identifier<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum BooleanLiteralOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct BooleanLiteral<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for BooleanLiteral<'a> {
type Inner = BooleanLiteral<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> BooleanLiteral<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
BooleanLiteral { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args BooleanLiteralArgs<'args>,
) -> flatbuffers::WIPOffset<BooleanLiteral<'bldr>> {
let mut builder = BooleanLiteralBuilder::new(_fbb);
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.add_value(args.value);
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_VALUE: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
BooleanLiteral::VT_LOC,
None,
)
}
#[inline]
pub fn value(&self) -> bool {
self._tab
.get::<bool>(BooleanLiteral::VT_VALUE, Some(false))
.unwrap()
}
}
pub struct BooleanLiteralArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub value: bool,
}
impl<'a> Default for BooleanLiteralArgs<'a> {
#[inline]
fn default() -> Self {
BooleanLiteralArgs {
loc: None,
value: false,
}
}
}
pub struct BooleanLiteralBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> BooleanLiteralBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
BooleanLiteral::VT_LOC,
loc,
);
}
#[inline]
pub fn add_value(&mut self, value: bool) {
self.fbb_
.push_slot::<bool>(BooleanLiteral::VT_VALUE, value, false);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> BooleanLiteralBuilder<'a, 'b> {
let start = _fbb.start_table();
BooleanLiteralBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<BooleanLiteral<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum DateTimeLiteralOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct DateTimeLiteral<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for DateTimeLiteral<'a> {
type Inner = DateTimeLiteral<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> DateTimeLiteral<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
DateTimeLiteral { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args DateTimeLiteralArgs<'args>,
) -> flatbuffers::WIPOffset<DateTimeLiteral<'bldr>> {
let mut builder = DateTimeLiteralBuilder::new(_fbb);
if let Some(x) = args.value {
builder.add_value(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_VALUE: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
DateTimeLiteral::VT_LOC,
None,
)
}
#[inline]
pub fn value(&self) -> Option<Time<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<Time<'a>>>(DateTimeLiteral::VT_VALUE, None)
}
}
pub struct DateTimeLiteralArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub value: Option<flatbuffers::WIPOffset<Time<'a>>>,
}
impl<'a> Default for DateTimeLiteralArgs<'a> {
#[inline]
fn default() -> Self {
DateTimeLiteralArgs {
loc: None,
value: None,
}
}
}
pub struct DateTimeLiteralBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> DateTimeLiteralBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
DateTimeLiteral::VT_LOC,
loc,
);
}
#[inline]
pub fn add_value(&mut self, value: flatbuffers::WIPOffset<Time<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<Time>>(DateTimeLiteral::VT_VALUE, value);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> DateTimeLiteralBuilder<'a, 'b> {
let start = _fbb.start_table();
DateTimeLiteralBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<DateTimeLiteral<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum TimeOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Time<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Time<'a> {
type Inner = Time<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Time<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Time { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args TimeArgs,
) -> flatbuffers::WIPOffset<Time<'bldr>> {
let mut builder = TimeBuilder::new(_fbb);
builder.add_secs(args.secs);
builder.add_offset(args.offset);
builder.add_nsecs(args.nsecs);
builder.finish()
}
pub const VT_SECS: flatbuffers::VOffsetT = 4;
pub const VT_NSECS: flatbuffers::VOffsetT = 6;
pub const VT_OFFSET: flatbuffers::VOffsetT = 8;
#[inline]
pub fn secs(&self) -> i64 {
self._tab.get::<i64>(Time::VT_SECS, Some(0)).unwrap()
}
#[inline]
pub fn nsecs(&self) -> u32 {
self._tab.get::<u32>(Time::VT_NSECS, Some(0)).unwrap()
}
#[inline]
pub fn offset(&self) -> i32 {
self._tab.get::<i32>(Time::VT_OFFSET, Some(0)).unwrap()
}
}
pub struct TimeArgs {
pub secs: i64,
pub nsecs: u32,
pub offset: i32,
}
impl<'a> Default for TimeArgs {
#[inline]
fn default() -> Self {
TimeArgs {
secs: 0,
nsecs: 0,
offset: 0,
}
}
}
pub struct TimeBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> TimeBuilder<'a, 'b> {
#[inline]
pub fn add_secs(&mut self, secs: i64) {
self.fbb_.push_slot::<i64>(Time::VT_SECS, secs, 0);
}
#[inline]
pub fn add_nsecs(&mut self, nsecs: u32) {
self.fbb_.push_slot::<u32>(Time::VT_NSECS, nsecs, 0);
}
#[inline]
pub fn add_offset(&mut self, offset: i32) {
self.fbb_.push_slot::<i32>(Time::VT_OFFSET, offset, 0);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TimeBuilder<'a, 'b> {
let start = _fbb.start_table();
TimeBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Time<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum DurationOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Duration<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Duration<'a> {
type Inner = Duration<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Duration<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Duration { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args DurationArgs,
) -> flatbuffers::WIPOffset<Duration<'bldr>> {
let mut builder = DurationBuilder::new(_fbb);
builder.add_nanoseconds(args.nanoseconds);
builder.add_months(args.months);
builder.add_negative(args.negative);
builder.finish()
}
pub const VT_MONTHS: flatbuffers::VOffsetT = 4;
pub const VT_NANOSECONDS: flatbuffers::VOffsetT = 6;
pub const VT_NEGATIVE: flatbuffers::VOffsetT = 8;
#[inline]
pub fn months(&self) -> i64 {
self._tab.get::<i64>(Duration::VT_MONTHS, Some(0)).unwrap()
}
#[inline]
pub fn nanoseconds(&self) -> i64 {
self._tab
.get::<i64>(Duration::VT_NANOSECONDS, Some(0))
.unwrap()
}
#[inline]
pub fn negative(&self) -> bool {
self._tab
.get::<bool>(Duration::VT_NEGATIVE, Some(false))
.unwrap()
}
}
pub struct DurationArgs {
pub months: i64,
pub nanoseconds: i64,
pub negative: bool,
}
impl<'a> Default for DurationArgs {
#[inline]
fn default() -> Self {
DurationArgs {
months: 0,
nanoseconds: 0,
negative: false,
}
}
}
pub struct DurationBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> DurationBuilder<'a, 'b> {
#[inline]
pub fn add_months(&mut self, months: i64) {
self.fbb_.push_slot::<i64>(Duration::VT_MONTHS, months, 0);
}
#[inline]
pub fn add_nanoseconds(&mut self, nanoseconds: i64) {
self.fbb_
.push_slot::<i64>(Duration::VT_NANOSECONDS, nanoseconds, 0);
}
#[inline]
pub fn add_negative(&mut self, negative: bool) {
self.fbb_
.push_slot::<bool>(Duration::VT_NEGATIVE, negative, false);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> DurationBuilder<'a, 'b> {
let start = _fbb.start_table();
DurationBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Duration<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum DurationLiteralOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct DurationLiteral<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for DurationLiteral<'a> {
type Inner = DurationLiteral<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> DurationLiteral<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
DurationLiteral { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args DurationLiteralArgs<'args>,
) -> flatbuffers::WIPOffset<DurationLiteral<'bldr>> {
let mut builder = DurationLiteralBuilder::new(_fbb);
if let Some(x) = args.value {
builder.add_value(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_VALUE: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
DurationLiteral::VT_LOC,
None,
)
}
#[inline]
pub fn value(
&self,
) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Duration<'a>>>> {
self._tab.get::<flatbuffers::ForwardsUOffset<
flatbuffers::Vector<flatbuffers::ForwardsUOffset<Duration<'a>>>,
>>(DurationLiteral::VT_VALUE, None)
}
}
pub struct DurationLiteralArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub value: Option<
flatbuffers::WIPOffset<
flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Duration<'a>>>,
>,
>,
}
impl<'a> Default for DurationLiteralArgs<'a> {
#[inline]
fn default() -> Self {
DurationLiteralArgs {
loc: None,
value: None,
}
}
}
pub struct DurationLiteralBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> DurationLiteralBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
DurationLiteral::VT_LOC,
loc,
);
}
#[inline]
pub fn add_value(
&mut self,
value: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<Duration<'b>>>,
>,
) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(DurationLiteral::VT_VALUE, value);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> DurationLiteralBuilder<'a, 'b> {
let start = _fbb.start_table();
DurationLiteralBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<DurationLiteral<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum IntegerLiteralOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct IntegerLiteral<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for IntegerLiteral<'a> {
type Inner = IntegerLiteral<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> IntegerLiteral<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
IntegerLiteral { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args IntegerLiteralArgs<'args>,
) -> flatbuffers::WIPOffset<IntegerLiteral<'bldr>> {
let mut builder = IntegerLiteralBuilder::new(_fbb);
builder.add_value(args.value);
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_VALUE: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
IntegerLiteral::VT_LOC,
None,
)
}
#[inline]
pub fn value(&self) -> i64 {
self._tab
.get::<i64>(IntegerLiteral::VT_VALUE, Some(0))
.unwrap()
}
}
pub struct IntegerLiteralArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub value: i64,
}
impl<'a> Default for IntegerLiteralArgs<'a> {
#[inline]
fn default() -> Self {
IntegerLiteralArgs {
loc: None,
value: 0,
}
}
}
pub struct IntegerLiteralBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> IntegerLiteralBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
IntegerLiteral::VT_LOC,
loc,
);
}
#[inline]
pub fn add_value(&mut self, value: i64) {
self.fbb_
.push_slot::<i64>(IntegerLiteral::VT_VALUE, value, 0);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> IntegerLiteralBuilder<'a, 'b> {
let start = _fbb.start_table();
IntegerLiteralBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<IntegerLiteral<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum FloatLiteralOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct FloatLiteral<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for FloatLiteral<'a> {
type Inner = FloatLiteral<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> FloatLiteral<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
FloatLiteral { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args FloatLiteralArgs<'args>,
) -> flatbuffers::WIPOffset<FloatLiteral<'bldr>> {
let mut builder = FloatLiteralBuilder::new(_fbb);
builder.add_value(args.value);
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_VALUE: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(FloatLiteral::VT_LOC, None)
}
#[inline]
pub fn value(&self) -> f64 {
self._tab
.get::<f64>(FloatLiteral::VT_VALUE, Some(0.0))
.unwrap()
}
}
pub struct FloatLiteralArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub value: f64,
}
impl<'a> Default for FloatLiteralArgs<'a> {
#[inline]
fn default() -> Self {
FloatLiteralArgs {
loc: None,
value: 0.0,
}
}
}
pub struct FloatLiteralBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> FloatLiteralBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
FloatLiteral::VT_LOC,
loc,
);
}
#[inline]
pub fn add_value(&mut self, value: f64) {
self.fbb_
.push_slot::<f64>(FloatLiteral::VT_VALUE, value, 0.0);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> FloatLiteralBuilder<'a, 'b> {
let start = _fbb.start_table();
FloatLiteralBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<FloatLiteral<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum RegexpLiteralOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct RegexpLiteral<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for RegexpLiteral<'a> {
type Inner = RegexpLiteral<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> RegexpLiteral<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
RegexpLiteral { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args RegexpLiteralArgs<'args>,
) -> flatbuffers::WIPOffset<RegexpLiteral<'bldr>> {
let mut builder = RegexpLiteralBuilder::new(_fbb);
if let Some(x) = args.value {
builder.add_value(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_VALUE: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
RegexpLiteral::VT_LOC,
None,
)
}
#[inline]
pub fn value(&self) -> Option<&'a str> {
self._tab
.get::<flatbuffers::ForwardsUOffset<&str>>(RegexpLiteral::VT_VALUE, None)
}
}
pub struct RegexpLiteralArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub value: Option<flatbuffers::WIPOffset<&'a str>>,
}
impl<'a> Default for RegexpLiteralArgs<'a> {
#[inline]
fn default() -> Self {
RegexpLiteralArgs {
loc: None,
value: None,
}
}
}
pub struct RegexpLiteralBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> RegexpLiteralBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
RegexpLiteral::VT_LOC,
loc,
);
}
#[inline]
pub fn add_value(&mut self, value: flatbuffers::WIPOffset<&'b str>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(RegexpLiteral::VT_VALUE, value);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> RegexpLiteralBuilder<'a, 'b> {
let start = _fbb.start_table();
RegexpLiteralBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<RegexpLiteral<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum StringLiteralOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct StringLiteral<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for StringLiteral<'a> {
type Inner = StringLiteral<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> StringLiteral<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
StringLiteral { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args StringLiteralArgs<'args>,
) -> flatbuffers::WIPOffset<StringLiteral<'bldr>> {
let mut builder = StringLiteralBuilder::new(_fbb);
if let Some(x) = args.value {
builder.add_value(x);
}
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_VALUE: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
StringLiteral::VT_LOC,
None,
)
}
#[inline]
pub fn value(&self) -> Option<&'a str> {
self._tab
.get::<flatbuffers::ForwardsUOffset<&str>>(StringLiteral::VT_VALUE, None)
}
}
pub struct StringLiteralArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub value: Option<flatbuffers::WIPOffset<&'a str>>,
}
impl<'a> Default for StringLiteralArgs<'a> {
#[inline]
fn default() -> Self {
StringLiteralArgs {
loc: None,
value: None,
}
}
}
pub struct StringLiteralBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> StringLiteralBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
StringLiteral::VT_LOC,
loc,
);
}
#[inline]
pub fn add_value(&mut self, value: flatbuffers::WIPOffset<&'b str>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<_>>(StringLiteral::VT_VALUE, value);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> StringLiteralBuilder<'a, 'b> {
let start = _fbb.start_table();
StringLiteralBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<StringLiteral<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
pub enum UnsignedIntegerLiteralOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct UnsignedIntegerLiteral<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for UnsignedIntegerLiteral<'a> {
type Inner = UnsignedIntegerLiteral<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> UnsignedIntegerLiteral<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
UnsignedIntegerLiteral { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args UnsignedIntegerLiteralArgs<'args>,
) -> flatbuffers::WIPOffset<UnsignedIntegerLiteral<'bldr>> {
let mut builder = UnsignedIntegerLiteralBuilder::new(_fbb);
builder.add_value(args.value);
if let Some(x) = args.loc {
builder.add_loc(x);
}
builder.finish()
}
pub const VT_LOC: flatbuffers::VOffsetT = 4;
pub const VT_VALUE: flatbuffers::VOffsetT = 6;
#[inline]
pub fn loc(&self) -> Option<SourceLocation<'a>> {
self._tab
.get::<flatbuffers::ForwardsUOffset<SourceLocation<'a>>>(
UnsignedIntegerLiteral::VT_LOC,
None,
)
}
#[inline]
pub fn value(&self) -> u64 {
self._tab
.get::<u64>(UnsignedIntegerLiteral::VT_VALUE, Some(0))
.unwrap()
}
}
pub struct UnsignedIntegerLiteralArgs<'a> {
pub loc: Option<flatbuffers::WIPOffset<SourceLocation<'a>>>,
pub value: u64,
}
impl<'a> Default for UnsignedIntegerLiteralArgs<'a> {
#[inline]
fn default() -> Self {
UnsignedIntegerLiteralArgs {
loc: None,
value: 0,
}
}
}
pub struct UnsignedIntegerLiteralBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> UnsignedIntegerLiteralBuilder<'a, 'b> {
#[inline]
pub fn add_loc(&mut self, loc: flatbuffers::WIPOffset<SourceLocation<'b>>) {
self.fbb_
.push_slot_always::<flatbuffers::WIPOffset<SourceLocation>>(
UnsignedIntegerLiteral::VT_LOC,
loc,
);
}
#[inline]
pub fn add_value(&mut self, value: u64) {
self.fbb_
.push_slot::<u64>(UnsignedIntegerLiteral::VT_VALUE, value, 0);
}
#[inline]
pub fn new(
_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
) -> UnsignedIntegerLiteralBuilder<'a, 'b> {
let start = _fbb.start_table();
UnsignedIntegerLiteralBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<UnsignedIntegerLiteral<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
#[inline]
pub fn get_root_as_package<'a>(buf: &'a [u8]) -> Package<'a> {
flatbuffers::get_root::<Package<'a>>(buf)
}
#[inline]
pub fn get_size_prefixed_root_as_package<'a>(buf: &'a [u8]) -> Package<'a> {
flatbuffers::get_size_prefixed_root::<Package<'a>>(buf)
}
#[inline]
pub fn finish_package_buffer<'a, 'b>(
fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
root: flatbuffers::WIPOffset<Package<'a>>,
) {
fbb.finish(root, None);
}
#[inline]
pub fn finish_size_prefixed_package_buffer<'a, 'b>(
fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
root: flatbuffers::WIPOffset<Package<'a>>,
) {
fbb.finish_size_prefixed(root, None);
}
} // pub mod fbsemantic
| 33.864992 | 100 | 0.514894 |
db50750211c5e34d89ad6ada28d8edb1dc36e00c | 4,381 | use std::collections::hash_map::{Entry, HashMap};
use crate::{
ast::InputValue,
parser::{SourcePosition, Spanning},
validation::{ValidatorContext, Visitor},
value::ScalarValue,
};
pub struct UniqueInputFieldNames<'a> {
known_name_stack: Vec<HashMap<&'a str, SourcePosition>>,
}
pub fn factory<'a>() -> UniqueInputFieldNames<'a> {
UniqueInputFieldNames {
known_name_stack: Vec::new(),
}
}
impl<'a, S> Visitor<'a, S> for UniqueInputFieldNames<'a>
where
S: ScalarValue,
{
fn enter_object_value(&mut self, _: &mut ValidatorContext<'a, S>, _: SpannedObject<'a, S>) {
self.known_name_stack.push(HashMap::new());
}
fn exit_object_value(&mut self, _: &mut ValidatorContext<'a, S>, _: SpannedObject<'a, S>) {
self.known_name_stack.pop();
}
fn enter_object_field(
&mut self,
ctx: &mut ValidatorContext<'a, S>,
&(ref field_name, _): &'a (Spanning<String>, Spanning<InputValue<S>>),
) {
if let Some(ref mut known_names) = self.known_name_stack.last_mut() {
match known_names.entry(&field_name.item) {
Entry::Occupied(e) => {
ctx.report_error(
&error_message(&field_name.item),
&[*e.get(), field_name.start],
);
}
Entry::Vacant(e) => {
e.insert(field_name.start);
}
}
}
}
}
type SpannedObject<'a, S> = Spanning<&'a Vec<(Spanning<String>, Spanning<InputValue<S>>)>>;
fn error_message(field_name: &str) -> String {
format!("There can only be one input field named \"{}\"", field_name)
}
#[cfg(test)]
mod tests {
use super::{error_message, factory};
use crate::{
parser::SourcePosition,
validation::{expect_fails_rule, expect_passes_rule, RuleError},
value::DefaultScalarValue,
};
#[test]
fn input_object_with_fields() {
expect_passes_rule::<_, _, DefaultScalarValue>(
factory,
r#"
{
field(arg: { f: true })
}
"#,
);
}
#[test]
fn same_input_object_within_two_args() {
expect_passes_rule::<_, _, DefaultScalarValue>(
factory,
r#"
{
field(arg1: { f: true }, arg2: { f: true })
}
"#,
);
}
#[test]
fn multiple_input_object_fields() {
expect_passes_rule::<_, _, DefaultScalarValue>(
factory,
r#"
{
field(arg: { f1: "value", f2: "value", f3: "value" })
}
"#,
);
}
#[test]
fn allows_for_nested_input_objects_with_similar_fields() {
expect_passes_rule::<_, _, DefaultScalarValue>(
factory,
r#"
{
field(arg: {
deep: {
deep: {
id: 1
}
id: 1
}
id: 1
})
}
"#,
);
}
#[test]
fn duplicate_input_object_fields() {
expect_fails_rule::<_, _, DefaultScalarValue>(
factory,
r#"
{
field(arg: { f1: "value", f1: "value" })
}
"#,
&[RuleError::new(
&error_message("f1"),
&[
SourcePosition::new(38, 2, 25),
SourcePosition::new(51, 2, 38),
],
)],
);
}
#[test]
fn many_duplicate_input_object_fields() {
expect_fails_rule::<_, _, DefaultScalarValue>(
factory,
r#"
{
field(arg: { f1: "value", f1: "value", f1: "value" })
}
"#,
&[
RuleError::new(
&error_message("f1"),
&[
SourcePosition::new(38, 2, 25),
SourcePosition::new(51, 2, 38),
],
),
RuleError::new(
&error_message("f1"),
&[
SourcePosition::new(38, 2, 25),
SourcePosition::new(64, 2, 51),
],
),
],
);
}
}
| 25.47093 | 96 | 0.453093 |
e4427e590f8f7f59e527cbcf51cc3a3036247b7f | 29,362 | // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//! This module provides a TCP-based boundary.
use serde::{Deserialize, Serialize};
use timely::dataflow::operators::capture::EventCore;
use timely::logging::WorkerIdentifier;
use tokio_serde::formats::Bincode;
use tokio_util::codec::LengthDelimitedCodec;
use mz_dataflow_types::DataflowError;
use mz_dataflow_types::SourceInstanceId;
/// Type alias for a source subscription including a source worker.
pub type SubscriptionId = (SourceInstanceId, WorkerIdentifier);
pub mod server {
//! TCP boundary server
use crate::server::boundary::StorageCapture;
use crate::server::tcp_boundary::{length_delimited_codec, Command, Framed, Response};
use crate::tcp_boundary::SubscriptionId;
use differential_dataflow::Collection;
use futures::{SinkExt, TryStreamExt};
use std::any::Any;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::{Arc, Weak};
use timely::dataflow::operators::capture::{EventCore, EventPusherCore};
use timely::dataflow::operators::Capture;
use timely::dataflow::Scope;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::{TcpListener, TcpStream, ToSocketAddrs};
use tokio::select;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::sync::Mutex;
use tokio::task::JoinHandle;
use tokio_serde::formats::Bincode;
use tracing::{debug, info, warn};
use mz_dataflow_types::DataflowError;
use mz_dataflow_types::SourceInstanceRequest;
use mz_repr::{Diff, Row, Timestamp};
/// A framed connection from the server's perspective.
type FramedServer<C> = Framed<C, Command, Response>;
/// Constructs a framed connection for the server.
fn framed_server<C>(conn: C) -> FramedServer<C>
where
C: AsyncRead + AsyncWrite,
{
tokio_serde::Framed::new(
tokio_util::codec::Framed::new(conn, length_delimited_codec()),
Bincode::default(),
)
}
/// Unique client identifier, only used internally
type ClientId = u64;
/// Shared state between main server loop and client-specific task.
#[derive(Debug, Default)]
struct Shared {
subscriptions: HashMap<SubscriptionId, SourceState>,
channels: HashMap<ClientId, UnboundedSender<Response>>,
}
/// Shared per-subscription state
#[derive(Debug, Default)]
struct SourceState {
/// Pending responses stashed before client registered.
stash: Vec<Response>,
/// Client, once it registered
client_id: Option<ClientId>,
/// Tokens to drop to terminate source.
token: Option<Arc<()>>,
}
/// Response from Timely workers to network handler.
#[derive(Debug)]
enum WorkerResponse {
/// Announce the presence of a captured source.
Announce {
subscription_id: SubscriptionId,
token: Arc<()>,
},
/// Data from a source
Response(Response),
}
/// Alias for a commonly used type for sending source instantiation requests.
type SourceRequestSender = tokio::sync::mpsc::UnboundedSender<SourceInstanceRequest>;
/// Start the boundary server listening for connections on `addr`.
///
/// Returns a handle implementing [StorageCapture] and a join handle to await termination.
pub async fn serve<A: ToSocketAddrs + std::fmt::Display>(
addr: A,
) -> std::io::Result<(
TcpEventLinkHandle,
tokio::sync::mpsc::UnboundedReceiver<SourceInstanceRequest>,
JoinHandle<std::io::Result<()>>,
)> {
let (worker_tx, worker_rx) = unbounded_channel();
let (request_tx, request_rx) = tokio::sync::mpsc::unbounded_channel();
info!("About to bind to {addr}");
let listener = TcpListener::bind(addr).await?;
info!(
"listening for storage connection on {:?}...",
listener.local_addr()
);
let thread =
mz_ore::task::spawn(|| "storage server", accept(listener, worker_rx, request_tx));
Ok((TcpEventLinkHandle { worker_tx }, request_rx, thread))
}
/// Accept connections on `listener` and listening for data on `worker_rx`.
async fn accept(
listener: TcpListener,
mut worker_rx: UnboundedReceiver<WorkerResponse>,
render_requests: SourceRequestSender,
) -> std::io::Result<()> {
debug!("server listening {listener:?}");
let shared = Default::default();
let state = Arc::new(Mutex::new(shared));
loop {
select! {
_ = async {
let mut client_id = 0;
loop {
client_id += 1;
match listener.accept().await {
Ok((socket, addr)) => {
let render_requests = render_requests.clone();
debug!("Accepting client {client_id} on {addr}...");
let state = Arc::clone(&state);
mz_ore::task::spawn(|| "client loop", async move {
handle_compute(client_id, Arc::clone(&state), socket, render_requests.clone()).await
});
}
Err(e) => {
warn!("Failed to accept connection: {e}");
}
}
}
} => {}
worker_response = worker_rx.recv() => match worker_response {
Some(WorkerResponse::Announce{subscription_id, token}) => {
debug!("Subscription announced: {subscription_id:?}");
let mut state = state.lock().await;
let subscription = state.subscriptions.entry(subscription_id).or_default();
subscription.token = Some(token);
}
Some(WorkerResponse::Response(response)) => {
let mut state = state.lock().await;
if let Some(subscription) = state.subscriptions.get_mut(&response.subscription_id) {
if let Some(client_id) = subscription.client_id {
state.channels.get_mut(&client_id).unwrap().send(response).unwrap();
} else {
subscription.stash.push(response);
}
}
}
None => return Ok(()),
},
}
}
}
/// Handle the server side of a compute client connection in `socket`, identified by
/// `client_id`. `state` is a handle to the shared state.
///
/// This function calls into the inner part and upon client termination cleans up state.
async fn handle_compute(
client_id: ClientId,
state: Arc<Mutex<Shared>>,
socket: TcpStream,
render_requests: SourceRequestSender,
) -> std::io::Result<()> {
let mut source_ids = HashSet::new();
let result = handle_compute_inner(
client_id,
Arc::clone(&state),
socket,
&mut source_ids,
render_requests,
)
.await;
let mut state = state.lock().await;
for source_id in source_ids {
state.subscriptions.remove(&source_id);
}
state.channels.remove(&client_id);
result
}
/// Inner portion to handle a compute client.
async fn handle_compute_inner(
client_id: ClientId,
state: Arc<Mutex<Shared>>,
socket: TcpStream,
active_source_ids: &mut HashSet<SubscriptionId>,
render_requests: SourceRequestSender,
) -> std::io::Result<()> {
let mut connection = framed_server(socket);
let (client_tx, mut client_rx) = unbounded_channel();
state.lock().await.channels.insert(client_id, client_tx);
loop {
select! {
cmd = connection.try_next() => match cmd? {
Some(Command::Subscribe(subscription_id, request)) => {
debug!("Subscribe client {client_id} to {subscription_id:?}");
let _ = render_requests.send(request);
let new = active_source_ids.insert(subscription_id);
assert!(new, "Duplicate key: {subscription_id:?}");
let stashed = {
let mut state = state.lock().await;
let subscription = state.subscriptions.entry(subscription_id).or_default();
assert!(subscription.client_id.is_none());
subscription.client_id = Some(client_id);
std::mem::take(&mut subscription.stash)
};
for stashed in stashed {
connection.send(stashed).await?;
}
}
Some(Command::Unsubscribe(subscription_id)) => {
debug!("Unsubscribe client {client_id} from {subscription_id:?}");
let mut state = state.lock().await;
state.subscriptions.remove(&subscription_id);
let removed = active_source_ids.remove(&subscription_id);
assert!(removed, "Unknown key: {subscription_id:?}");
}
None => {
return Ok(());
}
},
response = client_rx.recv() => connection.send(response.expect("Channel closed before dropping source")).await?,
}
}
}
/// A handle to the boundary service. Implements [StorageCapture] to capture sources.
#[derive(Clone, Debug)]
pub struct TcpEventLinkHandle {
worker_tx: UnboundedSender<WorkerResponse>,
}
impl StorageCapture for TcpEventLinkHandle {
fn capture<G: Scope<Timestamp = Timestamp>>(
&mut self,
id: mz_expr::GlobalId,
ok: Collection<G, Row, Diff>,
err: Collection<G, DataflowError, Diff>,
token: Rc<dyn Any>,
_name: &str,
dataflow_id: uuid::Uuid,
) {
let subscription_id = ((dataflow_id, id), ok.inner.scope().index());
let client_token = Arc::new(());
// Announce that we're capturing data, with the source ID and a token. Once the token
// is dropped, we drop the `token` to terminate the source.
self.worker_tx
.send(WorkerResponse::Announce {
subscription_id,
token: Arc::clone(&client_token),
})
.unwrap();
ok.inner.capture_into(UnboundedEventPusher::new(
self.worker_tx.clone(),
Rc::clone(&token),
&client_token,
move |event| {
WorkerResponse::Response(Response {
subscription_id,
data: Ok(event),
})
},
));
err.inner.capture_into(UnboundedEventPusher::new(
self.worker_tx.clone(),
token,
&client_token,
move |event| {
WorkerResponse::Response(Response {
subscription_id,
data: Err(event),
})
},
));
}
}
/// Helper struct to capture data into a sender and drop tokens once dropped itself.
struct UnboundedEventPusher<R, F> {
/// The sender to pass all data to.
sender: UnboundedSender<R>,
/// A function to convert the input data into something the sender can transport.
convert: F,
/// A token that's dropped once `client_token` is dropped.
token: Option<Rc<dyn Any>>,
/// A weak reference to a token that e.g. the network layer can drop.
client_token: Weak<()>,
}
impl<R, F> UnboundedEventPusher<R, F> {
/// Construct a new pusher. It'll retain a weak reference to `client_token`.
fn new(
sender: UnboundedSender<R>,
token: Rc<dyn Any>,
client_token: &Arc<()>,
convert: F,
) -> Self {
Self {
sender,
client_token: Arc::downgrade(client_token),
convert,
token: Some(token),
}
}
}
impl<T, D, R, F: Fn(EventCore<T, D>) -> R> EventPusherCore<T, D> for UnboundedEventPusher<R, F> {
fn push(&mut self, event: EventCore<T, D>) {
if self.client_token.upgrade().is_none() {
self.token.take();
}
if self.token.is_some() {
match self.sender.send((self.convert)(event)) {
Err(_) => {
self.token.take();
}
_ => {}
}
}
}
}
}
pub mod client {
//! TCP boundary client
use crate::activator::{ActivatorTrait, ArcActivator};
use crate::replay::MzReplay;
use crate::server::boundary::ComputeReplay;
use crate::server::tcp_boundary::{length_delimited_codec, Command, Framed, Response};
use differential_dataflow::{AsCollection, Collection};
use futures::{Sink, SinkExt, TryStreamExt};
use std::any::Any;
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Duration;
use timely::dataflow::operators::capture::event::EventIteratorCore;
use timely::dataflow::operators::capture::EventCore;
use timely::dataflow::Scope;
use timely::logging::WorkerIdentifier;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::{TcpStream, ToSocketAddrs};
use tokio::select;
use tokio::sync::mpsc::error::TryRecvError;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::task::JoinHandle;
use tokio_serde::formats::Bincode;
use tracing::{debug, info, warn};
use mz_dataflow_types::{DataflowError, SourceInstanceId};
use mz_repr::{Diff, Row, Timestamp};
/// A framed connection from the client's perspective.
type FramedClient<C> = Framed<C, Response, Command>;
/// Constructs a framed connection for the client.
fn framed_client<C>(conn: C) -> FramedClient<C>
where
C: AsyncRead + AsyncWrite,
{
tokio_serde::Framed::new(
tokio_util::codec::Framed::new(conn, length_delimited_codec()),
Bincode::default(),
)
}
/// A handle to the storage client. Implements [ComputeReplay].
#[derive(Debug, Clone)]
pub struct TcpEventLinkClientHandle {
announce_tx: UnboundedSender<Announce>,
storage_workers: usize,
}
/// State per worker and source.
#[derive(Debug)]
struct WorkerState<T, D, A: ActivatorTrait> {
sender: UnboundedSender<EventCore<T, D>>,
activator: Option<A>,
}
impl<T, D, A: ActivatorTrait> WorkerState<T, D, A> {
/// Construct a new state object with the provided `sender` and no activator.
fn new(sender: UnboundedSender<EventCore<T, D>>) -> Self {
Self {
sender,
activator: None,
}
}
/// Register an `activator` to wake the Timely operator.
fn register(&mut self, activator: A) {
self.activator = Some(activator);
}
/// Send data at the channel and activate if the activator is set.
fn send_and_activate(&mut self, event: EventCore<T, D>) {
let res = self.sender.send(event);
if res.is_err() {
warn!("Receiver hung up");
}
if let Some(activator) = &mut self.activator {
activator.activate();
}
}
}
#[derive(Debug, Default)]
struct SubscriptionState<T, R> {
ok_state: HashMap<WorkerIdentifier, WorkerState<T, Vec<(Row, T, R)>, ArcActivator>>,
err_state:
HashMap<WorkerIdentifier, WorkerState<T, Vec<(DataflowError, T, R)>, ArcActivator>>,
}
#[derive(Debug)]
struct ClientState {
subscriptions:
HashMap<SourceInstanceId, SubscriptionState<mz_repr::Timestamp, mz_repr::Diff>>,
workers: usize,
}
impl ClientState {
fn new(workers: usize) -> Self {
Self {
workers,
subscriptions: Default::default(),
}
}
async fn handle_announce<C: Sink<Command, Error = std::io::Error> + Unpin>(
&mut self,
client: &mut C,
announce: Announce,
) -> std::io::Result<()> {
match announce {
Announce::Register {
source_id,
worker,
request,
storage_workers,
ok_tx,
ok_activator,
err_activator,
err_tx,
} => {
let state = self.subscriptions.entry(source_id).or_default();
state.ok_state.insert(worker, WorkerState::new(ok_tx));
state.err_state.insert(worker, WorkerState::new(err_tx));
let worker_state = state.ok_state.get_mut(&worker).unwrap();
worker_state.register(ok_activator);
let worker_state = state.err_state.get_mut(&worker).unwrap();
worker_state.register(err_activator);
// Send subscription command to server
debug!("Subscribing to {source_id:?}");
client
.send_all(&mut futures::stream::iter(storage_workers.into_iter().map(
|storage_worker| {
Ok(Command::Subscribe(
(source_id, storage_worker),
request.clone(),
))
},
)))
.await?;
}
Announce::Drop(source_id, worker, storage_workers) => {
// Announce to unsubscribe from the source.
if let Some(state) = self.subscriptions.get_mut(&source_id) {
state.ok_state.remove(&worker);
state.err_state.remove(&worker);
debug!("Unsubscribing from {source_id:?}");
client
.send_all(&mut futures::stream::iter(storage_workers.into_iter().map(
|storage_worker| {
Ok(Command::Unsubscribe((source_id, storage_worker)))
},
)))
.await?;
let cleanup = state.ok_state.is_empty();
if cleanup {
self.subscriptions.remove(&source_id);
}
}
}
}
Ok(())
}
async fn handle_response(
&mut self,
Response {
subscription_id,
data,
}: Response,
) {
if let Some(state) = self.subscriptions.get_mut(&subscription_id.0) {
let worker = subscription_id.1 % self.workers;
match data {
Ok(event) => {
// We might have dropped the local worker already but still receive data
if let Some(channel) = state.ok_state.get_mut(&worker) {
channel.send_and_activate(event);
}
}
Err(event) => {
// We might have dropped the local worker already but still receive data
if let Some(channel) = state.err_state.get_mut(&worker) {
channel.send_and_activate(event);
}
}
}
}
}
}
/// Connect to a storage boundary server. Returns a handle to replay sources and a join handle
/// to await termination.
pub async fn connect<A: ToSocketAddrs + std::fmt::Debug>(
addr: A,
workers: usize,
storage_workers: usize,
) -> std::io::Result<(TcpEventLinkClientHandle, JoinHandle<std::io::Result<()>>)> {
let (announce_tx, announce_rx) = unbounded_channel();
info!("About to connect to {addr:?}");
let stream = TcpStream::connect(addr).await?;
info!("Connected to storage server");
let thread = mz_ore::task::spawn(
|| "storage client",
run_client(stream, announce_rx, workers),
);
Ok((
TcpEventLinkClientHandle {
announce_tx,
storage_workers,
},
thread,
))
}
/// Communicate data and subscriptions on `stream`, receiving local replay notifications on
/// `announce_rx`. `workers` is the number of local Timely workers.
async fn run_client(
stream: TcpStream,
mut announce_rx: UnboundedReceiver<Announce>,
workers: usize,
) -> std::io::Result<()> {
debug!("client: connected to server");
let mut client = framed_client(stream);
let mut state = ClientState::new(workers);
loop {
select! {
response = client.try_next() => match response? {
Some(response) => state.handle_response(response).await,
None => break,
},
announce = announce_rx.recv() => match announce {
Some(announce) => state.handle_announce(&mut client, announce).await?,
None => break,
}
}
}
Ok(())
}
/// Announcement protocol from a Timely worker to the storage client.
#[derive(Debug)]
enum Announce {
/// Provide activators for the source
Register {
source_id: SourceInstanceId,
worker: WorkerIdentifier,
request: mz_dataflow_types::SourceInstanceRequest,
storage_workers: Vec<WorkerIdentifier>,
ok_activator: ArcActivator,
err_activator: ArcActivator,
ok_tx: UnboundedSender<EventCore<Timestamp, Vec<(Row, Timestamp, Diff)>>>,
err_tx: UnboundedSender<EventCore<Timestamp, Vec<(DataflowError, Timestamp, Diff)>>>,
},
/// Replayer dropped
Drop(SourceInstanceId, WorkerIdentifier, Vec<WorkerIdentifier>),
}
impl ComputeReplay for TcpEventLinkClientHandle {
fn replay<G: Scope<Timestamp = Timestamp>>(
&mut self,
scope: &mut G,
name: &str,
request: mz_dataflow_types::SourceInstanceRequest,
) -> (
Collection<G, Row, Diff>,
Collection<G, DataflowError, Diff>,
Rc<dyn Any>,
) {
let source_id = request.unique_id();
// Create a channel to receive worker/replay-specific data channels
let (ok_tx, ok_rx) = unbounded_channel();
let (err_tx, err_rx) = unbounded_channel();
let ok_activator = ArcActivator::new(format!("{name}-ok-activator"), 1);
let err_activator = ArcActivator::new(format!("{name}-err-activator"), 1);
let storage_workers = (0..self.storage_workers)
.into_iter()
.map(|x| scope.index() + x * scope.peers())
.filter(|x| *x < self.storage_workers)
.collect::<Vec<_>>();
// Register with the storage client
let register = Announce::Register {
source_id,
worker: scope.index(),
request,
storage_workers: storage_workers.clone(),
ok_tx,
err_tx,
ok_activator: ok_activator.clone(),
err_activator: err_activator.clone(),
};
self.announce_tx.send(register).unwrap();
// Construct activators and replay data
let mut ok_rx = Some(ok_rx);
let ok = storage_workers
.iter()
.map(|_| {
UnboundedEventPuller::new(ok_rx.take().unwrap_or_else(|| unbounded_channel().1))
})
.mz_replay(scope, &format!("{name}-ok"), Duration::MAX, ok_activator)
.as_collection();
let mut err_rx = Some(err_rx);
let err = storage_workers
.iter()
.map(|_| {
UnboundedEventPuller::new(
err_rx.take().unwrap_or_else(|| unbounded_channel().1),
)
})
.mz_replay(scope, &format!("{name}-err"), Duration::MAX, err_activator)
.as_collection();
// Construct token to unsubscribe from source
let token = Rc::new(DropReplay {
announce_tx: self.announce_tx.clone(),
message: Some(Announce::Drop(source_id, scope.index(), storage_workers)),
});
(ok, err, Rc::new(token))
}
}
/// Utility to send a message on drop.
struct DropReplay {
/// Channel where to send the message
announce_tx: UnboundedSender<Announce>,
/// Pre-defined message to send
message: Option<Announce>,
}
impl Drop for DropReplay {
fn drop(&mut self) {
if let Some(message) = self.message.take() {
// Igore errors on send as it indicates the client is no longer running
let _ = self.announce_tx.send(message);
}
}
}
/// Puller reading from a `receiver` channel.
struct UnboundedEventPuller<D> {
/// The receiver to read from.
receiver: UnboundedReceiver<D>,
/// Current element
element: Option<D>,
}
impl<D> UnboundedEventPuller<D> {
/// Construct a new puller reading from `receiver`.
fn new(receiver: UnboundedReceiver<D>) -> Self {
Self {
receiver,
element: None,
}
}
}
impl<T, D> EventIteratorCore<T, D> for UnboundedEventPuller<EventCore<T, D>> {
fn next(&mut self) -> Option<&EventCore<T, D>> {
match self.receiver.try_recv() {
Ok(element) => {
self.element = Some(element);
self.element.as_ref()
}
Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => {
self.element.take();
None
}
}
}
}
}
/// A command sent from the storage client to the storage server.
#[derive(Clone, Debug, Serialize, Deserialize)]
enum Command {
/// Subscribe the client to `source_id`.
Subscribe(SubscriptionId, mz_dataflow_types::SourceInstanceRequest),
/// Unsubscribe the client from `source_id`.
Unsubscribe(SubscriptionId),
}
/// Data provided to the storage client from the storage server upon successful registration.
///
/// Each message has a source_id to identify the subscription, a worker that produced the data,
/// and the data itself. When replaying, the mapping of storage worker to compute worker needs
/// (at least) to be static.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct Response {
subscription_id: SubscriptionId,
/// Contents of the Ok-collection
data: Result<
EventCore<mz_repr::Timestamp, Vec<(mz_repr::Row, mz_repr::Timestamp, mz_repr::Diff)>>,
EventCore<mz_repr::Timestamp, Vec<(DataflowError, mz_repr::Timestamp, mz_repr::Diff)>>,
>,
}
/// A framed connection to a storage server.
pub type Framed<C, T, U> =
tokio_serde::Framed<tokio_util::codec::Framed<C, LengthDelimitedCodec>, T, U, Bincode<T, U>>;
fn length_delimited_codec() -> LengthDelimitedCodec {
// NOTE(benesch): using an unlimited maximum frame length is problematic
// because Tokio never shrinks its buffer. Sending or receiving one large
// message of size N means the client will hold on to a buffer of size
// N forever. We should investigate alternative transport protocols that
// do not have this limitation.
let mut codec = LengthDelimitedCodec::new();
codec.set_max_frame_length(usize::MAX);
codec
}
| 38.083009 | 128 | 0.537395 |
1e2a3c8df3d5d40d8d3b8bc8193b2473b234680e | 23,479 | #[cfg(test)]
mod test {
#[cfg(feature = "dim2")]
use na;
#[cfg(feature = "dim2")]
use na::{Vector1, Vector2, Isometry2};
#[cfg(feature = "dim2")]
use ncollide::shape::Cuboid;
#[cfg(feature = "dim2")]
use object::{ActivationState, RigidBody};
#[cfg(feature = "dim2")]
use world::World;
/// Gravity tests
#[cfg(feature = "dim2")]
#[test]
fn gravity2() {
// world
#[cfg(not(target_arch = "wasm32"))] let mut world = World::new(); #[cfg(target_arch = "wasm32")] let mut world = World::new(|| 0.0);
// rigidbody with side length 2, area 4 and mass 4
let geom = Cuboid::new(Vector2::new(1.0, 1.0));
let rb = RigidBody::new_dynamic(geom, 1.0, 0.3, 0.6);
let rb_handle = world.add_rigid_body(rb.clone());
// ensure it's at the origin
let expected = &Isometry2::new(na::zero(), na::zero());
assert!(na::approx_eq(rb_handle.borrow().position(), expected),
format!("Initial position should be at zero. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// set gravity
let gravity = Vector2::new(0.0, 20.0);
world.set_gravity(gravity);
// remove body and trigger a rust panic
// world.remove_body(&rb_handle2);
// add another body in same position triggers a panic in ncollide
// let mut rb3 = rb.clone();
// rb3.append_translation(&Vector2::new(0.0, 0.0));
// let rb_handle3 = world.add_body(rb3);
// simulate a huge time step
// The result is physically not correct as the acceleration integration
// happens at the beginning of the step and then the body moves with the
// terminal velocity for the entire time duration. Therefore it moves farther
// than it actually should. Use smaller time intervals to approximate more
// realistic values (see below).
let expected = &Isometry2::new(Vector2::new(0.0, 20.0), na::zero());
world.step(1.0);
assert!(na::approx_eq(rb_handle.borrow().position(), expected),
format!("Gravity did not pull object correctly (large time step). Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// reset the body
rb_handle.borrow_mut().set_lin_vel(Vector2::new(0.0, 0.0));
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
// simulate small time steps
let expected = &Isometry2::new(Vector2::new(0.0, 10.01), na::zero());
for _ in 0 .. 1000 {
world.step(0.001);
}
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Gravity did not pull object correctly (small time steps). Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// reset the body
rb_handle.borrow_mut().set_lin_vel(Vector2::new(0.0, 20.0));
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
// Switch off gravity globally
let expected = &Isometry2::new(Vector2::new(0.0, 20.0), na::zero());
world.set_gravity(na::zero());
for _ in 0 .. 1000 {
world.step(0.001);
}
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.001),
format!("Gravity did not correctly switch off (global). Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// reset the body
rb_handle.borrow_mut().set_lin_vel(Vector2::new(0.0, 0.0));
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
// Wait until body deactivates
for _ in 0 .. 1000 {
world.step(0.001);
}
assert!(*rb_handle.borrow().activation_state() == ActivationState::Inactive,
format!("Body should be inactive by now, but is {:?}", rb_handle.borrow().activation_state()));
rb_handle.borrow_mut().activate(1.0);
assert!(*rb_handle.borrow().activation_state() != ActivationState::Inactive,
format!("Body should be active by now, but is {:?}", rb_handle.borrow().activation_state()));
// Changing gravity has to work
let expected = &Isometry2::new(Vector2::new(0.0, 10.0), na::zero());
world.set_gravity(Vector2::new(0.0, 20.0));
for _ in 0 .. 1000 {
world.step(0.001);
}
world.set_gravity(Vector2::new(0.0, -20.0));
for _ in 0 .. 2000 {
world.step(0.001);
}
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.02),
format!("Gravity did not change correctly. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
}
/// Forces tests
#[cfg(feature = "dim2")]
#[test]
fn forces2() {
// world
#[cfg(not(target_arch = "wasm32"))] let mut world = World::new(); #[cfg(target_arch = "wasm32")] let mut world = World::new(|| 0.0);
// rigidbody with side length 2, area 4 and mass 4
let geom = Cuboid::new(Vector2::new(1.0, 1.0));
let rb = RigidBody::new_dynamic(geom.clone(), 1.0, 0.3, 0.6);
let rb_handle = world.add_rigid_body(rb.clone());
// add another body with double the density
let mut rb2 = RigidBody::new_dynamic(geom.clone(), 2.0, 0.3, 0.6);
rb2.append_translation(&Vector2::new(5.0, 0.0));
let rb_handle2 = world.add_rigid_body(rb2);
// switch off gravity
world.set_gravity(Vector2::new(0.0, 0.0));
// Force has to work for different masses
// apply force
rb_handle.borrow_mut().append_lin_force(Vector2::new(0.0, 10.0));
rb_handle2.borrow_mut().append_lin_force(Vector2::new(0.0, 10.0));
rb_handle.borrow_mut().set_deactivation_threshold(None);
rb_handle2.borrow_mut().set_deactivation_threshold(None);
// simulate
for _ in 0 .. 2000 {
world.step(0.001);
}
// mass of 4 (kg), force of 10 (N) => acc = force/mass = 2.5 (m/s^2)
// distance after 2 secs: x = 1/2 * acc * t^2 = 5 (m)
let expected = &Isometry2::new(Vector2::new(0.0, 5.0), na::zero());
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Force did not properly pull first body. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// mass of 8 (kg), force of 10 (N)=> acc = force/mass = 1.25 (m/s^2)
// distance after 2 secs: x = 1/2 * acc * t^2 = 2.5 (m)
let expected = &Isometry2::new(Vector2::new(5.0, 2.5), na::zero());
assert!(na::approx_eq_eps(rb_handle2.borrow().position(), expected, &0.01),
format!("Force did not properly pull second body. Actual: {:?}, Expected: {:?}",
rb_handle2.borrow().position(), expected));
// reset bodies
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
rb_handle.borrow_mut().set_lin_vel(Vector2::new(0.0, 0.0));
rb_handle2.borrow_mut().deactivate();
// clearing forces has to work
rb_handle.borrow_mut().clear_linear_force();
// simulate
for _ in 0 .. 1000 {
world.step(0.001);
}
let expected = &Isometry2::new(Vector2::new(0.0, 0.0), na::zero());
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Force should have been cleared. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// adding forces has to work
rb_handle.borrow_mut().append_lin_force(Vector2::new(0.0, 5.0));
rb_handle.borrow_mut().append_lin_force(Vector2::new(-10.0, 5.0));
// simulate
for _ in 0 .. 2000 {
world.step(0.001);
}
let expected = &Isometry2::new(Vector2::new(-5.0, 5.0), na::zero());
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Forces did not properly add up. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// angular force has to work correctly for different inertias and types
// reset bodies
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
rb_handle.borrow_mut().set_lin_vel(Vector2::new(0.0, 0.0));
rb_handle.borrow_mut().clear_forces();
rb_handle2.borrow_mut().set_transformation(Isometry2::new(Vector2::new(5.0, 0.0), na::zero()));
rb_handle2.borrow_mut().set_lin_vel(Vector2::new(0.0, 0.0));
rb_handle2.borrow_mut().activate(1.0);
rb_handle2.borrow_mut().clear_forces();
// add angular forces
rb_handle.borrow_mut().append_ang_force(Vector1::new(10.0));
rb_handle2.borrow_mut().append_ang_force(Vector1::new(10.0));
// simulate
for _ in 0 .. 1000 {
world.step(0.001);
}
// expected angle
// force of force of 10 (N), inertia of 2.67 => acc = force/inertia = 3.75 rad/s^2
// 1 sec acceleration => angle = 1/2 * acc * t^2 = 1.875
let expected = &Isometry2::new(na::zero(), Vector1::new(1.875));
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Rotation did not properly work. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// expected angle
// force of force of 10 (N), inertia of 5.33 => acc = force/inertia = 1.875 rad/s^2
// 1 sec acceleration => angle = 1/2 * acc * t^2 = 0.9375
let expected = &Isometry2::new(Vector2::new(5.0, 0.0), Vector1::new(0.9375));
assert!(na::approx_eq_eps(rb_handle2.borrow().position(), expected, &0.01),
format!("Rotation2 did not properly work. Actual: {:?}, Expected: {:?}",
rb_handle2.borrow().position(), expected));
// clear angular forces
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
rb_handle.borrow_mut().set_ang_vel(Vector1::new(0.0));
rb_handle2.borrow_mut().set_transformation(Isometry2::new(Vector2::new(5.0, 0.0), na::zero()));
rb_handle2.borrow_mut().set_ang_vel(Vector1::new(0.0));
rb_handle.borrow_mut().clear_angular_force();
rb_handle2.borrow_mut().clear_angular_force();
// simulate
for _ in 0 .. 1000 {
world.step(0.001);
}
// expected angle
let expected = &Isometry2::new(na::zero(), Vector1::new(0.0));
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Rotation did not properly stop. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// expected angle
let expected = &Isometry2::new(Vector2::new(5.0, 0.0), Vector1::new(0.0));
assert!(na::approx_eq_eps(rb_handle2.borrow().position(), expected, &0.01),
format!("Rotation2 did not properly stop. Actual: {:?}, Expected: {:?}",
rb_handle2.borrow().position(), expected));
// reset bodies
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
rb_handle.borrow_mut().set_ang_vel(Vector1::new(0.0));
rb_handle.borrow_mut().clear_angular_force();
rb_handle2.borrow_mut().deactivate();
// add angular forces
rb_handle.borrow_mut().append_ang_force(Vector1::new(10.0));
rb_handle.borrow_mut().append_ang_force(Vector1::new(-20.0));
// simulate
for _ in 0 .. 1000 {
world.step(0.001);
}
// expected angle
// resulting force of force of -10 (N), inertia of 2.67 => acc = force/inertia = -3.75 rad/s^2
// 1 sec acceleration => angle = 1/2 * acc * t^2 = -1.875
let expected = &Isometry2::new(na::zero(), Vector1::new(-1.875));
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Combined forces rotation did not properly work. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// reset bodies
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
rb_handle.borrow_mut().set_ang_vel(Vector1::new(0.0));
rb_handle.borrow_mut().clear_angular_force();
// set and clear both linear and angular forces
rb_handle.borrow_mut().append_lin_force(Vector2::new(0.0, 10.0));
rb_handle.borrow_mut().append_ang_force(Vector1::new(10.0));
rb_handle.borrow_mut().clear_forces();
// simulate
for _ in 0 .. 1000 {
world.step(0.001);
}
// expected result, body remains in the origin as all forces got cleared
let expected = &Isometry2::new(na::zero(), na::zero());
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Cleared forces shouldn't work anymore. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// reset bodies
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
rb_handle.borrow_mut().set_ang_vel(Vector1::new(0.0));
rb_handle.borrow_mut().clear_angular_force();
// only clear angular force
rb_handle.borrow_mut().append_lin_force(Vector2::new(0.0, 10.0));
rb_handle.borrow_mut().append_ang_force(Vector1::new(10.0));
rb_handle.borrow_mut().clear_angular_force();
// simulate
for _ in 0 .. 2000 {
world.step(0.001);
}
// expected result, body moves but doesn't rotate
let expected = &Isometry2::new(Vector2::new(0.0, 5.0), na::zero());
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Only linear movement is expected. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// reset bodies
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
rb_handle.borrow_mut().set_lin_vel(na::zero());
rb_handle.borrow_mut().set_ang_vel(na::zero());
rb_handle.borrow_mut().clear_forces();
// only clear linear force
rb_handle.borrow_mut().append_lin_force(Vector2::new(0.0, 10.0));
rb_handle.borrow_mut().append_ang_force(Vector1::new(10.0));
rb_handle.borrow_mut().clear_linear_force();
// simulate
for _ in 0 .. 1000 {
world.step(0.001);
}
// expected result, body rotates but doesn't move
let expected = &Isometry2::new(na::zero(), Vector1::new(1.875));
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Only rotation is expected. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// reset bodies
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
rb_handle.borrow_mut().set_lin_vel(na::zero());
rb_handle.borrow_mut().set_ang_vel(na::zero());
rb_handle.borrow_mut().clear_forces();
rb_handle.borrow_mut().activate(1.0);
rb_handle2.borrow_mut().set_transformation(Isometry2::new(Vector2::new(5.0, 0.0), na::zero()));
rb_handle2.borrow_mut().set_lin_vel(na::zero());
rb_handle2.borrow_mut().set_ang_vel(na::zero());
rb_handle2.borrow_mut().clear_forces();
rb_handle2.borrow_mut().activate(1.0);
// apply force on point
rb_handle.borrow_mut().append_force_wrt_point(Vector2::new(0.0, 10.0), Vector2::new(1.0, 1.0));
rb_handle2.borrow_mut().append_force_wrt_point(Vector2::new(0.0, 10.0), Vector2::new(1.0, 1.0));
// simulate
for _ in 0 .. 1000 {
world.step(0.001);
}
// expected result
// linear displacement 1.25
// angular rotation: -1.875
let expected = &Isometry2::new(Vector2::new(0.0, 1.25), Vector1::new(1.875));
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Only rotation is expected on body 1. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// expected result
// linear displacement 1.25
// angular rotation: -1.875
let expected = &Isometry2::new(Vector2::new(5.0, 0.625), Vector1::new(0.9375));
assert!(na::approx_eq_eps(rb_handle2.borrow().position(), expected, &0.01),
format!("Only rotation is expected on body 2. Actual: {:?}, Expected: {:?}",
rb_handle2.borrow().position(), expected));
}
/// Impulse tests
#[cfg(feature = "dim2")]
#[test]
fn impulse2() {
// world
#[cfg(not(target_arch = "wasm32"))] let mut world = World::new(); #[cfg(target_arch = "wasm32")] let mut world = World::new(|| 0.0);
// rigidbody with side length 2, area 4 and mass 4
let geom = Cuboid::new(Vector2::new(1.0, 1.0));
let rb = RigidBody::new_dynamic(geom.clone(), 1.0, 0.3, 0.6);
let rb_handle = world.add_rigid_body(rb.clone());
// add another body with double the density
let mut rb2 = RigidBody::new_dynamic(geom.clone(), 2.0, 0.3, 0.6);
rb2.append_translation(&Vector2::new(5.0, 0.0));
let rb_handle2 = world.add_rigid_body(rb2);
// switch off gravity
world.set_gravity(Vector2::new(0.0, 0.0));
// impulses have to work for different masses
rb_handle.borrow_mut().apply_central_impulse(Vector2::new(0.0, 10.0));
rb_handle2.borrow_mut().apply_central_impulse(Vector2::new(0.0, 10.0));
// simulate
for _ in 0 .. 1000 {
world.step(0.001);
}
// expected result
// impulse of 10 N*s on body with mass 4 (kg) results in
// velocity = impulse/mass = 10 N*s / 4 kg = 2.5 m/s
// distance = velocity * time = 2.5 m/s * 1 s = 2.5 m
let expected = &Isometry2::new(Vector2::new(0.0, 2.5), na::zero());
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Different impulse result is expected on body 1. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// expected result
// impulse of 10 N*s on body with mass 8 (kg) results in
// velocity = impulse/mass = 10 N*s / 8 kg = 1.25 m/s
// distance = velocity * time = 1.25 m/s * 1 s = 1.25 m
let expected = &Isometry2::new(Vector2::new(5.0, 1.25), na::zero());
assert!(na::approx_eq_eps(rb_handle2.borrow().position(), expected, &0.01),
format!("Different impulse result is expected on body 2. Actual: {:?}, Expected: {:?}",
rb_handle2.borrow().position(), expected));
// reset bodies
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
rb_handle.borrow_mut().set_lin_vel(na::zero());
rb_handle.borrow_mut().set_ang_vel(na::zero());
rb_handle.borrow_mut().clear_forces();
rb_handle.borrow_mut().activate(1.0);
rb_handle2.borrow_mut().set_transformation(Isometry2::new(Vector2::new(5.0, 0.0), na::zero()));
rb_handle2.borrow_mut().set_lin_vel(na::zero());
rb_handle2.borrow_mut().set_ang_vel(na::zero());
rb_handle2.borrow_mut().clear_forces();
rb_handle2.borrow_mut().activate(1.0);
// torques have to work for different inertias
rb_handle.borrow_mut().apply_angular_momentum(Vector1::new(10.0));
rb_handle2.borrow_mut().apply_angular_momentum(Vector1::new(10.0));
// simulate
for _ in 0 .. 1000 {
world.step(0.001);
}
// expected result
// torque of 10 N*m*s on body with inertia of 2.67 kg*m^2 results in
// rotation speed of rvel = 10 N*m*s / 2.67 kg*m^2 = 3.75 1/s
// angle after 1s: 3.75
let expected = &Isometry2::new(Vector2::new(0.0, 0.0), Vector1::new(3.75));
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Different torque result is expected on body 1. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// expected result
// torque of 10 N*m*s on body with inertia of 5.33 kg*m^2 results in
// rotation speed of rvel = 10 N*m*s / 5.33 kg*m^2 = 1.875 1/s
// angle after 1s: 1.875
let expected = &Isometry2::new(Vector2::new(5.0, 0.0), Vector1::new(1.875));
assert!(na::approx_eq_eps(rb_handle2.borrow().position(), expected, &0.01),
format!("Different torque result is expected on body 2. Actual: {:?}, Expected: {:?}",
rb_handle2.borrow().position(), expected));
// reset bodies
rb_handle.borrow_mut().set_transformation(Isometry2::new(na::zero(), na::zero()));
rb_handle.borrow_mut().set_lin_vel(na::zero());
rb_handle.borrow_mut().set_ang_vel(na::zero());
rb_handle.borrow_mut().clear_forces();
rb_handle.borrow_mut().activate(1.0);
rb_handle2.borrow_mut().set_transformation(Isometry2::new(Vector2::new(5.0, 0.0), na::zero()));
rb_handle2.borrow_mut().set_lin_vel(na::zero());
rb_handle2.borrow_mut().set_ang_vel(na::zero());
rb_handle2.borrow_mut().clear_forces();
rb_handle2.borrow_mut().activate(1.0);
// nudge
rb_handle.borrow_mut().apply_impulse_wrt_point(Vector2::new(0.0, 10.0), Vector2::new(1.0, 1.0));
rb_handle2.borrow_mut().apply_impulse_wrt_point(Vector2::new(0.0, 10.0), Vector2::new(1.0, 1.0));
// simulate
for _ in 0 .. 1000 {
world.step(0.001);
}
// expected values are the combination of the values in the two previous tests,
// except with opposite rotation direction
let expected = &Isometry2::new(Vector2::new(0.0, 2.5), Vector1::new(3.75));
assert!(na::approx_eq_eps(rb_handle.borrow().position(), expected, &0.01),
format!("Different torque result is expected on body 1. Actual: {:?}, Expected: {:?}",
rb_handle.borrow().position(), expected));
// expected values are the combination of the values in the two previous tests,
// except with opposite rotation direction
let expected = &Isometry2::new(Vector2::new(5.0, 1.25), Vector1::new(1.875));
assert!(na::approx_eq_eps(rb_handle2.borrow().position(), expected, &0.01),
format!("Different torque result is expected on body 2. Actual: {:?}, Expected: {:?}",
rb_handle2.borrow().position(), expected));
}
}
| 47.432323 | 152 | 0.583159 |
22a06b9f605dbdc66f5b70bdfb2fd84b5b079141 | 7,867 | // Copyright 2012-2017 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.
use super::*;
pub(crate) struct TerseFormatter<T> {
out: OutputLocation<T>,
use_color: bool,
is_multithreaded: bool,
/// Number of columns to fill when aligning names
max_name_len: usize,
test_count: usize,
}
impl<T: Write> TerseFormatter<T> {
pub fn new(
out: OutputLocation<T>,
use_color: bool,
max_name_len: usize,
is_multithreaded: bool,
) -> Self {
TerseFormatter {
out,
use_color,
max_name_len,
is_multithreaded,
test_count: 0,
}
}
pub fn write_ok(&mut self) -> io::Result<()> {
self.write_short_result(".", term::color::GREEN)
}
pub fn write_failed(&mut self) -> io::Result<()> {
self.write_short_result("F", term::color::RED)
}
pub fn write_ignored(&mut self) -> io::Result<()> {
self.write_short_result("i", term::color::YELLOW)
}
pub fn write_allowed_fail(&mut self) -> io::Result<()> {
self.write_short_result("a", term::color::YELLOW)
}
pub fn write_bench(&mut self) -> io::Result<()> {
self.write_pretty("bench", term::color::CYAN)
}
pub fn write_short_result(
&mut self,
result: &str,
color: term::color::Color,
) -> io::Result<()> {
self.write_pretty(result, color)?;
if self.test_count % QUIET_MODE_MAX_COLUMN == QUIET_MODE_MAX_COLUMN - 1 {
// we insert a new line every 100 dots in order to flush the
// screen when dealing with line-buffered output (e.g. piping to
// `stamp` in the rust CI).
self.write_plain("\n")?;
}
self.test_count += 1;
Ok(())
}
pub fn write_pretty(&mut self, word: &str, color: term::color::Color) -> io::Result<()> {
match self.out {
Pretty(ref mut term) => {
if self.use_color {
term.fg(color)?;
}
term.write_all(word.as_bytes())?;
if self.use_color {
term.reset()?;
}
term.flush()
}
Raw(ref mut stdout) => {
stdout.write_all(word.as_bytes())?;
stdout.flush()
}
}
}
pub fn write_plain<S: AsRef<str>>(&mut self, s: S) -> io::Result<()> {
let s = s.as_ref();
self.out.write_all(s.as_bytes())?;
self.out.flush()
}
pub fn write_outputs(&mut self, state: &ConsoleTestState) -> io::Result<()> {
self.write_plain("\nsuccesses:\n")?;
let mut successes = Vec::new();
let mut stdouts = String::new();
for &(ref f, ref stdout) in &state.not_failures {
successes.push(f.name.to_string());
if !stdout.is_empty() {
stdouts.push_str(&format!("---- {} stdout ----\n", f.name));
let output = String::from_utf8_lossy(stdout);
stdouts.push_str(&output);
stdouts.push_str("\n");
}
}
if !stdouts.is_empty() {
self.write_plain("\n")?;
self.write_plain(&stdouts)?;
}
self.write_plain("\nsuccesses:\n")?;
successes.sort();
for name in &successes {
self.write_plain(&format!(" {}\n", name))?;
}
Ok(())
}
pub fn write_failures(&mut self, state: &ConsoleTestState) -> io::Result<()> {
self.write_plain("\nfailures:\n")?;
let mut failures = Vec::new();
let mut fail_out = String::new();
for &(ref f, ref stdout) in &state.failures {
failures.push(f.name.to_string());
if !stdout.is_empty() {
fail_out.push_str(&format!("---- {} stdout ----\n", f.name));
let output = String::from_utf8_lossy(stdout);
fail_out.push_str(&output);
fail_out.push_str("\n");
}
}
if !fail_out.is_empty() {
self.write_plain("\n")?;
self.write_plain(&fail_out)?;
}
self.write_plain("\nfailures:\n")?;
failures.sort();
for name in &failures {
self.write_plain(&format!(" {}\n", name))?;
}
Ok(())
}
fn write_test_name(&mut self, desc: &TestDesc) -> io::Result<()> {
let name = desc.padded_name(self.max_name_len, desc.name.padding());
self.write_plain(&format!("test {} ... ", name))?;
Ok(())
}
}
impl<T: Write> OutputFormatter for TerseFormatter<T> {
fn write_run_start(&mut self, test_count: usize) -> io::Result<()> {
let noun = if test_count != 1 { "tests" } else { "test" };
self.write_plain(&format!("\nrunning {} {}\n", test_count, noun))
}
fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> {
// Remnants from old libtest code that used the padding value
// in order to indicate benchmarks.
// When running benchmarks, terse-mode should still print their name as if
// it is the Pretty formatter.
if !self.is_multithreaded && desc.name.padding() == PadOnRight {
self.write_test_name(desc)?;
}
Ok(())
}
fn write_result(&mut self, desc: &TestDesc, result: &TestResult, _: &[u8]) -> io::Result<()> {
match *result {
TrOk => self.write_ok(),
TrFailed | TrFailedMsg(_) => self.write_failed(),
TrIgnored => self.write_ignored(),
TrAllowedFail => self.write_allowed_fail(),
TrBench(ref bs) => {
if self.is_multithreaded {
self.write_test_name(desc)?;
}
self.write_bench()?;
self.write_plain(&format!(": {}\n", fmt_bench_samples(bs)))
}
}
}
fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()> {
self.write_plain(&format!(
"test {} has been running for over {} seconds\n",
desc.name, TEST_WARN_TIMEOUT_S
))
}
fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool> {
if state.options.display_output {
self.write_outputs(state)?;
}
let success = state.failed == 0;
if !success {
self.write_failures(state)?;
}
self.write_plain("\ntest result: ")?;
if success {
// There's no parallelism at this point so it's safe to use color
self.write_pretty("ok", term::color::GREEN)?;
} else {
self.write_pretty("FAILED", term::color::RED)?;
}
let s = if state.allowed_fail > 0 {
format!(
". {} passed; {} failed ({} allowed); {} ignored; {} measured; {} filtered out\n\n",
state.passed,
state.failed + state.allowed_fail,
state.allowed_fail,
state.ignored,
state.measured,
state.filtered_out
)
} else {
format!(
". {} passed; {} failed; {} ignored; {} measured; {} filtered out\n\n",
state.passed, state.failed, state.ignored, state.measured, state.filtered_out
)
};
self.write_plain(&s)?;
Ok(success)
}
}
| 32.508264 | 100 | 0.526376 |
693293facd4d51aa14c8a219764632bae589fd56 | 1,272 | // IO error is used here just as an example of an already existing
// Error
use std::io::{Error, ErrorKind};
// Rust technically doesn't have exception, but different
// types of error handling. Here are two examples of results.
pub fn valid_function() -> Result<usize, Error> {
Ok(100)
}
pub fn errored_function() -> Result<usize, Error> {
Err(Error::new(ErrorKind::Other, "Something wrong happened."))
}
// This should happen only when an unrecoverable error happened
pub fn panicking_function() {
panic!("Unrecoverable state reached");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_function() {
let result = match valid_function() {
Ok(number) => number,
Err(_) => panic!("This is not going to happen"),
};
assert_eq!(result, 100);
}
#[test]
fn test_errored_function() {
let result = match errored_function() {
Ok(_) => panic!("This is not going to happen"),
Err(e) => {
assert_eq!(e.to_string(), "Something wrong happened.");
0
}
};
assert_eq!(result, 0);
}
#[test]
#[should_panic]
fn test_panicking_function() {
panicking_function();
}
}
| 24.461538 | 71 | 0.587264 |
1deabc3f3fdbe6046fa81a0ddda5d4f4a64f2690 | 3,411 | //bring code from other libraries in scope of this file
extern crate clap;
use ansi_term::Colour::{Green, Red};
use ansi_term::Style;
use clap::{App, Arg};
use date_diff_lib;
///The starting point of the application
fn main() {
//this function is different for Windows and for Linux.
//Look at the code of this function (2 variations).
enable_ansi_support();
//define the CLI input line parameters using the clap library
let matches = App::new("bestia_date_diff")
.version("1.0")
.author("Bestia")
.about("date diff in days")
.arg(
Arg::with_name("first_date")
.value_name("first_date")
.help("first date for date diff"),
)
.arg(
Arg::with_name("second_date")
.value_name("second_date")
.help("second date for date diff"),
)
.get_matches();
//Get the values of input line parameters as strings
let first_date = matches.value_of("first_date").unwrap_or("");
println!("Value for first_date: {}", Red.paint(first_date));
let second_date = matches.value_of("second_date").unwrap_or("");
println!("Value for second_date: {}", Green.paint(second_date));
//convert the strings to i32 (integer)
//here I use 'variable shadowing'. The names stay the same, but the content is different.
//It is confusing, because, this variables are immutable, but "shadowing" allows to use
//the same name for other variable content.
//Immutability is only for the memory content, not for the variable name.
//And importantly I changed the datatype here.
//So later there is not too much confusion,
//because Rust compiler will return an error if the wrong datatype is used.
let first_date = first_date.parse::<i32>().unwrap();
let second_date = second_date.parse::<i32>().unwrap();
//I have to split this integer into parts: YYYYMMDD
let first_year = first_date / 10000;
let first_month = first_date % 10000 / 100;
let first_day = first_date % 100;
//just playing with bold
println!(
"parsed first_date: {}-{}-{}",
Style::new().bold().paint(first_year.to_string()),
first_month,
Style::new().bold().paint(first_day.to_string())
);
let second_year = second_date / 10000;
let second_month = second_date % 10000 / 100;
let second_day = second_date % 100;
println!(
"parsed second_date: {}-{}-{}",
Style::new().bold().paint(second_year.to_string()),
second_month,
Style::new().bold().paint(second_day.to_string())
);
//now I can call the library function. The code is in the lib.rs file.
let daydiff = date_diff_lib::daydiff(
first_year,
first_month,
first_day,
second_year,
second_month,
second_day,
);
//Finally output the result
println!(
"Date diff in days: {}",
Style::new().underline().paint(daydiff.to_string())
);
}
//region: different function code for Linux and Windows
#[cfg(target_family = "windows")]
///only on windows "enable ansi support" must be called
pub fn enable_ansi_support() {
let _enabled = ansi_term::enable_ansi_support();
}
#[cfg(target_family = "unix")]
//on Linux "enable ansi support" must not be called
pub fn enable_ansi_support() {
//do nothing
}
//endregion
| 35.53125 | 93 | 0.640281 |
1e746e8e4c6d336f09e13cefae886166a65af1d8 | 725 | #![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
use std::io;
use std::env;
use std::path::{Path, PathBuf};
use rocket::response::NamedFile;
#[get("/")]
fn index() -> io::Result<NamedFile> {
let page_directory_path = get_directory_path();
NamedFile::open(Path::new(&page_directory_path).join("index.html"))
}
#[get("/<file..>")]
fn files(file: PathBuf) -> io::Result<NamedFile> {
let page_directory_path = get_directory_path();
NamedFile::open(Path::new(&page_directory_path).join(file))
}
fn get_directory_path() -> String {
format!("{}/../frontend/build", env!("CARGO_MANIFEST_DIR"))
}
fn main() {
rocket::ignite().mount("/", routes![index, files]).launch();
} | 25 | 71 | 0.667586 |
143950e1e7f3d39cb0908650d0188d04a2db4e93 | 1,750 | extern crate run_length_encoding as rle;
// encoding tests
#[test]
fn test_encode_empty_string() {
assert_eq!("", rle::encode(""));
}
#[test]
#[ignore]
fn test_encode_single_characters() {
assert_eq!("XYZ", rle::encode("XYZ"));
}
#[test]
#[ignore]
fn test_encode_string_with_no_single_characters() {
assert_eq!("2A3B4C", rle::encode("AABBBCCCC"));
}
#[test]
#[ignore]
fn test_encode_single_characters_mixed_with_repeated_characters() {
assert_eq!("12WB12W3B24WB", rle::encode(
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"));
}
#[test]
#[ignore]
fn test_encode_multiple_whitespace_mixed_in_string() {
assert_eq!("2 hs2q q2w2 ", rle::encode(" hsqq qww "));
}
#[test]
#[ignore]
fn test_encode_lowercase_characters() {
assert_eq!("2a3b4c", rle::encode("aabbbcccc"));
}
// decoding tests
#[test]
#[ignore]
fn test_decode_empty_string() {
assert_eq!("", rle::decode(""));
}
#[test]
#[ignore]
fn test_decode_single_characters_only() {
assert_eq!("XYZ", rle::decode("XYZ"));
}
#[test]
#[ignore]
fn test_decode_string_with_no_single_characters() {
assert_eq!("AABBBCCCC", rle::decode("2A3B4C"));
}
#[test]
#[ignore]
fn test_decode_single_characters_with_repeated_characters() {
assert_eq!("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB",
rle::decode("12WB12W3B24WB"));
}
#[test]
#[ignore]
fn test_decode_multiple_whitespace_mixed_in_string() {
assert_eq!(" hsqq qww ", rle::decode("2 hs2q q2w2 "));
}
#[test]
#[ignore]
fn test_decode_lower_case_string() {
assert_eq!("aabbbcccc", rle::decode("2a3b4c"));
}
// consistency test
#[test]
#[ignore]
fn test_consistency() {
assert_eq!("zzz ZZ zZ", rle::decode(rle::encode("zzz ZZ zZ").as_str()));
}
| 20.114943 | 78 | 0.690857 |
2915e09e1fc3c2314eed5062f79c999908c8bf20 | 2,779 | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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::path::{Path, PathBuf};
use common;
use common::ui::{Status, UI};
use hcore;
use hcore::fs::{self, cache_artifact_path};
use hcore::package::{PackageIdent, PackageInstall};
use hcore::url::default_depot_url;
use {PRODUCT, VERSION};
use error::{Error, Result};
const MAX_RETRIES: u8 = 4;
/// Returns the absolute path to the given command from a package no older than the given package
/// identifier.
///
/// If the package is not locally installed, the package will be installed before recomputing.
/// There are a maximum number of times a re-installation will be attempted before returning an
/// error.
///
/// # Failures
///
/// * If the package is installed but the command cannot be found in the package
/// * If an error occurs when loading the local package from disk
/// * If the maximum number of installation retries has been exceeded
pub fn command_from_min_pkg<T>(
ui: &mut UI,
command: T,
ident: &PackageIdent,
cache_key_path: &Path,
retry: u8,
) -> Result<PathBuf>
where
T: Into<PathBuf>,
{
let command = command.into();
if retry > MAX_RETRIES {
return Err(Error::ExecCommandNotFound(command));
}
let fs_root_path = Path::new("/");
match PackageInstall::load_at_least(ident, None) {
Ok(pi) => {
match fs::find_command_in_pkg(&command, &pi, fs_root_path)? {
Some(cmd) => Ok(cmd),
None => Err(Error::ExecCommandNotFound(command)),
}
}
Err(hcore::Error::PackageNotFound(_)) => {
ui.status(
Status::Missing,
format!("package for {}", &ident),
)?;
common::command::package::install::start(
ui,
&default_depot_url(),
None,
&ident.to_string(),
PRODUCT,
VERSION,
fs_root_path,
&cache_artifact_path(None::<String>),
false,
)?;
command_from_min_pkg(ui, &command, &ident, &cache_key_path, retry + 1)
}
Err(e) => Err(Error::from(e)),
}
}
| 32.694118 | 97 | 0.623246 |
144bdab0390280700ec4d39b0fd01d432d1e6893 | 4,134 | use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::nu;
use nu_test_support::{pipeline, playground::Playground};
#[test]
fn takes_rows_of_nu_value_strings_and_pipes_it_to_stdin_of_external() {
Playground::setup("internal_to_external_pipe_test_1", |dirs, sandbox| {
sandbox.with_files(vec![FileWithContentToBeTrimmed(
"nu_times.csv",
r#"
name,rusty_luck,origin
Jason,1,Canada
Jonathan,1,New Zealand
Andrés,1,Ecuador
AndKitKatz,1,Estados Unidos
"#,
)]);
let actual = nu!(
cwd: dirs.test(), pipeline(
r#"
open nu_times.csv
| get name
| ^echo $it
| chop
| nth 3
| echo $it
"#
));
assert_eq!(actual.out, "AndKitKat");
})
}
#[test]
fn can_process_one_row_from_internal_and_pipes_it_to_stdin_of_external() {
let actual = nu!(
cwd: ".",
r#"echo "nushelll" | chop"#
);
assert_eq!(actual.out, "nushell");
}
mod parse {
use nu_test_support::nu;
/*
The debug command's signature is:
Usage:
> debug {flags}
flags:
-h, --help: Display this help message
-r, --raw: Prints the raw value representation.
*/
#[test]
fn errors_if_flag_passed_is_not_exact() {
let actual = nu!(cwd: ".", "debug -ra");
assert!(
actual.err.contains("unexpected flag"),
format!(
"error message '{}' should contain 'unexpected flag'",
actual.err
)
);
let actual = nu!(cwd: ".", "debug --rawx");
assert!(
actual.err.contains("unexpected flag"),
format!(
"error message '{}' should contain 'unexpected flag'",
actual.err
)
);
}
#[test]
fn errors_if_flag_is_not_supported() {
let actual = nu!(cwd: ".", "debug --ferris");
assert!(
actual.err.contains("unexpected flag"),
format!(
"error message '{}' should contain 'unexpected flag'",
actual.err
)
);
}
#[test]
fn errors_if_passed_an_unexpected_argument() {
let actual = nu!(cwd: ".", "debug ferris");
assert!(
actual.err.contains("unexpected argument"),
format!(
"error message '{}' should contain 'unexpected argument'",
actual.err
)
);
}
}
mod tilde_expansion {
use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::playground::Playground;
use nu_test_support::{nu, pipeline};
#[test]
#[should_panic]
fn as_home_directory_when_passed_as_argument_and_begins_with_tilde() {
let actual = nu!(
cwd: ".",
r#"
echo ~
"#
);
assert!(
!actual.out.contains('~'),
format!("'{}' should not contain ~", actual.out)
);
}
#[test]
fn does_not_expand_when_passed_as_argument_and_does_not_start_with_tilde() {
let actual = nu!(
cwd: ".",
r#"
echo "1~1"
"#
);
assert_eq!(actual.out, "1~1");
}
#[test]
fn proper_it_expansion() {
Playground::setup("ls_test_1", |dirs, sandbox| {
sandbox.with_files(vec![
EmptyFile("andres.txt"),
EmptyFile("gedge.txt"),
EmptyFile("jonathan.txt"),
EmptyFile("yehuda.txt"),
]);
let actual = nu!(
cwd: dirs.test(), pipeline(
r#"
ls | sort-by name | group-by type | each { get File.name | echo $it } | to json
"#
));
assert_eq!(
actual.out,
r#"["andres.txt","gedge.txt","jonathan.txt","yehuda.txt"]"#
);
})
}
}
| 24.903614 | 99 | 0.489115 |
0992e3a85ae94964023d9e2db4037b77640ee64b | 250 | #![feature(nll)]
fn main() {
let i = &3;
let f = |x: &i32| -> &i32 { x };
//~^ ERROR lifetime may not live long enough
let j = f(i);
let g = |x: &i32| { x };
//~^ ERROR lifetime may not live long enough
let k = g(i);
}
| 17.857143 | 48 | 0.48 |
5b6215d7c42caf499f32f546d02573622effe5d7 | 11,114 | #[doc = "Register `GMAC_TSR` reader"]
pub struct R(crate::R<GMAC_TSR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<GMAC_TSR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<GMAC_TSR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<GMAC_TSR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `GMAC_TSR` writer"]
pub struct W(crate::W<GMAC_TSR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<GMAC_TSR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<GMAC_TSR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<GMAC_TSR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `UBR` reader - Used Bit Read"]
pub struct UBR_R(crate::FieldReader<bool, bool>);
impl UBR_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
UBR_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for UBR_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `UBR` writer - Used Bit Read"]
pub struct UBR_W<'a> {
w: &'a mut W,
}
impl<'a> UBR_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w
}
}
#[doc = "Field `COL` reader - Collision Occurred"]
pub struct COL_R(crate::FieldReader<bool, bool>);
impl COL_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
COL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for COL_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `COL` writer - Collision Occurred"]
pub struct COL_W<'a> {
w: &'a mut W,
}
impl<'a> COL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1);
self.w
}
}
#[doc = "Field `RLE` reader - Retry Limit Exceeded"]
pub struct RLE_R(crate::FieldReader<bool, bool>);
impl RLE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
RLE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for RLE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `RLE` writer - Retry Limit Exceeded"]
pub struct RLE_W<'a> {
w: &'a mut W,
}
impl<'a> RLE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u32 & 0x01) << 2);
self.w
}
}
#[doc = "Field `TXGO` reader - Transmit Go"]
pub struct TXGO_R(crate::FieldReader<bool, bool>);
impl TXGO_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
TXGO_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for TXGO_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `TXGO` writer - Transmit Go"]
pub struct TXGO_W<'a> {
w: &'a mut W,
}
impl<'a> TXGO_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u32 & 0x01) << 3);
self.w
}
}
#[doc = "Field `TFC` reader - Transmit Frame Corruption Due to AHB Error"]
pub struct TFC_R(crate::FieldReader<bool, bool>);
impl TFC_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
TFC_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for TFC_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `TFC` writer - Transmit Frame Corruption Due to AHB Error"]
pub struct TFC_W<'a> {
w: &'a mut W,
}
impl<'a> TFC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4);
self.w
}
}
#[doc = "Field `TXCOMP` reader - Transmit Complete"]
pub struct TXCOMP_R(crate::FieldReader<bool, bool>);
impl TXCOMP_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
TXCOMP_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for TXCOMP_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `TXCOMP` writer - Transmit Complete"]
pub struct TXCOMP_W<'a> {
w: &'a mut W,
}
impl<'a> TXCOMP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | ((value as u32 & 0x01) << 5);
self.w
}
}
#[doc = "Field `HRESP` reader - HRESP Not OK"]
pub struct HRESP_R(crate::FieldReader<bool, bool>);
impl HRESP_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
HRESP_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for HRESP_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `HRESP` writer - HRESP Not OK"]
pub struct HRESP_W<'a> {
w: &'a mut W,
}
impl<'a> HRESP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | ((value as u32 & 0x01) << 8);
self.w
}
}
impl R {
#[doc = "Bit 0 - Used Bit Read"]
#[inline(always)]
pub fn ubr(&self) -> UBR_R {
UBR_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Collision Occurred"]
#[inline(always)]
pub fn col(&self) -> COL_R {
COL_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Retry Limit Exceeded"]
#[inline(always)]
pub fn rle(&self) -> RLE_R {
RLE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Transmit Go"]
#[inline(always)]
pub fn txgo(&self) -> TXGO_R {
TXGO_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Transmit Frame Corruption Due to AHB Error"]
#[inline(always)]
pub fn tfc(&self) -> TFC_R {
TFC_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Transmit Complete"]
#[inline(always)]
pub fn txcomp(&self) -> TXCOMP_R {
TXCOMP_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 8 - HRESP Not OK"]
#[inline(always)]
pub fn hresp(&self) -> HRESP_R {
HRESP_R::new(((self.bits >> 8) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Used Bit Read"]
#[inline(always)]
pub fn ubr(&mut self) -> UBR_W {
UBR_W { w: self }
}
#[doc = "Bit 1 - Collision Occurred"]
#[inline(always)]
pub fn col(&mut self) -> COL_W {
COL_W { w: self }
}
#[doc = "Bit 2 - Retry Limit Exceeded"]
#[inline(always)]
pub fn rle(&mut self) -> RLE_W {
RLE_W { w: self }
}
#[doc = "Bit 3 - Transmit Go"]
#[inline(always)]
pub fn txgo(&mut self) -> TXGO_W {
TXGO_W { w: self }
}
#[doc = "Bit 4 - Transmit Frame Corruption Due to AHB Error"]
#[inline(always)]
pub fn tfc(&mut self) -> TFC_W {
TFC_W { w: self }
}
#[doc = "Bit 5 - Transmit Complete"]
#[inline(always)]
pub fn txcomp(&mut self) -> TXCOMP_W {
TXCOMP_W { w: self }
}
#[doc = "Bit 8 - HRESP Not OK"]
#[inline(always)]
pub fn hresp(&mut self) -> HRESP_W {
HRESP_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Transmit Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gmac_tsr](index.html) module"]
pub struct GMAC_TSR_SPEC;
impl crate::RegisterSpec for GMAC_TSR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [gmac_tsr::R](R) reader structure"]
impl crate::Readable for GMAC_TSR_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [gmac_tsr::W](W) writer structure"]
impl crate::Writable for GMAC_TSR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets GMAC_TSR to value 0"]
impl crate::Resettable for GMAC_TSR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 28.065657 | 413 | 0.554706 |
1a42f91702d7533172b9f08fc1e74a88a00ff685 | 114,532 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_cluster_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateClusterOutput, crate::error::CreateClusterError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CreateClusterError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CreateClusterError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ConflictException" => {
crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::ConflictException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::conflict_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_conflict_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InternalServerException" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceQuotaExceededException" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::ServiceQuotaExceededException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_quota_exceeded_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_service_quota_exceeded_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::CreateClusterError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_cluster_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateClusterOutput, crate::error::CreateClusterError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::create_cluster_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_create_cluster(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_control_panel_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::CreateControlPanelOutput,
crate::error::CreateControlPanelError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CreateControlPanelError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CreateControlPanelError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::CreateControlPanelError {
meta: generic,
kind: crate::error::CreateControlPanelErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ConflictException" => {
crate::error::CreateControlPanelError {
meta: generic,
kind: crate::error::CreateControlPanelErrorKind::ConflictException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::conflict_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_conflict_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InternalServerException" => crate::error::CreateControlPanelError {
meta: generic,
kind: crate::error::CreateControlPanelErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::CreateControlPanelError {
meta: generic,
kind: crate::error::CreateControlPanelErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceQuotaExceededException" => crate::error::CreateControlPanelError {
meta: generic,
kind: crate::error::CreateControlPanelErrorKind::ServiceQuotaExceededException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_quota_exceeded_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_service_quota_exceeded_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::CreateControlPanelError {
meta: generic,
kind: crate::error::CreateControlPanelErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::CreateControlPanelError {
meta: generic,
kind: crate::error::CreateControlPanelErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::CreateControlPanelError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_control_panel_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::CreateControlPanelOutput,
crate::error::CreateControlPanelError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::create_control_panel_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_create_control_panel(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateControlPanelError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_routing_control_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::CreateRoutingControlOutput,
crate::error::CreateRoutingControlError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CreateRoutingControlError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CreateRoutingControlError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::CreateRoutingControlError {
meta: generic,
kind: crate::error::CreateRoutingControlErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ConflictException" => {
crate::error::CreateRoutingControlError {
meta: generic,
kind: crate::error::CreateRoutingControlErrorKind::ConflictException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::conflict_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_conflict_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InternalServerException" => crate::error::CreateRoutingControlError {
meta: generic,
kind: crate::error::CreateRoutingControlErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::CreateRoutingControlError {
meta: generic,
kind: crate::error::CreateRoutingControlErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceQuotaExceededException" => crate::error::CreateRoutingControlError {
meta: generic,
kind: crate::error::CreateRoutingControlErrorKind::ServiceQuotaExceededException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_quota_exceeded_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_service_quota_exceeded_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::CreateRoutingControlError {
meta: generic,
kind: crate::error::CreateRoutingControlErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::CreateRoutingControlError {
meta: generic,
kind: crate::error::CreateRoutingControlErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::CreateRoutingControlError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_routing_control_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::CreateRoutingControlOutput,
crate::error::CreateRoutingControlError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::create_routing_control_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_create_routing_control(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateRoutingControlError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_safety_rule_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateSafetyRuleOutput, crate::error::CreateSafetyRuleError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CreateSafetyRuleError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CreateSafetyRuleError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InternalServerException" => crate::error::CreateSafetyRuleError {
meta: generic,
kind: crate::error::CreateSafetyRuleErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateSafetyRuleError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::CreateSafetyRuleError {
meta: generic,
kind: crate::error::CreateSafetyRuleErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::CreateSafetyRuleError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::CreateSafetyRuleError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_safety_rule_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateSafetyRuleOutput, crate::error::CreateSafetyRuleError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::create_safety_rule_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_create_safety_rule(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateSafetyRuleError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_cluster_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteClusterOutput, crate::error::DeleteClusterError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DeleteClusterError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DeleteClusterError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::DeleteClusterError {
meta: generic,
kind: crate::error::DeleteClusterErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ConflictException" => {
crate::error::DeleteClusterError {
meta: generic,
kind: crate::error::DeleteClusterErrorKind::ConflictException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::conflict_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_conflict_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InternalServerException" => crate::error::DeleteClusterError {
meta: generic,
kind: crate::error::DeleteClusterErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::DeleteClusterError {
meta: generic,
kind: crate::error::DeleteClusterErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::DeleteClusterError {
meta: generic,
kind: crate::error::DeleteClusterErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::DeleteClusterError {
meta: generic,
kind: crate::error::DeleteClusterErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DeleteClusterError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_cluster_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteClusterOutput, crate::error::DeleteClusterError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::delete_cluster_output::Builder::default();
let _ = response;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_control_panel_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DeleteControlPanelOutput,
crate::error::DeleteControlPanelError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DeleteControlPanelError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DeleteControlPanelError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::DeleteControlPanelError {
meta: generic,
kind: crate::error::DeleteControlPanelErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ConflictException" => {
crate::error::DeleteControlPanelError {
meta: generic,
kind: crate::error::DeleteControlPanelErrorKind::ConflictException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::conflict_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_conflict_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InternalServerException" => crate::error::DeleteControlPanelError {
meta: generic,
kind: crate::error::DeleteControlPanelErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::DeleteControlPanelError {
meta: generic,
kind: crate::error::DeleteControlPanelErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::DeleteControlPanelError {
meta: generic,
kind: crate::error::DeleteControlPanelErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::DeleteControlPanelError {
meta: generic,
kind: crate::error::DeleteControlPanelErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DeleteControlPanelError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_control_panel_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DeleteControlPanelOutput,
crate::error::DeleteControlPanelError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::delete_control_panel_output::Builder::default();
let _ = response;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_routing_control_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DeleteRoutingControlOutput,
crate::error::DeleteRoutingControlError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DeleteRoutingControlError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DeleteRoutingControlError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::DeleteRoutingControlError {
meta: generic,
kind: crate::error::DeleteRoutingControlErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ConflictException" => {
crate::error::DeleteRoutingControlError {
meta: generic,
kind: crate::error::DeleteRoutingControlErrorKind::ConflictException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::conflict_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_conflict_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InternalServerException" => crate::error::DeleteRoutingControlError {
meta: generic,
kind: crate::error::DeleteRoutingControlErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::DeleteRoutingControlError {
meta: generic,
kind: crate::error::DeleteRoutingControlErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::DeleteRoutingControlError {
meta: generic,
kind: crate::error::DeleteRoutingControlErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::DeleteRoutingControlError {
meta: generic,
kind: crate::error::DeleteRoutingControlErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DeleteRoutingControlError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_routing_control_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DeleteRoutingControlOutput,
crate::error::DeleteRoutingControlError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::delete_routing_control_output::Builder::default();
let _ = response;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_safety_rule_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteSafetyRuleOutput, crate::error::DeleteSafetyRuleError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DeleteSafetyRuleError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DeleteSafetyRuleError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InternalServerException" => crate::error::DeleteSafetyRuleError {
meta: generic,
kind: crate::error::DeleteSafetyRuleErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteSafetyRuleError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::DeleteSafetyRuleError {
meta: generic,
kind: crate::error::DeleteSafetyRuleErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteSafetyRuleError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::DeleteSafetyRuleError {
meta: generic,
kind: crate::error::DeleteSafetyRuleErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteSafetyRuleError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DeleteSafetyRuleError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_safety_rule_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteSafetyRuleOutput, crate::error::DeleteSafetyRuleError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::delete_safety_rule_output::Builder::default();
let _ = response;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_cluster_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeClusterOutput, crate::error::DescribeClusterError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeClusterError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeClusterError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::DescribeClusterError {
meta: generic,
kind: crate::error::DescribeClusterErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ConflictException" => {
crate::error::DescribeClusterError {
meta: generic,
kind: crate::error::DescribeClusterErrorKind::ConflictException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::conflict_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_conflict_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InternalServerException" => crate::error::DescribeClusterError {
meta: generic,
kind: crate::error::DescribeClusterErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::DescribeClusterError {
meta: generic,
kind: crate::error::DescribeClusterErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::DescribeClusterError {
meta: generic,
kind: crate::error::DescribeClusterErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::DescribeClusterError {
meta: generic,
kind: crate::error::DescribeClusterErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeClusterError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_cluster_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeClusterOutput, crate::error::DescribeClusterError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_cluster_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_describe_cluster(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeClusterError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_control_panel_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeControlPanelOutput,
crate::error::DescribeControlPanelError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeControlPanelError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeControlPanelError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::DescribeControlPanelError {
meta: generic,
kind: crate::error::DescribeControlPanelErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ConflictException" => {
crate::error::DescribeControlPanelError {
meta: generic,
kind: crate::error::DescribeControlPanelErrorKind::ConflictException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::conflict_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_conflict_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InternalServerException" => crate::error::DescribeControlPanelError {
meta: generic,
kind: crate::error::DescribeControlPanelErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::DescribeControlPanelError {
meta: generic,
kind: crate::error::DescribeControlPanelErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::DescribeControlPanelError {
meta: generic,
kind: crate::error::DescribeControlPanelErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::DescribeControlPanelError {
meta: generic,
kind: crate::error::DescribeControlPanelErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeControlPanelError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_control_panel_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeControlPanelOutput,
crate::error::DescribeControlPanelError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_control_panel_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_describe_control_panel(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeControlPanelError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_routing_control_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeRoutingControlOutput,
crate::error::DescribeRoutingControlError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeRoutingControlError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => {
return Err(crate::error::DescribeRoutingControlError::unhandled(
generic,
))
}
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::DescribeRoutingControlError {
meta: generic,
kind: crate::error::DescribeRoutingControlErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ConflictException" => {
crate::error::DescribeRoutingControlError {
meta: generic,
kind: crate::error::DescribeRoutingControlErrorKind::ConflictException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::conflict_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_conflict_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InternalServerException" => crate::error::DescribeRoutingControlError {
meta: generic,
kind: crate::error::DescribeRoutingControlErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::DescribeRoutingControlError {
meta: generic,
kind: crate::error::DescribeRoutingControlErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::DescribeRoutingControlError {
meta: generic,
kind: crate::error::DescribeRoutingControlErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::DescribeRoutingControlError {
meta: generic,
kind: crate::error::DescribeRoutingControlErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeRoutingControlError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_routing_control_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeRoutingControlOutput,
crate::error::DescribeRoutingControlError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_routing_control_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_describe_routing_control(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeRoutingControlError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_safety_rule_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeSafetyRuleOutput,
crate::error::DescribeSafetyRuleError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeSafetyRuleError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeSafetyRuleError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ResourceNotFoundException" => crate::error::DescribeSafetyRuleError {
meta: generic,
kind: crate::error::DescribeSafetyRuleErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeSafetyRuleError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::DescribeSafetyRuleError {
meta: generic,
kind: crate::error::DescribeSafetyRuleErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeSafetyRuleError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeSafetyRuleError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_safety_rule_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeSafetyRuleOutput,
crate::error::DescribeSafetyRuleError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_safety_rule_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_describe_safety_rule(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeSafetyRuleError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_associated_route53_health_checks_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::ListAssociatedRoute53HealthChecksOutput,
crate::error::ListAssociatedRoute53HealthChecksError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::ListAssociatedRoute53HealthChecksError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => {
return Err(crate::error::ListAssociatedRoute53HealthChecksError::unhandled(generic))
}
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InternalServerException" => crate::error::ListAssociatedRoute53HealthChecksError {
meta: generic,
kind: crate::error::ListAssociatedRoute53HealthChecksErrorKind::InternalServerException(
{
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListAssociatedRoute53HealthChecksError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
},
),
},
"ResourceNotFoundException" => crate::error::ListAssociatedRoute53HealthChecksError {
meta: generic,
kind:
crate::error::ListAssociatedRoute53HealthChecksErrorKind::ResourceNotFoundException(
{
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListAssociatedRoute53HealthChecksError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
},
),
},
"ValidationException" => crate::error::ListAssociatedRoute53HealthChecksError {
meta: generic,
kind: crate::error::ListAssociatedRoute53HealthChecksErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListAssociatedRoute53HealthChecksError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::ListAssociatedRoute53HealthChecksError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_associated_route53_health_checks_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::ListAssociatedRoute53HealthChecksOutput,
crate::error::ListAssociatedRoute53HealthChecksError,
> {
Ok({
#[allow(unused_mut)]
let mut output =
crate::output::list_associated_route53_health_checks_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_list_associated_route53_health_checks(response.body().as_ref(), output).map_err(crate::error::ListAssociatedRoute53HealthChecksError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_clusters_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListClustersOutput, crate::error::ListClustersError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::ListClustersError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::ListClustersError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::ListClustersError {
meta: generic,
kind: crate::error::ListClustersErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListClustersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InternalServerException" => crate::error::ListClustersError {
meta: generic,
kind: crate::error::ListClustersErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListClustersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::ListClustersError {
meta: generic,
kind: crate::error::ListClustersErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListClustersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::ListClustersError {
meta: generic,
kind: crate::error::ListClustersErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListClustersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::ListClustersError {
meta: generic,
kind: crate::error::ListClustersErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListClustersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::ListClustersError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_clusters_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListClustersOutput, crate::error::ListClustersError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::list_clusters_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_list_clusters(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListClustersError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_control_panels_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListControlPanelsOutput, crate::error::ListControlPanelsError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::ListControlPanelsError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::ListControlPanelsError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::ListControlPanelsError {
meta: generic,
kind: crate::error::ListControlPanelsErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListControlPanelsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InternalServerException" => crate::error::ListControlPanelsError {
meta: generic,
kind: crate::error::ListControlPanelsErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListControlPanelsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::ListControlPanelsError {
meta: generic,
kind: crate::error::ListControlPanelsErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListControlPanelsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::ListControlPanelsError {
meta: generic,
kind: crate::error::ListControlPanelsErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListControlPanelsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::ListControlPanelsError {
meta: generic,
kind: crate::error::ListControlPanelsErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListControlPanelsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::ListControlPanelsError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_control_panels_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListControlPanelsOutput, crate::error::ListControlPanelsError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::list_control_panels_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_list_control_panels(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListControlPanelsError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_routing_controls_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::ListRoutingControlsOutput,
crate::error::ListRoutingControlsError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::ListRoutingControlsError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::ListRoutingControlsError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::ListRoutingControlsError {
meta: generic,
kind: crate::error::ListRoutingControlsErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListRoutingControlsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InternalServerException" => crate::error::ListRoutingControlsError {
meta: generic,
kind: crate::error::ListRoutingControlsErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListRoutingControlsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::ListRoutingControlsError {
meta: generic,
kind: crate::error::ListRoutingControlsErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListRoutingControlsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::ListRoutingControlsError {
meta: generic,
kind: crate::error::ListRoutingControlsErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListRoutingControlsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::ListRoutingControlsError {
meta: generic,
kind: crate::error::ListRoutingControlsErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListRoutingControlsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::ListRoutingControlsError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_routing_controls_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::ListRoutingControlsOutput,
crate::error::ListRoutingControlsError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::list_routing_controls_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_list_routing_controls(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListRoutingControlsError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_safety_rules_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListSafetyRulesOutput, crate::error::ListSafetyRulesError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::ListSafetyRulesError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::ListSafetyRulesError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::ListSafetyRulesError {
meta: generic,
kind: crate::error::ListSafetyRulesErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListSafetyRulesError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InternalServerException" => crate::error::ListSafetyRulesError {
meta: generic,
kind: crate::error::ListSafetyRulesErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListSafetyRulesError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::ListSafetyRulesError {
meta: generic,
kind: crate::error::ListSafetyRulesErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListSafetyRulesError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::ListSafetyRulesError {
meta: generic,
kind: crate::error::ListSafetyRulesErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListSafetyRulesError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::ListSafetyRulesError {
meta: generic,
kind: crate::error::ListSafetyRulesErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListSafetyRulesError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::ListSafetyRulesError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_safety_rules_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListSafetyRulesOutput, crate::error::ListSafetyRulesError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::list_safety_rules_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_list_safety_rules(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListSafetyRulesError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_control_panel_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::UpdateControlPanelOutput,
crate::error::UpdateControlPanelError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::UpdateControlPanelError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::UpdateControlPanelError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::UpdateControlPanelError {
meta: generic,
kind: crate::error::UpdateControlPanelErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ConflictException" => {
crate::error::UpdateControlPanelError {
meta: generic,
kind: crate::error::UpdateControlPanelErrorKind::ConflictException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::conflict_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_conflict_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InternalServerException" => crate::error::UpdateControlPanelError {
meta: generic,
kind: crate::error::UpdateControlPanelErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::UpdateControlPanelError {
meta: generic,
kind: crate::error::UpdateControlPanelErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::UpdateControlPanelError {
meta: generic,
kind: crate::error::UpdateControlPanelErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::UpdateControlPanelError {
meta: generic,
kind: crate::error::UpdateControlPanelErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateControlPanelError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::UpdateControlPanelError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_control_panel_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::UpdateControlPanelOutput,
crate::error::UpdateControlPanelError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::update_control_panel_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_update_control_panel(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateControlPanelError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_routing_control_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::UpdateRoutingControlOutput,
crate::error::UpdateRoutingControlError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::UpdateRoutingControlError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::UpdateRoutingControlError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"AccessDeniedException" => crate::error::UpdateRoutingControlError {
meta: generic,
kind: crate::error::UpdateRoutingControlErrorKind::AccessDeniedException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::access_denied_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ConflictException" => {
crate::error::UpdateRoutingControlError {
meta: generic,
kind: crate::error::UpdateRoutingControlErrorKind::ConflictException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::conflict_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_conflict_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InternalServerException" => crate::error::UpdateRoutingControlError {
meta: generic,
kind: crate::error::UpdateRoutingControlErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::UpdateRoutingControlError {
meta: generic,
kind: crate::error::UpdateRoutingControlErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ThrottlingException" => crate::error::UpdateRoutingControlError {
meta: generic,
kind: crate::error::UpdateRoutingControlErrorKind::ThrottlingException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::throttling_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::UpdateRoutingControlError {
meta: generic,
kind: crate::error::UpdateRoutingControlErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateRoutingControlError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::UpdateRoutingControlError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_routing_control_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::UpdateRoutingControlOutput,
crate::error::UpdateRoutingControlError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::update_routing_control_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_update_routing_control(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateRoutingControlError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_safety_rule_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UpdateSafetyRuleOutput, crate::error::UpdateSafetyRuleError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::UpdateSafetyRuleError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::UpdateSafetyRuleError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InternalServerException" => crate::error::UpdateSafetyRuleError {
meta: generic,
kind: crate::error::UpdateSafetyRuleErrorKind::InternalServerException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::internal_server_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_internal_server_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateSafetyRuleError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFoundException" => crate::error::UpdateSafetyRuleError {
meta: generic,
kind: crate::error::UpdateSafetyRuleErrorKind::ResourceNotFoundException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateSafetyRuleError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ValidationException" => crate::error::UpdateSafetyRuleError {
meta: generic,
kind: crate::error::UpdateSafetyRuleErrorKind::ValidationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::validation_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateSafetyRuleError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::UpdateSafetyRuleError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_safety_rule_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UpdateSafetyRuleOutput, crate::error::UpdateSafetyRuleError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::update_safety_rule_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_crate_operation_update_safety_rule(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateSafetyRuleError::unhandled)?;
output.build()
})
}
| 45.739617 | 230 | 0.556866 |
e22bc0bdc4892c5e3397f2de4838de31e9b102b3 | 6,317 | //! ABI definitions.
use crate::ir::{ArgumentExtension, StackSlot};
use crate::machinst::*;
use crate::settings;
use regalloc::{Reg, Set, SpillSlot, Writable};
/// Trait implemented by an object that tracks ABI-related state (e.g., stack
/// layout) and can generate code while emitting the *body* of a function.
pub trait ABIBody {
/// The instruction type for the ISA associated with this ABI.
type I: VCodeInst;
/// Get the settings controlling this function's compilation.
fn flags(&self) -> &settings::Flags;
/// Get the liveins of the function.
fn liveins(&self) -> Set<RealReg>;
/// Get the liveouts of the function.
fn liveouts(&self) -> Set<RealReg>;
/// Number of arguments.
fn num_args(&self) -> usize;
/// Number of return values.
fn num_retvals(&self) -> usize;
/// Number of stack slots (not spill slots).
fn num_stackslots(&self) -> usize;
/// Generate an instruction which copies an argument to a destination
/// register.
fn gen_copy_arg_to_reg(&self, idx: usize, into_reg: Writable<Reg>) -> Self::I;
/// Generate an instruction which copies a source register to a return value slot.
fn gen_copy_reg_to_retval(
&self,
idx: usize,
from_reg: Writable<Reg>,
ext: ArgumentExtension,
) -> Vec<Self::I>;
/// Generate a return instruction.
fn gen_ret(&self) -> Self::I;
/// Generate an epilogue placeholder. The returned instruction should return `true` from
/// `is_epilogue_placeholder()`; this is used to indicate to the lowering driver when
/// the epilogue should be inserted.
fn gen_epilogue_placeholder(&self) -> Self::I;
// -----------------------------------------------------------------
// Every function above this line may only be called pre-regalloc.
// Every function below this line may only be called post-regalloc.
// `spillslots()` must be called before any other post-regalloc
// function.
// ----------------------------------------------------------------
/// Update with the number of spillslots, post-regalloc.
fn set_num_spillslots(&mut self, slots: usize);
/// Update with the clobbered registers, post-regalloc.
fn set_clobbered(&mut self, clobbered: Set<Writable<RealReg>>);
/// Get the address of a stackslot.
fn stackslot_addr(&self, slot: StackSlot, offset: u32, into_reg: Writable<Reg>) -> Self::I;
/// Load from a stackslot.
fn load_stackslot(
&self,
slot: StackSlot,
offset: u32,
ty: Type,
into_reg: Writable<Reg>,
) -> Self::I;
/// Store to a stackslot.
fn store_stackslot(&self, slot: StackSlot, offset: u32, ty: Type, from_reg: Reg) -> Self::I;
/// Load from a spillslot.
fn load_spillslot(&self, slot: SpillSlot, ty: Type, into_reg: Writable<Reg>) -> Self::I;
/// Store to a spillslot.
fn store_spillslot(&self, slot: SpillSlot, ty: Type, from_reg: Reg) -> Self::I;
/// Generate a prologue, post-regalloc. This should include any stack
/// frame or other setup necessary to use the other methods (`load_arg`,
/// `store_retval`, and spillslot accesses.) `self` is mutable so that we
/// can store information in it which will be useful when creating the
/// epilogue.
fn gen_prologue(&mut self) -> Vec<Self::I>;
/// Generate an epilogue, post-regalloc. Note that this must generate the
/// actual return instruction (rather than emitting this in the lowering
/// logic), because the epilogue code comes before the return and the two are
/// likely closely related.
fn gen_epilogue(&self) -> Vec<Self::I>;
/// Returns the full frame size for the given function, after prologue emission has run. This
/// comprises the spill space, incoming argument space, alignment padding, etc.
fn frame_size(&self) -> u32;
/// Get the spill-slot size.
fn get_spillslot_size(&self, rc: RegClass, ty: Type) -> u32;
/// Generate a spill.
fn gen_spill(&self, to_slot: SpillSlot, from_reg: RealReg, ty: Type) -> Self::I;
/// Generate a reload (fill).
fn gen_reload(&self, to_reg: Writable<RealReg>, from_slot: SpillSlot, ty: Type) -> Self::I;
}
/// Trait implemented by an object that tracks ABI-related state and can
/// generate code while emitting a *call* to a function.
///
/// An instance of this trait returns information for a *particular*
/// callsite. It will usually be computed from the called function's
/// signature.
///
/// Unlike `ABIBody` above, methods on this trait are not invoked directly
/// by the machine-independent code. Rather, the machine-specific lowering
/// code will typically create an `ABICall` when creating machine instructions
/// for an IR call instruction inside `lower()`, directly emit the arg and
/// and retval copies, and attach the register use/def info to the call.
///
/// This trait is thus provided for convenience to the backends.
pub trait ABICall {
/// The instruction type for the ISA associated with this ABI.
type I: VCodeInst;
/// Get the number of arguments expected.
fn num_args(&self) -> usize;
/// Save the clobbered registers.
/// Copy an argument value from a source register, prior to the call.
fn gen_copy_reg_to_arg(&self, idx: usize, from_reg: Reg) -> Self::I;
/// Copy a return value into a destination register, after the call returns.
fn gen_copy_retval_to_reg(&self, idx: usize, into_reg: Writable<Reg>) -> Self::I;
/// Pre-adjust the stack, prior to argument copies and call.
fn gen_stack_pre_adjust(&self) -> Vec<Self::I>;
/// Post-adjust the satck, after call return and return-value copies.
fn gen_stack_post_adjust(&self) -> Vec<Self::I>;
/// Generate the call itself.
///
/// The returned instruction should have proper use- and def-sets according
/// to the argument registers, return-value registers, and clobbered
/// registers for this function signature in this ABI.
///
/// (Arg registers are uses, and retval registers are defs. Clobbered
/// registers are also logically defs, but should never be read; their
/// values are "defined" (to the regalloc) but "undefined" in every other
/// sense.)
fn gen_call(&self) -> Vec<Self::I>;
}
| 39.48125 | 97 | 0.660598 |
89497cde96787101c923a6d348d872f0a2f184d2 | 21,358 | //! This module contains the implementation of a virtual element node `VTag`.
use super::{Attributes, Classes, Listener, Listeners, Patch, Reform, VDiff, VNode};
use crate::html::{Component, Scope};
use log::warn;
use std::borrow::Cow;
use std::cmp::PartialEq;
use std::collections::HashSet;
use std::fmt;
use stdweb::unstable::TryFrom;
use stdweb::web::html_element::InputElement;
use stdweb::web::html_element::TextAreaElement;
use stdweb::web::{document, Element, EventListenerHandle, IElement, INode, Node};
#[allow(unused_imports)]
use stdweb::{_js_impl, js};
/// A type for a virtual
/// [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element)
/// representation.
pub struct VTag<COMP: Component> {
/// A tag of the element.
tag: Cow<'static, str>,
/// A reference to the `Element`.
pub reference: Option<Element>,
/// List of attached listeners.
pub listeners: Listeners<COMP>,
/// List of attributes.
pub attributes: Attributes,
/// The list of children nodes. Which also could have own children.
pub childs: Vec<VNode<COMP>>,
/// List of attached classes.
pub classes: Classes,
/// Contains a value of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
pub value: Option<String>,
/// Contains
/// [kind](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types)
/// value of an `InputElement`.
pub kind: Option<String>,
/// Represents `checked` attribute of
/// [input](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-checked).
/// It exists to override standard behavior of `checked` attribute, because
/// in original HTML it sets `defaultChecked` value of `InputElement`, but for reactive
/// frameworks it's more useful to control `checked` value of an `InputElement`.
pub checked: bool,
/// _Service field_. Keeps handler for attached listeners
/// to have an opportunity to drop them later.
captured: Vec<EventListenerHandle>,
}
impl<COMP: Component> VTag<COMP> {
/// Creates a new `VTag` instance with `tag` name (cannot be changed later in DOM).
pub fn new<S: Into<Cow<'static, str>>>(tag: S) -> Self {
VTag {
tag: tag.into(),
reference: None,
classes: Classes::new(),
attributes: Attributes::new(),
listeners: Vec::new(),
captured: Vec::new(),
childs: Vec::new(),
value: None,
kind: None,
// In HTML node `checked` attribute sets `defaultChecked` parameter,
// but we use own field to control real `checked` parameter
checked: false,
}
}
/// Returns tag of an `Element`. In HTML tags are always uppercase.
pub fn tag(&self) -> &str {
&self.tag
}
/// Add `VNode` child.
pub fn add_child(&mut self, child: VNode<COMP>) {
self.childs.push(child);
}
/// Add multiple `VNode` children.
pub fn add_children(&mut self, children: Vec<VNode<COMP>>) {
for child in children {
self.childs.push(child);
}
}
/// Adds a single class to this virtual node. Actually it will set by
/// [Element.classList.add](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)
/// call later.
pub fn add_class(&mut self, class: &str) {
let class = class.trim();
if !class.is_empty() {
self.classes.insert(class.into());
}
}
/// Adds multiple classes to this virtual node. Actually it will set by
/// [Element.classList.add](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)
/// call later.
pub fn add_classes(&mut self, classes: Vec<&str>) {
for class in classes {
let class = class.trim();
if !class.is_empty() {
self.classes.insert(class.into());
}
}
}
/// Add classes to this virtual node. Actually it will set by
/// [Element.classList.add](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)
/// call later.
pub fn set_classes(&mut self, classes: &str) {
self.classes = classes.split_whitespace().map(String::from).collect();
}
/// Sets `value` for an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
pub fn set_value<T: ToString>(&mut self, value: &T) {
self.value = Some(value.to_string());
}
/// Sets `kind` property of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
/// Same as set `type` attribute.
pub fn set_kind<T: ToString>(&mut self, value: &T) {
self.kind = Some(value.to_string());
}
/// Sets `checked` property of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
/// (Not a value of node's attribute).
pub fn set_checked(&mut self, value: bool) {
self.checked = value;
}
/// Adds attribute to a virtual node. Not every attribute works when
/// it set as attribute. We use workarounds for:
/// `class`, `type/kind`, `value` and `checked`.
pub fn add_attribute<T: ToString>(&mut self, name: &str, value: &T) {
self.attributes.insert(name.to_owned(), value.to_string());
}
/// Adds attributes to a virtual node. Not every attribute works when
/// it set as attribute. We use workarounds for:
/// `class`, `type/kind`, `value` and `checked`.
pub fn add_attributes(&mut self, attrs: Vec<(String, String)>) {
for (name, value) in attrs {
self.attributes.insert(name, value);
}
}
/// Adds new listener to the node.
/// It's boxed because we want to keep it in a single list.
/// Lates `Listener::attach` called to attach actual listener to a DOM node.
pub fn add_listener(&mut self, listener: Box<dyn Listener<COMP>>) {
self.listeners.push(listener);
}
/// Adds new listeners to the node.
/// They are boxed because we want to keep them in a single list.
/// Lates `Listener::attach` called to attach actual listener to a DOM node.
pub fn add_listeners(&mut self, listeners: Vec<Box<dyn Listener<COMP>>>) {
for listener in listeners {
self.listeners.push(listener);
}
}
/// Compute differences between the ancestor and determine patch changes.
///
/// If there is an ancestor:
/// - add the classes that are in self but NOT in ancestor.
/// - remove the classes that are in ancestor but NOT in self.
/// - items that are the same stay the same.
///
/// Otherwise just add everything.
fn diff_classes(&mut self, ancestor: &mut Option<Self>) -> Vec<Patch<String, ()>> {
let mut changes = Vec::new();
if let &mut Some(ref ancestor) = ancestor {
// Only change what is necessary.
let to_add = self
.classes
.difference(&ancestor.classes)
.map(|class| Patch::Add(class.to_owned(), ()));
changes.extend(to_add);
let to_remove = ancestor
.classes
.difference(&self.classes)
.map(|class| Patch::Remove(class.to_owned()));
changes.extend(to_remove);
} else {
// Add everything
let to_add = self
.classes
.iter()
.map(|class| Patch::Add(class.to_owned(), ()));
changes.extend(to_add);
}
changes
}
/// Similar to diff_classes except for attributes.
///
/// This also handles patching of attributes when the keys are equal but
/// the values are different.
fn diff_attributes(&mut self, ancestor: &mut Option<Self>) -> Vec<Patch<String, String>> {
let mut changes = Vec::new();
if let &mut Some(ref mut ancestor) = ancestor {
// Only change what is necessary.
let self_keys = self.attributes.keys().collect::<HashSet<_>>();
let ancestor_keys = ancestor.attributes.keys().collect::<HashSet<_>>();
let to_add = self_keys.difference(&ancestor_keys).map(|key| {
let value = self.attributes.get(*key).expect("attribute of vtag lost");
Patch::Add(key.to_string(), value.to_string())
});
changes.extend(to_add);
for key in self_keys.intersection(&ancestor_keys) {
let self_value = self
.attributes
.get(*key)
.expect("attribute of self side lost");
let ancestor_value = ancestor
.attributes
.get(*key)
.expect("attribute of ancestor side lost");
if self_value != ancestor_value {
let mutator = Patch::Replace(key.to_string(), self_value.to_string());
changes.push(mutator);
}
}
let to_remove = ancestor_keys
.difference(&self_keys)
.map(|key| Patch::Remove(key.to_string()));
changes.extend(to_remove);
} else {
// Add everything
for (key, value) in &self.attributes {
let mutator = Patch::Add(key.to_string(), value.to_string());
changes.push(mutator);
}
}
changes
}
/// Similar to `diff_attributers` except there is only a single `kind`.
fn diff_kind(&mut self, ancestor: &mut Option<Self>) -> Option<Patch<String, ()>> {
match (
&self.kind,
ancestor.as_mut().and_then(|anc| anc.kind.take()),
) {
(&Some(ref left), Some(ref right)) => {
if left != right {
Some(Patch::Replace(left.to_string(), ()))
} else {
None
}
}
(&Some(ref left), None) => Some(Patch::Add(left.to_string(), ())),
(&None, Some(right)) => Some(Patch::Remove(right)),
(&None, None) => None,
}
}
/// Almost identical in spirit to `diff_kind`
fn diff_value(&mut self, ancestor: &mut Option<Self>) -> Option<Patch<String, ()>> {
match (
&self.value,
ancestor.as_mut().and_then(|anc| anc.value.take()),
) {
(&Some(ref left), Some(ref right)) => {
if left != right {
Some(Patch::Replace(left.to_string(), ()))
} else {
None
}
}
(&Some(ref left), None) => Some(Patch::Add(left.to_string(), ())),
(&None, Some(right)) => Some(Patch::Remove(right)),
(&None, None) => None,
}
}
fn apply_diffs(&mut self, element: &Element, ancestor: &mut Option<Self>) {
// Update parameters
let changes = self.diff_classes(ancestor);
for change in changes {
let list = element.class_list();
match change {
Patch::Add(class, _) | Patch::Replace(class, _) => {
list.add(&class).expect("can't add a class");
}
Patch::Remove(class) => {
list.remove(&class).expect("can't remove a class");
}
}
}
let changes = self.diff_attributes(ancestor);
for change in changes {
match change {
Patch::Add(key, value) | Patch::Replace(key, value) => {
set_attribute(element, &key, &value);
}
Patch::Remove(key) => {
remove_attribute(element, &key);
}
}
}
// `input` element has extra parameters to control
// I override behavior of attributes to make it more clear
// and useful in templates. For example I interpret `checked`
// attribute as `checked` parameter, not `defaultChecked` as browsers do
if let Ok(input) = InputElement::try_from(element.clone()) {
if let Some(change) = self.diff_kind(ancestor) {
match change {
Patch::Add(kind, _) | Patch::Replace(kind, _) => {
//https://github.com/koute/stdweb/commit/3b85c941db00b8e3c942624afd50c5929085fb08
//input.set_kind(&kind);
let input = &input;
js! { @(no_return)
@{input}.type = @{kind};
}
}
Patch::Remove(_) => {
//input.set_kind("");
let input = &input;
js! { @(no_return)
@{input}.type = "";
}
}
}
}
if let Some(change) = self.diff_value(ancestor) {
match change {
Patch::Add(kind, _) | Patch::Replace(kind, _) => {
input.set_raw_value(&kind);
}
Patch::Remove(_) => {
input.set_raw_value("");
}
}
}
// IMPORTANT! This parameters have to be set every time
// to prevent strange behaviour in browser when DOM changed
set_checked(&input, self.checked);
} else if let Ok(tae) = TextAreaElement::try_from(element.clone()) {
if let Some(change) = self.diff_value(ancestor) {
match change {
Patch::Add(value, _) | Patch::Replace(value, _) => {
tae.set_value(&value);
}
Patch::Remove(_) => {
tae.set_value("");
}
}
}
}
}
}
impl<COMP: Component> VDiff for VTag<COMP> {
type Component = COMP;
/// Remove VTag from parent.
fn detach(&mut self, parent: &Node) -> Option<Node> {
let node = self
.reference
.take()
.expect("tried to remove not rendered VTag from DOM");
let sibling = node.next_sibling();
if parent.remove_child(&node).is_err() {
warn!("Node not found to remove VTag");
}
sibling
}
/// Renders virtual tag over DOM `Element`, but it also compares this with an ancestor `VTag`
/// to compute what to patch in the actual DOM nodes.
fn apply(
&mut self,
parent: &Node,
precursor: Option<&Node>,
ancestor: Option<VNode<Self::Component>>,
env: &Scope<Self::Component>,
) -> Option<Node> {
assert!(
self.reference.is_none(),
"reference is ignored so must not be set"
);
let (reform, mut ancestor) = {
match ancestor {
Some(VNode::VTag(mut vtag)) => {
if self.tag == vtag.tag {
// If tags are equal, preserve the reference that already exists.
self.reference = vtag.reference.take();
(Reform::Keep, Some(vtag))
} else {
// We have to create a new reference, remove ancestor.
let node = vtag.detach(parent);
(Reform::Before(node), None)
}
}
Some(mut vnode) => {
// It is not a VTag variant we must remove the ancestor.
let node = vnode.detach(parent);
(Reform::Before(node), None)
}
None => (Reform::Before(None), None),
}
};
// Ensure that `self.reference` exists.
//
// This can use the previous reference or create a new one.
// If we create a new one we must insert it in the correct
// place, which we use `before` or `precusor` for.
match reform {
Reform::Keep => {}
Reform::Before(before) => {
let element = document()
.create_element(&self.tag)
.expect("can't create element for vtag");
if let Some(sibling) = before {
parent
.insert_before(&element, &sibling)
.expect("can't insert tag before sibling");
} else {
let precursor = precursor.and_then(|before| before.next_sibling());
if let Some(precursor) = precursor {
parent
.insert_before(&element, &precursor)
.expect("can't insert tag before precursor");
} else {
parent.append_child(&element);
}
}
self.reference = Some(element);
}
}
let element = self.reference.clone().expect("element expected");
{
let mut ancestor_childs = {
if let Some(ref mut a) = ancestor {
a.childs.drain(..).map(Some).collect::<Vec<_>>()
} else {
Vec::new()
}
};
self.apply_diffs(&element, &mut ancestor);
// Every render it removes all listeners and attach it back later
// TODO Compare references of handler to do listeners update better
if let Some(mut ancestor) = ancestor {
for handle in ancestor.captured.drain(..) {
handle.remove();
}
}
for mut listener in self.listeners.drain(..) {
let handle = listener.attach(&element, env.clone());
self.captured.push(handle);
}
let mut self_childs = self.childs.iter_mut().map(Some).collect::<Vec<_>>();
// Process children
let diff = self_childs.len() as i32 - ancestor_childs.len() as i32;
if diff > 0 {
for _ in 0..diff {
ancestor_childs.push(None);
}
} else if diff < 0 {
for _ in 0..-diff {
self_childs.push(None);
}
}
// Start with an empty precursor, because it put childs to itself
let mut precursor = None;
for pair in self_childs.into_iter().zip(ancestor_childs) {
match pair {
(Some(left), right) => {
precursor = left.apply(element.as_node(), precursor.as_ref(), right, &env);
}
(None, Some(mut right)) => {
right.detach(element.as_node());
}
(None, None) => {
panic!("redundant iterations during diff");
}
}
}
}
self.reference.as_ref().map(|e| e.as_node().to_owned())
}
}
impl<COMP: Component> fmt::Debug for VTag<COMP> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "VTag {{ tag: {} }}", self.tag)
}
}
/// `stdweb` doesn't have methods to work with attributes now.
/// this is [workaround](https://github.com/koute/stdweb/issues/16#issuecomment-325195854)
fn set_attribute(element: &Element, name: &str, value: &str) {
js!( @(no_return) @{element}.setAttribute( @{name}, @{value} ); );
}
/// Removes attribute from a element by name.
fn remove_attribute(element: &Element, name: &str) {
js!( @(no_return) @{element}.removeAttribute( @{name} ); );
}
/// Set `checked` value for the `InputElement`.
fn set_checked(input: &InputElement, value: bool) {
js!( @(no_return) @{input}.checked = @{value}; );
}
impl<COMP: Component> PartialEq for VTag<COMP> {
fn eq(&self, other: &VTag<COMP>) -> bool {
if self.tag != other.tag {
return false;
}
if self.value != other.value {
return false;
}
if self.kind != other.kind {
return false;
}
if self.checked != other.checked {
return false;
}
if self.listeners.len() != other.listeners.len() {
return false;
}
for i in 0..self.listeners.len() {
let a = &self.listeners[i];
let b = &other.listeners[i];
if a.kind() != b.kind() {
return false;
}
}
if self.attributes != other.attributes {
return false;
}
if self.classes != other.classes {
return false;
}
if self.childs.len() != other.childs.len() {
return false;
}
for i in 0..self.childs.len() {
let a = &self.childs[i];
let b = &other.childs[i];
if a != b {
return false;
}
}
true
}
}
| 36.951557 | 105 | 0.517839 |
1ad9208e93f6cb0394bf4295684cda7d4aded3b6 | 3,621 | use wasm_bindgen_test::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(module = "tests/wasm/imports.js")]
extern {
fn test_simple();
fn simple_foo(s: &str);
fn simple_another(a: u32) -> i32;
fn simple_take_and_return_bool(a: bool) -> bool;
fn simple_return_object() -> JsValue;
#[allow(dead_code)]
fn missing_symbol(s: &str);
fn return_string() -> String;
fn take_and_ret_string(s: String) -> String;
#[wasm_bindgen(js_name = take_and_ret_string)]
fn take_and_ret_string2(s: &str) -> String;
fn exceptions_throw();
#[wasm_bindgen(catch)]
fn exceptions_throw2() -> Result<(), JsValue>;
fn test_exception_propagates();
fn assert_valid_error(val: JsValue);
static IMPORT: JsValue;
#[wasm_bindgen(js_name = return_three)]
fn rust_name_for_return_three() -> u32;
fn underscore(_: u8);
#[wasm_bindgen(js_name = self)]
fn js_function_named_rust_keyword() -> u32;
type bar;
#[wasm_bindgen(js_namespace = bar, js_name = foo)]
static FOO: JsValue;
fn take_custom_type(f: CustomType) -> CustomType;
fn touch_custom_type();
fn custom_type_return_2() -> CustomType;
#[wasm_bindgen(js_name = interpret_2_as_custom_type)]
fn js_interpret_2_as_custom_type();
#[wasm_bindgen(js_name = "baz$")]
fn renamed_with_dollar_sign();
#[wasm_bindgen(js_name = "$foo")]
static RENAMED: JsValue;
fn unused_import();
fn assert_dead_import_not_generated();
}
#[wasm_bindgen]
extern {
fn parseInt(a: &str) -> u32;
}
#[wasm_bindgen_test]
fn simple() {
test_simple();
}
#[wasm_bindgen]
pub fn simple_take_str(s: &str) {
simple_foo(s);
}
#[wasm_bindgen]
pub fn simple_another_thunk(a: u32) -> i32 {
simple_another(a)
}
#[wasm_bindgen]
pub fn simple_bool_thunk(a: bool) -> bool {
simple_take_and_return_bool(a)
}
#[wasm_bindgen]
pub fn simple_get_the_object() -> JsValue {
simple_return_object()
}
#[wasm_bindgen_test]
fn string_ret() {
assert_eq!(return_string(), "bar");
}
#[wasm_bindgen_test]
fn strings() {
assert_eq!(take_and_ret_string(String::from("a")), "ab");
assert_eq!(take_and_ret_string2("b"), "bb");
}
#[wasm_bindgen_test]
fn exceptions() {
test_exception_propagates();
assert!(exceptions_throw2().is_err());
}
#[wasm_bindgen]
pub fn exceptions_propagate() {
exceptions_throw();
}
#[wasm_bindgen_test]
fn exn_caught() {
assert_valid_error(exceptions_throw2().unwrap_err());
}
#[wasm_bindgen_test]
fn free_imports() {
assert_eq!(parseInt("3"), 3);
}
#[wasm_bindgen_test]
fn import_a_field() {
assert_eq!(IMPORT.as_f64(), Some(1.0));
}
#[wasm_bindgen_test]
fn rename() {
assert_eq!(rust_name_for_return_three(), 3);
}
#[wasm_bindgen_test]
fn underscore_pattern() {
underscore(2);
}
#[wasm_bindgen_test]
fn rust_keyword() {
assert_eq!(js_function_named_rust_keyword(), 2);
}
#[wasm_bindgen_test]
fn rust_keyword2() {
assert_eq!(FOO.as_f64(), Some(3.0));
}
#[wasm_bindgen_test]
fn custom_type() {
take_custom_type(CustomType(()));
touch_custom_type();
js_interpret_2_as_custom_type();
}
#[wasm_bindgen]
pub fn interpret_2_as_custom_type() {
custom_type_return_2();
}
#[wasm_bindgen]
pub struct CustomType(());
#[wasm_bindgen]
impl CustomType {
pub fn touch(&self) {
panic!()
}
}
#[wasm_bindgen_test]
fn rename_with_string() {
renamed_with_dollar_sign();
}
#[wasm_bindgen_test]
fn rename_static_with_string() {
assert_eq!(RENAMED.as_f64(), Some(1.0));
}
#[wasm_bindgen_test]
fn dead_imports_not_generated() {
assert_dead_import_not_generated();
}
| 20.22905 | 61 | 0.684341 |
675ca4cb73a5e99282cd34c90a070fc00a69515d | 2,786 | #[doc = "Reader of register TER"]
pub type R = crate::R<u32, super::TER>;
#[doc = "Writer for register TER"]
pub type W = crate::W<u32, super::TER>;
#[doc = "Register TER `reset()`'s with value 0x80"]
impl crate::ResetValue for super::TER {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x80
}
}
#[doc = "Reader of field `TXEN`"]
pub type TXEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TXEN`"]
pub struct TXEN_W<'a> {
w: &'a mut W,
}
impl<'a> TXEN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
impl R {
#[doc = "Bit 7 - When this bit is 1, as it is after a Reset, data written to the THR is output on the TXD pin as soon as any preceding data has been sent. If this bit cleared to 0 while a character is being sent, the transmission of that character is completed, but no further characters are sent until this bit is set again. In other words, a 0 in this bit blocks the transfer of characters from the THR or TX FIFO into the transmit shift register. Software can clear this bit when it detects that the a hardware-handshaking TX-permit signal (CTS) has gone false, or with software handshaking, when it receives an XOFF character (DC3). Software can set this bit again when it detects that the TX-permit signal has gone true, or when it receives an XON (DC1) character."]
#[inline(always)]
pub fn txen(&self) -> TXEN_R {
TXEN_R::new(((self.bits >> 7) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 7 - When this bit is 1, as it is after a Reset, data written to the THR is output on the TXD pin as soon as any preceding data has been sent. If this bit cleared to 0 while a character is being sent, the transmission of that character is completed, but no further characters are sent until this bit is set again. In other words, a 0 in this bit blocks the transfer of characters from the THR or TX FIFO into the transmit shift register. Software can clear this bit when it detects that the a hardware-handshaking TX-permit signal (CTS) has gone false, or with software handshaking, when it receives an XOFF character (DC3). Software can set this bit again when it detects that the TX-permit signal has gone true, or when it receives an XON (DC1) character."]
#[inline(always)]
pub fn txen(&mut self) -> TXEN_W {
TXEN_W { w: self }
}
}
| 54.627451 | 775 | 0.666906 |
f8a9c9b119a66b0f253fd4100d347dc1a8d1c24f | 5,983 | use crate::extensions::NodeExt as _;
use crate::hud;
use crate::mob;
use crate::player;
use gdnative::api::*;
use gdnative::*;
use rand::*;
use std::f64::consts::PI;
#[derive(Debug, Clone, PartialEq)]
pub enum ManageErrs {
CouldNotMakeInstance,
RootClassNotRigidBody2D(String),
}
#[derive(NativeClass)]
#[inherit(Node)]
#[user_data(user_data::LocalCellData<Main>)]
pub struct Main {
#[property]
mob: PackedScene,
score: i64,
}
#[methods]
impl Main {
fn _init(_owner: Node) -> Self {
Main {
mob: PackedScene::new(),
score: 0,
}
}
#[export]
fn _ready(&self, _owner: Node) {}
#[export]
unsafe fn game_over(&self, owner: Node) {
let score_timer: Timer = owner
.get_typed_node("score_timer")
.expect("Unable to cast to Timer");
let mob_timer: Timer = owner
.get_typed_node("mob_timer")
.expect("Unable to cast to Timer");
score_timer.stop();
mob_timer.stop();
let hud_node: CanvasLayer = owner
.get_typed_node("hud")
.expect("Unable to cast to CanvasLayer");
Instance::<hud::HUD>::try_from_unsafe_base(hud_node)
.and_then(|hud| hud.map(|x, o| x.show_game_over(o)).ok())
.unwrap_or_else(|| godot_print!("Unable to get hud"));
}
#[export]
unsafe fn new_game(&mut self, owner: Node) {
let start_position: Position2D = owner
.get_typed_node("start_position")
.expect("Unable to cast to Position2D");
let player: Area2D = owner
.get_typed_node("player")
.expect("Unable to cast to Area2D");
let start_timer: Timer = owner
.get_typed_node("start_timer")
.expect("Unable to cast to Timer");
self.score = 0;
Instance::<player::Player>::try_from_unsafe_base(player)
.and_then(|player| {
player
.map(|x, o| x.start(o, start_position.position()))
.ok()
})
.unwrap_or_else(|| godot_print!("Unable to get player"));
start_timer.start(0.0);
let hud_node: CanvasLayer = owner
.get_typed_node("hud")
.expect("Unable to cast to CanvasLayer");
Instance::<hud::HUD>::try_from_unsafe_base(hud_node)
.and_then(|hud| {
hud.map(|x, o| {
x.update_score(o, self.score);
x.show_message(o, "Get Ready".into());
})
.ok()
})
.unwrap_or_else(|| godot_print!("Unable to get hud"));
}
#[export]
unsafe fn on_start_timer_timeout(&self, owner: Node) {
owner
.get_typed_node::<Timer, _>("mob_timer")
.expect("Unable to cast to Timer")
.start(0.0);
owner
.get_typed_node::<Timer, _>("score_timer")
.expect("Unable to cast to Timer")
.start(0.0);
}
#[export]
unsafe fn on_score_timer_timeout(&mut self, owner: Node) {
self.score += 1;
let hud_node: CanvasLayer = owner
.get_typed_node("hud")
.expect("Unable to cast to CanvasLayer");
Instance::<hud::HUD>::try_from_unsafe_base(hud_node)
.and_then(|hud| hud.map(|x, o| x.update_score(o, self.score)).ok())
.unwrap_or_else(|| godot_print!("Unable to get hud"));
}
#[export]
unsafe fn on_mob_timer_timeout(&self, owner: Node) {
let mob_spawn_location: PathFollow2D = owner
.get_typed_node("mob_path/mob_spawn_locations")
.expect("Unable to cast to PathFollow2D");
let mob_scene: RigidBody2D = instance_scene(&self.mob).unwrap();
let mut rng = rand::thread_rng();
let offset = rng.gen_range(std::u32::MIN, std::u32::MAX);
mob_spawn_location.set_offset(offset.into());
owner.add_child(Some(mob_scene.to_node()), false);
let mut direction = mob_spawn_location.rotation() + PI / 2.0;
mob_scene.set_position(mob_spawn_location.position());
direction += rng.gen_range(-PI / 4.0, PI / 4.0);
mob_scene.set_rotation(direction);
let d = direction as f32;
let mob = Instance::<mob::Mob>::try_from_unsafe_base(mob_scene).unwrap();
mob.map(|x, mob_owner| {
mob_scene
.set_linear_velocity(Vector2::new(rng.gen_range(x.min_speed, x.max_speed), 0.0));
mob_scene
.set_linear_velocity(mob_scene.linear_velocity().rotated(Angle { radians: d }));
let hud_node: CanvasLayer = owner
.get_typed_node("hud")
.expect("Unable to cast to CanvasLayer");
let hud = Instance::<hud::HUD>::try_from_unsafe_base(hud_node).unwrap();
hud.map(|_, o| {
o.connect(
"start_game".into(),
Some(mob_owner.to_object()),
"on_start_game".into(),
VariantArray::new_shared(),
0,
)
.unwrap();
})
.unwrap();
})
.unwrap();
}
}
/// Root here is needs to be the same type (or a parent type) of the node that you put in the child
/// scene as the root. For instance Spatial is used for this example.
unsafe fn instance_scene<Root>(scene: &PackedScene) -> Result<Root, ManageErrs>
where
Root: gdnative::GodotObject,
{
let inst_option = scene.instance(PackedScene::GEN_EDIT_STATE_DISABLED);
if let Some(instance) = inst_option {
if let Some(instance_root) = instance.cast::<Root>() {
Ok(instance_root)
} else {
Err(ManageErrs::RootClassNotRigidBody2D(
instance.name().to_string(),
))
}
} else {
Err(ManageErrs::CouldNotMakeInstance)
}
}
| 30.52551 | 99 | 0.557747 |
5bb6caee621fe7d00fad5d2926c249cbfce63c6c | 753 | use crate::{
format_elements, group_elements, space_token, FormatElement, Formatter, ToFormatElement,
};
use rslint_parser::ast::IfStmt;
impl ToFormatElement for IfStmt {
fn to_format_element(&self, formatter: &Formatter) -> Option<FormatElement> {
let mut result = format_elements![
group_elements(format_elements![
formatter.format_token(&self.if_token()?)?,
space_token(),
formatter.format_node(self.condition()?)?,
space_token(),
]),
formatter.format_node(self.cons()?)?
];
if let Some(else_token) = self.else_token() {
result = format_elements![
result,
space_token(),
formatter.format_token(&else_token)?,
space_token(),
formatter.format_node(self.alt()?)?,
]
};
Some(result)
}
}
| 24.290323 | 89 | 0.690571 |
e64e8a1988d7e1aba0567af0b8f441b9ea1d9b41 | 438 | pub mod app;
mod cmd;
type Action = fn() -> anyhow::Result<()>;
pub struct Argument {
name: String,
usage: String,
value: Value,
hidden: bool,
required: bool,
aliases: Vec<String>,
env_vars: Vec<String>,
description: String,
}
pub enum Value{
Bool(bool),
I32(i32),
U32(u32),
I64(i64),
U64(u64),
String(String)
}
pub struct Author {
name: String,
email: Option<String>,
} | 15.103448 | 41 | 0.586758 |
ab5d410e7965dfde121e9c62bb4740f28d635a99 | 6,050 | // 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 {
crate::fidl_processor::{process_stream, RequestContext},
crate::switchboard::base::*,
crate::switchboard::hanging_get_handler::Sender,
failure::format_err,
fidl_fuchsia_settings::*,
fuchsia_async as fasync,
fuchsia_syslog::fx_log_err,
futures::future::LocalBoxFuture,
futures::prelude::*,
};
impl Sender<SystemSettings> for SystemWatchResponder {
fn send_response(self, data: SystemSettings) {
self.send(&mut Ok(data)).unwrap();
}
}
impl From<SettingResponse> for SystemSettings {
fn from(response: SettingResponse) -> Self {
if let SettingResponse::System(info) = response {
let mut system_settings = fidl_fuchsia_settings::SystemSettings::empty();
system_settings.mode =
Some(fidl_fuchsia_settings::LoginOverride::from(info.login_override_mode));
system_settings
} else {
panic!("incorrect value sent to system");
}
}
}
pub fn spawn_system_fidl_handler(
switchboard_handle: SwitchboardHandle,
stream: SystemRequestStream,
) {
process_stream::<SystemMarker, SystemSettings, SystemWatchResponder>(
stream,
switchboard_handle,
SettingType::System,
Box::new(
move |context,
req|
-> LocalBoxFuture<'_, Result<Option<SystemRequest>, failure::Error>> {
async move {
#[allow(unreachable_patterns)]
match req {
SystemRequest::Set { settings, responder } => {
if let Some(mode) = settings.mode {
change_login_override(
context.clone(),
SystemLoginOverrideMode::from(mode),
responder,
);
}
}
SystemRequest::Watch { responder } => {
context.watch(responder).await;
}
_ => {
return Ok(Some(req));
}
}
return Ok(None);
}
.boxed_local()
},
),
);
}
/// Sets the login mode and schedules accounts to be cleared. Upon success, the
/// device is scheduled to reboot so the change will take effect.
fn change_login_override(
context: RequestContext<SystemSettings, SystemWatchResponder>,
mode: SystemLoginOverrideMode,
responder: SystemSetResponder,
) {
fasync::spawn(async move {
let login_override_result = request(
context.switchboard.clone(),
SettingType::System,
SettingRequest::SetLoginOverrideMode(mode),
"set login override",
)
.await;
if login_override_result.is_err() {
responder.send(&mut Err(fidl_fuchsia_settings::Error::Failed)).ok();
return;
}
let schedule_account_clear_result = request(
context.switchboard.clone(),
SettingType::Account,
SettingRequest::ScheduleClearAccounts,
"clear accounts",
)
.await;
if schedule_account_clear_result.is_err() {
responder.send(&mut Err(fidl_fuchsia_settings::Error::Failed)).ok();
return;
}
let restart_result = request(
context.switchboard.clone(),
SettingType::Power,
SettingRequest::Reboot,
"rebooting",
)
.await;
if restart_result.is_err() {
responder.send(&mut Err(fidl_fuchsia_settings::Error::Failed)).ok();
return;
}
responder.send(&mut Ok(())).ok();
});
}
async fn request(
switchboard: SwitchboardHandle,
setting_type: SettingType,
setting_request: SettingRequest,
description: &str,
) -> SettingResponseResult {
let (response_tx, response_rx) = futures::channel::oneshot::channel::<SettingResponseResult>();
let result =
switchboard.clone().lock().await.request(setting_type, setting_request, response_tx);
match result {
Ok(()) => match response_rx.await {
Ok(result) => {
return result;
}
Err(error) => {
fx_log_err!("request failed: {} error: {}", description, error);
return Err(format_err!("request failed: {} error: {}", description, error));
}
},
Err(error) => {
fx_log_err!("request failed: {} error: {}", description, error);
return Err(error);
}
}
}
impl From<fidl_fuchsia_settings::LoginOverride> for SystemLoginOverrideMode {
fn from(item: fidl_fuchsia_settings::LoginOverride) -> Self {
match item {
fidl_fuchsia_settings::LoginOverride::AutologinGuest => {
SystemLoginOverrideMode::AutologinGuest
}
fidl_fuchsia_settings::LoginOverride::AuthProvider => {
SystemLoginOverrideMode::AuthProvider
}
fidl_fuchsia_settings::LoginOverride::None => SystemLoginOverrideMode::None,
}
}
}
impl From<SystemLoginOverrideMode> for fidl_fuchsia_settings::LoginOverride {
fn from(item: SystemLoginOverrideMode) -> Self {
match item {
SystemLoginOverrideMode::AutologinGuest => {
fidl_fuchsia_settings::LoginOverride::AutologinGuest
}
SystemLoginOverrideMode::AuthProvider => {
fidl_fuchsia_settings::LoginOverride::AuthProvider
}
SystemLoginOverrideMode::None => fidl_fuchsia_settings::LoginOverride::None,
}
}
}
| 33.798883 | 99 | 0.564628 |
080fc56e77ea2d7a059682260b64ef6bb0b698b4 | 279 | extern crate protoc_grpcio;
fn main() {
let proto_root = "src/protos";
println!("cargo:rerun-if-changed={}", proto_root);
protoc_grpcio::compile_grpc_protos(&["api.proto"], &[proto_root], &proto_root, None)
.expect("Failed to compile gRPC definitions!");
}
| 27.9 | 88 | 0.673835 |
229962cbcca2846fa402b3166fd7903b891ec1c4 | 16,161 | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::account_address::AccountAddress;
use crate::transaction::{RawUserTransaction, SignedUserTransaction};
use anyhow::{ensure, Error, Result};
#[cfg(any(test, feature = "fuzzing"))]
use proptest_derive::Arbitrary;
use rand::{rngs::OsRng, Rng};
use serde::{Deserialize, Serialize};
use starcoin_crypto::ed25519::{
Ed25519PrivateKey, ED25519_PRIVATE_KEY_LENGTH, ED25519_PUBLIC_KEY_LENGTH,
};
use starcoin_crypto::multi_ed25519::multi_shard::{
MultiEd25519KeyShard, MultiEd25519SignatureShard,
};
use starcoin_crypto::{
derive::{DeserializeKey, SerializeKey},
ed25519::{Ed25519PublicKey, Ed25519Signature},
hash::{CryptoHash, CryptoHasher},
multi_ed25519::{MultiEd25519PublicKey, MultiEd25519Signature},
traits::Signature,
CryptoMaterialError, HashValue, PrivateKey, SigningKey, ValidCryptoMaterial,
ValidCryptoMaterialStringExt,
};
use std::{convert::TryFrom, fmt, str::FromStr};
/// A `TransactionAuthenticator` is an an abstraction of a signature scheme. It must know:
/// (1) How to check its signature against a message and public key
/// (2) How to convert its public key into an `AuthenticationKeyPreimage` structured as
/// (public_key | signaure_scheme_id).
/// Each on-chain `DiemAccount` must store an `AuthenticationKey` (computed via a sha3 hash of an
/// `AuthenticationKeyPreimage`).
/// Each transaction submitted to the Diem blockchain contains a `TransactionAuthenticator`. During
/// transaction execution, the executor will check if the `TransactionAuthenticator`'s signature on
/// the transaction hash is well-formed (1) and whether the sha3 hash of the
/// `TransactionAuthenticator`'s `AuthenticationKeyPreimage` matches the `AuthenticationKey` stored
/// under the transaction's sender account address (2).
// TODO: in the future, can tie these to the TransactionAuthenticator enum directly with https://github.com/rust-lang/rust/issues/60553
#[derive(Debug)]
#[repr(u8)]
pub enum Scheme {
Ed25519 = 0,
MultiEd25519 = 1,
// ... add more schemes here
}
impl fmt::Display for Scheme {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let display = match self {
Scheme::Ed25519 => "Ed25519",
Scheme::MultiEd25519 => "MultiEd25519",
};
write!(f, "Scheme::{}", display)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub enum TransactionAuthenticator {
/// Single signature
Ed25519 {
public_key: Ed25519PublicKey,
signature: Ed25519Signature,
},
/// K-of-N multisignature
MultiEd25519 {
public_key: MultiEd25519PublicKey,
signature: MultiEd25519Signature,
},
// ... add more schemes here
}
impl TransactionAuthenticator {
/// Unique identifier for the signature scheme
pub fn scheme(&self) -> Scheme {
match self {
Self::Ed25519 { .. } => Scheme::Ed25519,
Self::MultiEd25519 { .. } => Scheme::MultiEd25519,
}
}
/// Create a single-signature ed25519 authenticator
pub fn ed25519(public_key: Ed25519PublicKey, signature: Ed25519Signature) -> Self {
Self::Ed25519 {
public_key,
signature,
}
}
/// Create a multisignature ed25519 authenticator
pub fn multi_ed25519(
public_key: MultiEd25519PublicKey,
signature: MultiEd25519Signature,
) -> Self {
Self::MultiEd25519 {
public_key,
signature,
}
}
/// Return Ok if the authenticator's public key matches its signature, Err otherwise
pub fn verify<T: Serialize + CryptoHash>(&self, message: &T) -> Result<()> {
match self {
Self::Ed25519 {
public_key,
signature,
} => signature.verify(message, public_key),
Self::MultiEd25519 {
public_key,
signature,
} => signature.verify(message, public_key),
}
}
/// Return the raw bytes of `self.public_key`
pub fn public_key_bytes(&self) -> Vec<u8> {
match self {
Self::Ed25519 { public_key, .. } => public_key.to_bytes().to_vec(),
Self::MultiEd25519 { public_key, .. } => public_key.to_bytes().to_vec(),
}
}
pub fn public_key(&self) -> AccountPublicKey {
match self {
Self::Ed25519 { public_key, .. } => AccountPublicKey::Single(public_key.clone()),
Self::MultiEd25519 { public_key, .. } => AccountPublicKey::Multi(public_key.clone()),
}
}
/// Return the raw bytes of `self.signature`
pub fn signature_bytes(&self) -> Vec<u8> {
match self {
Self::Ed25519 { signature, .. } => signature.to_bytes().to_vec(),
Self::MultiEd25519 { signature, .. } => signature.to_bytes().to_vec(),
}
}
/// Return an authentication key preimage derived from `self`'s public key and scheme id
pub fn authentication_key_preimage(&self) -> AuthenticationKeyPreimage {
AuthenticationKeyPreimage::new(self.public_key_bytes(), self.scheme())
}
/// Return an authentication key derived from `self`'s public key and scheme id
pub fn authentication_key(&self) -> AuthenticationKey {
AuthenticationKey::from_preimage(&self.authentication_key_preimage())
}
}
/// A struct that represents an account authentication key. An account's address is the last 16
/// bytes of authentication key used to create it
#[derive(
Clone,
Copy,
CryptoHasher,
Debug,
DeserializeKey,
Eq,
Hash,
Ord,
PartialEq,
PartialOrd,
SerializeKey,
)]
#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))]
pub struct AuthenticationKey([u8; AuthenticationKey::LENGTH]);
impl AuthenticationKey {
/// Create an authentication key from `bytes`
pub const fn new(bytes: [u8; Self::LENGTH]) -> Self {
Self(bytes)
}
/// The number of bytes in an authentication key.
pub const LENGTH: usize = 32;
/// Create an authentication key from a preimage by taking its sha3 hash
pub fn from_preimage(preimage: &AuthenticationKeyPreimage) -> AuthenticationKey {
AuthenticationKey::new(*HashValue::sha3_256_of(&preimage.0).as_ref())
}
/// Create an authentication key from an Ed25519 public key
pub fn ed25519(public_key: &Ed25519PublicKey) -> AuthenticationKey {
Self::from_preimage(&AuthenticationKeyPreimage::ed25519(public_key))
}
/// Create an authentication key from a MultiEd25519 public key
pub fn multi_ed25519(public_key: &MultiEd25519PublicKey) -> Self {
Self::from_preimage(&AuthenticationKeyPreimage::multi_ed25519(public_key))
}
/// Return an address derived from the last `AccountAddress::LENGTH` bytes of this
/// authentication key.
pub fn derived_address(&self) -> AccountAddress {
// keep only last 16 bytes
let mut array = [0u8; AccountAddress::LENGTH];
array.copy_from_slice(&self.0[Self::LENGTH - AccountAddress::LENGTH..]);
AccountAddress::new(array)
}
/// Return the first AccountAddress::LENGTH bytes of this authentication key
pub fn prefix(&self) -> [u8; AccountAddress::LENGTH] {
let mut array = [0u8; AccountAddress::LENGTH];
array.copy_from_slice(&self.0[..AccountAddress::LENGTH]);
array
}
/// Construct a vector from this authentication key
pub fn to_vec(&self) -> Vec<u8> {
self.0.to_vec()
}
/// Create a random authentication key. For testing only
pub fn random() -> Self {
let mut rng = OsRng;
let buf: [u8; Self::LENGTH] = rng.gen();
AuthenticationKey::new(buf)
}
}
impl ValidCryptoMaterial for AuthenticationKey {
fn to_bytes(&self) -> Vec<u8> {
self.to_vec()
}
}
/// A value that can be hashed to produce an authentication key
pub struct AuthenticationKeyPreimage(Vec<u8>);
impl AuthenticationKeyPreimage {
/// Return bytes for (public_key | scheme_id)
fn new(mut public_key_bytes: Vec<u8>, scheme: Scheme) -> Self {
public_key_bytes.push(scheme as u8);
Self(public_key_bytes)
}
/// Construct a preimage from an Ed25519 public key
pub fn ed25519(public_key: &Ed25519PublicKey) -> AuthenticationKeyPreimage {
Self::new(public_key.to_bytes().to_vec(), Scheme::Ed25519)
}
/// Construct a preimage from a MultiEd25519 public key
pub fn multi_ed25519(public_key: &MultiEd25519PublicKey) -> AuthenticationKeyPreimage {
Self::new(public_key.to_bytes(), Scheme::MultiEd25519)
}
/// Construct a vector from this authentication key
pub fn into_vec(self) -> Vec<u8> {
self.0
}
}
impl fmt::Display for TransactionAuthenticator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"TransactionAuthenticator[scheme id: {:?}, public key: {}, signature: {}]",
self.scheme(),
hex::encode(&self.public_key_bytes()),
hex::encode(&self.signature_bytes())
)
}
}
impl TryFrom<&[u8]> for AuthenticationKey {
type Error = CryptoMaterialError;
fn try_from(bytes: &[u8]) -> std::result::Result<AuthenticationKey, CryptoMaterialError> {
if bytes.len() != Self::LENGTH {
return Err(CryptoMaterialError::WrongLengthError);
}
let mut addr = [0u8; Self::LENGTH];
addr.copy_from_slice(bytes);
Ok(AuthenticationKey(addr))
}
}
impl TryFrom<Vec<u8>> for AuthenticationKey {
type Error = CryptoMaterialError;
fn try_from(bytes: Vec<u8>) -> std::result::Result<AuthenticationKey, CryptoMaterialError> {
AuthenticationKey::try_from(&bytes[..])
}
}
impl FromStr for AuthenticationKey {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
ensure!(
!s.is_empty(),
"authentication key string should not be empty.",
);
Ok(AuthenticationKey::from_encoded_string(s)?)
}
}
impl AsRef<[u8]> for AuthenticationKey {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl fmt::LowerHex for AuthenticationKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", hex::encode(&self.0))
}
}
impl fmt::Display for AuthenticationKey {
fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
// Forward to the LowerHex impl with a "0x" prepended (the # flag).
write!(f, "0x{:#x}", self)
}
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, DeserializeKey, SerializeKey)]
pub enum AccountPublicKey {
Single(Ed25519PublicKey),
Multi(MultiEd25519PublicKey),
}
#[derive(Eq, PartialEq, Debug, DeserializeKey, SerializeKey)]
pub enum AccountPrivateKey {
Single(Ed25519PrivateKey),
Multi(MultiEd25519KeyShard),
}
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum AccountSignature {
Single(Ed25519PublicKey, Ed25519Signature),
Multi(MultiEd25519PublicKey, MultiEd25519SignatureShard),
}
impl ValidCryptoMaterial for AccountPublicKey {
fn to_bytes(&self) -> Vec<u8> {
match self {
Self::Single(key) => key.to_bytes().to_vec(),
Self::Multi(key) => key.to_bytes(),
}
}
}
impl AccountPublicKey {
pub fn derived_address(&self) -> AccountAddress {
self.authentication_key().derived_address()
}
/// Return an authentication key preimage derived from `self`'s public key and scheme id
pub fn authentication_key_preimage(&self) -> AuthenticationKeyPreimage {
match self {
Self::Single(p) => AuthenticationKeyPreimage::ed25519(p),
Self::Multi(p) => AuthenticationKeyPreimage::multi_ed25519(p),
}
}
/// Return an authentication key derived from `self`'s public key and scheme id
pub fn authentication_key(&self) -> AuthenticationKey {
AuthenticationKey::from_preimage(&self.authentication_key_preimage())
}
/// Return the raw bytes of `self.public_key`
pub fn public_key_bytes(&self) -> Vec<u8> {
match self {
Self::Single(public_key) => public_key.to_bytes().to_vec(),
Self::Multi(public_key) => public_key.to_bytes().to_vec(),
}
}
/// Unique identifier for the signature scheme
pub fn scheme(&self) -> Scheme {
match self {
Self::Single { .. } => Scheme::Ed25519,
Self::Multi { .. } => Scheme::MultiEd25519,
}
}
pub fn as_single(&self) -> Option<Ed25519PublicKey> {
match self {
Self::Single(key) => Some(key.clone()),
_ => None,
}
}
pub fn as_multi(&self) -> Option<MultiEd25519PublicKey> {
match self {
Self::Multi(key) => Some(key.clone()),
_ => None,
}
}
}
impl TryFrom<&[u8]> for AccountPublicKey {
type Error = CryptoMaterialError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
if value.len() == ED25519_PUBLIC_KEY_LENGTH {
Ed25519PublicKey::try_from(value).map(Self::Single)
} else {
MultiEd25519PublicKey::try_from(value).map(Self::Multi)
}
}
}
impl Into<AccountPublicKey> for Ed25519PublicKey {
fn into(self) -> AccountPublicKey {
AccountPublicKey::Single(self)
}
}
impl Into<AccountPublicKey> for MultiEd25519PublicKey {
fn into(self) -> AccountPublicKey {
AccountPublicKey::Multi(self)
}
}
impl ValidCryptoMaterial for AccountPrivateKey {
fn to_bytes(&self) -> Vec<u8> {
match self {
Self::Single(key) => key.to_bytes().to_vec(),
Self::Multi(key) => key.to_bytes(),
}
}
}
impl AccountPrivateKey {
pub fn public_key(&self) -> AccountPublicKey {
match self {
Self::Single(key) => AccountPublicKey::Single(key.public_key()),
Self::Multi(key) => AccountPublicKey::Multi(key.public_key()),
}
}
pub fn sign<T: CryptoHash + Serialize>(&self, message: &T) -> AccountSignature {
match self {
Self::Single(key) => AccountSignature::Single(key.public_key(), key.sign(message)),
Self::Multi(key) => AccountSignature::Multi(key.public_key(), key.sign(message)),
}
}
}
impl Into<AccountPrivateKey> for Ed25519PrivateKey {
fn into(self) -> AccountPrivateKey {
AccountPrivateKey::Single(self)
}
}
impl Into<AccountPrivateKey> for MultiEd25519KeyShard {
fn into(self) -> AccountPrivateKey {
AccountPrivateKey::Multi(self)
}
}
impl TryFrom<&[u8]> for AccountPrivateKey {
type Error = CryptoMaterialError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
if value.len() == ED25519_PRIVATE_KEY_LENGTH {
Ed25519PrivateKey::try_from(value).map(Self::Single)
} else {
MultiEd25519KeyShard::try_from(value).map(Self::Multi)
}
}
}
impl AccountSignature {
pub fn build_transaction(self, raw_txn: RawUserTransaction) -> Result<SignedUserTransaction> {
Ok(match self {
Self::Single(public_key, signature) => {
SignedUserTransaction::ed25519(raw_txn, public_key, signature)
}
Self::Multi(public_key, signature) => {
if signature.is_enough() {
SignedUserTransaction::multi_ed25519(raw_txn, public_key, signature.into())
} else {
anyhow::bail!(
"MultiEd25519SignatureShard do not have enough signatures, current: {}, threshold: {}",
signature.signatures().len(),
signature.threshold()
)
}
}
})
}
}
#[cfg(test)]
mod tests {
use crate::transaction::authenticator::AuthenticationKey;
use std::str::FromStr;
#[test]
fn test_from_str_should_not_panic_by_given_empty_string() {
assert!(AuthenticationKey::from_str("").is_err());
}
}
| 32.582661 | 135 | 0.635171 |
0ae971542a04b897774d0a025eaf268c5df2b2b5 | 15,887 | // Copyright (c) 2017 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
use std::fmt;
use std::hash::Hash;
use std::hash::Hasher;
use std::marker::PhantomData;
use std::ptr;
use std::sync::Arc;
use std::u32;
use buffer::BufferAccess;
use descriptor::descriptor::DescriptorDesc;
use descriptor::descriptor_set::UnsafeDescriptorSetLayout;
use descriptor::pipeline_layout::PipelineLayoutDesc;
use descriptor::pipeline_layout::PipelineLayoutDescPcRange;
use descriptor::pipeline_layout::PipelineLayoutSys;
use descriptor::PipelineLayoutAbstract;
use device::Device;
use device::DeviceOwned;
use format::ClearValue;
use framebuffer::AttachmentDescription;
use framebuffer::PassDependencyDescription;
use framebuffer::PassDescription;
use framebuffer::RenderPassAbstract;
use framebuffer::RenderPassDesc;
use framebuffer::RenderPassDescClearValues;
use framebuffer::RenderPassSys;
use framebuffer::Subpass;
use pipeline::shader::EmptyEntryPointDummy;
use pipeline::vertex::BufferlessDefinition;
use pipeline::vertex::IncompatibleVertexDefinitionError;
use pipeline::vertex::VertexDefinition;
use pipeline::vertex::VertexSource;
use vk;
use SafeDeref;
use VulkanObject;
pub use self::builder::GraphicsPipelineBuilder;
pub use self::creation_error::GraphicsPipelineCreationError;
mod builder;
mod creation_error;
// FIXME: restore
//mod tests;
/// Defines how the implementation should perform a draw operation.
///
/// This object contains the shaders and the various fixed states that describe how the
/// implementation should perform the various operations needed by a draw command.
pub struct GraphicsPipeline<VertexDefinition, Layout, RenderP> {
inner: Inner,
layout: Layout,
render_pass: RenderP,
render_pass_subpass: u32,
vertex_definition: VertexDefinition,
dynamic_line_width: bool,
dynamic_viewport: bool,
dynamic_scissor: bool,
dynamic_depth_bias: bool,
dynamic_depth_bounds: bool,
dynamic_stencil_compare_mask: bool,
dynamic_stencil_write_mask: bool,
dynamic_stencil_reference: bool,
dynamic_blend_constants: bool,
num_viewports: u32,
}
#[derive(PartialEq, Eq, Hash)]
struct Inner {
pipeline: vk::Pipeline,
device: Arc<Device>,
}
impl GraphicsPipeline<(), (), ()> {
/// Starts the building process of a graphics pipeline. Returns a builder object that you can
/// fill with the various parameters.
pub fn start<'a>() -> GraphicsPipelineBuilder<
BufferlessDefinition,
EmptyEntryPointDummy,
(),
EmptyEntryPointDummy,
(),
EmptyEntryPointDummy,
(),
EmptyEntryPointDummy,
(),
EmptyEntryPointDummy,
(),
(),
> {
GraphicsPipelineBuilder::new()
}
}
impl<Mv, L, Rp> GraphicsPipeline<Mv, L, Rp> {
/// Returns the vertex definition used in the constructor.
#[inline]
pub fn vertex_definition(&self) -> &Mv {
&self.vertex_definition
}
/// Returns the device used to create this pipeline.
#[inline]
pub fn device(&self) -> &Arc<Device> {
&self.inner.device
}
}
impl<Mv, L, Rp> GraphicsPipeline<Mv, L, Rp>
where
L: PipelineLayoutAbstract,
{
/// Returns the pipeline layout used in the constructor.
#[inline]
pub fn layout(&self) -> &L {
&self.layout
}
}
impl<Mv, L, Rp> GraphicsPipeline<Mv, L, Rp>
where
Rp: RenderPassDesc,
{
/// Returns the pass used in the constructor.
#[inline]
pub fn subpass(&self) -> Subpass<&Rp> {
Subpass::from(&self.render_pass, self.render_pass_subpass).unwrap()
}
}
impl<Mv, L, Rp> GraphicsPipeline<Mv, L, Rp> {
/// Returns the render pass used in the constructor.
#[inline]
pub fn render_pass(&self) -> &Rp {
&self.render_pass
}
/// Returns true if the line width used by this pipeline is dynamic.
#[inline]
pub fn has_dynamic_line_width(&self) -> bool {
self.dynamic_line_width
}
/// Returns the number of viewports and scissors of this pipeline.
#[inline]
pub fn num_viewports(&self) -> u32 {
self.num_viewports
}
/// Returns true if the viewports used by this pipeline are dynamic.
#[inline]
pub fn has_dynamic_viewports(&self) -> bool {
self.dynamic_viewport
}
/// Returns true if the scissors used by this pipeline are dynamic.
#[inline]
pub fn has_dynamic_scissors(&self) -> bool {
self.dynamic_scissor
}
/// Returns true if the depth bounds used by this pipeline are dynamic.
#[inline]
pub fn has_dynamic_depth_bounds(&self) -> bool {
self.dynamic_depth_bounds
}
/// Returns true if the stencil compare masks used by this pipeline are dynamic.
#[inline]
pub fn has_dynamic_stencil_compare_mask(&self) -> bool {
self.dynamic_stencil_compare_mask
}
/// Returns true if the stencil write masks used by this pipeline are dynamic.
#[inline]
pub fn has_dynamic_stencil_write_mask(&self) -> bool {
self.dynamic_stencil_write_mask
}
/// Returns true if the stencil references used by this pipeline are dynamic.
#[inline]
pub fn has_dynamic_stencil_reference(&self) -> bool {
self.dynamic_stencil_reference
}
}
unsafe impl<Mv, L, Rp> PipelineLayoutAbstract for GraphicsPipeline<Mv, L, Rp>
where
L: PipelineLayoutAbstract,
{
#[inline]
fn sys(&self) -> PipelineLayoutSys {
self.layout.sys()
}
#[inline]
fn descriptor_set_layout(&self, index: usize) -> Option<&Arc<UnsafeDescriptorSetLayout>> {
self.layout.descriptor_set_layout(index)
}
}
unsafe impl<Mv, L, Rp> PipelineLayoutDesc for GraphicsPipeline<Mv, L, Rp>
where
L: PipelineLayoutDesc,
{
#[inline]
fn num_sets(&self) -> usize {
self.layout.num_sets()
}
#[inline]
fn num_bindings_in_set(&self, set: usize) -> Option<usize> {
self.layout.num_bindings_in_set(set)
}
#[inline]
fn descriptor(&self, set: usize, binding: usize) -> Option<DescriptorDesc> {
self.layout.descriptor(set, binding)
}
#[inline]
fn num_push_constants_ranges(&self) -> usize {
self.layout.num_push_constants_ranges()
}
#[inline]
fn push_constants_range(&self, num: usize) -> Option<PipelineLayoutDescPcRange> {
self.layout.push_constants_range(num)
}
}
unsafe impl<Mv, L, Rp> DeviceOwned for GraphicsPipeline<Mv, L, Rp> {
#[inline]
fn device(&self) -> &Arc<Device> {
&self.inner.device
}
}
impl<Mv, L, Rp> fmt::Debug for GraphicsPipeline<Mv, L, Rp> {
#[inline]
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fmt, "<Vulkan graphics pipeline {:?}>", self.inner.pipeline)
}
}
unsafe impl<Mv, L, Rp> RenderPassAbstract for GraphicsPipeline<Mv, L, Rp>
where
Rp: RenderPassAbstract,
{
#[inline]
fn inner(&self) -> RenderPassSys {
self.render_pass.inner()
}
}
unsafe impl<Mv, L, Rp> RenderPassDesc for GraphicsPipeline<Mv, L, Rp>
where
Rp: RenderPassDesc,
{
#[inline]
fn num_attachments(&self) -> usize {
self.render_pass.num_attachments()
}
#[inline]
fn attachment_desc(&self, num: usize) -> Option<AttachmentDescription> {
self.render_pass.attachment_desc(num)
}
#[inline]
fn num_subpasses(&self) -> usize {
self.render_pass.num_subpasses()
}
#[inline]
fn subpass_desc(&self, num: usize) -> Option<PassDescription> {
self.render_pass.subpass_desc(num)
}
#[inline]
fn num_dependencies(&self) -> usize {
self.render_pass.num_dependencies()
}
#[inline]
fn dependency_desc(&self, num: usize) -> Option<PassDependencyDescription> {
self.render_pass.dependency_desc(num)
}
}
unsafe impl<C, Mv, L, Rp> RenderPassDescClearValues<C> for GraphicsPipeline<Mv, L, Rp>
where
Rp: RenderPassDescClearValues<C>,
{
#[inline]
fn convert_clear_values(&self, vals: C) -> Box<dyn Iterator<Item = ClearValue>> {
self.render_pass.convert_clear_values(vals)
}
}
unsafe impl<Mv, L, Rp> VulkanObject for GraphicsPipeline<Mv, L, Rp> {
type Object = vk::Pipeline;
const TYPE: vk::ObjectType = vk::OBJECT_TYPE_PIPELINE;
#[inline]
fn internal_object(&self) -> vk::Pipeline {
self.inner.pipeline
}
}
impl Drop for Inner {
#[inline]
fn drop(&mut self) {
unsafe {
let vk = self.device.pointers();
vk.DestroyPipeline(self.device.internal_object(), self.pipeline, ptr::null());
}
}
}
/// Trait implemented on objects that reference a graphics pipeline. Can be made into a trait
/// object.
/// When using this trait `AutoCommandBufferBuilder::draw*` calls will need the buffers to be
/// wrapped in a `vec!()`.
pub unsafe trait GraphicsPipelineAbstract:
PipelineLayoutAbstract
+ RenderPassAbstract
+ VertexSource<Vec<Arc<dyn BufferAccess + Send + Sync>>>
+ DeviceOwned
{
/// Returns an opaque object that represents the inside of the graphics pipeline.
fn inner(&self) -> GraphicsPipelineSys;
/// Returns the index of the subpass this graphics pipeline is rendering to.
fn subpass_index(&self) -> u32;
/// Returns the subpass this graphics pipeline is rendering to.
#[inline]
fn subpass(self) -> Subpass<Self>
where
Self: Sized,
{
let index = self.subpass_index();
Subpass::from(self, index)
.expect("Wrong subpass index in GraphicsPipelineAbstract::subpass")
}
/// Returns true if the line width used by this pipeline is dynamic.
fn has_dynamic_line_width(&self) -> bool;
/// Returns the number of viewports and scissors of this pipeline.
fn num_viewports(&self) -> u32;
/// Returns true if the viewports used by this pipeline are dynamic.
fn has_dynamic_viewports(&self) -> bool;
/// Returns true if the scissors used by this pipeline are dynamic.
fn has_dynamic_scissors(&self) -> bool;
/// Returns true if the depth bounds used by this pipeline are dynamic.
fn has_dynamic_depth_bounds(&self) -> bool;
/// Returns true if the stencil compare masks used by this pipeline are dynamic.
fn has_dynamic_stencil_compare_mask(&self) -> bool;
/// Returns true if the stencil write masks used by this pipeline are dynamic.
fn has_dynamic_stencil_write_mask(&self) -> bool;
/// Returns true if the stencil references used by this pipeline are dynamic.
fn has_dynamic_stencil_reference(&self) -> bool;
}
unsafe impl<Mv, L, Rp> GraphicsPipelineAbstract for GraphicsPipeline<Mv, L, Rp>
where
L: PipelineLayoutAbstract,
Rp: RenderPassAbstract,
Mv: VertexSource<Vec<Arc<dyn BufferAccess + Send + Sync>>>,
{
#[inline]
fn inner(&self) -> GraphicsPipelineSys {
GraphicsPipelineSys(self.inner.pipeline, PhantomData)
}
#[inline]
fn subpass_index(&self) -> u32 {
self.render_pass_subpass
}
#[inline]
fn has_dynamic_line_width(&self) -> bool {
self.dynamic_line_width
}
#[inline]
fn num_viewports(&self) -> u32 {
self.num_viewports
}
#[inline]
fn has_dynamic_viewports(&self) -> bool {
self.dynamic_viewport
}
#[inline]
fn has_dynamic_scissors(&self) -> bool {
self.dynamic_scissor
}
#[inline]
fn has_dynamic_depth_bounds(&self) -> bool {
self.dynamic_depth_bounds
}
#[inline]
fn has_dynamic_stencil_compare_mask(&self) -> bool {
self.dynamic_stencil_compare_mask
}
#[inline]
fn has_dynamic_stencil_write_mask(&self) -> bool {
self.dynamic_stencil_write_mask
}
#[inline]
fn has_dynamic_stencil_reference(&self) -> bool {
self.dynamic_stencil_reference
}
}
unsafe impl<T> GraphicsPipelineAbstract for T
where
T: SafeDeref,
T::Target: GraphicsPipelineAbstract,
{
#[inline]
fn inner(&self) -> GraphicsPipelineSys {
GraphicsPipelineAbstract::inner(&**self)
}
#[inline]
fn subpass_index(&self) -> u32 {
(**self).subpass_index()
}
#[inline]
fn has_dynamic_line_width(&self) -> bool {
(**self).has_dynamic_line_width()
}
#[inline]
fn num_viewports(&self) -> u32 {
(**self).num_viewports()
}
#[inline]
fn has_dynamic_viewports(&self) -> bool {
(**self).has_dynamic_viewports()
}
#[inline]
fn has_dynamic_scissors(&self) -> bool {
(**self).has_dynamic_scissors()
}
#[inline]
fn has_dynamic_depth_bounds(&self) -> bool {
(**self).has_dynamic_depth_bounds()
}
#[inline]
fn has_dynamic_stencil_compare_mask(&self) -> bool {
(**self).has_dynamic_stencil_compare_mask()
}
#[inline]
fn has_dynamic_stencil_write_mask(&self) -> bool {
(**self).has_dynamic_stencil_write_mask()
}
#[inline]
fn has_dynamic_stencil_reference(&self) -> bool {
(**self).has_dynamic_stencil_reference()
}
}
impl<Mv, L, Rp> PartialEq for GraphicsPipeline<Mv, L, Rp>
where
L: PipelineLayoutAbstract,
Rp: RenderPassAbstract,
Mv: VertexSource<Vec<Arc<dyn BufferAccess + Send + Sync>>>,
{
#[inline]
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<Mv, L, Rp> Eq for GraphicsPipeline<Mv, L, Rp>
where
L: PipelineLayoutAbstract,
Rp: RenderPassAbstract,
Mv: VertexSource<Vec<Arc<dyn BufferAccess + Send + Sync>>>,
{
}
impl<Mv, L, Rp> Hash for GraphicsPipeline<Mv, L, Rp>
where
L: PipelineLayoutAbstract,
Rp: RenderPassAbstract,
Mv: VertexSource<Vec<Arc<dyn BufferAccess + Send + Sync>>>,
{
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.inner.hash(state);
}
}
impl PartialEq for dyn GraphicsPipelineAbstract + Send + Sync {
#[inline]
fn eq(&self, other: &Self) -> bool {
GraphicsPipelineAbstract::inner(self).0 == GraphicsPipelineAbstract::inner(other).0
&& DeviceOwned::device(self) == DeviceOwned::device(other)
}
}
impl Eq for dyn GraphicsPipelineAbstract + Send + Sync {}
impl Hash for dyn GraphicsPipelineAbstract + Send + Sync {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
GraphicsPipelineAbstract::inner(self).0.hash(state);
DeviceOwned::device(self).hash(state);
}
}
/// Opaque object that represents the inside of the graphics pipeline.
#[derive(Debug, Copy, Clone)]
pub struct GraphicsPipelineSys<'a>(vk::Pipeline, PhantomData<&'a ()>);
unsafe impl<'a> VulkanObject for GraphicsPipelineSys<'a> {
type Object = vk::Pipeline;
const TYPE: vk::ObjectType = vk::OBJECT_TYPE_PIPELINE;
#[inline]
fn internal_object(&self) -> vk::Pipeline {
self.0
}
}
unsafe impl<Mv, L, Rp, I> VertexDefinition<I> for GraphicsPipeline<Mv, L, Rp>
where
Mv: VertexDefinition<I>,
{
type BuffersIter = <Mv as VertexDefinition<I>>::BuffersIter;
type AttribsIter = <Mv as VertexDefinition<I>>::AttribsIter;
#[inline]
fn definition(
&self,
interface: &I,
) -> Result<(Self::BuffersIter, Self::AttribsIter), IncompatibleVertexDefinitionError> {
self.vertex_definition.definition(interface)
}
}
unsafe impl<Mv, L, Rp, S> VertexSource<S> for GraphicsPipeline<Mv, L, Rp>
where
Mv: VertexSource<S>,
{
#[inline]
fn decode(&self, s: S) -> (Vec<Box<dyn BufferAccess + Send + Sync>>, usize, usize) {
self.vertex_definition.decode(s)
}
}
| 27.018707 | 97 | 0.664883 |
167b303f073212fa16b912c79f23ed354a6210e6 | 5,925 | use std::io;
use monoio::buf::IoBufMut;
use monoio::io::AsyncWriteRent;
use monoio::BufResult;
use monoio::{io::AsyncReadRent, net::TcpStream};
use crate::box_future::MaybeArmedBoxFuture;
use crate::buf::Buf;
pub struct TcpStreamCompat {
stream: TcpStream,
read_buf: Option<Buf>,
write_buf: Option<Buf>,
read_fut: MaybeArmedBoxFuture<BufResult<usize, Buf>>,
write_fut: MaybeArmedBoxFuture<BufResult<usize, Buf>>,
flush_fut: MaybeArmedBoxFuture<io::Result<()>>,
shutdown_fut: MaybeArmedBoxFuture<io::Result<()>>,
// used for checking
last_write_len: usize,
}
impl From<TcpStreamCompat> for TcpStream {
fn from(stream: TcpStreamCompat) -> Self {
stream.stream
}
}
impl TcpStreamCompat {
/// Creates a new `TcpStreamCompat` from a monoio `TcpStream`.
///
/// # Safety
/// User must ensure that the data slices provided to `poll_write`
/// before Poll::Ready are with the same data.
pub unsafe fn new(stream: TcpStream) -> Self {
let r_buf = Buf::new(8 * 1024);
let w_buf = Buf::new(8 * 1024);
Self {
stream,
read_buf: Some(r_buf),
write_buf: Some(w_buf),
read_fut: Default::default(),
write_fut: Default::default(),
flush_fut: Default::default(),
shutdown_fut: Default::default(),
last_write_len: 0,
}
}
}
impl tokio::io::AsyncRead for TcpStreamCompat {
fn poll_read(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
let this = self.get_mut();
loop {
// if the future not armed, this means maybe buffer has data.
if !this.read_fut.armed() {
// if there is some data left in our buf, copy it and return.
let read_buf_mut = unsafe { this.read_buf.as_mut().unwrap_unchecked() };
if !read_buf_mut.is_empty() {
// copy directly from inner buf to buf
let our_buf = read_buf_mut.buf_to_read(buf.remaining());
let our_buf_len = our_buf.len();
buf.put_slice(our_buf);
unsafe { read_buf_mut.advance_offset(our_buf_len) };
return std::task::Poll::Ready(Ok(()));
}
// there is no data in buffer. we will construct the future
let buf = unsafe { this.read_buf.take().unwrap_unchecked() };
// we must leak the stream
#[allow(clippy::cast_ref_to_mut)]
let stream = unsafe { &mut *(&this.stream as *const TcpStream as *mut TcpStream) };
this.read_fut.arm_future(AsyncReadRent::read(stream, buf));
}
// the future slot is armed now. we will poll it.
let (ret, buf) = match this.read_fut.poll(cx) {
std::task::Poll::Ready(out) => out,
std::task::Poll::Pending => {
return std::task::Poll::Pending;
}
};
this.read_buf = Some(buf);
if ret? == 0 {
// on eof, return directly; otherwise goto next loop.
return std::task::Poll::Ready(Ok(()));
}
}
}
}
impl tokio::io::AsyncWrite for TcpStreamCompat {
fn poll_write(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<Result<usize, std::io::Error>> {
let this = self.get_mut();
// if there is no write future armed, we will copy the data and construct it
if !this.write_fut.armed() {
let mut owned_buf = unsafe { this.write_buf.take().unwrap_unchecked() };
let owned_buf_mut = owned_buf.buf_to_write();
let len = buf.len().min(owned_buf_mut.len());
owned_buf_mut[..len].copy_from_slice(&buf[..len]);
unsafe { owned_buf.set_init(len) };
this.last_write_len = len;
// we must leak the stream
#[allow(clippy::cast_ref_to_mut)]
let stream = unsafe { &mut *(&this.stream as *const TcpStream as *mut TcpStream) };
this.write_fut
.arm_future(AsyncWriteRent::write(stream, owned_buf));
}
// Check if the slice between different poll_write calls is the same
if buf.len() != this.last_write_len {
panic!("write slice length mismatch between poll_write");
}
// the future must be armed
let (ret, owned_buf) = match this.write_fut.poll(cx) {
std::task::Poll::Ready(r) => r,
std::task::Poll::Pending => {
return std::task::Poll::Pending;
}
};
this.write_buf = Some(owned_buf);
std::task::Poll::Ready(ret)
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), std::io::Error>> {
let this = self.get_mut();
if !this.flush_fut.armed() {
#[allow(clippy::cast_ref_to_mut)]
let stream = unsafe { &mut *(&this.stream as *const TcpStream as *mut TcpStream) };
this.flush_fut.arm_future(stream.flush());
}
this.flush_fut.poll(cx)
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), std::io::Error>> {
let this = self.get_mut();
if !this.shutdown_fut.armed() {
#[allow(clippy::cast_ref_to_mut)]
let stream = unsafe { &mut *(&this.stream as *const TcpStream as *mut TcpStream) };
this.shutdown_fut.arm_future(stream.shutdown());
}
this.shutdown_fut.poll(cx)
}
}
| 35.479042 | 99 | 0.552911 |
398572d12fc87320cd4bf79e7fe6d180019c7524 | 3,167 | use std::mem;
/// Represents a value that is not checked at first, and upon being checked it might be available
/// or unavailable.
pub enum MaybeUnavailable<T> {
// I'm not that great at naming.
NotChecked,
Unavailable,
Available(T),
}
impl<T> MaybeUnavailable<T> {
/// Resets this value to the not checked state.
#[inline]
pub fn reset(&mut self) {
*self = MaybeUnavailable::NotChecked;
}
/// If the value is available, returns it, otherwise returns `None`.
#[inline]
pub fn available(self) -> Option<T> {
match self {
MaybeUnavailable::Available(x) => Some(x),
_ => None,
}
}
/// Takes a value out of the `MaybeUnavailable`, leaving `NotChecked` in its place if it was
/// `Available` and retains the value otherwise.
#[inline]
pub fn take(&mut self) -> Option<T> {
let new_value = match self {
MaybeUnavailable::NotChecked => MaybeUnavailable::NotChecked,
MaybeUnavailable::Unavailable => MaybeUnavailable::Unavailable,
MaybeUnavailable::Available(_) => MaybeUnavailable::NotChecked,
};
mem::replace(self, new_value).available()
}
/// Moves the value `v` out of the `MaybeUnavailable<T>` if it is `Available(v)`.
///
/// # Panics
///
/// Panics if the self value does not equal `Available(v)`.
#[inline]
pub fn unwrap(self) -> T {
match self {
MaybeUnavailable::Available(x) => x,
MaybeUnavailable::NotChecked => {
panic!("called `MaybeUnavailable::unwrap()` on a `NotChecked` value")
}
MaybeUnavailable::Unavailable => {
panic!("called `MaybeUnavailable::unwrap()` on a `Unavailable` value")
}
}
}
/// Returns `true` if the value is `NotChecked`.
#[inline]
pub fn is_not_checked(&self) -> bool {
match self {
MaybeUnavailable::NotChecked => true,
_ => false,
}
}
/// Converts from `MaybeUnavailable<T>` to `MaybeUnavailable<&T>`.
#[inline]
pub fn as_ref(&self) -> MaybeUnavailable<&T> {
match *self {
MaybeUnavailable::NotChecked => MaybeUnavailable::NotChecked,
MaybeUnavailable::Unavailable => MaybeUnavailable::Unavailable,
MaybeUnavailable::Available(ref x) => MaybeUnavailable::Available(x),
}
}
/// Converts from `MaybeUnavailable<T>` to `MaybeUnavailable<&mut T>`.
#[inline]
pub fn as_mut(&mut self) -> MaybeUnavailable<&mut T> {
match *self {
MaybeUnavailable::NotChecked => MaybeUnavailable::NotChecked,
MaybeUnavailable::Unavailable => MaybeUnavailable::Unavailable,
MaybeUnavailable::Available(ref mut x) => MaybeUnavailable::Available(x),
}
}
/// Returns `Available(x)` if passed `Some(x)` and `Unavailable` otherwise.
#[inline]
pub fn from_check_result(x: Option<T>) -> Self {
match x {
Some(x) => MaybeUnavailable::Available(x),
None => MaybeUnavailable::Unavailable,
}
}
}
| 32.649485 | 97 | 0.590148 |
dda79d13acc4e77b237c0400f2918ea273c43fa0 | 4,475 | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
local_client::LocalClient,
persistent_storage::PersistentStorage,
remote_service::RemoteService,
serializer::{SerializerClient, SerializerService},
spawned_process::SpawnedProcess,
thread::ThreadService,
SafetyRules, TSafetyRules,
};
use consensus_types::common::{Author, Payload};
use libra_config::config::{NodeConfig, SafetyRulesBackend, SafetyRulesService};
use libra_secure_storage::{InMemoryStorage, OnDiskStorage, Storage};
use std::sync::{Arc, RwLock};
pub fn extract_service_inputs(config: &mut NodeConfig) -> (Author, PersistentStorage) {
let author = config
.validator_network
.as_ref()
.expect("Missing validator network")
.peer_id;
let backend = &config.consensus.safety_rules.backend;
let (initialize, internal_storage): (bool, Box<dyn Storage>) = match backend {
SafetyRulesBackend::InMemoryStorage => (true, Box::new(InMemoryStorage::new())),
SafetyRulesBackend::OnDiskStorage(config) => {
(config.default, Box::new(OnDiskStorage::new(config.path())))
}
};
let storage = if initialize {
let test_config = config.test.as_mut().expect("Missing test config");
let private_key = test_config
.consensus_keypair
.as_mut()
.expect("Missing consensus keypair in test config")
.take_private()
.expect("Failed to take Consensus private key, key absent or already read");
PersistentStorage::initialize(internal_storage, private_key)
} else {
PersistentStorage::new(internal_storage)
};
(author, storage)
}
enum SafetyRulesWrapper<T> {
Local(Arc<RwLock<SafetyRules<T>>>),
Serializer(Arc<RwLock<SerializerService<T>>>),
SpawnedProcess(SpawnedProcess<T>),
Thread(ThreadService<T>),
}
pub struct SafetyRulesManager<T> {
internal_safety_rules: SafetyRulesWrapper<T>,
}
impl<T: Payload> SafetyRulesManager<T> {
pub fn new(config: &mut NodeConfig) -> Self {
if let SafetyRulesService::SpawnedProcess(_) = config.consensus.safety_rules.service {
return Self::new_spawned_process(config);
}
let (author, storage) = extract_service_inputs(config);
let sr_config = &config.consensus.safety_rules;
match sr_config.service {
SafetyRulesService::Local => Self::new_local(author, storage),
SafetyRulesService::Serializer => Self::new_serializer(author, storage),
SafetyRulesService::Thread => Self::new_thread(author, storage),
_ => panic!("Unimplemented SafetyRulesService: {:?}", sr_config.service),
}
}
pub fn new_local(author: Author, storage: PersistentStorage) -> Self {
let safety_rules = SafetyRules::new(author, storage);
Self {
internal_safety_rules: SafetyRulesWrapper::Local(Arc::new(RwLock::new(safety_rules))),
}
}
pub fn new_serializer(author: Author, storage: PersistentStorage) -> Self {
let safety_rules = SafetyRules::new(author, storage);
let serializer_service = SerializerService::new(safety_rules);
Self {
internal_safety_rules: SafetyRulesWrapper::Serializer(Arc::new(RwLock::new(
serializer_service,
))),
}
}
pub fn new_spawned_process(config: &NodeConfig) -> Self {
let process = SpawnedProcess::<T>::new(config);
Self {
internal_safety_rules: SafetyRulesWrapper::SpawnedProcess(process),
}
}
pub fn new_thread(author: Author, storage: PersistentStorage) -> Self {
let thread = ThreadService::<T>::new(author, storage);
Self {
internal_safety_rules: SafetyRulesWrapper::Thread(thread),
}
}
pub fn client(&self) -> Box<dyn TSafetyRules<T> + Send + Sync> {
match &self.internal_safety_rules {
SafetyRulesWrapper::Local(safety_rules) => {
Box::new(LocalClient::new(safety_rules.clone()))
}
SafetyRulesWrapper::Serializer(serializer_service) => {
Box::new(SerializerClient::new(serializer_service.clone()))
}
SafetyRulesWrapper::SpawnedProcess(process) => Box::new(process.client()),
SafetyRulesWrapper::Thread(thread) => Box::new(thread.client()),
}
}
}
| 36.983471 | 98 | 0.651397 |
38fcabb5cc170fc360b8de518de23a80b10b5dba | 158 | #![feature(existential_type)]
existential type Foo: Fn() -> Foo;
//~^ ERROR: could not find defining uses
fn crash(x: Foo) -> Foo {
x
}
fn main() {
}
| 12.153846 | 40 | 0.607595 |
eb059f09343fceb02dc329668198ba19ee7ec896 | 2,140 | use bitvec::prelude::*;
struct ParseResult {
len: usize,
version_sum: u64,
result: u64,
}
fn parse_packet(packet: &BitSlice<Msb0, u8>) -> ParseResult {
let version: u8 = packet[0..3].load_be();
let type_id: u8 = packet[3..6].load_be();
if type_id == 4 {
let mut len = 6;
let mut value = BitVec::<Msb0, u8>::new();
loop {
let last = !packet[len];
value.extend(&packet[len + 1..len + 5]);
len += 5;
if last {
break;
}
}
return ParseResult {
len,
result: value.load_be(),
version_sum: version as u64,
};
}
let mut len;
let mut version_sum = version as u64;
let mut results = Vec::new();
if packet[6] {
let ops_count: u64 = packet[7..18].load_be();
len = 18;
for _ in 0..ops_count {
let op = parse_packet(&packet[len..]);
len += op.len;
version_sum += op.version_sum;
results.push(op.result);
}
} else {
let ops_len: usize = packet[7..22].load_be();
len = 22;
while len != 22 + ops_len {
let op = parse_packet(&packet[len..]);
len += op.len;
version_sum += op.version_sum;
results.push(op.result);
}
}
let result = match type_id {
0 => results.iter().sum(),
1 => results.iter().product(),
2 => *results.iter().min().unwrap(),
3 => *results.iter().max().unwrap(),
5 => (results[0] > results[1]) as u64,
6 => (results[0] < results[1]) as u64,
7 => (results[0] == results[1]) as u64,
_ => panic!("invalid type id"),
};
ParseResult {
len,
version_sum,
result,
}
}
pub fn solve(input: &str) -> u64 {
let mut bytes = Vec::new();
for i in (0..input.len()).step_by(2) {
bytes.push(u8::from_str_radix(&input[i..i + 2], 16).unwrap());
}
let packet = BitVec::<Msb0, _>::from_vec(bytes);
let parsed = parse_packet(&packet);
parsed.result
}
| 26.097561 | 70 | 0.488785 |
913442572c593b7ad388322f9acc1c2639288a26 | 9,563 | // Copyright 2020 The Matrix.org Foundation C.I.C.
//
// 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.
//! Collection of small in-memory stores that can be used to cache Olm objects.
//!
//! Note: You'll only be interested in these if you are implementing a custom
//! `CryptoStore`.
use std::{collections::HashMap, sync::Arc};
use dashmap::{DashMap, ReadOnlyView};
use matrix_sdk_common::{
identifiers::{DeviceId, RoomId, UserId},
locks::Mutex,
};
use crate::{
identities::ReadOnlyDevice,
olm::{InboundGroupSession, Session},
};
/// In-memory store for Olm Sessions.
#[derive(Debug, Default, Clone)]
pub struct SessionStore {
entries: Arc<DashMap<String, Arc<Mutex<Vec<Session>>>>>,
}
impl SessionStore {
/// Create a new empty Session store.
pub fn new() -> Self {
SessionStore {
entries: Arc::new(DashMap::new()),
}
}
/// Add a session to the store.
///
/// Returns true if the the session was added, false if the session was
/// already in the store.
pub async fn add(&self, session: Session) -> bool {
let sessions_lock = self
.entries
.entry(session.sender_key.to_string())
.or_insert_with(|| Arc::new(Mutex::new(Vec::new())));
let mut sessions = sessions_lock.lock().await;
if !sessions.contains(&session) {
sessions.push(session);
true
} else {
false
}
}
/// Get all the sessions that belong to the given sender key.
pub fn get(&self, sender_key: &str) -> Option<Arc<Mutex<Vec<Session>>>> {
#[allow(clippy::map_clone)]
self.entries.get(sender_key).map(|s| s.clone())
}
/// Add a list of sessions belonging to the sender key.
pub fn set_for_sender(&self, sender_key: &str, sessions: Vec<Session>) {
self.entries
.insert(sender_key.to_owned(), Arc::new(Mutex::new(sessions)));
}
}
#[derive(Debug, Default, Clone)]
/// In-memory store that holds inbound group sessions.
pub struct GroupSessionStore {
#[allow(clippy::type_complexity)]
entries: Arc<DashMap<RoomId, HashMap<String, HashMap<String, InboundGroupSession>>>>,
}
impl GroupSessionStore {
/// Create a new empty store.
pub fn new() -> Self {
GroupSessionStore {
entries: Arc::new(DashMap::new()),
}
}
/// Add an inbound group session to the store.
///
/// Returns true if the the session was added, false if the session was
/// already in the store.
pub fn add(&self, session: InboundGroupSession) -> bool {
self.entries
.entry((&*session.room_id).clone())
.or_insert_with(HashMap::new)
.entry(session.sender_key.to_string())
.or_insert_with(HashMap::new)
.insert(session.session_id().to_owned(), session)
.is_none()
}
/// Get a inbound group session from our store.
///
/// # Arguments
/// * `room_id` - The room id of the room that the session belongs to.
///
/// * `sender_key` - The sender key that sent us the session.
///
/// * `session_id` - The unique id of the session.
pub fn get(
&self,
room_id: &RoomId,
sender_key: &str,
session_id: &str,
) -> Option<InboundGroupSession> {
self.entries
.get(room_id)
.and_then(|m| m.get(sender_key).and_then(|m| m.get(session_id).cloned()))
}
}
/// In-memory store holding the devices of users.
#[derive(Clone, Debug, Default)]
pub struct DeviceStore {
entries: Arc<DashMap<UserId, DashMap<Box<DeviceId>, ReadOnlyDevice>>>,
}
/// A read only view over all devices belonging to a user.
#[derive(Debug)]
pub struct ReadOnlyUserDevices {
entries: ReadOnlyView<Box<DeviceId>, ReadOnlyDevice>,
}
impl ReadOnlyUserDevices {
/// Get the specific device with the given device id.
pub fn get(&self, device_id: &DeviceId) -> Option<ReadOnlyDevice> {
self.entries.get(device_id).cloned()
}
/// Iterator over all the device ids of the user devices.
pub fn keys(&self) -> impl Iterator<Item = &DeviceId> {
self.entries.keys().map(|id| id.as_ref())
}
/// Iterator over all the devices of the user devices.
pub fn devices(&self) -> impl Iterator<Item = &ReadOnlyDevice> {
self.entries.values()
}
}
impl DeviceStore {
/// Create a new empty device store.
pub fn new() -> Self {
DeviceStore {
entries: Arc::new(DashMap::new()),
}
}
/// Add a device to the store.
///
/// Returns true if the device was already in the store, false otherwise.
pub fn add(&self, device: ReadOnlyDevice) -> bool {
let user_id = device.user_id();
self.entries
.entry(user_id.to_owned())
.or_insert_with(DashMap::new)
.insert(device.device_id().into(), device)
.is_none()
}
/// Get the device with the given device_id and belonging to the given user.
pub fn get(&self, user_id: &UserId, device_id: &DeviceId) -> Option<ReadOnlyDevice> {
self.entries
.get(user_id)
.and_then(|m| m.get(device_id).map(|d| d.value().clone()))
}
/// Remove the device with the given device_id and belonging to the given user.
///
/// Returns the device if it was removed, None if it wasn't in the store.
pub fn remove(&self, user_id: &UserId, device_id: &DeviceId) -> Option<ReadOnlyDevice> {
self.entries
.get(user_id)
.and_then(|m| m.remove(device_id))
.map(|(_, d)| d)
}
/// Get a read-only view over all devices of the given user.
pub fn user_devices(&self, user_id: &UserId) -> ReadOnlyUserDevices {
ReadOnlyUserDevices {
entries: self
.entries
.entry(user_id.clone())
.or_insert_with(DashMap::new)
.clone()
.into_read_only(),
}
}
}
#[cfg(test)]
mod test {
use crate::{
identities::device::test::get_device,
olm::{test::get_account_and_session, InboundGroupSession},
store::caches::{DeviceStore, GroupSessionStore, SessionStore},
};
use matrix_sdk_common::identifiers::room_id;
#[tokio::test]
async fn test_session_store() {
let (_, session) = get_account_and_session().await;
let store = SessionStore::new();
assert!(store.add(session.clone()).await);
assert!(!store.add(session.clone()).await);
let sessions = store.get(&session.sender_key).unwrap();
let sessions = sessions.lock().await;
let loaded_session = &sessions[0];
assert_eq!(&session, loaded_session);
}
#[tokio::test]
async fn test_session_store_bulk_storing() {
let (_, session) = get_account_and_session().await;
let store = SessionStore::new();
store.set_for_sender(&session.sender_key, vec![session.clone()]);
let sessions = store.get(&session.sender_key).unwrap();
let sessions = sessions.lock().await;
let loaded_session = &sessions[0];
assert_eq!(&session, loaded_session);
}
#[tokio::test]
async fn test_group_session_store() {
let (account, _) = get_account_and_session().await;
let room_id = room_id!("!test:localhost");
let (outbound, _) = account
.create_group_session_pair(&room_id, Default::default())
.await
.unwrap();
assert_eq!(0, outbound.message_index().await);
assert!(!outbound.shared());
outbound.mark_as_shared();
assert!(outbound.shared());
let inbound = InboundGroupSession::new(
"test_key",
"test_key",
&room_id,
outbound.session_key().await,
)
.unwrap();
let store = GroupSessionStore::new();
store.add(inbound.clone());
let loaded_session = store
.get(&room_id, "test_key", outbound.session_id())
.unwrap();
assert_eq!(inbound, loaded_session);
}
#[tokio::test]
async fn test_device_store() {
let device = get_device();
let store = DeviceStore::new();
assert!(store.add(device.clone()));
assert!(!store.add(device.clone()));
let loaded_device = store.get(device.user_id(), device.device_id()).unwrap();
assert_eq!(device, loaded_device);
let user_devices = store.user_devices(device.user_id());
assert_eq!(user_devices.keys().next().unwrap(), device.device_id());
assert_eq!(user_devices.devices().next().unwrap(), &device);
let loaded_device = user_devices.get(device.device_id()).unwrap();
assert_eq!(device, loaded_device);
store.remove(device.user_id(), device.device_id());
let loaded_device = store.get(device.user_id(), device.device_id());
assert!(loaded_device.is_none());
}
}
| 31.048701 | 92 | 0.60985 |
bb5149fc08a8df37de9c05819df50c5069325359 | 1,478 | use std::num::NonZeroU32;
use std::sync::atomic::{AtomicU32, Ordering};
use crate::context::ModuleId;
/// Identifier for a local variable within a module
///
/// This is not globally unique; it must be combined with a `ModuleId`
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, PartialOrd, Ord)]
pub struct LocalId(NonZeroU32);
/// Identifier for a variable exported from another module
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, PartialOrd, Ord)]
pub struct ExportId(ModuleId, LocalId);
impl ExportId {
pub fn new(module_id: ModuleId, local_id: LocalId) -> Self {
Self(module_id, local_id)
}
pub fn module_id(self) -> ModuleId {
self.0
}
pub fn local_id(self) -> LocalId {
self.1
}
}
pub struct LocalIdAlloc {
local_id_counter: AtomicU32,
}
impl LocalIdAlloc {
pub fn new() -> Self {
Self {
local_id_counter: AtomicU32::new(1),
}
}
/// Allocates a `LocalId` using atomic operations on a shared instance
pub fn alloc(&self) -> LocalId {
LocalId(NonZeroU32::new(self.local_id_counter.fetch_add(1, Ordering::Relaxed)).unwrap())
}
/// Allocates a `LocalId` using non-atomic operations on an exclusive instance
pub fn alloc_mut(&mut self) -> LocalId {
let local_id_counter = self.local_id_counter.get_mut();
let raw_id = *local_id_counter;
*local_id_counter += 1;
LocalId(NonZeroU32::new(raw_id).unwrap())
}
}
| 26.392857 | 96 | 0.655616 |
e4de74168443d19e5000e920a893b21d70949d55 | 12,352 | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::Accessible;
use crate::AccessibleRole;
use crate::Adjustment;
use crate::Align;
use crate::Buildable;
use crate::ConstraintTarget;
use crate::LayoutManager;
use crate::Orientable;
use crate::Orientation;
use crate::Overflow;
use crate::Widget;
use glib::object::Cast;
use glib::object::IsA;
use glib::object::ObjectType as ObjectType_;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::StaticType;
use glib::ToValue;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
glib::wrapper! {
pub struct Scrollbar(Object<ffi::GtkScrollbar>) @extends Widget, @implements Accessible, Buildable, ConstraintTarget, Orientable;
match fn {
get_type => || ffi::gtk_scrollbar_get_type(),
}
}
impl Scrollbar {
#[doc(alias = "gtk_scrollbar_new")]
pub fn new<P: IsA<Adjustment>>(orientation: Orientation, adjustment: Option<&P>) -> Scrollbar {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_scrollbar_new(
orientation.to_glib(),
adjustment.map(|p| p.as_ref()).to_glib_none().0,
))
.unsafe_cast()
}
}
#[doc(alias = "gtk_scrollbar_get_adjustment")]
pub fn get_adjustment(&self) -> Option<Adjustment> {
unsafe { from_glib_none(ffi::gtk_scrollbar_get_adjustment(self.to_glib_none().0)) }
}
#[doc(alias = "gtk_scrollbar_set_adjustment")]
pub fn set_adjustment<P: IsA<Adjustment>>(&self, adjustment: Option<&P>) {
unsafe {
ffi::gtk_scrollbar_set_adjustment(
self.to_glib_none().0,
adjustment.map(|p| p.as_ref()).to_glib_none().0,
);
}
}
pub fn connect_property_adjustment_notify<F: Fn(&Scrollbar) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_adjustment_trampoline<F: Fn(&Scrollbar) + 'static>(
this: *mut ffi::GtkScrollbar,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::adjustment\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_adjustment_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
#[derive(Clone, Default)]
pub struct ScrollbarBuilder {
adjustment: Option<Adjustment>,
can_focus: Option<bool>,
can_target: Option<bool>,
css_classes: Option<Vec<String>>,
css_name: Option<String>,
cursor: Option<gdk::Cursor>,
focus_on_click: Option<bool>,
focusable: Option<bool>,
halign: Option<Align>,
has_tooltip: Option<bool>,
height_request: Option<i32>,
hexpand: Option<bool>,
hexpand_set: Option<bool>,
layout_manager: Option<LayoutManager>,
margin_bottom: Option<i32>,
margin_end: Option<i32>,
margin_start: Option<i32>,
margin_top: Option<i32>,
name: Option<String>,
opacity: Option<f64>,
overflow: Option<Overflow>,
receives_default: Option<bool>,
sensitive: Option<bool>,
tooltip_markup: Option<String>,
tooltip_text: Option<String>,
valign: Option<Align>,
vexpand: Option<bool>,
vexpand_set: Option<bool>,
visible: Option<bool>,
width_request: Option<i32>,
accessible_role: Option<AccessibleRole>,
orientation: Option<Orientation>,
}
impl ScrollbarBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn build(self) -> Scrollbar {
let mut properties: Vec<(&str, &dyn ToValue)> = vec![];
if let Some(ref adjustment) = self.adjustment {
properties.push(("adjustment", adjustment));
}
if let Some(ref can_focus) = self.can_focus {
properties.push(("can-focus", can_focus));
}
if let Some(ref can_target) = self.can_target {
properties.push(("can-target", can_target));
}
if let Some(ref css_classes) = self.css_classes {
properties.push(("css-classes", css_classes));
}
if let Some(ref css_name) = self.css_name {
properties.push(("css-name", css_name));
}
if let Some(ref cursor) = self.cursor {
properties.push(("cursor", cursor));
}
if let Some(ref focus_on_click) = self.focus_on_click {
properties.push(("focus-on-click", focus_on_click));
}
if let Some(ref focusable) = self.focusable {
properties.push(("focusable", focusable));
}
if let Some(ref halign) = self.halign {
properties.push(("halign", halign));
}
if let Some(ref has_tooltip) = self.has_tooltip {
properties.push(("has-tooltip", has_tooltip));
}
if let Some(ref height_request) = self.height_request {
properties.push(("height-request", height_request));
}
if let Some(ref hexpand) = self.hexpand {
properties.push(("hexpand", hexpand));
}
if let Some(ref hexpand_set) = self.hexpand_set {
properties.push(("hexpand-set", hexpand_set));
}
if let Some(ref layout_manager) = self.layout_manager {
properties.push(("layout-manager", layout_manager));
}
if let Some(ref margin_bottom) = self.margin_bottom {
properties.push(("margin-bottom", margin_bottom));
}
if let Some(ref margin_end) = self.margin_end {
properties.push(("margin-end", margin_end));
}
if let Some(ref margin_start) = self.margin_start {
properties.push(("margin-start", margin_start));
}
if let Some(ref margin_top) = self.margin_top {
properties.push(("margin-top", margin_top));
}
if let Some(ref name) = self.name {
properties.push(("name", name));
}
if let Some(ref opacity) = self.opacity {
properties.push(("opacity", opacity));
}
if let Some(ref overflow) = self.overflow {
properties.push(("overflow", overflow));
}
if let Some(ref receives_default) = self.receives_default {
properties.push(("receives-default", receives_default));
}
if let Some(ref sensitive) = self.sensitive {
properties.push(("sensitive", sensitive));
}
if let Some(ref tooltip_markup) = self.tooltip_markup {
properties.push(("tooltip-markup", tooltip_markup));
}
if let Some(ref tooltip_text) = self.tooltip_text {
properties.push(("tooltip-text", tooltip_text));
}
if let Some(ref valign) = self.valign {
properties.push(("valign", valign));
}
if let Some(ref vexpand) = self.vexpand {
properties.push(("vexpand", vexpand));
}
if let Some(ref vexpand_set) = self.vexpand_set {
properties.push(("vexpand-set", vexpand_set));
}
if let Some(ref visible) = self.visible {
properties.push(("visible", visible));
}
if let Some(ref width_request) = self.width_request {
properties.push(("width-request", width_request));
}
if let Some(ref accessible_role) = self.accessible_role {
properties.push(("accessible-role", accessible_role));
}
if let Some(ref orientation) = self.orientation {
properties.push(("orientation", orientation));
}
let ret = glib::Object::new::<Scrollbar>(&properties).expect("object new");
ret
}
pub fn adjustment<P: IsA<Adjustment>>(mut self, adjustment: &P) -> Self {
self.adjustment = Some(adjustment.clone().upcast());
self
}
pub fn can_focus(mut self, can_focus: bool) -> Self {
self.can_focus = Some(can_focus);
self
}
pub fn can_target(mut self, can_target: bool) -> Self {
self.can_target = Some(can_target);
self
}
pub fn css_classes(mut self, css_classes: Vec<String>) -> Self {
self.css_classes = Some(css_classes);
self
}
pub fn css_name(mut self, css_name: &str) -> Self {
self.css_name = Some(css_name.to_string());
self
}
pub fn cursor(mut self, cursor: &gdk::Cursor) -> Self {
self.cursor = Some(cursor.clone());
self
}
pub fn focus_on_click(mut self, focus_on_click: bool) -> Self {
self.focus_on_click = Some(focus_on_click);
self
}
pub fn focusable(mut self, focusable: bool) -> Self {
self.focusable = Some(focusable);
self
}
pub fn halign(mut self, halign: Align) -> Self {
self.halign = Some(halign);
self
}
pub fn has_tooltip(mut self, has_tooltip: bool) -> Self {
self.has_tooltip = Some(has_tooltip);
self
}
pub fn height_request(mut self, height_request: i32) -> Self {
self.height_request = Some(height_request);
self
}
pub fn hexpand(mut self, hexpand: bool) -> Self {
self.hexpand = Some(hexpand);
self
}
pub fn hexpand_set(mut self, hexpand_set: bool) -> Self {
self.hexpand_set = Some(hexpand_set);
self
}
pub fn layout_manager<P: IsA<LayoutManager>>(mut self, layout_manager: &P) -> Self {
self.layout_manager = Some(layout_manager.clone().upcast());
self
}
pub fn margin_bottom(mut self, margin_bottom: i32) -> Self {
self.margin_bottom = Some(margin_bottom);
self
}
pub fn margin_end(mut self, margin_end: i32) -> Self {
self.margin_end = Some(margin_end);
self
}
pub fn margin_start(mut self, margin_start: i32) -> Self {
self.margin_start = Some(margin_start);
self
}
pub fn margin_top(mut self, margin_top: i32) -> Self {
self.margin_top = Some(margin_top);
self
}
pub fn name(mut self, name: &str) -> Self {
self.name = Some(name.to_string());
self
}
pub fn opacity(mut self, opacity: f64) -> Self {
self.opacity = Some(opacity);
self
}
pub fn overflow(mut self, overflow: Overflow) -> Self {
self.overflow = Some(overflow);
self
}
pub fn receives_default(mut self, receives_default: bool) -> Self {
self.receives_default = Some(receives_default);
self
}
pub fn sensitive(mut self, sensitive: bool) -> Self {
self.sensitive = Some(sensitive);
self
}
pub fn tooltip_markup(mut self, tooltip_markup: &str) -> Self {
self.tooltip_markup = Some(tooltip_markup.to_string());
self
}
pub fn tooltip_text(mut self, tooltip_text: &str) -> Self {
self.tooltip_text = Some(tooltip_text.to_string());
self
}
pub fn valign(mut self, valign: Align) -> Self {
self.valign = Some(valign);
self
}
pub fn vexpand(mut self, vexpand: bool) -> Self {
self.vexpand = Some(vexpand);
self
}
pub fn vexpand_set(mut self, vexpand_set: bool) -> Self {
self.vexpand_set = Some(vexpand_set);
self
}
pub fn visible(mut self, visible: bool) -> Self {
self.visible = Some(visible);
self
}
pub fn width_request(mut self, width_request: i32) -> Self {
self.width_request = Some(width_request);
self
}
pub fn accessible_role(mut self, accessible_role: AccessibleRole) -> Self {
self.accessible_role = Some(accessible_role);
self
}
pub fn orientation(mut self, orientation: Orientation) -> Self {
self.orientation = Some(orientation);
self
}
}
impl fmt::Display for Scrollbar {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("Scrollbar")
}
}
| 30.957393 | 133 | 0.589702 |
e5b6dcfe2099219bad64667f98ba9a25086559c3 | 1,338 | #![allow(unused_variables)]
#![allow(dead_code)]
fn main() {
enum Opt<T> {
Some(T),
None,
}
let x: Opt<i32> = Opt::Some(3);
let y: Opt<f64> = Opt::Some(5.0);
enum Res<T, E> {
Ok(T),
Err(E),
}
let x: Res<i32, &'static str> = Res::Ok(3);
let y: Res<i32, &'static str> = Res::Err("404");
match x {
Res::Ok(x) => println!("Success {}", x),
Res::Err(e) => println!("Error {}", e),
}
match y {
Res::Ok(x) => println!("Success {}", x),
Res::Err(e) => println!("Error {}", e),
}
fn swap<T>(x: &mut T, y: &mut T) {
std::mem::swap(x, y);
}
let (mut x, mut y) = (3, 6);
println!("x: {} y: {}", x, y);
swap(&mut x, &mut y);
println!("x: {} y: {}", x, y);
let (mut x, mut y) = ("Hello ", "World! ");
println!("{}{}", x, y);
swap(&mut x, &mut y);
println!("{}{}", x, y);
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn swap(&mut self) {
std::mem::swap(&mut self.x, &mut self.y);
}
}
let int_origin = Point { x: 0, y: 0 };
let float_origin = Point { x: 0.0, y: 0.0 };
let mut pnt = Point { x: 1, y: 2 };
println!("({}, {})", pnt.x, pnt.y);
pnt.swap();
println!("({}, {})", pnt.x, pnt.y);
}
| 20.90625 | 53 | 0.414051 |
d9e99103fa419ff7fd1f880e4836e7d62548add9 | 4,731 | use arrayvec::ArrayVec;
use super::{ascii, DataEncodingError, EncodingContext};
pub(crate) const UNLATCH: u8 = 0b011111;
#[cfg(test)]
use alloc::vec;
#[inline]
pub(crate) fn is_encodable(ch: u8) -> bool {
matches!(ch, 32..=94)
}
/// Encode 1 to 4 characters using EDIFACT and write it to the context.
fn write4<T: EncodingContext>(ctx: &mut T, s: &ArrayVec<u8, 4>) {
let s1 = s.get(1).cloned().unwrap_or(0) & 0b11_1111;
ctx.push((s[0] << 2) | (s1 >> 4));
if s.len() >= 2 {
let s2 = s.get(2).cloned().unwrap_or(0) & 0b11_1111;
ctx.push((s1 << 4) | (s2 >> 2));
if s.len() >= 3 {
let s3 = s.get(3).cloned().unwrap_or(0) & 0b11_1111;
ctx.push((s2 << 6) | s3);
}
}
}
fn handle_end<T: EncodingContext>(
ctx: &mut T,
mut symbols: ArrayVec<u8, 4>,
) -> Result<(), DataEncodingError> {
// check case "encoding with <= 2 ASCII, no UNLATCH"
let rest_chars = symbols.len() + ctx.characters_left();
if rest_chars <= 4 {
// The standard allows ASCII encoding without UNLATCH if there
// are <= 2 words of space left in the symbol and
// we can encode the rest with ASCII in this space.
let rest: ArrayVec<u8, 4> = symbols
.iter()
.cloned()
.chain(ctx.rest().iter().cloned())
.collect();
let ascii_size = ascii::encoding_size(&rest);
if ascii_size <= 2 {
match ctx.symbol_size_left(ascii_size).map(|x| x + ascii_size) {
Some(space) if space <= 2 && ascii_size <= space => {
ctx.backup(symbols.len());
ctx.set_ascii_until_end();
return Ok(());
}
_ => (),
}
}
}
if symbols.is_empty() {
if !ctx.has_more_characters() {
// eod
let space_left = ctx
.symbol_size_left(0)
.ok_or(DataEncodingError::TooMuchOrIllegalData)?;
// padding case
if space_left > 0 {
// the other case is caught in the "special end of data rule" above
assert!(space_left > 2);
ctx.push(UNLATCH << 2);
ctx.set_ascii_until_end();
}
} else {
// mode switch
ctx.push(UNLATCH << 2);
}
} else {
assert!(symbols.len() <= 3);
if !ctx.has_more_characters() {
// eod, maybe add UNLATCH for padding if space allows
let space_left = ctx
.symbol_size_left(symbols.len())
.ok_or(DataEncodingError::TooMuchOrIllegalData)?
> 0;
if space_left || symbols.len() == 3 {
symbols.push(UNLATCH);
ctx.set_ascii_until_end();
}
} else {
symbols.push(UNLATCH);
}
write4(ctx, &symbols);
}
Ok(())
}
pub(super) fn encode<T: EncodingContext>(ctx: &mut T) -> Result<(), DataEncodingError> {
let mut symbols = ArrayVec::<u8, 4>::new();
while let Some(ch) = ctx.eat() {
symbols.push(ch);
if symbols.len() == 4 {
write4(ctx, &symbols);
symbols.clear();
if ctx.maybe_switch_mode()? {
break;
}
} else if ctx.maybe_switch_mode()? {
break;
}
}
handle_end(ctx, symbols)
}
#[test]
fn test_write4_four() {
use super::tests::DummyLogic;
let mut enc = DummyLogic::new(vec![], 3, -1);
write4(&mut enc, &[0b10_01_00, 0b11_01_10, 0b011010, 1].into());
assert_eq!(
enc.codewords,
vec![0b10_01_00_11, 0b01_10_01_10, 0b10_00_00_01]
);
}
#[test]
fn test_write4_three() {
use super::tests::DummyLogic;
let mut enc = DummyLogic::new(vec![], 3, -1);
let mut s = ArrayVec::<u8, 4>::new();
s.try_extend_from_slice(&[0b10_01_00, 0b11_01_10, 0b011010])
.unwrap();
write4(&mut enc, &s);
assert_eq!(
enc.codewords,
vec![0b10_01_00_11, 0b01_10_01_10, 0b10_00_00_00]
);
}
#[test]
fn test_write4_two() {
use super::tests::DummyLogic;
let mut enc = DummyLogic::new(vec![], 2, -1);
let mut s = ArrayVec::<u8, 4>::new();
s.try_extend_from_slice(&[0b10_01_00, 0b11_01_10]).unwrap();
write4(&mut enc, &s);
assert_eq!(enc.codewords, vec![0b10_01_00_11, 0b01_10_00_00]);
}
#[test]
fn test_write4_one() {
use super::tests::DummyLogic;
let mut enc = DummyLogic::new(vec![], 1, -1);
let mut s = ArrayVec::<u8, 4>::new();
s.try_extend_from_slice(&[0b10_01_00]).unwrap();
write4(&mut enc, &s);
assert_eq!(enc.codewords, vec![0b10_01_00_00]);
}
| 30.133758 | 88 | 0.534771 |
71864b3e65b649e7f0db8e92afde00860af494f2 | 17,783 | use super::{Interest, Ready, ReadyEvent, Tick};
use crate::loom::sync::atomic::AtomicUsize;
use crate::loom::sync::Mutex;
use crate::util::bit;
use crate::util::slab::Entry;
use std::sync::atomic::Ordering::{AcqRel, Acquire, Release};
use std::task::{Context, Poll, Waker};
use super::Direction;
cfg_io_readiness! {
use crate::util::linked_list::{self, LinkedList};
use std::cell::UnsafeCell;
use std::future::Future;
use std::marker::PhantomPinned;
use std::pin::Pin;
use std::ptr::NonNull;
}
/// Stored in the I/O driver resource slab.
#[derive(Debug)]
pub(crate) struct ScheduledIo {
/// Packs the resource's readiness with the resource's generation.
readiness: AtomicUsize,
waiters: Mutex<Waiters>,
}
cfg_io_readiness! {
type WaitList = LinkedList<Waiter, <Waiter as linked_list::Link>::Target>;
}
#[derive(Debug, Default)]
struct Waiters {
#[cfg(feature = "net")]
/// List of all current waiters
list: WaitList,
/// Waker used for AsyncRead
reader: Option<Waker>,
/// Waker used for AsyncWrite
writer: Option<Waker>,
/// True if this ScheduledIo has been killed due to IO driver shutdown
is_shutdown: bool,
}
cfg_io_readiness! {
#[derive(Debug)]
struct Waiter {
pointers: linked_list::Pointers<Waiter>,
/// The waker for this task
waker: Option<Waker>,
/// The interest this waiter is waiting on
interest: Interest,
is_ready: bool,
/// Should never be `!Unpin`
_p: PhantomPinned,
}
/// Future returned by `readiness()`
struct Readiness<'a> {
scheduled_io: &'a ScheduledIo,
state: State,
/// Entry in the waiter `LinkedList`.
waiter: UnsafeCell<Waiter>,
}
enum State {
Init,
Waiting,
Done,
}
}
// The `ScheduledIo::readiness` (`AtomicUsize`) is packed full of goodness.
//
// | reserved | generation | driver tick | readinesss |
// |----------+------------+--------------+------------|
// | 1 bit | 7 bits + 8 bits + 16 bits |
const READINESS: bit::Pack = bit::Pack::least_significant(16);
const TICK: bit::Pack = READINESS.then(8);
const GENERATION: bit::Pack = TICK.then(7);
#[test]
fn test_generations_assert_same() {
assert_eq!(super::GENERATION, GENERATION);
}
// ===== impl ScheduledIo =====
impl Entry for ScheduledIo {
fn reset(&self) {
let state = self.readiness.load(Acquire);
let generation = GENERATION.unpack(state);
let next = GENERATION.pack_lossy(generation + 1, 0);
self.readiness.store(next, Release);
}
}
impl Default for ScheduledIo {
fn default() -> ScheduledIo {
ScheduledIo {
readiness: AtomicUsize::new(0),
waiters: Mutex::new(Default::default()),
}
}
}
impl ScheduledIo {
pub(crate) fn generation(&self) -> usize {
GENERATION.unpack(self.readiness.load(Acquire))
}
/// Invoked when the IO driver is shut down; forces this ScheduledIo into a
/// permanently ready state.
pub(super) fn shutdown(&self) {
self.wake0(Ready::ALL, true)
}
/// Sets the readiness on this `ScheduledIo` by invoking the given closure on
/// the current value, returning the previous readiness value.
///
/// # Arguments
/// - `token`: the token for this `ScheduledIo`.
/// - `tick`: whether setting the tick or trying to clear readiness for a
/// specific tick.
/// - `f`: a closure returning a new readiness value given the previous
/// readiness.
///
/// # Returns
///
/// If the given token's generation no longer matches the `ScheduledIo`'s
/// generation, then the corresponding IO resource has been removed and
/// replaced with a new resource. In that case, this method returns `Err`.
/// Otherwise, this returns the previous readiness.
pub(super) fn set_readiness(
&self,
token: Option<usize>,
tick: Tick,
f: impl Fn(Ready) -> Ready,
) -> Result<(), ()> {
let mut current = self.readiness.load(Acquire);
loop {
let current_generation = GENERATION.unpack(current);
if let Some(token) = token {
// Check that the generation for this access is still the
// current one.
if GENERATION.unpack(token) != current_generation {
return Err(());
}
}
// Mask out the tick/generation bits so that the modifying
// function doesn't see them.
let current_readiness = Ready::from_usize(current);
let new = f(current_readiness);
let packed = match tick {
Tick::Set(t) => TICK.pack(t as usize, new.as_usize()),
Tick::Clear(t) => {
if TICK.unpack(current) as u8 != t {
// Trying to clear readiness with an old event!
return Err(());
}
TICK.pack(t as usize, new.as_usize())
}
};
let next = GENERATION.pack(current_generation, packed);
match self
.readiness
.compare_exchange(current, next, AcqRel, Acquire)
{
Ok(_) => return Ok(()),
// we lost the race, retry!
Err(actual) => current = actual,
}
}
}
/// Notifies all pending waiters that have registered interest in `ready`.
///
/// There may be many waiters to notify. Waking the pending task **must** be
/// done from outside of the lock otherwise there is a potential for a
/// deadlock.
///
/// A stack array of wakers is created and filled with wakers to notify, the
/// lock is released, and the wakers are notified. Because there may be more
/// than 32 wakers to notify, if the stack array fills up, the lock is
/// released, the array is cleared, and the iteration continues.
pub(super) fn wake(&self, ready: Ready) {
self.wake0(ready, false);
}
fn wake0(&self, ready: Ready, shutdown: bool) {
const NUM_WAKERS: usize = 32;
let mut wakers: [Option<Waker>; NUM_WAKERS] = Default::default();
let mut curr = 0;
let mut waiters = self.waiters.lock();
waiters.is_shutdown |= shutdown;
// check for AsyncRead slot
if ready.is_readable() {
if let Some(waker) = waiters.reader.take() {
wakers[curr] = Some(waker);
curr += 1;
}
}
// check for AsyncWrite slot
if ready.is_writable() {
if let Some(waker) = waiters.writer.take() {
wakers[curr] = Some(waker);
curr += 1;
}
}
#[cfg(feature = "net")]
'outer: loop {
let mut iter = waiters.list.drain_filter(|w| ready.satisfies(w.interest));
while curr < NUM_WAKERS {
match iter.next() {
Some(waiter) => {
let waiter = unsafe { &mut *waiter.as_ptr() };
if let Some(waker) = waiter.waker.take() {
waiter.is_ready = true;
wakers[curr] = Some(waker);
curr += 1;
}
}
None => {
break 'outer;
}
}
}
drop(waiters);
for waker in wakers.iter_mut().take(curr) {
waker.take().unwrap().wake();
}
curr = 0;
// Acquire the lock again.
waiters = self.waiters.lock();
}
// Release the lock before notifying
drop(waiters);
for waker in wakers.iter_mut().take(curr) {
waker.take().unwrap().wake();
}
}
pub(super) fn ready_event(&self, interest: Interest) -> ReadyEvent {
let curr = self.readiness.load(Acquire);
ReadyEvent {
tick: TICK.unpack(curr) as u8,
ready: interest.mask() & Ready::from_usize(READINESS.unpack(curr)),
}
}
/// Poll version of checking readiness for a certain direction.
///
/// These are to support `AsyncRead` and `AsyncWrite` polling methods,
/// which cannot use the `async fn` version. This uses reserved reader
/// and writer slots.
pub(super) fn poll_readiness(
&self,
cx: &mut Context<'_>,
direction: Direction,
) -> Poll<ReadyEvent> {
let curr = self.readiness.load(Acquire);
let ready = direction.mask() & Ready::from_usize(READINESS.unpack(curr));
if ready.is_empty() {
// Update the task info
let mut waiters = self.waiters.lock();
let slot = match direction {
Direction::Read => &mut waiters.reader,
Direction::Write => &mut waiters.writer,
};
// Avoid cloning the waker if one is already stored that matches the
// current task.
match slot {
Some(existing) => {
if !existing.will_wake(cx.waker()) {
*existing = cx.waker().clone();
}
}
None => {
*slot = Some(cx.waker().clone());
}
}
// Try again, in case the readiness was changed while we were
// taking the waiters lock
let curr = self.readiness.load(Acquire);
let ready = direction.mask() & Ready::from_usize(READINESS.unpack(curr));
if waiters.is_shutdown {
Poll::Ready(ReadyEvent {
tick: TICK.unpack(curr) as u8,
ready: direction.mask(),
})
} else if ready.is_empty() {
Poll::Pending
} else {
Poll::Ready(ReadyEvent {
tick: TICK.unpack(curr) as u8,
ready,
})
}
} else {
Poll::Ready(ReadyEvent {
tick: TICK.unpack(curr) as u8,
ready,
})
}
}
pub(crate) fn clear_readiness(&self, event: ReadyEvent) {
// This consumes the current readiness state **except** for closed
// states. Closed states are excluded because they are final states.
let mask_no_closed = event.ready - Ready::READ_CLOSED - Ready::WRITE_CLOSED;
// result isn't important
let _ = self.set_readiness(None, Tick::Clear(event.tick), |curr| curr - mask_no_closed);
}
pub(crate) fn clear_wakers(&self) {
let mut waiters = self.waiters.lock();
waiters.reader.take();
waiters.writer.take();
}
}
impl Drop for ScheduledIo {
fn drop(&mut self) {
self.wake(Ready::ALL);
}
}
unsafe impl Send for ScheduledIo {}
unsafe impl Sync for ScheduledIo {}
cfg_io_readiness! {
impl ScheduledIo {
/// An async version of `poll_readiness` which uses a linked list of wakers
pub(crate) async fn readiness(&self, interest: Interest) -> ReadyEvent {
self.readiness_fut(interest).await
}
// This is in a separate function so that the borrow checker doesn't think
// we are borrowing the `UnsafeCell` possibly over await boundaries.
//
// Go figure.
fn readiness_fut(&self, interest: Interest) -> Readiness<'_> {
Readiness {
scheduled_io: self,
state: State::Init,
waiter: UnsafeCell::new(Waiter {
pointers: linked_list::Pointers::new(),
waker: None,
is_ready: false,
interest,
_p: PhantomPinned,
}),
}
}
}
unsafe impl linked_list::Link for Waiter {
type Handle = NonNull<Waiter>;
type Target = Waiter;
fn as_raw(handle: &NonNull<Waiter>) -> NonNull<Waiter> {
*handle
}
unsafe fn from_raw(ptr: NonNull<Waiter>) -> NonNull<Waiter> {
ptr
}
unsafe fn pointers(mut target: NonNull<Waiter>) -> NonNull<linked_list::Pointers<Waiter>> {
NonNull::from(&mut target.as_mut().pointers)
}
}
// ===== impl Readiness =====
impl Future for Readiness<'_> {
type Output = ReadyEvent;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
use std::sync::atomic::Ordering::SeqCst;
let (scheduled_io, state, waiter) = unsafe {
let me = self.get_unchecked_mut();
(&me.scheduled_io, &mut me.state, &me.waiter)
};
loop {
match *state {
State::Init => {
// Optimistically check existing readiness
let curr = scheduled_io.readiness.load(SeqCst);
let ready = Ready::from_usize(READINESS.unpack(curr));
// Safety: `waiter.interest` never changes
let interest = unsafe { (*waiter.get()).interest };
let ready = ready.intersection(interest);
if !ready.is_empty() {
// Currently ready!
let tick = TICK.unpack(curr) as u8;
*state = State::Done;
return Poll::Ready(ReadyEvent { ready, tick });
}
// Wasn't ready, take the lock (and check again while locked).
let mut waiters = scheduled_io.waiters.lock();
let curr = scheduled_io.readiness.load(SeqCst);
let mut ready = Ready::from_usize(READINESS.unpack(curr));
if waiters.is_shutdown {
ready = Ready::ALL;
}
let ready = ready.intersection(interest);
if !ready.is_empty() {
// Currently ready!
let tick = TICK.unpack(curr) as u8;
*state = State::Done;
return Poll::Ready(ReadyEvent { ready, tick });
}
// Not ready even after locked, insert into list...
// Safety: called while locked
unsafe {
(*waiter.get()).waker = Some(cx.waker().clone());
}
// Insert the waiter into the linked list
//
// safety: pointers from `UnsafeCell` are never null.
waiters
.list
.push_front(unsafe { NonNull::new_unchecked(waiter.get()) });
*state = State::Waiting;
}
State::Waiting => {
// Currently in the "Waiting" state, implying the caller has
// a waiter stored in the waiter list (guarded by
// `notify.waiters`). In order to access the waker fields,
// we must hold the lock.
let waiters = scheduled_io.waiters.lock();
// Safety: called while locked
let w = unsafe { &mut *waiter.get() };
if w.is_ready {
// Our waker has been notified.
*state = State::Done;
} else {
// Update the waker, if necessary.
if !w.waker.as_ref().unwrap().will_wake(cx.waker()) {
w.waker = Some(cx.waker().clone());
}
return Poll::Pending;
}
// Explicit drop of the lock to indicate the scope that the
// lock is held. Because holding the lock is required to
// ensure safe access to fields not held within the lock, it
// is helpful to visualize the scope of the critical
// section.
drop(waiters);
}
State::Done => {
let tick = TICK.unpack(scheduled_io.readiness.load(Acquire)) as u8;
// Safety: State::Done means it is no longer shared
let w = unsafe { &mut *waiter.get() };
return Poll::Ready(ReadyEvent {
tick,
ready: Ready::from_interest(w.interest),
});
}
}
}
}
}
impl Drop for Readiness<'_> {
fn drop(&mut self) {
let mut waiters = self.scheduled_io.waiters.lock();
// Safety: `waiter` is only ever stored in `waiters`
unsafe {
waiters
.list
.remove(NonNull::new_unchecked(self.waiter.get()))
};
}
}
unsafe impl Send for Readiness<'_> {}
unsafe impl Sync for Readiness<'_> {}
}
| 32.629358 | 99 | 0.500534 |
9b83e258f75aca57f827b1b8c54ecf76f5682b5e | 5,475 | // Copyright 2020 Google LLC
//
// 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
//
// https://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 crate::types::QualifiedName;
use std::collections::HashSet;
use syn::{ForeignItemFn, Ident, ImplItem, Item, ItemConst, ItemType, ItemUse, Type};
use super::{convert_error::ErrorContext, parse::type_converter::TypeConverter, ConvertError};
#[derive(Copy, Clone, Eq, PartialEq)]
pub(crate) enum TypeKind {
Pod, // trivial. Can be moved and copied in Rust.
NonPod, // has destructor or non-trivial move constructors. Can only hold by UniquePtr
Abstract, // has pure virtual members - can't even generate UniquePtr
}
impl TypeKind {
pub(crate) fn can_be_instantiated(&self) -> bool {
match self {
TypeKind::Pod | TypeKind::NonPod => true,
TypeKind::Abstract => false,
}
}
}
/// An entry which needs to go into an `impl` block for a given type.
pub(crate) struct ImplBlockDetails {
pub(crate) item: ImplItem,
pub(crate) ty: Ident,
}
/// A ForeignItemFn with a little bit of context about the
/// type which is most likely to be 'this'
#[derive(Clone)]
pub(crate) struct FuncToConvert {
pub(crate) item: ForeignItemFn,
pub(crate) virtual_this_type: Option<QualifiedName>,
pub(crate) self_ty: Option<QualifiedName>,
}
/// Layers of analysis which may be applied to decorate each API.
/// See description of the purpose of this trait within `Api`.
pub(crate) trait ApiAnalysis {
type TypeAnalysis;
type FunAnalysis;
}
/// No analysis has been applied to this API.
pub(crate) struct NullAnalysis;
impl ApiAnalysis for NullAnalysis {
type TypeAnalysis = ();
type FunAnalysis = ();
}
pub(crate) enum TypedefKind {
Type(ItemType),
Use(ItemUse),
}
/// Different types of API we might encounter.
pub(crate) enum ApiDetail<T: ApiAnalysis> {
/// A forward declared type for which no definition is available.
ForwardDeclaration,
/// A synthetic type we've manufactured in order to
/// concretize some templated C++ type.
ConcreteType { rs_definition: Box<Type> },
/// A simple note that we want to make a constructor for
/// a `std::string` on the heap.
StringConstructor,
/// A function. May include some analysis.
Function {
fun: Box<FuncToConvert>,
analysis: T::FunAnalysis,
},
/// A constant.
Const { const_item: ItemConst },
/// A typedef found in the bindgen output which we wish
/// to pass on in our output
Typedef { payload: TypedefKind },
/// A type (struct or enum) encountered in the
/// `bindgen` output.
Type {
bindgen_mod_item: Option<Item>,
analysis: T::TypeAnalysis,
},
/// A variable-length C integer type (e.g. int, unsigned long).
CType { typename: QualifiedName },
/// A typedef which doesn't point to any actual useful kind of
/// type, but instead to something which `bindgen` couldn't figure out
/// and has therefore itself made opaque and mysterious.
OpaqueTypedef,
/// Some item which couldn't be processed by autocxx for some reason.
/// We will have emitted a warning message about this, but we want
/// to mark that it's ignored so that we don't attempt to process
/// dependent items.
IgnoredItem {
err: ConvertError,
ctx: ErrorContext,
},
}
/// Any API we encounter in the input bindgen rs which we might want to pass
/// onto the output Rust or C++.
///
/// This type is parameterized over an `ApiAnalysis`. This is any additional
/// information which we wish to apply to our knowledge of our APIs later
/// during analysis phases. It might be a excessively traity to parameterize
/// this type; we might be better off relying on an `Option<SomeKindOfAnalysis>`
/// but for now it's working.
///
/// This is not as high-level as the equivalent types in `cxx` or `bindgen`,
/// because sometimes we pass on the `bindgen` output directly in the
/// Rust codegen output.
pub(crate) struct Api<T: ApiAnalysis> {
pub(crate) name: QualifiedName,
/// Any dependencies of this API, such that during garbage collection
/// we can ensure to keep them.
pub(crate) deps: HashSet<QualifiedName>,
/// Details of this specific API kind.
pub(crate) detail: ApiDetail<T>,
}
pub(crate) type UnanalyzedApi = Api<NullAnalysis>;
impl<T: ApiAnalysis> Api<T> {
pub(crate) fn typename(&self) -> QualifiedName {
self.name.clone()
}
}
/// Results of parsing the bindgen mod. This is what is passed from
/// the parser to the analysis phases.
pub(crate) struct ParseResults<'a> {
/// All APIs encountered. This is the main thing.
pub(crate) apis: Vec<UnanalyzedApi>,
/// A database containing known relationships between types.
/// In particular, any typedefs detected.
/// This should probably be replaced by extracting this information
/// from APIs as necessary later. TODO
pub(crate) type_converter: TypeConverter<'a>,
}
| 35.784314 | 93 | 0.690046 |
f49c2647077462ab4a886f26fd85c596ec7f8ad8 | 742 | use js_sys::Math::random;
/// Container for cross-platform Random methods
#[derive(Debug)]
pub struct Random {}
impl Random {
/// returns a random f32 value between an upper & lower bound
pub fn gen_range_f32(lower: f32, upper: f32) -> f32 {
let rand_range: f32 = random() as f32 * (upper - lower);
return rand_range + lower;
}
/// returns a random u32 value between an upper & lower bound
pub fn gen_range_u32(lower: u32, upper: u32) -> u32 {
let rand_range: u32 = (random() * f64::from(upper - lower)) as u32;
return rand_range + lower;
}
/// returns a random boolean value between an upper & lower bound
pub fn gen_bool() -> bool {
return random() < 0.5;
}
}
| 29.68 | 75 | 0.623989 |
db72450347970485b80b58c3ddc265afd36b2e62 | 13,145 | use libc::{c_int, c_void, size_t};
use libproc::libproc::bsd_info::BSDInfo;
use libproc::libproc::file_info::{pidfdinfo, ListFDs, ProcFDType};
use libproc::libproc::net_info::{InSockInfo, SocketFDInfo, SocketInfoKind, TcpSockInfo};
use libproc::libproc::pid_rusage::{pidrusage, RUsageInfoV2};
use libproc::libproc::proc_pid::{listpidinfo, listpids, pidinfo, ListThreads, ProcType};
use libproc::libproc::task_info::{TaskAllInfo, TaskInfo};
use libproc::libproc::thread_info::ThreadInfo;
use std::cmp;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::thread;
use std::time::{Duration, Instant};
pub struct ProcessInfo {
pub pid: i32,
pub ppid: i32,
pub curr_task: TaskAllInfo,
pub prev_task: TaskAllInfo,
pub curr_path: Option<PathInfo>,
pub curr_threads: Vec<ThreadInfo>,
pub curr_udps: Vec<InSockInfo>,
pub curr_tcps: Vec<TcpSockInfo>,
pub curr_res: Option<RUsageInfoV2>,
pub prev_res: Option<RUsageInfoV2>,
pub interval: Duration,
}
#[cfg_attr(tarpaulin, skip)]
pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec<ProcessInfo> {
let mut base_procs = Vec::new();
let mut ret = Vec::new();
let arg_max = get_arg_max();
if let Ok(procs) = listpids(ProcType::ProcAllPIDS) {
for p in procs {
if let Ok(task) = pidinfo::<TaskAllInfo>(p as i32, 0) {
let res = pidrusage::<RUsageInfoV2>(p as i32).ok();
let time = Instant::now();
base_procs.push((p as i32, task, res, time));
}
}
}
thread::sleep(interval);
for (pid, prev_task, prev_res, prev_time) in base_procs {
let curr_task = if let Ok(task) = pidinfo::<TaskAllInfo>(pid, 0) {
task
} else {
clone_task_all_info(&prev_task)
};
let curr_path = get_path_info(pid, arg_max);
let threadids = listpidinfo::<ListThreads>(pid, curr_task.ptinfo.pti_threadnum as usize);
let mut curr_threads = Vec::new();
if let Ok(threadids) = threadids {
for t in threadids {
if let Ok(thread) = pidinfo::<ThreadInfo>(pid, t) {
curr_threads.push(thread);
}
}
}
let mut curr_tcps = Vec::new();
let mut curr_udps = Vec::new();
let fds = listpidinfo::<ListFDs>(pid, curr_task.pbsd.pbi_nfiles as usize);
if let Ok(fds) = fds {
for fd in fds {
if let ProcFDType::Socket = fd.proc_fdtype.into() {
if let Ok(socket) = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd) {
match socket.psi.soi_kind.into() {
SocketInfoKind::In => {
if socket.psi.soi_protocol == libc::IPPROTO_UDP {
let info = unsafe { socket.psi.soi_proto.pri_in };
curr_udps.push(info);
}
}
SocketInfoKind::Tcp => {
let info = unsafe { socket.psi.soi_proto.pri_tcp };
curr_tcps.push(info);
}
_ => (),
}
}
}
}
}
let curr_res = pidrusage::<RUsageInfoV2>(pid).ok();
let curr_time = Instant::now();
let interval = curr_time - prev_time;
let ppid = curr_task.pbsd.pbi_ppid as i32;
let proc = ProcessInfo {
pid,
ppid,
curr_task,
prev_task,
curr_path,
curr_threads,
curr_udps,
curr_tcps,
curr_res,
prev_res,
interval,
};
ret.push(proc);
}
ret
}
#[cfg_attr(tarpaulin, skip)]
fn get_arg_max() -> size_t {
let mut mib: [c_int; 2] = [libc::CTL_KERN, libc::KERN_ARGMAX];
let mut arg_max = 0i32;
let mut size = ::std::mem::size_of::<c_int>();
unsafe {
while libc::sysctl(
mib.as_mut_ptr(),
2,
(&mut arg_max) as *mut i32 as *mut c_void,
&mut size,
::std::ptr::null_mut(),
0,
) == -1
{}
}
arg_max as size_t
}
pub struct PathInfo {
pub name: String,
pub exe: PathBuf,
pub root: PathBuf,
pub cmd: Vec<String>,
pub env: Vec<String>,
}
#[cfg_attr(tarpaulin, skip)]
unsafe fn get_unchecked_str(cp: *mut u8, start: *mut u8) -> String {
let len = cp as usize - start as usize;
let part = Vec::from_raw_parts(start, len, len);
let tmp = String::from_utf8_unchecked(part.clone());
::std::mem::forget(part);
tmp
}
#[cfg_attr(tarpaulin, skip)]
fn get_path_info(pid: i32, mut size: size_t) -> Option<PathInfo> {
let mut proc_args = Vec::with_capacity(size as usize);
let ptr: *mut u8 = proc_args.as_mut_slice().as_mut_ptr();
let mut mib: [c_int; 3] = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid as c_int];
unsafe {
let ret = libc::sysctl(
mib.as_mut_ptr(),
3,
ptr as *mut c_void,
&mut size,
::std::ptr::null_mut(),
0,
);
if ret != -1 {
let mut n_args: c_int = 0;
libc::memcpy(
(&mut n_args) as *mut c_int as *mut c_void,
ptr as *const c_void,
::std::mem::size_of::<c_int>(),
);
let mut cp = ptr.add(::std::mem::size_of::<c_int>());
let mut start = cp;
if cp < ptr.add(size) {
while cp < ptr.add(size) && *cp != 0 {
cp = cp.offset(1);
}
let exe = Path::new(get_unchecked_str(cp, start).as_str()).to_path_buf();
let name = exe
.file_name()
.unwrap_or_else(|| OsStr::new(""))
.to_str()
.unwrap_or("")
.to_owned();
let mut need_root = true;
let mut root = Default::default();
if exe.is_absolute() {
if let Some(parent) = exe.parent() {
root = parent.to_path_buf();
need_root = false;
}
}
while cp < ptr.add(size) && *cp == 0 {
cp = cp.offset(1);
}
start = cp;
let mut c = 0;
let mut cmd = Vec::new();
while c < n_args && cp < ptr.add(size) {
if *cp == 0 {
c += 1;
cmd.push(get_unchecked_str(cp, start));
start = cp.offset(1);
}
cp = cp.offset(1);
}
start = cp;
let mut env = Vec::new();
while cp < ptr.add(size) {
if *cp == 0 {
if cp == start {
break;
}
env.push(get_unchecked_str(cp, start));
start = cp.offset(1);
}
cp = cp.offset(1);
}
if need_root {
for env in env.iter() {
if env.starts_with("PATH=") {
root = Path::new(&env[6..]).to_path_buf();
break;
}
}
}
Some(PathInfo {
exe,
name,
root,
cmd,
env,
})
} else {
None
}
} else {
None
}
}
}
#[cfg_attr(tarpaulin, skip)]
fn clone_task_all_info(src: &TaskAllInfo) -> TaskAllInfo {
let pbsd = BSDInfo {
pbi_flags: src.pbsd.pbi_flags,
pbi_status: src.pbsd.pbi_status,
pbi_xstatus: src.pbsd.pbi_xstatus,
pbi_pid: src.pbsd.pbi_pid,
pbi_ppid: src.pbsd.pbi_ppid,
pbi_uid: src.pbsd.pbi_uid,
pbi_gid: src.pbsd.pbi_gid,
pbi_ruid: src.pbsd.pbi_ruid,
pbi_rgid: src.pbsd.pbi_rgid,
pbi_svuid: src.pbsd.pbi_svuid,
pbi_svgid: src.pbsd.pbi_svgid,
rfu_1: src.pbsd.rfu_1,
pbi_comm: src.pbsd.pbi_comm,
pbi_name: src.pbsd.pbi_name,
pbi_nfiles: src.pbsd.pbi_nfiles,
pbi_pgid: src.pbsd.pbi_pgid,
pbi_pjobc: src.pbsd.pbi_pjobc,
e_tdev: src.pbsd.e_tdev,
e_tpgid: src.pbsd.e_tpgid,
pbi_nice: src.pbsd.pbi_nice,
pbi_start_tvsec: src.pbsd.pbi_start_tvsec,
pbi_start_tvusec: src.pbsd.pbi_start_tvusec,
};
let ptinfo = TaskInfo {
pti_virtual_size: src.ptinfo.pti_virtual_size,
pti_resident_size: src.ptinfo.pti_resident_size,
pti_total_user: src.ptinfo.pti_total_user,
pti_total_system: src.ptinfo.pti_total_system,
pti_threads_user: src.ptinfo.pti_threads_user,
pti_threads_system: src.ptinfo.pti_threads_system,
pti_policy: src.ptinfo.pti_policy,
pti_faults: src.ptinfo.pti_faults,
pti_pageins: src.ptinfo.pti_pageins,
pti_cow_faults: src.ptinfo.pti_cow_faults,
pti_messages_sent: src.ptinfo.pti_messages_sent,
pti_messages_received: src.ptinfo.pti_messages_received,
pti_syscalls_mach: src.ptinfo.pti_syscalls_mach,
pti_syscalls_unix: src.ptinfo.pti_syscalls_unix,
pti_csw: src.ptinfo.pti_csw,
pti_threadnum: src.ptinfo.pti_threadnum,
pti_numrunning: src.ptinfo.pti_numrunning,
pti_priority: src.ptinfo.pti_priority,
};
TaskAllInfo { pbsd, ptinfo }
}
impl ProcessInfo {
/// PID of process
pub fn pid(&self) -> i32 {
self.pid
}
/// Name of command
pub fn name(&self) -> String {
// self.command()
// .split(' ')
// .collect::<Vec<_>>()
// .first()
// .map(|x| x.to_string())
// .unwrap_or_default()
self.command_only()
}
/// Full name of command, with arguments
pub fn command(&self) -> String {
if let Some(path) = &self.curr_path {
if !path.cmd.is_empty() {
let mut cmd = path
.cmd
.iter()
.cloned()
.map(|mut x| {
x.push(' ');
x
})
.collect::<String>();
cmd.pop();
cmd = cmd.replace("\n", " ").replace("\t", " ");
cmd
} else {
String::from("")
}
} else {
String::from("")
}
}
/// Full name of comand only
pub fn command_only(&self) -> String {
if let Some(path) = &self.curr_path {
if !path.cmd.is_empty() {
path.exe.to_string_lossy().to_string()
} else {
String::from("")
}
} else {
String::from("")
}
}
/// Get the status of the process
pub fn status(&self) -> String {
let mut state = 7;
for t in &self.curr_threads {
let s = match t.pth_run_state {
1 => 1, // TH_STATE_RUNNING
2 => 5, // TH_STATE_STOPPED
3 => {
if t.pth_sleep_time > 20 {
4
} else {
3
}
} // TH_STATE_WAITING
4 => 2, // TH_STATE_UNINTERRUPTIBLE
5 => 6, // TH_STATE_HALTED
_ => 7,
};
state = cmp::min(s, state);
}
let state = match state {
0 => "",
1 => "Running",
2 => "Uninterruptible",
3 => "Sleep",
4 => "Waiting",
5 => "Stopped",
6 => "Halted",
_ => "?",
};
state.to_string()
}
/// CPU usage as a percent of total
pub fn cpu_usage(&self) -> f64 {
let curr_time =
self.curr_task.ptinfo.pti_total_user + self.curr_task.ptinfo.pti_total_system;
let prev_time =
self.prev_task.ptinfo.pti_total_user + self.prev_task.ptinfo.pti_total_system;
let usage_ms = (curr_time - prev_time) / 1000000u64;
let interval_ms = self.interval.as_secs() * 1000 + u64::from(self.interval.subsec_millis());
usage_ms as f64 * 100.0 / interval_ms as f64
}
/// Memory size in number of bytes
pub fn mem_size(&self) -> u64 {
self.curr_task.ptinfo.pti_resident_size
}
/// Virtual memory size in bytes
pub fn virtual_size(&self) -> u64 {
self.curr_task.ptinfo.pti_virtual_size
}
}
| 32.376847 | 100 | 0.483454 |
09fc25fd01c0e85a21eff204df986729923cd851 | 5,664 | //! Naming is confusing, but RawMap -> InitialMap -> Map. InitialMap is separate pretty much just
//! for the step of producing <https://a-b-street.github.io/docs/map/importing/geometry.html>.
use std::collections::{BTreeMap, BTreeSet};
use anyhow::Result;
use abstutil::{Tags, Timer};
use geom::{Bounds, Circle, Distance, PolyLine, Polygon, Pt2D};
pub use self::geometry::intersection_polygon;
use crate::raw::{OriginalRoad, RawMap, RawRoad};
use crate::{osm, IntersectionType, LaneSpec, MapConfig};
mod geometry;
pub mod lane_specs;
pub struct InitialMap {
pub roads: BTreeMap<OriginalRoad, Road>,
pub intersections: BTreeMap<osm::NodeID, Intersection>,
pub bounds: Bounds,
}
pub struct Road {
// Redundant but useful to embed
pub id: OriginalRoad,
pub src_i: osm::NodeID,
pub dst_i: osm::NodeID,
// The true center of the road, including sidewalks
pub trimmed_center_pts: PolyLine,
pub half_width: Distance,
pub lane_specs_ltr: Vec<LaneSpec>,
pub osm_tags: Tags,
}
impl Road {
pub fn new(id: OriginalRoad, r: &RawRoad, cfg: &MapConfig) -> Result<Road> {
let lane_specs_ltr = lane_specs::get_lane_specs_ltr(&r.osm_tags, cfg);
let (trimmed_center_pts, total_width) = r.get_geometry(id, cfg)?;
Ok(Road {
id,
src_i: id.i1,
dst_i: id.i2,
trimmed_center_pts,
half_width: total_width / 2.0,
lane_specs_ltr,
osm_tags: r.osm_tags.clone(),
})
}
}
pub struct Intersection {
// Redundant but useful to embed
pub id: osm::NodeID,
pub polygon: Polygon,
pub roads: BTreeSet<OriginalRoad>,
pub intersection_type: IntersectionType,
pub elevation: Distance,
}
impl InitialMap {
pub fn new(
raw: &RawMap,
bounds: &Bounds,
merged_intersections: &BTreeSet<osm::NodeID>,
timer: &mut Timer,
) -> InitialMap {
let mut m = InitialMap {
roads: BTreeMap::new(),
intersections: BTreeMap::new(),
bounds: bounds.clone(),
};
for (id, i) in &raw.intersections {
m.intersections.insert(
*id,
Intersection {
id: *id,
// Dummy thing to start with
polygon: Circle::new(Pt2D::new(0.0, 0.0), Distance::meters(1.0)).to_polygon(),
roads: BTreeSet::new(),
intersection_type: i.intersection_type,
elevation: i.elevation,
},
);
}
for (id, r) in &raw.roads {
if id.i1 == id.i2 {
warn!("Skipping loop {}", id);
continue;
}
if PolyLine::new(r.center_points.clone()).is_err() {
warn!("Skipping broken geom {}", id);
continue;
}
m.intersections.get_mut(&id.i1).unwrap().roads.insert(*id);
m.intersections.get_mut(&id.i2).unwrap().roads.insert(*id);
m.roads.insert(*id, Road::new(*id, r, &raw.config).unwrap());
}
timer.start_iter("find each intersection polygon", m.intersections.len());
for i in m.intersections.values_mut() {
timer.next();
match intersection_polygon(
i.id,
i.roads.clone(),
&mut m.roads,
merged_intersections.contains(&i.id),
) {
Ok((poly, _)) => {
i.polygon = poly;
}
Err(err) => {
error!("Can't make intersection geometry for {}: {}", i.id, err);
// Don't trim lines back at all
let r = &m.roads[i.roads.iter().next().unwrap()];
let pt = if r.src_i == i.id {
r.trimmed_center_pts.first_pt()
} else {
r.trimmed_center_pts.last_pt()
};
i.polygon = Circle::new(pt, Distance::meters(3.0)).to_polygon();
// Also don't attempt to make Movements later!
i.intersection_type = IntersectionType::StopSign;
}
}
}
// Some roads near borders get completely squished. Stretch them out here. Attempting to do
// this in the convert_osm layer doesn't work, because predicting how much roads will be
// trimmed is impossible.
let min_len = Distance::meters(5.0);
for i in m.intersections.values_mut() {
if i.intersection_type != IntersectionType::Border {
continue;
}
let r = m.roads.get_mut(i.roads.iter().next().unwrap()).unwrap();
if r.trimmed_center_pts.length() >= min_len {
continue;
}
if r.dst_i == i.id {
r.trimmed_center_pts = r.trimmed_center_pts.extend_to_length(min_len);
} else {
r.trimmed_center_pts = r
.trimmed_center_pts
.reversed()
.extend_to_length(min_len)
.reversed();
}
i.polygon = intersection_polygon(
i.id,
i.roads.clone(),
&mut m.roads,
merged_intersections.contains(&i.id),
)
.unwrap()
.0;
info!(
"Shifted border {} out a bit to make the road a reasonable length",
i.id
);
}
m
}
}
| 32.551724 | 99 | 0.519421 |
1d25bed917f6d17f82514a7f330efa4d141a80f2 | 3,743 | //! **ls-tiny** is a less functional `ls` command
//! it is somewhat richer than when no argument to the ls command is specified. (Because it's a little colored.)
#[macro_use]
extern crate clap;
use clap::{Arg, App};
use colored::Colorize;
use std::path::{Path, PathBuf};
/// The Config structure has four fields
/// * the path of the directory you want to look up
/// * the number of directories
/// * the number of files
/// * the total number of them.
pub struct Config {
/// directory name given by the first argument
search_dir: PathBuf,
/// Number of directories
dirs: u64,
/// Number of files
files: u64,
/// total entries
entries: u64
}
/// Define the initial value of the Config structure.
impl Default for Config {
fn default() -> Self {
Self {
search_dir: PathBuf::new(),
dirs: 0,
files: 0,
entries: 0
}
}
}
impl Config {
/// parse the arguments.
/// If you want more information, such as methods, check out the following links
/// clap https://crates.io/crates/clap
fn parse_arguments<'a>() -> clap::ArgMatches<'a> {
App::new(crate_name!())
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.arg(Arg::with_name("PATH")
.help("Sets the directory")
.required(true)
.index(1)
)
.get_matches()
}
/// If an existing directory is specified, the Ok-wrapped Config structure is returned.
/// Assign the directory specified by the first argument to the search_dir field of the Config structure.
/// All other fields are assigned a 0.(call the default method)
///
/// # Panics
/// An error is returned when the first argument is a file or a non-existent directory is specified.
pub fn new() -> Result<Config, String> {
let matches = Self::parse_arguments();
let mut search_dir = PathBuf::new();
if let Some(path) = matches.value_of("PATH") {
search_dir.push(path);
}
if search_dir.is_file() {
return Err(format!("error: sets the directory"));
}
if !search_dir.exists() {
return Err(format!("error: {} cannot find", search_dir.display()));
}
Ok( Config { search_dir, ..Config::default() } )
}
/// check the entries in the directory specified by the first argument.
/// If you want to know more about specifying colors, see the following links:
/// [colored](https://crates.io/crates/colored)
pub fn run(&mut self) {
for dir_entry in self.search_dir.read_dir().expect("cannot read dir") {
self.entries += 1;
if let Ok(entry) = dir_entry {
let entry_type = if entry.path().is_file() {
self.files += 1;
"file".green()
} else {
self.dirs += 1;
"dir ".cyan()
};
println!("{}: {} - {}", self.entries , entry_type , get_name(&entry.path()));
}
}
// let dir_name = get_name(self.search_dir.as_path()).magenta();
let dir_name = self.search_dir.as_path().to_str().unwrap().magenta();
let entries = self.entries.to_string().magenta();
println!("\ndir: {}, file: {}", self.dirs.to_string().cyan(), self.files.to_string().green());
println!("{} directory has {} entries.", dir_name, entries);
}
}
/// extracts only the name from the path
fn get_name(path: &Path) -> &str {
path.file_name().unwrap().to_str().unwrap()
} | 32.833333 | 112 | 0.565589 |
909fca2ab586f2e983894772c5cf87231422616d | 3,065 | #![allow(non_snake_case)]
use syntax::{register_diagnostics, register_long_diagnostics};
register_long_diagnostics! {
E0454: r##"
A link name was given with an empty name. Erroneous code example:
```ignore (cannot-test-this-because-rustdoc-stops-compile-fail-before-codegen)
#[link(name = "")] extern {}
// error: `#[link(name = "")]` given with empty name
```
The rust compiler cannot link to an external library if you don't give it its
name. Example:
```no_run
#[link(name = "some_lib")] extern {} // ok!
```
"##,
E0455: r##"
Linking with `kind=framework` is only supported when targeting macOS,
as frameworks are specific to that operating system.
Erroneous code example:
```ignore (should-compile_fail-but-cannot-doctest-conditionally-without-macos)
#[link(name = "FooCoreServices", kind = "framework")] extern {}
// OS used to compile is Linux for example
```
To solve this error you can use conditional compilation:
```
#[cfg_attr(target="macos", link(name = "FooCoreServices", kind = "framework"))]
extern {}
```
See more:
https://doc.rust-lang.org/reference/attributes.html#conditional-compilation
"##,
E0458: r##"
An unknown "kind" was specified for a link attribute. Erroneous code example:
```ignore (cannot-test-this-because-rustdoc-stops-compile-fail-before-codegen)
#[link(kind = "wonderful_unicorn")] extern {}
// error: unknown kind: `wonderful_unicorn`
```
Please specify a valid "kind" value, from one of the following:
* static
* dylib
* framework
"##,
E0459: r##"
A link was used without a name parameter. Erroneous code example:
```ignore (cannot-test-this-because-rustdoc-stops-compile-fail-before-codegen)
#[link(kind = "dylib")] extern {}
// error: `#[link(...)]` specified without `name = "foo"`
```
Please add the name parameter to allow the rust compiler to find the library
you want. Example:
```no_run
#[link(kind = "dylib", name = "some_lib")] extern {} // ok!
```
"##,
E0463: r##"
A plugin/crate was declared but cannot be found. Erroneous code example:
```compile_fail,E0463
#![feature(plugin)]
#![plugin(cookie_monster)] // error: can't find crate for `cookie_monster`
extern crate cake_is_a_lie; // error: can't find crate for `cake_is_a_lie`
```
You need to link your code to the relevant crate in order to be able to use it
(through Cargo or the `-L` option of rustc example). Plugins are crates as
well, and you link to them the same way.
"##,
}
register_diagnostics! {
E0456, // plugin `..` is not available for triple `..`
E0457, // plugin `..` only found in rlib format, but must be available...
E0514, // metadata version mismatch
E0460, // found possibly newer version of crate `..`
E0461, // couldn't find crate `..` with expected target triple ..
E0462, // found staticlib `..` instead of rlib or dylib
E0464, // multiple matching crates for `..`
E0465, // multiple .. candidates for `..` found
E0519, // local crate and dependency have same (crate-name, disambiguator)
E0523, // two dependencies have same (crate-name, disambiguator) but different SVH
}
| 29.471154 | 86 | 0.703752 |
9021b485e7711ec2bc0dc4b36c040eee4e3c1cd8 | 803 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn serialize_structure_create_workspace_input(
object: &mut smithy_json::serialize::JsonObjectWriter,
input: &crate::input::CreateWorkspaceInput,
) {
if let Some(var_1) = &input.alias {
object.key("alias").string(var_1);
}
if let Some(var_2) = &input.client_token {
object.key("clientToken").string(var_2);
}
}
pub fn serialize_structure_update_workspace_alias_input(
object: &mut smithy_json::serialize::JsonObjectWriter,
input: &crate::input::UpdateWorkspaceAliasInput,
) {
if let Some(var_3) = &input.alias {
object.key("alias").string(var_3);
}
if let Some(var_4) = &input.client_token {
object.key("clientToken").string(var_4);
}
}
| 32.12 | 80 | 0.684932 |
f785cd0857f072c3e56fea57bf79e02e1d32ae7b | 92 | fn main() {
let i = 0;
let mut i = 1;
i += 1;
i += 1;
print!("{}", i);
} | 13.142857 | 20 | 0.315217 |
87859a54a13bb57f83bfd4959940d42805ffe458 | 21,025 | #![cfg_attr(feature = "clippy", allow(while_let_on_iterator))]
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use client::{Cluster, Metadata};
use errors::{Error, Result};
use network::TopicPartition;
/// Strategy for assigning partitions to consumer streams.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AssignmentStrategy {
/// Range partitioning works on a per-topic basis.
///
/// For each topic, we lay out the available partitions in numeric order
/// and the consumer threads in lexicographic order.
/// We then divide the number of partitions by the total number of consumer streams
/// (threads) to determine the number of partitions to assign to each consumer.
/// If it does not evenly divide, then the first few consumers will have one extra
/// partition.
Range,
/// The round-robin partition assignor lays out all the available partitions
/// and all the available consumer threads.
///
/// It then proceeds to do a round-robin assignment from partition to consumer thread.
/// If the subscriptions of all consumer instances are identical,
/// then the partitions will be uniformly distributed.
/// (i.e., the partition ownership counts will be within a delta of exactly one across all
/// consumer threads.)
///
/// Round-robin assignment is permitted only if:
/// (a) Every topic has the same number of streams within a consumer instance
/// (b) The set of subscribed topics is identical for every consumer instance within the
/// group.
RoundRobin,
/// The sticky assignor serves two purposes.
///
/// First, it guarantees an assignment that is as balanced as possible, meaning either:
/// - the numbers of topic partitions assigned to consumers differ by at most one; or
/// - each consumer that has 2+ fewer topic partitions than some other consumer
/// cannot get any of those topic partitions transferred to it.
///
/// Second, it preserved as many existing assignment as possible when a reassignment occurs.
/// This helps in saving some of the overhead processing
/// when topic partitions move from one consumer to another.
Sticky,
/// unsupported custom strategy
Custom(String),
}
impl AssignmentStrategy {
pub fn assignor(&self) -> Option<Box<PartitionAssignor>> {
match *self {
AssignmentStrategy::Range => Some(Box::new(RangeAssignor::default())),
AssignmentStrategy::RoundRobin => Some(Box::new(RoundRobinAssignor::default())),
AssignmentStrategy::Sticky => Some(Box::new(StickyAssignor::default())),
AssignmentStrategy::Custom(ref strategy) => {
warn!("unsupported assignment strategy: {}", strategy);
None
}
}
}
}
impl FromStr for AssignmentStrategy {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"range" => Ok(AssignmentStrategy::Range),
"roundrobin" => Ok(AssignmentStrategy::RoundRobin),
"sticky" => Ok(AssignmentStrategy::Sticky),
_ => Ok(AssignmentStrategy::Custom(s.to_owned())),
}
}
}
/// Define custom partition assignment for use in `KafkaConsumer`
///
/// Members of the consumer group subscribe to the topics they are interested in
/// and forward their subscriptions to a Kafka broker serving as the group coordinator.
/// The coordinator selects one member to perform the group assignment
/// and propagates the subscriptions of all members to it.
/// Then `PartitionAssignor::assign` is called to perform the assignment
/// and the results are forwarded back to each respective members
pub trait PartitionAssignor {
/// Unique name for this assignor
fn name(&self) -> &'static str;
/// strategy for this assignor
fn strategy(&self) -> AssignmentStrategy;
/// Return a serializable object representing the local member's
/// subscription.
fn subscription<'a>(&self, topics: Vec<Cow<'a, str>>) -> Subscription<'a> {
Subscription {
topics,
user_data: None,
}
}
/// Perform the group assignment given the member subscriptions and current cluster
/// metadata.
fn assign<'a>(
&self,
metadata: &'a Metadata,
subscriptions: HashMap<Cow<'a, str>, Subscription<'a>>,
) -> HashMap<Cow<'a, str>, Assignment<'a>>;
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Subscription<'a> {
pub topics: Vec<Cow<'a, str>>,
pub user_data: Option<Cow<'a, [u8]>>,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Assignment<'a> {
pub partitions: Vec<TopicPartition<'a>>,
pub user_data: Option<Cow<'a, [u8]>>,
}
/// The range assignor works on a per-topic basis.
///
/// For each topic, we lay out the available partitions in numeric order and the consumers in
/// lexicographic order.
/// We then divide the number of partitions by the total number of consumers to determine
/// the number of partitions to assign to each consumer.
/// If it does not evenly divide, then the first few consumers will have one extra partition.
///
/// For example, suppose there are two consumers C0 and C1, two topics t0 and t1, and each topic
/// has 3 partitions,
/// resulting in partitions t0p0, t0p1, t0p2, t1p0, t1p1, and t1p2.
///
/// The assignment will be:
/// C0: [t0p0, t0p1, t1p0, t1p1]
/// C1: [t0p2, t1p2]
#[derive(Debug, Default)]
pub struct RangeAssignor {}
impl PartitionAssignor for RangeAssignor {
fn name(&self) -> &'static str {
"range"
}
fn strategy(&self) -> AssignmentStrategy {
AssignmentStrategy::Range
}
fn assign<'a>(
&self,
metadata: &'a Metadata,
subscriptions: HashMap<Cow<'a, str>, Subscription<'a>>,
) -> HashMap<Cow<'a, str>, Assignment<'a>> {
let mut consumers_per_topic = HashMap::new();
for (member_id, subscription) in subscriptions {
for topic_name in subscription.topics {
consumers_per_topic
.entry(topic_name)
.or_insert_with(Vec::new)
.push(member_id.clone());
}
}
let mut assignment = HashMap::new();
let mut topic_names: Vec<Cow<'a, str>> = consumers_per_topic.keys().cloned().collect();
topic_names.sort();
for topic_name in topic_names {
if let (Some(mut partitions), Some(mut consumers)) = (
metadata.partitions_for_topic(&topic_name),
consumers_per_topic.get_mut(&topic_name),
) {
consumers.sort();
let partitions_per_consumer = partitions.len() / consumers.len();
let consumers_with_extra_partition = partitions.len() % consumers.len();
for (i, member_id) in consumers.iter().enumerate() {
let remaining = partitions
.split_off(partitions_per_consumer + if i >= consumers_with_extra_partition { 0 } else { 1 });
assignment
.entry(member_id.clone())
.or_insert_with(Assignment::default)
.partitions
.append(&mut partitions);
partitions = remaining;
}
}
}
assignment
}
}
/// The round robin assignor lays out all the available partitions and all the available consumers.
///
/// It then proceeds to do a round robin assignment from partition to consumer. If the
/// subscriptions of all consumer
/// instances are identical, then the partitions will be uniformly distributed. (i.e., the
/// partition ownership counts
/// will be within a delta of exactly one across all consumers.)
///
/// For example, suppose there are two consumers C0 and C1, two topics t0 and t1, and each topic
/// has 3 partitions,
/// resulting in partitions t0p0, t0p1, t0p2, t1p0, t1p1, and t1p2.
///
/// The assignment will be:
/// C0: [t0p0, t0p2, t1p1]
/// C1: [t0p1, t1p0, t1p2]
///
/// When subscriptions differ across consumer instances, the assignment process still considers each
/// consumer instance in round robin fashion but skips over an instance if it is not subscribed to
/// the topic. Unlike the case when subscriptions are identical, this can result in imbalanced
/// assignments. For example, we have three consumers C0, C1, C2, and three topics t0, t1, t2,
/// with 1, 2, and 3 partitions, respectively. Therefore, the partitions are t0p0, t1p0, t1p1, t2p0,
/// t2p1, t2p2. C0 is subscribed to t0; C1 is subscribed to t0, t1; and C2 is subscribed to t0, t1,
/// t2.
///
/// Tha assignment will be:
/// C0: [t0p0]
/// C1: [t1p0]
/// C2: [t1p1, t2p0, t2p1, t2p2]
#[derive(Debug, Default)]
pub struct RoundRobinAssignor {}
impl PartitionAssignor for RoundRobinAssignor {
fn name(&self) -> &'static str {
"roundrobin"
}
fn strategy(&self) -> AssignmentStrategy {
AssignmentStrategy::RoundRobin
}
fn assign<'a>(
&self,
metadata: &'a Metadata,
subscriptions: HashMap<Cow<'a, str>, Subscription<'a>>,
) -> HashMap<Cow<'a, str>, Assignment<'a>> {
// get sorted consumers
let mut consumers: Vec<&Cow<'a, str>> = subscriptions.keys().collect();
consumers.sort();
let mut consumers = consumers.iter().cycle();
// get sorted topic names
let mut topic_names = HashSet::new();
topic_names.extend(
subscriptions
.values()
.flat_map(|subscription| subscription.topics.iter().cloned()),
);
let mut topic_names: Vec<Cow<'a, str>> = topic_names.into_iter().collect();
topic_names.sort();
let mut assignment = HashMap::new();
for topic_name in topic_names {
if let Some(partitions) = metadata.partitions_for_topic(&topic_name) {
for partition in partitions {
while let Some(consumer) = consumers.next() {
if subscriptions[*consumer].topics.contains(&partition.topic_name) {
assignment
.entry((*consumer).clone())
.or_insert_with(Assignment::default)
.partitions
.push(partition.clone());
break;
}
}
}
}
}
assignment
}
}
/// The sticky assignor serves two purposes.
///
/// First, it guarantees an assignment that is as balanced as possible, meaning either:
/// - the numbers of topic partitions assigned to consumers differ by at most one; or
/// - each consumer that has 2+ fewer topic partitions than some other consumer
/// cannot get any of those topic partitions transferred to it.
///
/// Second, it preserved as many existing assignment as possible when a reassignment occurs.
/// This helps in saving some of the overhead processing when topic partitions move from one
/// consumer to another.
///
/// Starting fresh it would work by distributing the partitions over consumers as evenly as
/// possible.
/// Even though this may sound similar to how round robin assignor works,
/// the second example below shows that it is not.
///
/// During a reassignment it would perform the reassignment in such a way that in the new assignment
/// 1. topic partitions are still distributed as evenly as possible, and
/// 2. topic partitions stay with their previously assigned consumers as much as possible.
/// Of course, the first goal above takes precedence over the second one.
///
/// Example 1. Suppose there are three consumers `C0, `C1`, `C2`,
/// four topics `t0,` `t1`, `t2`, `t3`, and each topic has 2 partitions,
/// resulting in partitions `t0p0`, `t0p1`, `t1p0`, `t1p1`, `t2p0`, `t2p1`, `t3p0`, `t3p1`.
/// Each consumer is subscribed to all three topics.
///
/// The assignment with both sticky and round robin assignors will be:
///
/// - `C0: [t0p0, t1p1, t3p0]`
/// - `C1: [t0p1, t2p0, t3p1]`
/// - `C2: [t1p0, t2p1]`
///
/// Now, let's assume `C1` is removed and a reassignment is about to happen.
/// The round robin assignor would produce:
///
/// - `C0: [t0p0, t1p0, t2p0, t3p0]`
/// - `C2: [t0p1, t1p1, t2p1, t3p1]`
///
/// while the sticky assignor would result in:
///
/// - `C0 [t0p0, t1p1, t3p0, t2p0]`
/// - `C2 [t1p0, t2p1, t0p1, t3p1]`
///
/// preserving all the previous assignments (unlike the round robin assignor).
///
/// Example 2. There are three consumers `C0`, `C1`, `C2`,
/// and three topics `t0`, `t1`, `t2`, with 1, 2, and 3 partitions respectively.
/// Therefore, the partitions are `t0p0`, `t1p0`, `t1p1`, `t2p0`, `t2p1`, `t2p2`.
/// `C0` is subscribed to `t0`; `C1` is subscribed to `t0`, `t1`;
/// and `C2` is subscribed to `t0`, `t1`, `t2`.
///
/// The round robin assignor would come up with the following assignment:
///
/// - `C0 [t0p0]`
/// - `C1 [t1p0]`
/// - `C2 [t1p1, t2p0, t2p1, t2p2]`
///
/// which is not as balanced as the assignment suggested by sticky assignor:
///
/// - `C0 [t0p0]`
/// - `C1 [t1p0, t1p1]`
/// - `C2 [t2p0, t2p1, t2p2]`
///
/// Now, if consumer `C0` is removed, these two assignors would produce the following assignments.
/// Round Robin (preserves 3 partition assignments):
///
/// - `C1 [t0p0, t1p1]`
/// - `C2 [t1p0, t2p0, t2p1, t2p2]`
///
/// Sticky (preserves 5 partition assignments):
///
/// - `C1 [t1p0, t1p1, t0p0]`
/// - `C2 [t2p0, t2p1, t2p2]`
///
#[derive(Debug, Default)]
pub struct StickyAssignor {}
impl PartitionAssignor for StickyAssignor {
fn name(&self) -> &'static str {
"sticky"
}
fn strategy(&self) -> AssignmentStrategy {
AssignmentStrategy::Sticky
}
fn assign<'a>(
&self,
_metadata: &'a Metadata,
_subscriptions: HashMap<Cow<'a, str>, Subscription<'a>>,
) -> HashMap<Cow<'a, str>, Assignment<'a>> {
unimplemented!()
}
}
#[cfg(test)]
mod tests {
use std::iter::FromIterator;
use client::PartitionInfo;
use super::*;
/// For example, suppose there are two consumers C0 and C1, two topics t0 and t1, and each
/// topic has 3 partitions,
/// resulting in partitions t0p0, t0p1, t0p2, t1p0, t1p1, and t1p2.
///
/// The assignment will be:
/// C0: [t0p0, t0p1, t1p0, t1p1]
/// C1: [t0p2, t1p2]
#[test]
fn test_range_assignor() {
let assignor = RangeAssignor::default();
let metadata = Metadata::with_topics(vec![
(
"t0".into(),
vec![PartitionInfo::new(0), PartitionInfo::new(1), PartitionInfo::new(2)],
),
(
"t1".into(),
vec![PartitionInfo::new(0), PartitionInfo::new(1), PartitionInfo::new(2)],
),
]);
let subscriptions = HashMap::from_iter(
vec![
(
"c0".into(),
Subscription {
topics: vec!["t0".into(), "t1".into()],
user_data: None,
},
),
(
"c1".into(),
Subscription {
topics: vec!["t0".into(), "t1".into()],
user_data: None,
},
),
].into_iter(),
);
let assignment = assignor.assign(&metadata, subscriptions);
assert_eq!(assignment.len(), 2);
assert_eq!(
assignment["c0"],
Assignment {
partitions: vec![
topic_partition!("t0", 0),
topic_partition!("t0", 1),
topic_partition!("t1", 0),
topic_partition!("t1", 1),
],
user_data: None,
}
);
assert_eq!(
assignment["c1"],
Assignment {
partitions: vec![topic_partition!("t0", 2), topic_partition!("t1", 2)],
user_data: None,
}
);
}
/// For example, suppose there are two consumers C0 and C1, two topics t0 and t1, and each
/// topic has 3 partitions,
/// resulting in partitions t0p0, t0p1, t0p2, t1p0, t1p1, and t1p2.
///
/// The assignment will be:
/// C0: [t0p0, t0p2, t1p1]
/// C1: [t0p1, t1p0, t1p2]
///
#[test]
fn test_roundrobin_assignor() {
let assignor = RoundRobinAssignor::default();
let metadata = Metadata::with_topics(vec![
(
"t0".into(),
vec![PartitionInfo::new(0), PartitionInfo::new(1), PartitionInfo::new(2)],
),
(
"t1".into(),
vec![PartitionInfo::new(0), PartitionInfo::new(1), PartitionInfo::new(2)],
),
]);
let subscriptions = HashMap::from_iter(
vec![
(
"c0".into(),
Subscription {
topics: vec!["t0".into(), "t1".into()],
user_data: None,
},
),
(
"c1".into(),
Subscription {
topics: vec!["t0".into(), "t1".into()],
user_data: None,
},
),
].into_iter(),
);
let assignment = assignor.assign(&metadata, subscriptions);
assert_eq!(assignment.len(), 2);
assert_eq!(
assignment["c0"],
Assignment {
partitions: vec![
topic_partition!("t0", 0),
topic_partition!("t0", 2),
topic_partition!("t1", 1),
],
user_data: None,
}
);
assert_eq!(
assignment["c1"],
Assignment {
partitions: vec![
topic_partition!("t0", 1),
topic_partition!("t1", 0),
topic_partition!("t1", 2),
],
user_data: None,
}
);
}
/// For example, we have three consumers C0, C1, C2, and three topics t0, t1, t2,
/// with 1, 2, and 3 partitions, respectively. Therefore, the partitions are t0p0, t1p0,
/// t1p1, t2p0,
/// t2p1, t2p2. C0 is subscribed to t0; C1 is subscribed to t0, t1; and C2 is subscribed to
/// t0, t1, t2.
///
/// Tha assignment will be:
/// C0: [t0p0]
/// C1: [t1p0]
/// C2: [t1p1, t2p0, t2p1, t2p2]
#[test]
fn test_roundrobin_assignor_more() {
let assignor = RoundRobinAssignor::default();
let metadata = Metadata::with_topics(vec![
("t0".into(), vec![PartitionInfo::new(0)]),
("t1".into(), vec![PartitionInfo::new(0), PartitionInfo::new(1)]),
(
"t2".into(),
vec![PartitionInfo::new(0), PartitionInfo::new(1), PartitionInfo::new(2)],
),
]);
let subscriptions = HashMap::from_iter(
vec![
(
"c0".into(),
Subscription {
topics: vec!["t0".into()],
user_data: None,
},
),
(
"c1".into(),
Subscription {
topics: vec!["t0".into(), "t1".into()],
user_data: None,
},
),
(
"c2".into(),
Subscription {
topics: vec!["t0".into(), "t1".into(), "t2".into()],
user_data: None,
},
),
].into_iter(),
);
let assignment = assignor.assign(&metadata, subscriptions);
assert_eq!(assignment.len(), 3);
assert_eq!(
assignment["c0"],
Assignment {
partitions: vec![topic_partition!("t0", 0)],
user_data: None,
}
);
assert_eq!(
assignment["c1"],
Assignment {
partitions: vec![topic_partition!("t1", 0)],
user_data: None,
}
);
assert_eq!(
assignment["c2"],
Assignment {
partitions: vec![
topic_partition!("t1", 1),
topic_partition!("t2", 0),
topic_partition!("t2", 1),
topic_partition!("t2", 2),
],
user_data: None,
}
);
}
}
| 34.637562 | 118 | 0.557194 |
90407282a5ea4836725d7f011a6ca3aaa2404c3c | 5,953 | // This file is auto-generated! Any changes to this file will be lost!
mod tests {
use woothee::parser::Parser;
#[test]
fn test_mobilephone_misc() {
let parser = Parser::new();
match parser.parse(r#"Mozilla/5.0 (jig browser core; SH03B)"#) {
None => panic!(r#"invalid parse. "Mozilla/5.0 (jig browser core; SH03B)""#),
Some(result) => {
assert_eq!(result.category, "mobilephone");
assert_eq!(result.name, "jig browser");
assert_eq!(result.os, "jig");
assert_eq!(result.os_version, "UNKNOWN".to_string());
assert_eq!(result.version, "SH03B");
}
}
match parser.parse(r#"Mozilla/4.0 (jig browser9i 1.5.0; F10B; 2004)"#) {
None => panic!(r#"invalid parse. "Mozilla/4.0 (jig browser9i 1.5.0; F10B; 2004)""#),
Some(result) => {
assert_eq!(result.category, "mobilephone");
assert_eq!(result.name, "jig browser");
assert_eq!(result.os, "jig");
assert_eq!(result.os_version, "UNKNOWN".to_string());
assert_eq!(result.version, "F10B");
}
}
match parser.parse(r#"Mozilla/4.0 (jig browser9)"#) {
None => panic!(r#"invalid parse. "Mozilla/4.0 (jig browser9)""#),
Some(result) => {
assert_eq!(result.category, "mobilephone");
assert_eq!(result.name, "jig browser");
assert_eq!(result.os, "jig");
assert_eq!(result.os_version, "UNKNOWN".to_string());
assert_eq!(result.version, "UNKNOWN");
}
}
match parser.parse(r#"emobile/1.0.0 (H11T; like Gecko; Wireless) NetFront/3.4"#) {
None => panic!(r#"invalid parse. "emobile/1.0.0 (H11T; like Gecko; Wireless) NetFront/3.4""#),
Some(result) => {
assert_eq!(result.category, "mobilephone");
assert_eq!(result.name, "emobile");
assert_eq!(result.os, "emobile");
assert_eq!(result.os_version, "UNKNOWN".to_string());
assert_eq!(result.version, "UNKNOWN");
}
}
match parser.parse(r#"IAC/1.0 (H31IA;like Gecko;OpenBrowser) WWW Browser/ver1.0"#) {
None => panic!(r#"invalid parse. "IAC/1.0 (H31IA;like Gecko;OpenBrowser) WWW Browser/ver1.0""#),
Some(result) => {
assert_eq!(result.category, "mobilephone");
assert_eq!(result.name, "emobile");
assert_eq!(result.os, "emobile");
assert_eq!(result.os_version, "UNKNOWN".to_string());
assert_eq!(result.version, "UNKNOWN");
}
}
match parser.parse(r#"Mozilla/5.0 (H11T; like Gecko; OpenBrowser) NetFront/3.4"#) {
None => panic!(r#"invalid parse. "Mozilla/5.0 (H11T; like Gecko; OpenBrowser) NetFront/3.4""#),
Some(result) => {
assert_eq!(result.category, "mobilephone");
assert_eq!(result.name, "emobile");
assert_eq!(result.os, "emobile");
assert_eq!(result.os_version, "UNKNOWN".to_string());
assert_eq!(result.version, "UNKNOWN");
}
}
match parser.parse(r#"Huawei/1.0/H12HW/B000 Browser/Obigo-Browser/Q04A"#) {
None => panic!(r#"invalid parse. "Huawei/1.0/H12HW/B000 Browser/Obigo-Browser/Q04A""#),
Some(result) => {
assert_eq!(result.category, "mobilephone");
assert_eq!(result.name, "emobile");
assert_eq!(result.os, "emobile");
assert_eq!(result.os_version, "UNKNOWN".to_string());
assert_eq!(result.version, "UNKNOWN");
}
}
match parser.parse(r#"Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaE66-1/500.21.009; Profile/MIDP-2.0 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413"#) {
None => panic!(r#"invalid parse. "Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaE66-1/500.21.009; Profile/MIDP-2.0 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413""#),
Some(result) => {
assert_eq!(result.category, "mobilephone");
assert_eq!(result.name, "Safari");
assert_eq!(result.os, "SymbianOS");
assert_eq!(result.os_version, "UNKNOWN".to_string());
assert_eq!(result.version, "UNKNOWN");
}
}
match parser.parse(r#"Mozilla/5.0 (en-us) AppleWebKit/534.14 (KHTML, like Gecko; Google Wireless Transcoder) Chrome/9.0.597 Safari/534.14"#) {
None => panic!(r#"invalid parse. "Mozilla/5.0 (en-us) AppleWebKit/534.14 (KHTML, like Gecko; Google Wireless Transcoder) Chrome/9.0.597 Safari/534.14""#),
Some(result) => {
assert_eq!(result.category, "mobilephone");
assert_eq!(result.name, "Mobile Transcoder");
assert_eq!(result.os, "Mobile Transcoder");
assert_eq!(result.os_version, "UNKNOWN".to_string());
assert_eq!(result.version, "Google");
}
}
match parser
.parse(r#"Mozilla/5.0 (compatible; livedoor-Mobile-Gateway/0.02; +http://p.m.livedoor.com/help.html)"#)
{
None => panic!(
r#"invalid parse. "Mozilla/5.0 (compatible; livedoor-Mobile-Gateway/0.02; +http://p.m.livedoor.com/help.html)""#
),
Some(result) => {
assert_eq!(result.category, "mobilephone");
assert_eq!(result.name, "Mobile Transcoder");
assert_eq!(result.os, "Mobile Transcoder");
assert_eq!(result.os_version, "UNKNOWN".to_string());
assert_eq!(result.version, "livedoor");
}
}
}
}
| 51.318966 | 206 | 0.543088 |
f81eac64275f906d83fdd3c36dce421d16358267 | 44,836 | use std::panic::Location;
use std::fmt::Debug;
use std::pin::Pin;
use std::marker::Unpin;
use std::future::Future;
use std::task::{Context, Poll};
use log::trace;
use futures_core::stream::Stream;
use futures_util::stream;
use futures_util::stream::StreamExt;
use pin_project::pin_project;
use crate::internal::Map2;
use crate::signal_vec::{VecDiff, SignalVec};
// TODO impl for AssertUnwindSafe ?
// TODO documentation for Signal contract:
// * a Signal must always return Poll::Ready(Some(...)) the first time it is polled, no exceptions
// * after the first time it can then return Poll::Ready(None) which means that the Signal is ended (i.e. there won't be any future changes)
// * or it can return Poll::Pending, which means the Signal hasn't changed from its previous value
// * whenever the Signal's value has changed, it must call cx.waker().wake_by_ref() which will notify the consumer that the Signal has changed
// * If wake_by_ref() hasn't been called, then the consumer assumes that nothing has changed, so it won't re-poll the Signal
// * unlike Streams, the consumer does not poll again if it receives Poll::Ready(Some(...)), it will only repoll if wake_by_ref() is called
// * If the Signal returns Poll::Ready(None) then the consumer must not re-poll the Signal
#[must_use = "Signals do nothing unless polled"]
pub trait Signal {
type Item;
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>>;
}
// Copied from Future in the Rust stdlib
impl<'a, A> Signal for &'a mut A where A: ?Sized + Signal + Unpin {
type Item = A::Item;
#[inline]
fn poll_change(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
A::poll_change(Pin::new(&mut **self), cx)
}
}
// Copied from Future in the Rust stdlib
impl<A> Signal for Box<A> where A: ?Sized + Signal + Unpin {
type Item = A::Item;
#[inline]
fn poll_change(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
A::poll_change(Pin::new(&mut *self), cx)
}
}
// Copied from Future in the Rust stdlib
impl<A> Signal for Pin<A>
where A: Unpin + ::std::ops::DerefMut,
A::Target: Signal {
type Item = <<A as ::std::ops::Deref>::Target as Signal>::Item;
#[inline]
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
Pin::get_mut(self).as_mut().poll_change(cx)
}
}
// TODO Seal this
pub trait SignalExt: Signal {
/// Creates a `Stream` which contains the values of `self`.
///
/// When the output `Stream` is spawned:
///
/// 1. It immediately outputs the current value of `self`.
///
/// 2. Whenever `self` changes it outputs the new value of `self`.
///
/// Like *all* of the `Signal` methods, `to_stream` might skip intermediate changes.
/// So you ***cannot*** rely upon it containing every intermediate change.
/// But you ***can*** rely upon it always containing the most recent change.
///
/// # Performance
///
/// This is ***extremely*** efficient: it is *guaranteed* constant time, and it does not do
/// any heap allocation.
#[inline]
fn to_stream(self) -> SignalStream<Self>
where Self: Sized {
SignalStream {
signal: self,
}
}
// TODO maybe remove this ?
#[inline]
fn to_future(self) -> SignalFuture<Self>
where Self: Sized {
SignalFuture {
signal: self,
value: None,
}
}
/// Creates a `Signal` which uses a closure to transform the value.
///
/// When the output `Signal` is spawned:
///
/// 1. It calls the closure with the current value of `self`.
///
/// 2. Then it puts the return value of the closure into the output `Signal`.
///
/// 3. Whenever `self` changes it repeats the above steps.
///
/// This happens automatically and efficiently.
///
/// It will call the closure at most once for each change in `self`.
///
/// Like *all* of the `Signal` methods, `map` might skip intermediate changes.
/// So you ***cannot*** rely upon the closure being called for every intermediate change.
/// But you ***can*** rely upon it always being called with the most recent change.
///
/// # Examples
///
/// Add `1` to the value:
///
/// ```rust
/// # use futures_signals::signal::{always, SignalExt};
/// # let input = always(1);
/// let mapped = input.map(|value| value + 1);
/// ```
///
/// `mapped` will always contain the current value of `input`, except with `1` added to it.
///
/// If `input` has the value `10`, then `mapped` will have the value `11`.
///
/// If `input` has the value `5`, then `mapped` will have the value `6`, etc.
///
/// ----
///
/// Formatting to a `String`:
///
/// ```rust
/// # use futures_signals::signal::{always, SignalExt};
/// # let input = always(1);
/// let mapped = input.map(|value| format!("{}", value));
/// ```
///
/// `mapped` will always contain the current value of `input`, except formatted as a `String`.
///
/// If `input` has the value `10`, then `mapped` will have the value `"10"`.
///
/// If `input` has the value `5`, then `mapped` will have the value `"5"`, etc.
///
/// # Performance
///
/// This is ***extremely*** efficient: it is *guaranteed* constant time, and it does not do
/// any heap allocation.
#[inline]
fn map<A, B>(self, callback: B) -> Map<Self, B>
where B: FnMut(Self::Item) -> A,
Self: Sized {
Map {
signal: self,
callback,
}
}
#[inline]
fn inspect<A>(self, callback: A) -> Inspect<Self, A>
where A: FnMut(&Self::Item),
Self: Sized {
Inspect {
signal: self,
callback,
}
}
#[inline]
fn eq(self, value: Self::Item) -> Eq<Self>
where Self::Item: PartialEq,
Self: Sized {
Eq {
signal: self,
matches: None,
value,
}
}
#[inline]
fn neq(self, value: Self::Item) -> Neq<Self>
where Self::Item: PartialEq,
Self: Sized {
Neq {
signal: self,
matches: None,
value,
}
}
/// Creates a `Signal` which uses a closure to transform the value.
///
/// This is exactly the same as `map`, except:
///
/// 1. It calls the closure with a mutable reference to the input value.
///
/// 2. If the new input value is the same as the old input value, it will ***not*** call the closure, instead
/// it will completely ignore the new value, like as if it never happened.
///
/// It uses the `PartialEq` implementation to determine whether the new value is the same as the old value.
///
/// It only keeps track of the most recent value: that means that it ***won't*** call the closure for consecutive
/// duplicates, however it ***will*** call the closure for non-consecutive duplicates.
///
/// Because `dedupe_map` has the same behavior as `map`, it is useful solely as a performance optimization.
///
/// # Performance
///
/// The performance is the same as `map`, except with an additional call to `eq`.
///
/// If the `eq` call is fast, then `dedupe_map` can be faster than `map`, because it doesn't call the closure
/// when the new and old values are the same, and it also doesn't update any child Signals.
///
/// On the other hand, if the `eq` call is slow, then `dedupe_map` is probably slower than `map`.
#[inline]
fn dedupe_map<A, B>(self, callback: B) -> DedupeMap<Self, B>
// TODO should this use & instead of &mut ?
where B: FnMut(&mut Self::Item) -> A,
Self::Item: PartialEq,
Self: Sized {
DedupeMap {
old_value: None,
signal: self,
callback,
}
}
#[inline]
fn dedupe(self) -> Dedupe<Self>
where Self::Item: PartialEq,
Self: Sized {
Dedupe {
old_value: None,
signal: self,
}
}
#[inline]
fn dedupe_cloned(self) -> DedupeCloned<Self>
where Self::Item: PartialEq,
Self: Sized {
DedupeCloned {
old_value: None,
signal: self,
}
}
/// Creates a `Signal` which uses a closure to asynchronously transform the value.
///
/// When the output `Signal` is spawned:
///
/// 1. It calls the closure with the current value of `self`.
///
/// 2. The closure returns a `Future`. It waits for that `Future` to finish, and then
/// it puts the return value of the `Future` into the output `Signal`.
///
/// 3. Whenever `self` changes it repeats the above steps.
///
/// It will call the closure at most once for each change in `self`.
///
/// Because Signals must always have a current value, if the `Future` is not ready yet, then the
/// output `Signal` will start with the value `None`. When the `Future` finishes it then changes
/// to `Some`. This can be used to detect whether the `Future` has finished or not.
///
/// If `self` changes before the old `Future` is finished, it will cancel the old `Future`.
/// That means if `self` changes faster than the `Future`, then it will never output any values.
///
/// Like *all* of the `Signal` methods, `map_future` might skip intermediate changes.
/// So you ***cannot*** rely upon the closure being called for every intermediate change.
/// But you ***can*** rely upon it always being called with the most recent change.
///
/// # Examples
///
/// Call an asynchronous network API whenever the input changes:
///
/// ```rust
/// # use futures_signals::signal::{always, SignalExt};
/// # use futures_util::future::{ready, Ready};
/// # fn call_network_api(value: u32) -> Ready<()> { ready(()) }
/// # fn main() {
/// # let input = always(1);
/// #
/// let mapped = input.map_future(|value| call_network_api(value));
/// # }
/// ```
///
/// # Performance
///
/// This is ***extremely*** efficient: it does not do any heap allocation, and it has *very* little overhead.
///
/// Of course the performance will also depend upon the `Future` which is returned from the closure.
#[inline]
fn map_future<A, B>(self, callback: B) -> MapFuture<Self, A, B>
where A: Future,
B: FnMut(Self::Item) -> A,
Self: Sized {
MapFuture {
signal: Some(self),
future: None,
callback,
first: true,
}
}
/// Creates a `Signal` which uses a closure to filter and transform the value.
///
/// When the output `Signal` is spawned:
///
/// 1. The output `Signal` starts with the value `None`.
///
/// 2. It calls the closure with the current value of `self`.
///
/// 3. If the closure returns `Some`, then it puts the return value of the closure into the output `Signal`.
///
/// 4. If the closure returns `None`, then it does nothing.
///
/// 5. Whenever `self` changes it repeats steps 2 - 4.
///
/// The output `Signal` will only be `None` for the initial value. After that it will always be `Some`.
///
/// If the closure returns `Some` for the initial value, then the output `Signal` will never be `None`.
///
/// It will call the closure at most once for each change in `self`.
///
/// Like *all* of the `Signal` methods, `filter_map` might skip intermediate changes.
/// So you ***cannot*** rely upon the closure being called for every intermediate change.
/// But you ***can*** rely upon it always being called with the most recent change.
///
/// # Examples
///
/// Add `1` to the value, but only if the value is less than `5`:
///
/// ```rust
/// # use futures_signals::signal::{always, SignalExt};
/// # let input = always(1);
/// let mapped = input.filter_map(|value| {
/// if value < 5 {
/// Some(value + 1)
///
/// } else {
/// None
/// }
/// });
/// ```
///
/// If the initial value of `input` is `5` or greater then `mapped` will be `None`.
///
/// If the current value of `input` is `5` or greater then `mapped` will keep its old value.
///
/// Otherwise `mapped` will be `Some(input + 1)`.
///
/// # Performance
///
/// This is ***extremely*** efficient: it does not do any heap allocation, and it has *very* little overhead.
#[inline]
fn filter_map<A, B>(self, callback: B) -> FilterMap<Self, B>
where B: FnMut(Self::Item) -> Option<A>,
Self: Sized {
FilterMap {
signal: self,
callback,
first: true,
}
}
/// Creates a `Signal` which delays updates until a `Future` finishes.
///
/// This can be used to throttle a `Signal` so that it only updates once every X seconds.
///
/// If multiple updates happen while it's being delayed, it will only output the most recent
/// value.
///
/// # Examples
///
/// Wait 1 second between each update:
///
/// ```rust
/// # use core::future::Future;
/// # use futures_signals::signal::{always, SignalExt};
/// # fn sleep(ms: i32) -> impl Future<Output = ()> { async {} }
/// # let input = always(1);
/// let output = input.throttle(|| sleep(1_000));
/// ```
///
/// # Performance
///
/// This is ***extremely*** efficient: it does not do any heap allocation, and it has *very* little overhead.
#[inline]
fn throttle<A, B>(self, callback: B) -> Throttle<Self, A, B>
where A: Future<Output = ()>,
B: FnMut() -> A,
Self: Sized {
Throttle {
signal: Some(self),
future: None,
callback,
}
}
/// Creates a `Signal` which flattens `self`.
///
/// When the output `Signal` is spawned:
///
/// 1. It retrieves the current value of `self` (this value is also a `Signal`).
///
/// 2. Then it puts the current value of the inner `Signal` into the output `Signal`.
///
/// 3. Whenever the inner `Signal` changes it puts the new value into the output `Signal`.
///
/// 4. Whenever `self` changes it repeats the above steps.
///
/// This happens automatically and efficiently.
///
/// Like *all* of the `Signal` methods, `flatten` might skip intermediate changes.
/// So you ***cannot*** rely upon it containing every intermediate change.
/// But you ***can*** rely upon it always containing the most recent change.
///
/// # Performance
///
/// This is very efficient: it is *guaranteed* constant time, and it does not do
/// any heap allocation.
#[inline]
fn flatten(self) -> Flatten<Self>
where Self::Item: Signal,
Self: Sized {
Flatten {
signal: Some(self),
inner: None,
}
}
#[inline]
fn switch<A, B>(self, callback: B) -> Switch<Self, A, B>
where A: Signal,
B: FnMut(Self::Item) -> A,
Self: Sized {
Switch {
inner: self.map(callback).flatten()
}
}
#[inline]
fn switch_signal_vec<A, F>(self, callback: F) -> SwitchSignalVec<Self, A, F>
where A: SignalVec,
F: FnMut(Self::Item) -> A,
Self: Sized {
SwitchSignalVec {
signal: Some(self),
signal_vec: None,
callback,
is_empty: true,
pending: None,
}
}
#[inline]
// TODO file Rust bug about bad error message when `callback` isn't marked as `mut`
fn for_each<U, F>(self, callback: F) -> ForEach<Self, U, F>
where U: Future<Output = ()>,
F: FnMut(Self::Item) -> U,
Self: Sized {
// TODO a bit hacky
ForEach {
inner: SignalStream {
signal: self,
}.for_each(callback)
}
}
#[inline]
fn to_signal_vec(self) -> SignalSignalVec<Self>
where Self: Sized {
SignalSignalVec {
signal: self
}
}
#[inline]
fn wait_for(self, value: Self::Item) -> WaitFor<Self>
where Self::Item: PartialEq,
Self: Sized {
WaitFor {
signal: self,
value: value,
}
}
#[inline]
fn first(self) -> First<Self> where Self: Sized {
First {
signal: Some(self),
}
}
#[inline]
#[track_caller]
fn debug(self) -> SignalDebug<Self> where Self: Sized, Self::Item: Debug {
SignalDebug {
signal: self,
location: Location::caller(),
}
}
/// A convenience for calling `Signal::poll_change` on `Unpin` types.
#[inline]
fn poll_change_unpin(&mut self, cx: &mut Context) -> Poll<Option<Self::Item>> where Self: Unpin + Sized {
Pin::new(self).poll_change(cx)
}
#[inline]
fn boxed<'a>(self) -> Pin<Box<dyn Signal<Item = Self::Item> + Send + 'a>>
where Self: Sized + Send + 'a {
Box::pin(self)
}
#[inline]
fn boxed_local<'a>(self) -> Pin<Box<dyn Signal<Item = Self::Item> + 'a>>
where Self: Sized + 'a {
Box::pin(self)
}
}
// TODO why is this ?Sized
impl<T: ?Sized> SignalExt for T where T: Signal {}
// TODO make this into a method later
#[inline]
pub fn not<A>(signal: A) -> impl Signal<Item = bool>
where A: Signal<Item = bool> {
signal.map(|x| !x)
}
// TODO make this into a method later
// TODO use short-circuiting if the left signal returns false ?
#[inline]
pub fn and<A, B>(left: A, right: B) -> impl Signal<Item = bool>
where A: Signal<Item = bool>,
B: Signal<Item = bool> {
Map2::new(left, right, |a, b| *a && *b)
}
// TODO make this into a method later
// TODO use short-circuiting if the left signal returns true ?
#[inline]
pub fn or<A, B>(left: A, right: B) -> impl Signal<Item = bool>
where A: Signal<Item = bool>,
B: Signal<Item = bool> {
Map2::new(left, right, |a, b| *a || *b)
}
#[pin_project]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct SignalDebug<A> {
#[pin]
signal: A,
location: &'static Location<'static>,
}
impl<A> Signal for SignalDebug<A> where A: Signal, A::Item: Debug {
type Item = A::Item;
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let this = self.project();
let poll = this.signal.poll_change(cx);
trace!("[{}] {:#?}", this.location, poll);
poll
}
}
#[pin_project]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct FromFuture<A> {
// TODO is this valid with pinned types ?
#[pin]
future: Option<A>,
first: bool,
}
impl<A> Signal for FromFuture<A> where A: Future {
type Item = Option<A::Output>;
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let mut this = self.project();
// TODO is this valid with pinned types ?
match this.future.as_mut().as_pin_mut().map(|future| future.poll(cx)) {
None => {
Poll::Ready(None)
},
Some(Poll::Ready(value)) => {
this.future.set(None);
Poll::Ready(Some(Some(value)))
},
Some(Poll::Pending) => {
if *this.first {
*this.first = false;
Poll::Ready(Some(None))
} else {
Poll::Pending
}
},
}
}
}
#[inline]
pub fn from_future<A>(future: A) -> FromFuture<A> where A: Future {
FromFuture { future: Some(future), first: true }
}
#[pin_project]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct FromStream<A> {
#[pin]
stream: A,
first: bool,
}
impl<A> Signal for FromStream<A> where A: Stream {
type Item = Option<A::Item>;
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let this = self.project();
match this.stream.poll_next(cx) {
Poll::Ready(None) => {
Poll::Ready(None)
},
Poll::Ready(Some(value)) => {
*this.first = false;
Poll::Ready(Some(Some(value)))
},
Poll::Pending => {
if *this.first {
*this.first = false;
Poll::Ready(Some(None))
} else {
Poll::Pending
}
},
}
}
}
#[inline]
pub fn from_stream<A>(stream: A) -> FromStream<A> where A: Stream {
FromStream { stream, first: true }
}
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct Always<A> {
value: Option<A>,
}
impl<A> Unpin for Always<A> {}
impl<A> Signal for Always<A> {
type Item = A;
#[inline]
fn poll_change(mut self: Pin<&mut Self>, _: &mut Context) -> Poll<Option<Self::Item>> {
Poll::Ready(self.value.take())
}
}
#[inline]
pub fn always<A>(value: A) -> Always<A> {
Always {
value: Some(value),
}
}
#[pin_project]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct First<A> {
#[pin]
signal: Option<A>,
}
impl<A> Signal for First<A> where A: Signal {
type Item = A::Item;
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let mut this = self.project();
// TODO maybe it's safe to replace this with take ?
if let Some(poll) = this.signal.as_mut().as_pin_mut().map(|signal| signal.poll_change(cx)) {
this.signal.set(None);
poll
} else {
Poll::Ready(None)
}
}
}
#[pin_project]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct Switch<A, B, C> where A: Signal, C: FnMut(A::Item) -> B {
#[pin]
inner: Flatten<Map<A, C>>,
}
impl<A, B, C> Signal for Switch<A, B, C>
where A: Signal,
B: Signal,
C: FnMut(A::Item) -> B {
type Item = B::Item;
#[inline]
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
self.project().inner.poll_change(cx)
}
}
// TODO faster for_each which doesn't poll twice on Poll::Ready
#[pin_project]
#[derive(Debug)]
#[must_use = "Futures do nothing unless polled"]
pub struct ForEach<A, B, C> {
#[pin]
inner: stream::ForEach<SignalStream<A>, B, C>,
}
impl<A, B, C> Future for ForEach<A, B, C>
where A: Signal,
B: Future<Output = ()>,
C: FnMut(A::Item) -> B {
type Output = ();
#[inline]
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
self.project().inner.poll(cx)
}
}
#[pin_project]
#[derive(Debug)]
#[must_use = "Streams do nothing unless polled"]
pub struct SignalStream<A> {
#[pin]
signal: A,
}
impl<A: Signal> Stream for SignalStream<A> {
type Item = A::Item;
#[inline]
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
self.project().signal.poll_change(cx)
}
}
// TODO maybe remove this ?
#[pin_project]
#[derive(Debug)]
#[must_use = "Futures do nothing unless polled"]
pub struct SignalFuture<A> where A: Signal {
#[pin]
signal: A,
value: Option<A::Item>,
}
impl<A> Future for SignalFuture<A> where A: Signal {
type Output = A::Item;
#[inline]
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut this = self.project();
loop {
return match this.signal.as_mut().poll_change(cx) {
Poll::Ready(None) => {
Poll::Ready(this.value.take().unwrap())
},
Poll::Ready(Some(new_value)) => {
*this.value = Some(new_value);
continue;
},
Poll::Pending => {
Poll::Pending
},
}
}
}
}
#[pin_project(project = MapProj)]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct Map<A, B> {
#[pin]
signal: A,
callback: B,
}
impl<A, B, C> Signal for Map<A, B>
where A: Signal,
B: FnMut(A::Item) -> C {
type Item = C;
#[inline]
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let MapProj { signal, callback } = self.project();
signal.poll_change(cx).map(|opt| opt.map(|value| callback(value)))
}
}
#[pin_project(project = EqProj)]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct Eq<A> where A: Signal {
#[pin]
signal: A,
matches: Option<bool>,
value: A::Item,
}
impl<A> Signal for Eq<A>
where A: Signal,
A::Item: PartialEq {
type Item = bool;
#[inline]
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let EqProj { signal, matches, value } = self.project();
match signal.poll_change(cx) {
Poll::Ready(Some(new_value)) => {
let new = Some(new_value == *value);
if *matches != new {
*matches = new;
Poll::Ready(new)
} else {
Poll::Pending
}
},
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
#[pin_project(project = NeqProj)]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct Neq<A> where A: Signal {
#[pin]
signal: A,
matches: Option<bool>,
value: A::Item,
}
impl<A> Signal for Neq<A>
where A: Signal,
A::Item: PartialEq {
type Item = bool;
#[inline]
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let NeqProj { signal, matches, value } = self.project();
match signal.poll_change(cx) {
Poll::Ready(Some(new_value)) => {
let new = Some(new_value != *value);
if *matches != new {
*matches = new;
Poll::Ready(new)
} else {
Poll::Pending
}
},
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
#[pin_project]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct Inspect<A, B> {
#[pin]
signal: A,
callback: B,
}
impl<A, B> Signal for Inspect<A, B>
where A: Signal,
B: FnMut(&A::Item) {
type Item = A::Item;
#[inline]
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let this = self.project();
let poll = this.signal.poll_change(cx);
if let Poll::Ready(Some(ref value)) = poll {
(this.callback)(value);
}
poll
}
}
#[pin_project(project = MapFutureProj)]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct MapFuture<A, B, C> {
#[pin]
signal: Option<A>,
#[pin]
future: Option<B>,
callback: C,
first: bool,
}
impl<A, B, C> Signal for MapFuture<A, B, C>
where A: Signal,
B: Future,
C: FnMut(A::Item) -> B {
type Item = Option<B::Output>;
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let MapFutureProj { mut signal, mut future, callback, first } = self.project();
let mut done = false;
loop {
match signal.as_mut().as_pin_mut().map(|signal| signal.poll_change(cx)) {
None => {
done = true;
},
Some(Poll::Ready(None)) => {
signal.set(None);
done = true;
},
Some(Poll::Ready(Some(value))) => {
let value = Some(callback(value));
future.set(value);
continue;
},
Some(Poll::Pending) => {},
}
break;
}
match future.as_mut().as_pin_mut().map(|future| future.poll(cx)) {
None => {},
Some(Poll::Ready(value)) => {
future.set(None);
*first = false;
return Poll::Ready(Some(Some(value)));
},
Some(Poll::Pending) => {
done = false;
},
}
if *first {
*first = false;
Poll::Ready(Some(None))
} else if done {
Poll::Ready(None)
} else {
Poll::Pending
}
}
}
#[pin_project(project = ThrottleProj)]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct Throttle<A, B, C> where A: Signal {
#[pin]
signal: Option<A>,
#[pin]
future: Option<B>,
callback: C,
}
impl<A, B, C> Signal for Throttle<A, B, C>
where A: Signal,
B: Future<Output = ()>,
C: FnMut() -> B {
type Item = A::Item;
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let ThrottleProj { mut signal, mut future, callback } = self.project();
match future.as_mut().as_pin_mut().map(|future| future.poll(cx)) {
None => {},
Some(Poll::Ready(())) => {
future.set(None);
},
Some(Poll::Pending) => {
// TODO does this need to poll the Signal as well ?
return Poll::Pending;
},
}
match signal.as_mut().as_pin_mut().map(|signal| signal.poll_change(cx)) {
None => {
Poll::Ready(None)
},
Some(Poll::Ready(None)) => {
// TODO maybe remove the future too ?
signal.set(None);
Poll::Ready(None)
},
Some(Poll::Ready(Some(value))) => {
future.set(Some(callback()));
if let Some(Poll::Ready(())) = future.as_mut().as_pin_mut().map(|future| future.poll(cx)) {
future.set(None);
}
Poll::Ready(Some(value))
},
Some(Poll::Pending) => {
Poll::Pending
},
}
}
}
#[pin_project]
#[derive(Debug)]
#[must_use = "Futures do nothing unless polled"]
pub struct WaitFor<A>
where A: Signal,
A::Item: PartialEq {
#[pin]
signal: A,
value: A::Item,
}
impl<A> Future for WaitFor<A>
where A: Signal,
A::Item: PartialEq {
type Output = Option<A::Item>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut this = self.project();
loop {
let poll = this.signal.as_mut().poll_change(cx);
if let Poll::Ready(Some(ref new_value)) = poll {
if new_value != this.value {
continue;
}
}
return poll;
}
}
}
#[pin_project]
#[derive(Debug)]
#[must_use = "SignalVecs do nothing unless polled"]
pub struct SignalSignalVec<A> {
#[pin]
signal: A,
}
impl<A, B> SignalVec for SignalSignalVec<A>
where A: Signal<Item = Vec<B>> {
type Item = B;
#[inline]
fn poll_vec_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<VecDiff<Self::Item>>> {
self.project().signal.poll_change(cx).map(|opt| opt.map(|values| VecDiff::Replace { values }))
}
}
// TODO should this inline ?
fn dedupe<A, S, F>(mut signal: Pin<&mut S>, cx: &mut Context, old_value: &mut Option<S::Item>, f: F) -> Poll<Option<A>>
where S: Signal,
S::Item: PartialEq,
F: FnOnce(&mut S::Item) -> A {
loop {
return match signal.as_mut().poll_change(cx) {
Poll::Ready(Some(mut new_value)) => {
let has_changed = match old_value {
Some(old_value) => *old_value != new_value,
None => true,
};
if has_changed {
let output = f(&mut new_value);
*old_value = Some(new_value);
Poll::Ready(Some(output))
} else {
continue;
}
},
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
#[pin_project(project = DedupeMapProj)]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct DedupeMap<A, B> where A: Signal {
old_value: Option<A::Item>,
#[pin]
signal: A,
callback: B,
}
impl<A, B, C> Signal for DedupeMap<A, B>
where A: Signal,
A::Item: PartialEq,
// TODO should this use & instead of &mut ?
// TODO should this use Fn instead ?
B: FnMut(&mut A::Item) -> C {
type Item = C;
// TODO should this use #[inline] ?
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let DedupeMapProj { old_value, signal, callback } = self.project();
dedupe(signal, cx, old_value, callback)
}
}
#[pin_project(project = DedupeProj)]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct Dedupe<A> where A: Signal {
old_value: Option<A::Item>,
#[pin]
signal: A,
}
impl<A> Signal for Dedupe<A>
where A: Signal,
A::Item: PartialEq + Copy {
type Item = A::Item;
// TODO should this use #[inline] ?
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let DedupeProj { old_value, signal } = self.project();
dedupe(signal, cx, old_value, |value| *value)
}
}
#[pin_project(project = DedupeClonedProj)]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct DedupeCloned<A> where A: Signal {
old_value: Option<A::Item>,
#[pin]
signal: A,
}
impl<A> Signal for DedupeCloned<A>
where A: Signal,
A::Item: PartialEq + Clone {
type Item = A::Item;
// TODO should this use #[inline] ?
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let DedupeClonedProj { old_value, signal } = self.project();
dedupe(signal, cx, old_value, |value| value.clone())
}
}
#[pin_project(project = FilterMapProj)]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct FilterMap<A, B> {
#[pin]
signal: A,
callback: B,
first: bool,
}
impl<A, B, C> Signal for FilterMap<A, B>
where A: Signal,
B: FnMut(A::Item) -> Option<C> {
type Item = Option<C>;
// TODO should this use #[inline] ?
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let FilterMapProj { mut signal, callback, first } = self.project();
loop {
return match signal.as_mut().poll_change(cx) {
Poll::Ready(Some(value)) => match callback(value) {
Some(value) => {
*first = false;
Poll::Ready(Some(Some(value)))
},
None => {
if *first {
*first = false;
Poll::Ready(Some(None))
} else {
continue;
}
},
},
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
}
// TODO test the Unpin impl of this
// impl<A> Unpin for Flatten<A> where A: Unpin + Signal, A::Item: Unpin {}
#[pin_project(project = FlattenProj)]
#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct Flatten<A> where A: Signal {
#[pin]
signal: Option<A>,
#[pin]
inner: Option<A::Item>,
}
// Poll parent => Has inner => Poll inner => Output
// --------------------------------------------------------
// Some(inner) => => Some(value) => Some(value)
// Some(inner) => => None => Pending
// Some(inner) => => Pending => Pending
// None => Some(inner) => Some(value) => Some(value)
// None => Some(inner) => None => None
// None => Some(inner) => Pending => Pending
// None => None => => None
// Pending => Some(inner) => Some(value) => Some(value)
// Pending => Some(inner) => None => Pending
// Pending => Some(inner) => Pending => Pending
// Pending => None => => Pending
impl<A> Signal for Flatten<A>
where A: Signal,
A::Item: Signal {
type Item = <A::Item as Signal>::Item;
#[inline]
fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let FlattenProj { mut signal, mut inner } = self.project();
let done = match signal.as_mut().as_pin_mut().map(|signal| signal.poll_change(cx)) {
None => true,
Some(Poll::Ready(None)) => {
signal.set(None);
true
},
Some(Poll::Ready(Some(new_inner))) => {
inner.set(Some(new_inner));
false
},
Some(Poll::Pending) => false,
};
match inner.as_mut().as_pin_mut().map(|inner| inner.poll_change(cx)) {
Some(Poll::Ready(None)) => {
inner.set(None);
},
Some(poll) => {
return poll;
},
None => {},
}
if done {
Poll::Ready(None)
} else {
Poll::Pending
}
}
}
#[pin_project(project = SwitchSignalVecProj)]
#[derive(Debug)]
#[must_use = "SignalVecs do nothing unless polled"]
pub struct SwitchSignalVec<A, B, C> where B: SignalVec {
#[pin]
signal: Option<A>,
#[pin]
signal_vec: Option<B>,
callback: C,
is_empty: bool,
pending: Option<VecDiff<B::Item>>,
}
impl<A, B, C> SignalVec for SwitchSignalVec<A, B, C>
where A: Signal,
B: SignalVec,
C: FnMut(A::Item) -> B {
type Item = B::Item;
fn poll_vec_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<VecDiff<Self::Item>>> {
let SwitchSignalVecProj { mut signal, mut signal_vec, callback, is_empty, pending } = self.project();
match pending.take() {
Some(value) => Poll::Ready(Some(value)),
None => {
let mut signal_value = None;
// TODO is this loop a good idea ?
let signal_done = loop {
break match signal.as_mut().as_pin_mut().map(|signal| signal.poll_change(cx)) {
None => {
Poll::Ready(None)
},
Some(Poll::Pending) => {
Poll::Pending
},
Some(Poll::Ready(None)) => {
signal.set(None);
Poll::Ready(None)
},
Some(Poll::Ready(Some(value))) => {
signal_value = Some(value);
continue;
},
}
};
fn done<A>(is_empty: &mut bool, signal_done: Poll<Option<VecDiff<A>>>) -> Poll<Option<VecDiff<A>>> {
if *is_empty {
signal_done
} else {
*is_empty = true;
Poll::Ready(Some(VecDiff::Replace { values: vec![] }))
}
}
fn replace<A>(is_empty: &mut bool, values: Vec<A>) -> Poll<Option<VecDiff<A>>> {
let new_is_empty = values.is_empty();
if *is_empty && new_is_empty {
Poll::Pending
} else {
*is_empty = new_is_empty;
Poll::Ready(Some(VecDiff::Replace { values }))
}
}
if let Some(value) = signal_value {
signal_vec.set(Some(callback(value)));
match signal_vec.as_mut().as_pin_mut().map(|signal| signal.poll_vec_change(cx)) {
None => {
done(is_empty, signal_done)
},
Some(Poll::Pending) => {
done(is_empty, Poll::Pending)
},
Some(Poll::Ready(None)) => {
signal_vec.set(None);
done(is_empty, signal_done)
},
Some(Poll::Ready(Some(VecDiff::Replace { values }))) => {
replace(is_empty, values)
},
Some(Poll::Ready(Some(vec_diff))) => {
if *is_empty {
*is_empty = false;
Poll::Ready(Some(vec_diff))
} else {
*pending = Some(vec_diff);
*is_empty = true;
Poll::Ready(Some(VecDiff::Replace { values: vec![] }))
}
},
}
} else {
match signal_vec.as_mut().as_pin_mut().map(|signal| signal.poll_vec_change(cx)) {
None => {
signal_done
},
Some(Poll::Pending) => {
Poll::Pending
},
Some(Poll::Ready(None)) => {
signal_vec.set(None);
signal_done
},
Some(Poll::Ready(Some(VecDiff::Replace { values }))) => {
replace(is_empty, values)
},
Some(Poll::Ready(Some(vec_diff))) => {
*is_empty = false;
Poll::Ready(Some(vec_diff))
},
}
}
},
}
}
}
| 30.335589 | 143 | 0.500067 |
2698f964cc69dfd128fa4aa719b7b0bf9d1f6449 | 3,268 | use crate::prelude::*;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue, Value};
pub struct FromToml;
#[async_trait]
impl WholeStreamCommand for FromToml {
fn name(&self) -> &str {
"from toml"
}
fn signature(&self) -> Signature {
Signature::build("from toml")
}
fn usage(&self) -> &str {
"Parse text as .toml and create table."
}
async fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_toml(args).await
}
}
pub fn convert_toml_value_to_nu_value(v: &toml::Value, tag: impl Into<Tag>) -> Value {
let tag = tag.into();
let span = tag.span;
match v {
toml::Value::Boolean(b) => UntaggedValue::boolean(*b).into_value(tag),
toml::Value::Integer(n) => UntaggedValue::int(*n).into_value(tag),
toml::Value::Float(n) => UntaggedValue::decimal_from_float(*n, span).into_value(tag),
toml::Value::String(s) => {
UntaggedValue::Primitive(Primitive::String(String::from(s))).into_value(tag)
}
toml::Value::Array(a) => UntaggedValue::Table(
a.iter()
.map(|x| convert_toml_value_to_nu_value(x, &tag))
.collect(),
)
.into_value(tag),
toml::Value::Datetime(dt) => {
UntaggedValue::Primitive(Primitive::String(dt.to_string())).into_value(tag)
}
toml::Value::Table(t) => {
let mut collected = TaggedDictBuilder::new(&tag);
for (k, v) in t.iter() {
collected.insert_value(k.clone(), convert_toml_value_to_nu_value(v, &tag));
}
collected.into_value()
}
}
}
pub fn from_toml_string_to_value(s: String, tag: impl Into<Tag>) -> Result<Value, toml::de::Error> {
let v: toml::Value = s.parse::<toml::Value>()?;
Ok(convert_toml_value_to_nu_value(&v, tag))
}
pub async fn from_toml(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once().await?;
let tag = args.name_tag();
let input = args.input;
let concat_string = input.collect_string(tag.clone()).await?;
Ok(
match from_toml_string_to_value(concat_string.item, tag.clone()) {
Ok(x) => match x {
Value {
value: UntaggedValue::Table(list),
..
} => futures::stream::iter(list.into_iter().map(ReturnSuccess::value))
.to_output_stream(),
x => OutputStream::one(ReturnSuccess::value(x)),
},
Err(_) => {
return Err(ShellError::labeled_error_with_secondary(
"Could not parse as TOML",
"input cannot be parsed as TOML",
&tag,
"value originates from here",
concat_string.tag,
))
}
},
)
}
#[cfg(test)]
mod tests {
use super::FromToml;
use super::ShellError;
#[test]
fn examples_work_as_expected() -> Result<(), ShellError> {
use crate::examples::test as test_examples;
test_examples(FromToml {})
}
}
| 31.12381 | 100 | 0.566095 |
Subsets and Splits