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
|
---|---|---|---|---|---|
896d200b4858e344ae37bab1f4dc53069eb30ab9
| 8,992 |
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::fs;
use std::path::Path;
use std::sync::Arc;
use engine_traits::{
Error, IterOptions, Iterable, KvEngine, Mutable, Peekable, ReadOptions, Result, WriteOptions,
};
use rocksdb::{DBIterator, Writable, DB};
use crate::db_vector::RocksDBVector;
use crate::options::{RocksReadOptions, RocksWriteOptions};
use crate::util::get_cf_handle;
use crate::{RocksEngineIterator, RocksSnapshot};
#[derive(Clone, Debug)]
#[repr(transparent)]
pub struct RocksEngine(Arc<DB>);
impl RocksEngine {
pub fn from_db(db: Arc<DB>) -> Self {
RocksEngine(db)
}
pub fn from_ref(db: &Arc<DB>) -> &Self {
unsafe { &*(db as *const Arc<DB> as *const RocksEngine) }
}
pub fn as_inner(&self) -> &Arc<DB> {
&self.0
}
pub fn get_sync_db(&self) -> Arc<DB> {
self.0.clone()
}
pub fn exists(path: &str) -> bool {
let path = Path::new(path);
if !path.exists() || !path.is_dir() {
return false;
}
// If path is not an empty directory, we say db exists. If path is not an empty directory
// but db has not been created, `DB::list_column_families` fails and we can clean up
// the directory by this indication.
fs::read_dir(&path).unwrap().next().is_some()
}
}
impl KvEngine for RocksEngine {
type Snapshot = RocksSnapshot;
type WriteBatch = crate::WriteBatch;
fn write_opt(&self, opts: &WriteOptions, wb: &Self::WriteBatch) -> Result<()> {
if wb.get_db().path() != self.0.path() {
return Err(Error::Engine("mismatched db path".to_owned()));
}
let opt: RocksWriteOptions = opts.into();
self.0
.write_opt(wb.as_ref(), &opt.into_raw())
.map_err(Error::Engine)
}
fn write_batch_with_cap(&self, cap: usize) -> Self::WriteBatch {
Self::WriteBatch::with_capacity(Arc::clone(&self.0), cap)
}
fn write_batch(&self) -> Self::WriteBatch {
Self::WriteBatch::new(Arc::clone(&self.0))
}
fn snapshot(&self) -> RocksSnapshot {
RocksSnapshot::new(self.0.clone())
}
fn sync(&self) -> Result<()> {
self.0.sync_wal().map_err(Error::Engine)
}
fn cf_names(&self) -> Vec<&str> {
self.0.cf_names()
}
}
impl Iterable for RocksEngine {
type Iterator = RocksEngineIterator;
fn iterator_opt(&self, opts: IterOptions) -> Result<Self::Iterator> {
let opt: RocksReadOptions = opts.into();
Ok(RocksEngineIterator::from_raw(DBIterator::new(
self.0.clone(),
opt.into_raw(),
)))
}
fn iterator_cf_opt(&self, cf: &str, opts: IterOptions) -> Result<Self::Iterator> {
let handle = get_cf_handle(&self.0, cf)?;
let opt: RocksReadOptions = opts.into();
Ok(RocksEngineIterator::from_raw(DBIterator::new_cf(
self.0.clone(),
handle,
opt.into_raw(),
)))
}
}
impl Peekable for RocksEngine {
type DBVector = RocksDBVector;
fn get_value_opt(&self, opts: &ReadOptions, key: &[u8]) -> Result<Option<RocksDBVector>> {
let opt: RocksReadOptions = opts.into();
let v = self.0.get_opt(key, &opt.into_raw())?;
Ok(v.map(RocksDBVector::from_raw))
}
fn get_value_cf_opt(
&self,
opts: &ReadOptions,
cf: &str,
key: &[u8],
) -> Result<Option<RocksDBVector>> {
let opt: RocksReadOptions = opts.into();
let handle = get_cf_handle(&self.0, cf)?;
let v = self.0.get_cf_opt(handle, key, &opt.into_raw())?;
Ok(v.map(RocksDBVector::from_raw))
}
}
impl Mutable for RocksEngine {
fn put_opt(&self, _: &WriteOptions, key: &[u8], value: &[u8]) -> Result<()> {
self.0.put(key, value).map_err(Error::Engine)
}
fn put_cf_opt(&self, _: &WriteOptions, cf: &str, key: &[u8], value: &[u8]) -> Result<()> {
let handle = get_cf_handle(&self.0, cf)?;
self.0.put_cf(handle, key, value).map_err(Error::Engine)
}
fn delete_opt(&self, _: &WriteOptions, key: &[u8]) -> Result<()> {
self.0.delete(key).map_err(Error::Engine)
}
fn delete_cf_opt(&self, _: &WriteOptions, cf: &str, key: &[u8]) -> Result<()> {
let handle = get_cf_handle(&self.0, cf)?;
self.0.delete_cf(handle, key).map_err(Error::Engine)
}
}
#[cfg(test)]
mod tests {
use engine::rocks::util;
use engine_traits::{Iterable, KvEngine, Mutable, Peekable};
use kvproto::metapb::Region;
use std::sync::Arc;
use tempfile::Builder;
use crate::{RocksEngine, RocksSnapshot};
#[test]
fn test_base() {
let path = Builder::new().prefix("var").tempdir().unwrap();
let cf = "cf";
let engine = RocksEngine::from_db(Arc::new(
util::new_engine(path.path().to_str().unwrap(), None, &[cf], None).unwrap(),
));
let mut r = Region::default();
r.set_id(10);
let key = b"key";
engine.put_msg(key, &r).unwrap();
engine.put_msg_cf(cf, key, &r).unwrap();
let snap = engine.snapshot();
let mut r1: Region = engine.get_msg(key).unwrap().unwrap();
assert_eq!(r, r1);
let r1_cf: Region = engine.get_msg_cf(cf, key).unwrap().unwrap();
assert_eq!(r, r1_cf);
let mut r2: Region = snap.get_msg(key).unwrap().unwrap();
assert_eq!(r, r2);
let r2_cf: Region = snap.get_msg_cf(cf, key).unwrap().unwrap();
assert_eq!(r, r2_cf);
r.set_id(11);
engine.put_msg(key, &r).unwrap();
r1 = engine.get_msg(key).unwrap().unwrap();
r2 = snap.get_msg(key).unwrap().unwrap();
assert_ne!(r1, r2);
let b: Option<Region> = engine.get_msg(b"missing_key").unwrap();
assert!(b.is_none());
}
#[test]
fn test_peekable() {
let path = Builder::new().prefix("var").tempdir().unwrap();
let cf = "cf";
let engine = RocksEngine::from_db(Arc::new(
util::new_engine(path.path().to_str().unwrap(), None, &[cf], None).unwrap(),
));
engine.put(b"k1", b"v1").unwrap();
engine.put_cf(cf, b"k1", b"v2").unwrap();
assert_eq!(&*engine.get_value(b"k1").unwrap().unwrap(), b"v1");
assert!(engine.get_value_cf("foo", b"k1").is_err());
assert_eq!(&*engine.get_value_cf(cf, b"k1").unwrap().unwrap(), b"v2");
}
#[test]
fn test_scan() {
let path = Builder::new().prefix("var").tempdir().unwrap();
let cf = "cf";
let engine = RocksEngine::from_db(Arc::new(
util::new_engine(path.path().to_str().unwrap(), None, &[cf], None).unwrap(),
));
engine.put(b"a1", b"v1").unwrap();
engine.put(b"a2", b"v2").unwrap();
engine.put_cf(cf, b"a1", b"v1").unwrap();
engine.put_cf(cf, b"a2", b"v22").unwrap();
let mut data = vec![];
engine
.scan(b"", &[0xFF, 0xFF], false, |key, value| {
data.push((key.to_vec(), value.to_vec()));
Ok(true)
})
.unwrap();
assert_eq!(
data,
vec![
(b"a1".to_vec(), b"v1".to_vec()),
(b"a2".to_vec(), b"v2".to_vec()),
]
);
data.clear();
engine
.scan_cf(cf, b"", &[0xFF, 0xFF], false, |key, value| {
data.push((key.to_vec(), value.to_vec()));
Ok(true)
})
.unwrap();
assert_eq!(
data,
vec![
(b"a1".to_vec(), b"v1".to_vec()),
(b"a2".to_vec(), b"v22".to_vec()),
]
);
data.clear();
let pair = engine.seek(b"a1").unwrap().unwrap();
assert_eq!(pair, (b"a1".to_vec(), b"v1".to_vec()));
assert!(engine.seek(b"a3").unwrap().is_none());
let pair_cf = engine.seek_cf(cf, b"a1").unwrap().unwrap();
assert_eq!(pair_cf, (b"a1".to_vec(), b"v1".to_vec()));
assert!(engine.seek_cf(cf, b"a3").unwrap().is_none());
let mut index = 0;
engine
.scan(b"", &[0xFF, 0xFF], false, |key, value| {
data.push((key.to_vec(), value.to_vec()));
index += 1;
Ok(index != 1)
})
.unwrap();
assert_eq!(data.len(), 1);
let snap = RocksSnapshot::new(engine.get_sync_db());
engine.put(b"a3", b"v3").unwrap();
assert!(engine.seek(b"a3").unwrap().is_some());
let pair = snap.seek(b"a1").unwrap().unwrap();
assert_eq!(pair, (b"a1".to_vec(), b"v1".to_vec()));
assert!(snap.seek(b"a3").unwrap().is_none());
data.clear();
snap.scan(b"", &[0xFF, 0xFF], false, |key, value| {
data.push((key.to_vec(), value.to_vec()));
Ok(true)
})
.unwrap();
assert_eq!(data.len(), 2);
}
}
| 30.481356 | 97 | 0.541704 |
f81b471ebc60fdc915feb4ed052f7fd4baedcd3b
| 36,747 |
#[doc = "Reader of register MISC0_SET"]
pub type R = crate::R<u32, super::MISC0_SET>;
#[doc = "Writer for register MISC0_SET"]
pub type W = crate::W<u32, super::MISC0_SET>;
#[doc = "Register MISC0_SET `reset()`'s with value 0x0400_0000"]
impl crate::ResetValue for super::MISC0_SET {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0400_0000
}
}
#[doc = "Reader of field `REFTOP_PWD`"]
pub type REFTOP_PWD_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `REFTOP_PWD`"]
pub struct REFTOP_PWD_W<'a> {
w: &'a mut W,
}
impl<'a> REFTOP_PWD_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 = "Control bit to disable the self-bias circuit in the analog bandgap\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum REFTOP_SELFBIASOFF_A {
#[doc = "0: Uses coarse bias currents for startup"]
REFTOP_SELFBIASOFF_0 = 0,
#[doc = "1: Uses bandgap-based bias currents for best performance."]
REFTOP_SELFBIASOFF_1 = 1,
}
impl From<REFTOP_SELFBIASOFF_A> for bool {
#[inline(always)]
fn from(variant: REFTOP_SELFBIASOFF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `REFTOP_SELFBIASOFF`"]
pub type REFTOP_SELFBIASOFF_R = crate::R<bool, REFTOP_SELFBIASOFF_A>;
impl REFTOP_SELFBIASOFF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> REFTOP_SELFBIASOFF_A {
match self.bits {
false => REFTOP_SELFBIASOFF_A::REFTOP_SELFBIASOFF_0,
true => REFTOP_SELFBIASOFF_A::REFTOP_SELFBIASOFF_1,
}
}
#[doc = "Checks if the value of the field is `REFTOP_SELFBIASOFF_0`"]
#[inline(always)]
pub fn is_reftop_selfbiasoff_0(&self) -> bool {
*self == REFTOP_SELFBIASOFF_A::REFTOP_SELFBIASOFF_0
}
#[doc = "Checks if the value of the field is `REFTOP_SELFBIASOFF_1`"]
#[inline(always)]
pub fn is_reftop_selfbiasoff_1(&self) -> bool {
*self == REFTOP_SELFBIASOFF_A::REFTOP_SELFBIASOFF_1
}
}
#[doc = "Write proxy for field `REFTOP_SELFBIASOFF`"]
pub struct REFTOP_SELFBIASOFF_W<'a> {
w: &'a mut W,
}
impl<'a> REFTOP_SELFBIASOFF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: REFTOP_SELFBIASOFF_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Uses coarse bias currents for startup"]
#[inline(always)]
pub fn reftop_selfbiasoff_0(self) -> &'a mut W {
self.variant(REFTOP_SELFBIASOFF_A::REFTOP_SELFBIASOFF_0)
}
#[doc = "Uses bandgap-based bias currents for best performance."]
#[inline(always)]
pub fn reftop_selfbiasoff_1(self) -> &'a mut W {
self.variant(REFTOP_SELFBIASOFF_A::REFTOP_SELFBIASOFF_1)
}
#[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 = "Not related to oscillator.\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum REFTOP_VBGADJ_A {
#[doc = "0: Nominal VBG"]
REFTOP_VBGADJ_0 = 0,
#[doc = "1: VBG+0.78%"]
REFTOP_VBGADJ_1 = 1,
#[doc = "2: VBG+1.56%"]
REFTOP_VBGADJ_2 = 2,
#[doc = "3: VBG+2.34%"]
REFTOP_VBGADJ_3 = 3,
#[doc = "4: VBG-0.78%"]
REFTOP_VBGADJ_4 = 4,
#[doc = "5: VBG-1.56%"]
REFTOP_VBGADJ_5 = 5,
#[doc = "6: VBG-2.34%"]
REFTOP_VBGADJ_6 = 6,
#[doc = "7: VBG-3.12%"]
REFTOP_VBGADJ_7 = 7,
}
impl From<REFTOP_VBGADJ_A> for u8 {
#[inline(always)]
fn from(variant: REFTOP_VBGADJ_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `REFTOP_VBGADJ`"]
pub type REFTOP_VBGADJ_R = crate::R<u8, REFTOP_VBGADJ_A>;
impl REFTOP_VBGADJ_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> REFTOP_VBGADJ_A {
match self.bits {
0 => REFTOP_VBGADJ_A::REFTOP_VBGADJ_0,
1 => REFTOP_VBGADJ_A::REFTOP_VBGADJ_1,
2 => REFTOP_VBGADJ_A::REFTOP_VBGADJ_2,
3 => REFTOP_VBGADJ_A::REFTOP_VBGADJ_3,
4 => REFTOP_VBGADJ_A::REFTOP_VBGADJ_4,
5 => REFTOP_VBGADJ_A::REFTOP_VBGADJ_5,
6 => REFTOP_VBGADJ_A::REFTOP_VBGADJ_6,
7 => REFTOP_VBGADJ_A::REFTOP_VBGADJ_7,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `REFTOP_VBGADJ_0`"]
#[inline(always)]
pub fn is_reftop_vbgadj_0(&self) -> bool {
*self == REFTOP_VBGADJ_A::REFTOP_VBGADJ_0
}
#[doc = "Checks if the value of the field is `REFTOP_VBGADJ_1`"]
#[inline(always)]
pub fn is_reftop_vbgadj_1(&self) -> bool {
*self == REFTOP_VBGADJ_A::REFTOP_VBGADJ_1
}
#[doc = "Checks if the value of the field is `REFTOP_VBGADJ_2`"]
#[inline(always)]
pub fn is_reftop_vbgadj_2(&self) -> bool {
*self == REFTOP_VBGADJ_A::REFTOP_VBGADJ_2
}
#[doc = "Checks if the value of the field is `REFTOP_VBGADJ_3`"]
#[inline(always)]
pub fn is_reftop_vbgadj_3(&self) -> bool {
*self == REFTOP_VBGADJ_A::REFTOP_VBGADJ_3
}
#[doc = "Checks if the value of the field is `REFTOP_VBGADJ_4`"]
#[inline(always)]
pub fn is_reftop_vbgadj_4(&self) -> bool {
*self == REFTOP_VBGADJ_A::REFTOP_VBGADJ_4
}
#[doc = "Checks if the value of the field is `REFTOP_VBGADJ_5`"]
#[inline(always)]
pub fn is_reftop_vbgadj_5(&self) -> bool {
*self == REFTOP_VBGADJ_A::REFTOP_VBGADJ_5
}
#[doc = "Checks if the value of the field is `REFTOP_VBGADJ_6`"]
#[inline(always)]
pub fn is_reftop_vbgadj_6(&self) -> bool {
*self == REFTOP_VBGADJ_A::REFTOP_VBGADJ_6
}
#[doc = "Checks if the value of the field is `REFTOP_VBGADJ_7`"]
#[inline(always)]
pub fn is_reftop_vbgadj_7(&self) -> bool {
*self == REFTOP_VBGADJ_A::REFTOP_VBGADJ_7
}
}
#[doc = "Write proxy for field `REFTOP_VBGADJ`"]
pub struct REFTOP_VBGADJ_W<'a> {
w: &'a mut W,
}
impl<'a> REFTOP_VBGADJ_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: REFTOP_VBGADJ_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "Nominal VBG"]
#[inline(always)]
pub fn reftop_vbgadj_0(self) -> &'a mut W {
self.variant(REFTOP_VBGADJ_A::REFTOP_VBGADJ_0)
}
#[doc = "VBG+0.78%"]
#[inline(always)]
pub fn reftop_vbgadj_1(self) -> &'a mut W {
self.variant(REFTOP_VBGADJ_A::REFTOP_VBGADJ_1)
}
#[doc = "VBG+1.56%"]
#[inline(always)]
pub fn reftop_vbgadj_2(self) -> &'a mut W {
self.variant(REFTOP_VBGADJ_A::REFTOP_VBGADJ_2)
}
#[doc = "VBG+2.34%"]
#[inline(always)]
pub fn reftop_vbgadj_3(self) -> &'a mut W {
self.variant(REFTOP_VBGADJ_A::REFTOP_VBGADJ_3)
}
#[doc = "VBG-0.78%"]
#[inline(always)]
pub fn reftop_vbgadj_4(self) -> &'a mut W {
self.variant(REFTOP_VBGADJ_A::REFTOP_VBGADJ_4)
}
#[doc = "VBG-1.56%"]
#[inline(always)]
pub fn reftop_vbgadj_5(self) -> &'a mut W {
self.variant(REFTOP_VBGADJ_A::REFTOP_VBGADJ_5)
}
#[doc = "VBG-2.34%"]
#[inline(always)]
pub fn reftop_vbgadj_6(self) -> &'a mut W {
self.variant(REFTOP_VBGADJ_A::REFTOP_VBGADJ_6)
}
#[doc = "VBG-3.12%"]
#[inline(always)]
pub fn reftop_vbgadj_7(self) -> &'a mut W {
self.variant(REFTOP_VBGADJ_A::REFTOP_VBGADJ_7)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 4)) | (((value as u32) & 0x07) << 4);
self.w
}
}
#[doc = "Reader of field `REFTOP_VBGUP`"]
pub type REFTOP_VBGUP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `REFTOP_VBGUP`"]
pub struct REFTOP_VBGUP_W<'a> {
w: &'a mut W,
}
impl<'a> REFTOP_VBGUP_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
}
}
#[doc = "Configure the analog behavior in stop mode.Not related to oscillator.\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum STOP_MODE_CONFIG_A {
#[doc = "0: All analog except rtc powered down on stop mode assertion. XtalOsc=on, RCOsc=off;"]
STOP_MODE_CONFIG_0 = 0,
#[doc = "1: Certain analog functions such as certain regulators left up. XtalOsc=on, RCOsc=off;"]
STOP_MODE_CONFIG_1 = 1,
#[doc = "2: XtalOsc=off, RCOsc=on, Old BG=on, New BG=off."]
STOP_MODE_CONFIG_2 = 2,
#[doc = "3: XtalOsc=off, RCOsc=on, Old BG=off, New BG=on."]
STOP_MODE_CONFIG_3 = 3,
}
impl From<STOP_MODE_CONFIG_A> for u8 {
#[inline(always)]
fn from(variant: STOP_MODE_CONFIG_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `STOP_MODE_CONFIG`"]
pub type STOP_MODE_CONFIG_R = crate::R<u8, STOP_MODE_CONFIG_A>;
impl STOP_MODE_CONFIG_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> STOP_MODE_CONFIG_A {
match self.bits {
0 => STOP_MODE_CONFIG_A::STOP_MODE_CONFIG_0,
1 => STOP_MODE_CONFIG_A::STOP_MODE_CONFIG_1,
2 => STOP_MODE_CONFIG_A::STOP_MODE_CONFIG_2,
3 => STOP_MODE_CONFIG_A::STOP_MODE_CONFIG_3,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `STOP_MODE_CONFIG_0`"]
#[inline(always)]
pub fn is_stop_mode_config_0(&self) -> bool {
*self == STOP_MODE_CONFIG_A::STOP_MODE_CONFIG_0
}
#[doc = "Checks if the value of the field is `STOP_MODE_CONFIG_1`"]
#[inline(always)]
pub fn is_stop_mode_config_1(&self) -> bool {
*self == STOP_MODE_CONFIG_A::STOP_MODE_CONFIG_1
}
#[doc = "Checks if the value of the field is `STOP_MODE_CONFIG_2`"]
#[inline(always)]
pub fn is_stop_mode_config_2(&self) -> bool {
*self == STOP_MODE_CONFIG_A::STOP_MODE_CONFIG_2
}
#[doc = "Checks if the value of the field is `STOP_MODE_CONFIG_3`"]
#[inline(always)]
pub fn is_stop_mode_config_3(&self) -> bool {
*self == STOP_MODE_CONFIG_A::STOP_MODE_CONFIG_3
}
}
#[doc = "Write proxy for field `STOP_MODE_CONFIG`"]
pub struct STOP_MODE_CONFIG_W<'a> {
w: &'a mut W,
}
impl<'a> STOP_MODE_CONFIG_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: STOP_MODE_CONFIG_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "All analog except rtc powered down on stop mode assertion. XtalOsc=on, RCOsc=off;"]
#[inline(always)]
pub fn stop_mode_config_0(self) -> &'a mut W {
self.variant(STOP_MODE_CONFIG_A::STOP_MODE_CONFIG_0)
}
#[doc = "Certain analog functions such as certain regulators left up. XtalOsc=on, RCOsc=off;"]
#[inline(always)]
pub fn stop_mode_config_1(self) -> &'a mut W {
self.variant(STOP_MODE_CONFIG_A::STOP_MODE_CONFIG_1)
}
#[doc = "XtalOsc=off, RCOsc=on, Old BG=on, New BG=off."]
#[inline(always)]
pub fn stop_mode_config_2(self) -> &'a mut W {
self.variant(STOP_MODE_CONFIG_A::STOP_MODE_CONFIG_2)
}
#[doc = "XtalOsc=off, RCOsc=on, Old BG=off, New BG=on."]
#[inline(always)]
pub fn stop_mode_config_3(self) -> &'a mut W {
self.variant(STOP_MODE_CONFIG_A::STOP_MODE_CONFIG_3)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 10)) | (((value as u32) & 0x03) << 10);
self.w
}
}
#[doc = "This bit controls a switch from VDD_HIGH_IN to VDD_SNVS_IN.\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DISCON_HIGH_SNVS_A {
#[doc = "0: Turn on the switch"]
DISCON_HIGH_SNVS_0 = 0,
#[doc = "1: Turn off the switch"]
DISCON_HIGH_SNVS_1 = 1,
}
impl From<DISCON_HIGH_SNVS_A> for bool {
#[inline(always)]
fn from(variant: DISCON_HIGH_SNVS_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `DISCON_HIGH_SNVS`"]
pub type DISCON_HIGH_SNVS_R = crate::R<bool, DISCON_HIGH_SNVS_A>;
impl DISCON_HIGH_SNVS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DISCON_HIGH_SNVS_A {
match self.bits {
false => DISCON_HIGH_SNVS_A::DISCON_HIGH_SNVS_0,
true => DISCON_HIGH_SNVS_A::DISCON_HIGH_SNVS_1,
}
}
#[doc = "Checks if the value of the field is `DISCON_HIGH_SNVS_0`"]
#[inline(always)]
pub fn is_discon_high_snvs_0(&self) -> bool {
*self == DISCON_HIGH_SNVS_A::DISCON_HIGH_SNVS_0
}
#[doc = "Checks if the value of the field is `DISCON_HIGH_SNVS_1`"]
#[inline(always)]
pub fn is_discon_high_snvs_1(&self) -> bool {
*self == DISCON_HIGH_SNVS_A::DISCON_HIGH_SNVS_1
}
}
#[doc = "Write proxy for field `DISCON_HIGH_SNVS`"]
pub struct DISCON_HIGH_SNVS_W<'a> {
w: &'a mut W,
}
impl<'a> DISCON_HIGH_SNVS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DISCON_HIGH_SNVS_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Turn on the switch"]
#[inline(always)]
pub fn discon_high_snvs_0(self) -> &'a mut W {
self.variant(DISCON_HIGH_SNVS_A::DISCON_HIGH_SNVS_0)
}
#[doc = "Turn off the switch"]
#[inline(always)]
pub fn discon_high_snvs_1(self) -> &'a mut W {
self.variant(DISCON_HIGH_SNVS_A::DISCON_HIGH_SNVS_1)
}
#[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 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "This field determines the bias current in the 24MHz oscillator\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum OSC_I_A {
#[doc = "0: Nominal"]
NOMINAL = 0,
#[doc = "1: Decrease current by 12.5%"]
MINUS_12_5_PERCENT = 1,
#[doc = "2: Decrease current by 25.0%"]
MINUS_25_PERCENT = 2,
#[doc = "3: Decrease current by 37.5%"]
MINUS_37_5_PERCENT = 3,
}
impl From<OSC_I_A> for u8 {
#[inline(always)]
fn from(variant: OSC_I_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `OSC_I`"]
pub type OSC_I_R = crate::R<u8, OSC_I_A>;
impl OSC_I_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> OSC_I_A {
match self.bits {
0 => OSC_I_A::NOMINAL,
1 => OSC_I_A::MINUS_12_5_PERCENT,
2 => OSC_I_A::MINUS_25_PERCENT,
3 => OSC_I_A::MINUS_37_5_PERCENT,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `NOMINAL`"]
#[inline(always)]
pub fn is_nominal(&self) -> bool {
*self == OSC_I_A::NOMINAL
}
#[doc = "Checks if the value of the field is `MINUS_12_5_PERCENT`"]
#[inline(always)]
pub fn is_minus_12_5_percent(&self) -> bool {
*self == OSC_I_A::MINUS_12_5_PERCENT
}
#[doc = "Checks if the value of the field is `MINUS_25_PERCENT`"]
#[inline(always)]
pub fn is_minus_25_percent(&self) -> bool {
*self == OSC_I_A::MINUS_25_PERCENT
}
#[doc = "Checks if the value of the field is `MINUS_37_5_PERCENT`"]
#[inline(always)]
pub fn is_minus_37_5_percent(&self) -> bool {
*self == OSC_I_A::MINUS_37_5_PERCENT
}
}
#[doc = "Write proxy for field `OSC_I`"]
pub struct OSC_I_W<'a> {
w: &'a mut W,
}
impl<'a> OSC_I_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: OSC_I_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "Nominal"]
#[inline(always)]
pub fn nominal(self) -> &'a mut W {
self.variant(OSC_I_A::NOMINAL)
}
#[doc = "Decrease current by 12.5%"]
#[inline(always)]
pub fn minus_12_5_percent(self) -> &'a mut W {
self.variant(OSC_I_A::MINUS_12_5_PERCENT)
}
#[doc = "Decrease current by 25.0%"]
#[inline(always)]
pub fn minus_25_percent(self) -> &'a mut W {
self.variant(OSC_I_A::MINUS_25_PERCENT)
}
#[doc = "Decrease current by 37.5%"]
#[inline(always)]
pub fn minus_37_5_percent(self) -> &'a mut W {
self.variant(OSC_I_A::MINUS_37_5_PERCENT)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 13)) | (((value as u32) & 0x03) << 13);
self.w
}
}
#[doc = "Reader of field `OSC_XTALOK`"]
pub type OSC_XTALOK_R = crate::R<bool, bool>;
#[doc = "Reader of field `OSC_XTALOK_EN`"]
pub type OSC_XTALOK_EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OSC_XTALOK_EN`"]
pub struct OSC_XTALOK_EN_W<'a> {
w: &'a mut W,
}
impl<'a> OSC_XTALOK_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "This bit allows disabling the clock gate (always ungated) for the xtal 24MHz clock that clocks the digital logic in the analog block\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CLKGATE_CTRL_A {
#[doc = "0: Allow the logic to automatically gate the clock when the XTAL is powered down."]
ALLOW_AUTO_GATE = 0,
#[doc = "1: Prevent the logic from ever gating off the clock."]
NO_AUTO_GATE = 1,
}
impl From<CLKGATE_CTRL_A> for bool {
#[inline(always)]
fn from(variant: CLKGATE_CTRL_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `CLKGATE_CTRL`"]
pub type CLKGATE_CTRL_R = crate::R<bool, CLKGATE_CTRL_A>;
impl CLKGATE_CTRL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CLKGATE_CTRL_A {
match self.bits {
false => CLKGATE_CTRL_A::ALLOW_AUTO_GATE,
true => CLKGATE_CTRL_A::NO_AUTO_GATE,
}
}
#[doc = "Checks if the value of the field is `ALLOW_AUTO_GATE`"]
#[inline(always)]
pub fn is_allow_auto_gate(&self) -> bool {
*self == CLKGATE_CTRL_A::ALLOW_AUTO_GATE
}
#[doc = "Checks if the value of the field is `NO_AUTO_GATE`"]
#[inline(always)]
pub fn is_no_auto_gate(&self) -> bool {
*self == CLKGATE_CTRL_A::NO_AUTO_GATE
}
}
#[doc = "Write proxy for field `CLKGATE_CTRL`"]
pub struct CLKGATE_CTRL_W<'a> {
w: &'a mut W,
}
impl<'a> CLKGATE_CTRL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CLKGATE_CTRL_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Allow the logic to automatically gate the clock when the XTAL is powered down."]
#[inline(always)]
pub fn allow_auto_gate(self) -> &'a mut W {
self.variant(CLKGATE_CTRL_A::ALLOW_AUTO_GATE)
}
#[doc = "Prevent the logic from ever gating off the clock."]
#[inline(always)]
pub fn no_auto_gate(self) -> &'a mut W {
self.variant(CLKGATE_CTRL_A::NO_AUTO_GATE)
}
#[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 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "This field specifies the delay between powering up the XTAL 24MHz clock and releasing the clock to the digital logic inside the analog block\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CLKGATE_DELAY_A {
#[doc = "0: 0.5ms"]
CLKGATE_DELAY_0 = 0,
#[doc = "1: 1.0ms"]
CLKGATE_DELAY_1 = 1,
#[doc = "2: 2.0ms"]
CLKGATE_DELAY_2 = 2,
#[doc = "3: 3.0ms"]
CLKGATE_DELAY_3 = 3,
#[doc = "4: 4.0ms"]
CLKGATE_DELAY_4 = 4,
#[doc = "5: 5.0ms"]
CLKGATE_DELAY_5 = 5,
#[doc = "6: 6.0ms"]
CLKGATE_DELAY_6 = 6,
#[doc = "7: 7.0ms"]
CLKGATE_DELAY_7 = 7,
}
impl From<CLKGATE_DELAY_A> for u8 {
#[inline(always)]
fn from(variant: CLKGATE_DELAY_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CLKGATE_DELAY`"]
pub type CLKGATE_DELAY_R = crate::R<u8, CLKGATE_DELAY_A>;
impl CLKGATE_DELAY_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CLKGATE_DELAY_A {
match self.bits {
0 => CLKGATE_DELAY_A::CLKGATE_DELAY_0,
1 => CLKGATE_DELAY_A::CLKGATE_DELAY_1,
2 => CLKGATE_DELAY_A::CLKGATE_DELAY_2,
3 => CLKGATE_DELAY_A::CLKGATE_DELAY_3,
4 => CLKGATE_DELAY_A::CLKGATE_DELAY_4,
5 => CLKGATE_DELAY_A::CLKGATE_DELAY_5,
6 => CLKGATE_DELAY_A::CLKGATE_DELAY_6,
7 => CLKGATE_DELAY_A::CLKGATE_DELAY_7,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `CLKGATE_DELAY_0`"]
#[inline(always)]
pub fn is_clkgate_delay_0(&self) -> bool {
*self == CLKGATE_DELAY_A::CLKGATE_DELAY_0
}
#[doc = "Checks if the value of the field is `CLKGATE_DELAY_1`"]
#[inline(always)]
pub fn is_clkgate_delay_1(&self) -> bool {
*self == CLKGATE_DELAY_A::CLKGATE_DELAY_1
}
#[doc = "Checks if the value of the field is `CLKGATE_DELAY_2`"]
#[inline(always)]
pub fn is_clkgate_delay_2(&self) -> bool {
*self == CLKGATE_DELAY_A::CLKGATE_DELAY_2
}
#[doc = "Checks if the value of the field is `CLKGATE_DELAY_3`"]
#[inline(always)]
pub fn is_clkgate_delay_3(&self) -> bool {
*self == CLKGATE_DELAY_A::CLKGATE_DELAY_3
}
#[doc = "Checks if the value of the field is `CLKGATE_DELAY_4`"]
#[inline(always)]
pub fn is_clkgate_delay_4(&self) -> bool {
*self == CLKGATE_DELAY_A::CLKGATE_DELAY_4
}
#[doc = "Checks if the value of the field is `CLKGATE_DELAY_5`"]
#[inline(always)]
pub fn is_clkgate_delay_5(&self) -> bool {
*self == CLKGATE_DELAY_A::CLKGATE_DELAY_5
}
#[doc = "Checks if the value of the field is `CLKGATE_DELAY_6`"]
#[inline(always)]
pub fn is_clkgate_delay_6(&self) -> bool {
*self == CLKGATE_DELAY_A::CLKGATE_DELAY_6
}
#[doc = "Checks if the value of the field is `CLKGATE_DELAY_7`"]
#[inline(always)]
pub fn is_clkgate_delay_7(&self) -> bool {
*self == CLKGATE_DELAY_A::CLKGATE_DELAY_7
}
}
#[doc = "Write proxy for field `CLKGATE_DELAY`"]
pub struct CLKGATE_DELAY_W<'a> {
w: &'a mut W,
}
impl<'a> CLKGATE_DELAY_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CLKGATE_DELAY_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "0.5ms"]
#[inline(always)]
pub fn clkgate_delay_0(self) -> &'a mut W {
self.variant(CLKGATE_DELAY_A::CLKGATE_DELAY_0)
}
#[doc = "1.0ms"]
#[inline(always)]
pub fn clkgate_delay_1(self) -> &'a mut W {
self.variant(CLKGATE_DELAY_A::CLKGATE_DELAY_1)
}
#[doc = "2.0ms"]
#[inline(always)]
pub fn clkgate_delay_2(self) -> &'a mut W {
self.variant(CLKGATE_DELAY_A::CLKGATE_DELAY_2)
}
#[doc = "3.0ms"]
#[inline(always)]
pub fn clkgate_delay_3(self) -> &'a mut W {
self.variant(CLKGATE_DELAY_A::CLKGATE_DELAY_3)
}
#[doc = "4.0ms"]
#[inline(always)]
pub fn clkgate_delay_4(self) -> &'a mut W {
self.variant(CLKGATE_DELAY_A::CLKGATE_DELAY_4)
}
#[doc = "5.0ms"]
#[inline(always)]
pub fn clkgate_delay_5(self) -> &'a mut W {
self.variant(CLKGATE_DELAY_A::CLKGATE_DELAY_5)
}
#[doc = "6.0ms"]
#[inline(always)]
pub fn clkgate_delay_6(self) -> &'a mut W {
self.variant(CLKGATE_DELAY_A::CLKGATE_DELAY_6)
}
#[doc = "7.0ms"]
#[inline(always)]
pub fn clkgate_delay_7(self) -> &'a mut W {
self.variant(CLKGATE_DELAY_A::CLKGATE_DELAY_7)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 26)) | (((value as u32) & 0x07) << 26);
self.w
}
}
#[doc = "This field indicates which chip source is being used for the rtc clock.\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RTC_XTAL_SOURCE_A {
#[doc = "0: Internal ring oscillator"]
RTC_XTAL_SOURCE_0 = 0,
#[doc = "1: RTC_XTAL"]
RTC_XTAL_SOURCE_1 = 1,
}
impl From<RTC_XTAL_SOURCE_A> for bool {
#[inline(always)]
fn from(variant: RTC_XTAL_SOURCE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `RTC_XTAL_SOURCE`"]
pub type RTC_XTAL_SOURCE_R = crate::R<bool, RTC_XTAL_SOURCE_A>;
impl RTC_XTAL_SOURCE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RTC_XTAL_SOURCE_A {
match self.bits {
false => RTC_XTAL_SOURCE_A::RTC_XTAL_SOURCE_0,
true => RTC_XTAL_SOURCE_A::RTC_XTAL_SOURCE_1,
}
}
#[doc = "Checks if the value of the field is `RTC_XTAL_SOURCE_0`"]
#[inline(always)]
pub fn is_rtc_xtal_source_0(&self) -> bool {
*self == RTC_XTAL_SOURCE_A::RTC_XTAL_SOURCE_0
}
#[doc = "Checks if the value of the field is `RTC_XTAL_SOURCE_1`"]
#[inline(always)]
pub fn is_rtc_xtal_source_1(&self) -> bool {
*self == RTC_XTAL_SOURCE_A::RTC_XTAL_SOURCE_1
}
}
#[doc = "Reader of field `XTAL_24M_PWD`"]
pub type XTAL_24M_PWD_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `XTAL_24M_PWD`"]
pub struct XTAL_24M_PWD_W<'a> {
w: &'a mut W,
}
impl<'a> XTAL_24M_PWD_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 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Predivider for the source clock of the PLL's. Not related to oscillator.\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VID_PLL_PREDIV_A {
#[doc = "0: Divide by 1"]
VID_PLL_PREDIV_0 = 0,
#[doc = "1: Divide by 2"]
VID_PLL_PREDIV_1 = 1,
}
impl From<VID_PLL_PREDIV_A> for bool {
#[inline(always)]
fn from(variant: VID_PLL_PREDIV_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `VID_PLL_PREDIV`"]
pub type VID_PLL_PREDIV_R = crate::R<bool, VID_PLL_PREDIV_A>;
impl VID_PLL_PREDIV_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> VID_PLL_PREDIV_A {
match self.bits {
false => VID_PLL_PREDIV_A::VID_PLL_PREDIV_0,
true => VID_PLL_PREDIV_A::VID_PLL_PREDIV_1,
}
}
#[doc = "Checks if the value of the field is `VID_PLL_PREDIV_0`"]
#[inline(always)]
pub fn is_vid_pll_prediv_0(&self) -> bool {
*self == VID_PLL_PREDIV_A::VID_PLL_PREDIV_0
}
#[doc = "Checks if the value of the field is `VID_PLL_PREDIV_1`"]
#[inline(always)]
pub fn is_vid_pll_prediv_1(&self) -> bool {
*self == VID_PLL_PREDIV_A::VID_PLL_PREDIV_1
}
}
#[doc = "Write proxy for field `VID_PLL_PREDIV`"]
pub struct VID_PLL_PREDIV_W<'a> {
w: &'a mut W,
}
impl<'a> VID_PLL_PREDIV_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: VID_PLL_PREDIV_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Divide by 1"]
#[inline(always)]
pub fn vid_pll_prediv_0(self) -> &'a mut W {
self.variant(VID_PLL_PREDIV_A::VID_PLL_PREDIV_0)
}
#[doc = "Divide by 2"]
#[inline(always)]
pub fn vid_pll_prediv_1(self) -> &'a mut W {
self.variant(VID_PLL_PREDIV_A::VID_PLL_PREDIV_1)
}
#[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 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - Control bit to power-down the analog bandgap reference circuitry"]
#[inline(always)]
pub fn reftop_pwd(&self) -> REFTOP_PWD_R {
REFTOP_PWD_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 3 - Control bit to disable the self-bias circuit in the analog bandgap"]
#[inline(always)]
pub fn reftop_selfbiasoff(&self) -> REFTOP_SELFBIASOFF_R {
REFTOP_SELFBIASOFF_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bits 4:6 - Not related to oscillator."]
#[inline(always)]
pub fn reftop_vbgadj(&self) -> REFTOP_VBGADJ_R {
REFTOP_VBGADJ_R::new(((self.bits >> 4) & 0x07) as u8)
}
#[doc = "Bit 7 - Status bit that signals the analog bandgap voltage is up and stable"]
#[inline(always)]
pub fn reftop_vbgup(&self) -> REFTOP_VBGUP_R {
REFTOP_VBGUP_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bits 10:11 - Configure the analog behavior in stop mode.Not related to oscillator."]
#[inline(always)]
pub fn stop_mode_config(&self) -> STOP_MODE_CONFIG_R {
STOP_MODE_CONFIG_R::new(((self.bits >> 10) & 0x03) as u8)
}
#[doc = "Bit 12 - This bit controls a switch from VDD_HIGH_IN to VDD_SNVS_IN."]
#[inline(always)]
pub fn discon_high_snvs(&self) -> DISCON_HIGH_SNVS_R {
DISCON_HIGH_SNVS_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bits 13:14 - This field determines the bias current in the 24MHz oscillator"]
#[inline(always)]
pub fn osc_i(&self) -> OSC_I_R {
OSC_I_R::new(((self.bits >> 13) & 0x03) as u8)
}
#[doc = "Bit 15 - Status bit that signals that the output of the 24-MHz crystal oscillator is stable"]
#[inline(always)]
pub fn osc_xtalok(&self) -> OSC_XTALOK_R {
OSC_XTALOK_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - This bit enables the detector that signals when the 24MHz crystal oscillator is stable."]
#[inline(always)]
pub fn osc_xtalok_en(&self) -> OSC_XTALOK_EN_R {
OSC_XTALOK_EN_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 25 - This bit allows disabling the clock gate (always ungated) for the xtal 24MHz clock that clocks the digital logic in the analog block"]
#[inline(always)]
pub fn clkgate_ctrl(&self) -> CLKGATE_CTRL_R {
CLKGATE_CTRL_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bits 26:28 - This field specifies the delay between powering up the XTAL 24MHz clock and releasing the clock to the digital logic inside the analog block"]
#[inline(always)]
pub fn clkgate_delay(&self) -> CLKGATE_DELAY_R {
CLKGATE_DELAY_R::new(((self.bits >> 26) & 0x07) as u8)
}
#[doc = "Bit 29 - This field indicates which chip source is being used for the rtc clock."]
#[inline(always)]
pub fn rtc_xtal_source(&self) -> RTC_XTAL_SOURCE_R {
RTC_XTAL_SOURCE_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 30 - This field powers down the 24M crystal oscillator if set true."]
#[inline(always)]
pub fn xtal_24m_pwd(&self) -> XTAL_24M_PWD_R {
XTAL_24M_PWD_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - Predivider for the source clock of the PLL's. Not related to oscillator."]
#[inline(always)]
pub fn vid_pll_prediv(&self) -> VID_PLL_PREDIV_R {
VID_PLL_PREDIV_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Control bit to power-down the analog bandgap reference circuitry"]
#[inline(always)]
pub fn reftop_pwd(&mut self) -> REFTOP_PWD_W {
REFTOP_PWD_W { w: self }
}
#[doc = "Bit 3 - Control bit to disable the self-bias circuit in the analog bandgap"]
#[inline(always)]
pub fn reftop_selfbiasoff(&mut self) -> REFTOP_SELFBIASOFF_W {
REFTOP_SELFBIASOFF_W { w: self }
}
#[doc = "Bits 4:6 - Not related to oscillator."]
#[inline(always)]
pub fn reftop_vbgadj(&mut self) -> REFTOP_VBGADJ_W {
REFTOP_VBGADJ_W { w: self }
}
#[doc = "Bit 7 - Status bit that signals the analog bandgap voltage is up and stable"]
#[inline(always)]
pub fn reftop_vbgup(&mut self) -> REFTOP_VBGUP_W {
REFTOP_VBGUP_W { w: self }
}
#[doc = "Bits 10:11 - Configure the analog behavior in stop mode.Not related to oscillator."]
#[inline(always)]
pub fn stop_mode_config(&mut self) -> STOP_MODE_CONFIG_W {
STOP_MODE_CONFIG_W { w: self }
}
#[doc = "Bit 12 - This bit controls a switch from VDD_HIGH_IN to VDD_SNVS_IN."]
#[inline(always)]
pub fn discon_high_snvs(&mut self) -> DISCON_HIGH_SNVS_W {
DISCON_HIGH_SNVS_W { w: self }
}
#[doc = "Bits 13:14 - This field determines the bias current in the 24MHz oscillator"]
#[inline(always)]
pub fn osc_i(&mut self) -> OSC_I_W {
OSC_I_W { w: self }
}
#[doc = "Bit 16 - This bit enables the detector that signals when the 24MHz crystal oscillator is stable."]
#[inline(always)]
pub fn osc_xtalok_en(&mut self) -> OSC_XTALOK_EN_W {
OSC_XTALOK_EN_W { w: self }
}
#[doc = "Bit 25 - This bit allows disabling the clock gate (always ungated) for the xtal 24MHz clock that clocks the digital logic in the analog block"]
#[inline(always)]
pub fn clkgate_ctrl(&mut self) -> CLKGATE_CTRL_W {
CLKGATE_CTRL_W { w: self }
}
#[doc = "Bits 26:28 - This field specifies the delay between powering up the XTAL 24MHz clock and releasing the clock to the digital logic inside the analog block"]
#[inline(always)]
pub fn clkgate_delay(&mut self) -> CLKGATE_DELAY_W {
CLKGATE_DELAY_W { w: self }
}
#[doc = "Bit 30 - This field powers down the 24M crystal oscillator if set true."]
#[inline(always)]
pub fn xtal_24m_pwd(&mut self) -> XTAL_24M_PWD_W {
XTAL_24M_PWD_W { w: self }
}
#[doc = "Bit 31 - Predivider for the source clock of the PLL's. Not related to oscillator."]
#[inline(always)]
pub fn vid_pll_prediv(&mut self) -> VID_PLL_PREDIV_W {
VID_PLL_PREDIV_W { w: self }
}
}
| 34.765374 | 172 | 0.608866 |
62b440b2af9ba3607c25f83d7d6881995bcf105a
| 7,133 |
//! Weights for zd_refresh_reputation
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0
//! DATE: 2021-11-26, STEPS: [50, ], REPEAT: 20, LOW RANGE: [], HIGH RANGE: []
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128
// Executed Command:
// ./target/release/zerodao-node
// benchmark
// --chain=dev
// --execution=wasm
// --wasm-execution=compiled
// --pallet=zd_refresh_reputation
// --extrinsic=*
// --steps=50
// --repeat=20
// --heap-pages=4096
// --output=./pallets/refresh-reputation/src/weights.rs
// --template=./scripts/pallet-weight-template.hbs
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(clippy::unnecessary_cast)]
use frame_support::{
traits::Get,
weights::{constants::RocksDbWeight, Weight},
};
use sp_std::marker::PhantomData;
/// Weight functions needed for zd_refresh_reputation.
pub trait WeightInfo {
fn start() -> Weight;
fn refresh(a: u32, ) -> Weight;
fn harvest_ref_all() -> Weight;
fn harvest_ref_all_sweeper() -> Weight;
fn challenge() -> Weight;
fn challenge_update(a: u32, ) -> Weight;
fn harvest_challenge() -> Weight;
fn arbitral(a: u32, ) -> Weight;
}
/// Weights for zd_refresh_reputation using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
#[cfg(not(tarpaulin_include))]
fn start() -> Weight {
(889_200_000 as Weight)
.saturating_add(T::DbWeight::get().reads(27 as Weight))
.saturating_add(T::DbWeight::get().writes(24 as Weight))
}
#[cfg(not(tarpaulin_include))]
fn refresh(a: u32, ) -> Weight {
(0 as Weight)
.saturating_add((4_486_820_000 as Weight).saturating_mul(a as Weight))
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().reads((604 as Weight).saturating_mul(a as Weight)))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
.saturating_add(T::DbWeight::get().writes((602 as Weight).saturating_mul(a as Weight)))
}
#[cfg(not(tarpaulin_include))]
fn harvest_ref_all() -> Weight {
(775_600_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(503 as Weight))
}
#[cfg(not(tarpaulin_include))]
fn harvest_ref_all_sweeper() -> Weight {
(843_900_000 as Weight)
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().writes(504 as Weight))
}
#[cfg(not(tarpaulin_include))]
fn challenge() -> Weight {
(162_100_000 as Weight)
.saturating_add(T::DbWeight::get().reads(11 as Weight))
.saturating_add(T::DbWeight::get().writes(7 as Weight))
}
#[cfg(not(tarpaulin_include))]
fn challenge_update(a: u32, ) -> Weight {
(49_271_000 as Weight)
.saturating_add((10_464_000 as Weight).saturating_mul(a as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(a as Weight)))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(a as Weight)))
}
#[cfg(not(tarpaulin_include))]
fn harvest_challenge() -> Weight {
(179_800_000 as Weight)
.saturating_add(T::DbWeight::get().reads(8 as Weight))
.saturating_add(T::DbWeight::get().writes(7 as Weight))
}
#[cfg(not(tarpaulin_include))]
fn arbitral(a: u32, ) -> Weight {
(0 as Weight)
.saturating_add((135_562_000 as Weight).saturating_mul(a as Weight))
.saturating_add(T::DbWeight::get().reads(21 as Weight))
.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(a as Weight)))
.saturating_add(T::DbWeight::get().writes(8 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(a as Weight)))
}
}
// For backwards compatibility and tests
impl WeightInfo for () {
#[cfg(not(tarpaulin_include))]
fn start() -> Weight {
(889_200_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(27 as Weight))
.saturating_add(RocksDbWeight::get().writes(24 as Weight))
}
#[cfg(not(tarpaulin_include))]
fn refresh(a: u32, ) -> Weight {
(0 as Weight)
.saturating_add((4_486_820_000 as Weight).saturating_mul(a as Weight))
.saturating_add(RocksDbWeight::get().reads(7 as Weight))
.saturating_add(RocksDbWeight::get().reads((604 as Weight).saturating_mul(a as Weight)))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
.saturating_add(RocksDbWeight::get().writes((602 as Weight).saturating_mul(a as Weight)))
}
#[cfg(not(tarpaulin_include))]
fn harvest_ref_all() -> Weight {
(775_600_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(503 as Weight))
}
#[cfg(not(tarpaulin_include))]
fn harvest_ref_all_sweeper() -> Weight {
(843_900_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(6 as Weight))
.saturating_add(RocksDbWeight::get().writes(504 as Weight))
}
#[cfg(not(tarpaulin_include))]
fn challenge() -> Weight {
(162_100_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(11 as Weight))
.saturating_add(RocksDbWeight::get().writes(7 as Weight))
}
#[cfg(not(tarpaulin_include))]
fn challenge_update(a: u32, ) -> Weight {
(49_271_000 as Weight)
.saturating_add((10_464_000 as Weight).saturating_mul(a as Weight))
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(a as Weight)))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(a as Weight)))
}
#[cfg(not(tarpaulin_include))]
fn harvest_challenge() -> Weight {
(179_800_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(8 as Weight))
.saturating_add(RocksDbWeight::get().writes(7 as Weight))
}
#[cfg(not(tarpaulin_include))]
fn arbitral(a: u32, ) -> Weight {
(0 as Weight)
.saturating_add((135_562_000 as Weight).saturating_mul(a as Weight))
.saturating_add(RocksDbWeight::get().reads(21 as Weight))
.saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(a as Weight)))
.saturating_add(RocksDbWeight::get().writes(8 as Weight))
.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(a as Weight)))
}
}
| 42.96988 | 101 | 0.63802 |
e418e6576ea30a1eb3f9b412434622ea6a29bb10
| 4,236 |
use crate::ast::{Spanned, SpannedError};
use crate::compile::{IrValue, Meta};
use crate::parse::{ResolveError, ResolveErrorKind};
use crate::query::{QueryError, QueryErrorKind};
use crate::runtime::{AccessError, TypeInfo, TypeOf};
use crate::shared::{ScopeError, ScopeErrorKind};
use thiserror::Error;
error! {
/// An error raised during compiling.
#[derive(Debug)]
pub struct IrError {
kind: IrErrorKind,
}
impl From<ResolveError>;
impl From<QueryError>;
impl From<ScopeError>;
}
impl IrError {
/// An error raised when we expect a certain constant value but get another.
pub(crate) fn expected<S, E>(spanned: S, actual: &IrValue) -> Self
where
S: Spanned,
E: TypeOf,
{
IrError::new(
spanned,
IrErrorKind::Expected {
expected: E::type_info(),
actual: actual.type_info(),
},
)
}
/// Construct a callback to build an access error with the given spanned.
pub(crate) fn access<S>(spanned: S) -> impl FnOnce(AccessError) -> Self
where
S: Spanned,
{
move |error| Self::new(spanned, error)
}
}
impl From<IrError> for SpannedError {
fn from(error: IrError) -> Self {
SpannedError::new(error.span, *error.kind)
}
}
/// Error when encoding AST.
#[derive(Debug, Error)]
#[allow(missing_docs)]
#[non_exhaustive]
pub enum IrErrorKind {
#[error("{message}")]
Custom { message: &'static str },
/// A scope error.
#[error("scope error: {error}")]
ScopeError {
/// The kind of the scope error.
#[source]
#[from]
error: ScopeErrorKind,
},
/// An access error raised during compilation.
#[error("access error: {error}")]
AccessError {
/// The source error.
#[source]
#[from]
error: AccessError,
},
/// An access error raised during queries.
#[error("{error}")]
QueryError {
/// The source error.
#[source]
#[from]
error: Box<QueryErrorKind>,
},
#[error("{error}")]
ResolveError {
#[source]
#[from]
error: ResolveErrorKind,
},
/// Encountered an expression that is not supported as a constant
/// expression.
#[error("expected a constant expression")]
NotConst,
/// Trying to process a cycle of constants.
#[error("constant cycle detected")]
ConstCycle,
/// Encountered a compile meta used in an inappropriate position.
#[error("{meta} is not supported here")]
UnsupportedMeta {
/// Unsupported compile meta.
meta: Meta,
},
/// A constant evaluation errored.
#[error("expected a value of type {expected} but got {actual}")]
Expected {
/// The expected value.
expected: TypeInfo,
/// The value we got instead.
actual: TypeInfo,
},
/// Exceeded evaluation budget.
#[error("evaluation budget exceeded")]
BudgetExceeded,
/// Integer underflow.
#[error("integer underflow")]
IntegerUnderflow,
/// Missing a tuple index.
#[error("missing index {index}")]
MissingIndex {
/// The index that was missing.
index: usize,
},
/// Missing an object field.
#[error("missing field `{field}`")]
MissingField {
/// The field that was missing.
field: Box<str>,
},
/// Missing local with the given name.
#[error("missing local `{name}`")]
MissingLocal {
/// Name of the missing local.
name: Box<str>,
},
/// Missing const or local with the given name.
#[error("no constant or local matching `{name}`")]
MissingConst {
/// Name of the missing thing.
name: Box<str>,
},
/// Error raised when trying to use a break outside of a loop.
#[error("break outside of supported loop")]
BreakOutsideOfLoop,
#[error("function not found")]
FnNotFound,
#[error("argument count mismatch, got {actual} but expected {expected}")]
ArgumentCountMismatch { actual: usize, expected: usize },
#[error("value `{value}` is outside of the supported integer range")]
NotInteger { value: num::BigInt },
}
| 28.24 | 80 | 0.591832 |
fe34794b139253e69711146faa051addd80bc268
| 19,051 |
#![type_length_limit = "1138969"]
mod config;
use crate::config::{get_mqtt_options, read_sensor_names, Config};
use backoff::future::retry;
use backoff::ExponentialBackoff;
use eyre::{eyre, Report};
use futures::stream::StreamExt;
use futures::TryFutureExt;
use homie_device::{HomieDevice, Node, Property};
use itertools::Itertools;
use mijia::bluetooth::{BluetoothError, BluetoothSession, DeviceId, MacAddress};
use mijia::{MijiaEvent, MijiaSession, Readings, SensorProps};
use stable_eyre::eyre;
use stable_eyre::eyre::WrapErr;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
use tokio::{time, try_join};
const SCAN_INTERVAL: Duration = Duration::from_secs(15);
const CONNECT_INTERVAL: Duration = Duration::from_secs(1);
const UPDATE_TIMEOUT: Duration = Duration::from_secs(60);
// SENSOR_CONNECT_RETRY_TIMEOUT must be smaller than
// SENSOR_CONNECT_RESERVATION_TIMEOUT by at least a couple of dbus timeouts in
// order to avoid races.
const SENSOR_CONNECT_RESERVATION_TIMEOUT: Duration = Duration::from_secs(5 * 60);
const SENSOR_CONNECT_RETRY_TIMEOUT: Duration = Duration::from_secs(60);
#[tokio::main]
async fn main() -> Result<(), eyre::Report> {
stable_eyre::install()?;
pretty_env_logger::init();
color_backtrace::install();
let config = Config::from_file()?;
let sensor_names = read_sensor_names(&config.homie.sensor_names_filename)?;
let mqtt_options = get_mqtt_options(config.mqtt, &config.homie.device_id);
let device_base = format!("{}/{}", config.homie.prefix, config.homie.device_id);
let mut homie_builder =
HomieDevice::builder(&device_base, &config.homie.device_name, mqtt_options);
homie_builder.set_firmware(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
let (homie, homie_handle) = homie_builder.spawn().await?;
// Connect a Bluetooth session.
let (dbus_handle, session) = MijiaSession::new().await?;
let min_update_period = config.homie.min_update_period;
let sensor_handle = run_sensor_system(homie, &session, &sensor_names, min_update_period);
// Poll everything to completion, until the first one bombs out.
let res: Result<_, eyre::Report> = try_join! {
// If this ever finishes, we lost connection to D-Bus.
dbus_handle.err_into(),
// Bluetooth finished first. Convert error and get on with your life.
sensor_handle.err_into(),
// MQTT event loop finished first.
homie_handle.err_into(),
};
res?;
Ok(())
}
#[derive(Debug, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum ConnectionStatus {
/// Not yet attempted to connect. Might already be connected from a previous
/// run of this program.
Unknown,
/// Currently connecting. Don't try again until the timeout expires.
Connecting { reserved_until: Instant },
/// We explicity disconnected, either because we failed to connect or
/// because we stopped receiving updates. The device is definitely
/// disconnected now. Promise.
Disconnected,
/// We received a Disconnected event.
/// This should only be treated as informational, because disconnection
/// events might be received racily. The sensor might actually be Connected.
MarkedDisconnected,
/// Connected and subscribed to updates
Connected { id: DeviceId },
}
#[derive(Debug, Clone)]
struct Sensor {
mac_address: MacAddress,
name: String,
/// The last time an update was received from the sensor.
last_update_timestamp: Instant,
/// The last time an update from the sensor was sent to the server. This may be earlier than
/// `last_update_timestamp` if the `min_update_time` config parameter is set.
last_sent_timestamp: Instant,
connection_status: ConnectionStatus,
ids: Vec<DeviceId>,
}
impl Sensor {
const PROPERTY_ID_TEMPERATURE: &'static str = "temperature";
const PROPERTY_ID_HUMIDITY: &'static str = "humidity";
const PROPERTY_ID_BATTERY: &'static str = "battery";
pub fn new(props: SensorProps, sensor_names: &HashMap<MacAddress, String>) -> Self {
let name = sensor_names
.get(&props.mac_address)
.cloned()
.unwrap_or_else(|| props.mac_address.to_string());
Self {
mac_address: props.mac_address,
name,
last_update_timestamp: Instant::now(),
// This should really be something like Instant::MIN, but there is no such constant so
// one hour in the past should be more than enough.
last_sent_timestamp: Instant::now() - Duration::from_secs(3600),
connection_status: ConnectionStatus::Unknown,
ids: vec![props.id],
}
}
pub fn node_id(&self) -> String {
self.mac_address.to_string().replace(":", "")
}
fn as_node(&self) -> Node {
Node::new(
&self.node_id(),
&self.name,
"Mijia sensor",
vec![
Property::float(
Self::PROPERTY_ID_TEMPERATURE,
"Temperature",
false,
true,
Some("ºC"),
None,
),
Property::integer(
Self::PROPERTY_ID_HUMIDITY,
"Humidity",
false,
true,
Some("%"),
None,
),
Property::integer(
Self::PROPERTY_ID_BATTERY,
"Battery level",
false,
true,
Some("%"),
None,
),
],
)
}
async fn publish_readings(
&mut self,
homie: &HomieDevice,
readings: &Readings,
min_update_period: Duration,
) -> Result<(), eyre::Report> {
println!("{} {} ({})", self.mac_address, readings, self.name);
let now = Instant::now();
self.last_update_timestamp = now;
if now > self.last_sent_timestamp + min_update_period {
let node_id = self.node_id();
homie
.publish_value(
&node_id,
Self::PROPERTY_ID_TEMPERATURE,
format!("{:.2}", readings.temperature),
)
.await?;
homie
.publish_value(&node_id, Self::PROPERTY_ID_HUMIDITY, readings.humidity)
.await?;
homie
.publish_value(
&node_id,
Self::PROPERTY_ID_BATTERY,
readings.battery_percent,
)
.await?;
self.last_sent_timestamp = now;
} else {
log::trace!(
"Not sending, as last update sent {} seconds ago.",
(now - self.last_sent_timestamp).as_secs()
);
}
Ok(())
}
async fn mark_connected(
&mut self,
homie: &mut HomieDevice,
id: DeviceId,
) -> Result<(), eyre::Report> {
assert!(self.ids.contains(&id));
homie.add_node(self.as_node()).await?;
self.connection_status = ConnectionStatus::Connected { id };
Ok(())
}
}
async fn run_sensor_system(
mut homie: HomieDevice,
session: &MijiaSession,
sensor_names: &HashMap<MacAddress, String>,
min_update_period: Duration,
) -> Result<(), eyre::Report> {
homie.ready().await?;
let state = Arc::new(Mutex::new(SensorState {
sensors: HashMap::new(),
homie,
min_update_period,
}));
let connection_loop_handle = bluetooth_connection_loop(state.clone(), session, sensor_names);
let event_loop_handle = service_bluetooth_event_queue(state.clone(), session);
try_join!(connection_loop_handle, event_loop_handle).map(|((), ())| ())
}
async fn bluetooth_connection_loop(
state: Arc<Mutex<SensorState>>,
session: &MijiaSession,
sensor_names: &HashMap<MacAddress, String>,
) -> Result<(), eyre::Report> {
let mut next_scan_due = Instant::now();
loop {
// Print count and list of sensors in each state.
{
let state = state.lock().await;
let counts = state
.sensors
.values()
.map(|sensor| (&sensor.connection_status, sensor.name.to_owned()))
.into_group_map();
for (state, names) in counts.iter().sorted() {
println!("{:?}: {} {:?}", state, names.len(), names);
}
}
// Look for more sensors if enough time has elapsed since last time we tried.
let now = Instant::now();
if now > next_scan_due && state.lock().await.sensors.len() < sensor_names.len() {
next_scan_due = now + SCAN_INTERVAL;
check_for_sensors(state.clone(), session, &sensor_names).await?;
}
// Check the state of each sensor and act on it if appropriate.
{
let mac_addresses: Vec<MacAddress> =
state.lock().await.sensors.keys().cloned().collect();
for mac_address in mac_addresses {
let connection_status = state
.lock()
.await
.sensors
.get(&mac_address)
.map(|sensor| {
log::trace!("State of {} is {:?}", sensor.name, sensor.connection_status);
sensor.connection_status.to_owned()
})
.expect("sensors cannot be deleted");
action_sensor(state.clone(), session, &mac_address, connection_status).await?;
}
}
time::sleep(CONNECT_INTERVAL).await;
}
}
#[derive(Debug)]
struct SensorState {
sensors: HashMap<MacAddress, Sensor>,
homie: HomieDevice,
min_update_period: Duration,
}
/// Get the sensor entry for the given id, if any.
fn get_mut_sensor_by_id<'a>(
sensors: &'a mut HashMap<MacAddress, Sensor>,
id: &DeviceId,
) -> Option<&'a mut Sensor> {
sensors.values_mut().find(|sensor| sensor.ids.contains(id))
}
async fn action_sensor(
state: Arc<Mutex<SensorState>>,
session: &MijiaSession,
mac_address: &MacAddress,
status: ConnectionStatus,
) -> Result<(), eyre::Report> {
match status {
ConnectionStatus::Connecting { reserved_until } if reserved_until > Instant::now() => {
Ok(())
}
ConnectionStatus::Unknown
| ConnectionStatus::Connecting { .. }
| ConnectionStatus::Disconnected
| ConnectionStatus::MarkedDisconnected => {
connect_sensor_with_id(state, session, mac_address).await?;
Ok(())
}
ConnectionStatus::Connected { id } => {
check_for_stale_sensor(state, session, mac_address, &id).await?;
Ok(())
}
}
}
async fn check_for_sensors(
state: Arc<Mutex<SensorState>>,
session: &MijiaSession,
sensor_names: &HashMap<MacAddress, String>,
) -> Result<(), eyre::Report> {
session.bt_session.start_discovery().await?;
let sensors = session.get_sensors().await?;
let state = &mut *state.lock().await;
for props in sensors {
if sensor_names.contains_key(&props.mac_address) {
if let Some(sensor) = state.sensors.get_mut(&props.mac_address) {
if !sensor.ids.contains(&props.id) {
// If we already know about the sensor but on a different Bluetooth adapter, add
// this one too.
sensor.ids.push(props.id);
}
} else {
// If we don't know about the sensor on any adapter, add it.
let sensor = Sensor::new(props, &sensor_names);
state.sensors.insert(sensor.mac_address.clone(), sensor);
}
}
}
Ok(())
}
async fn connect_sensor_with_id(
state: Arc<Mutex<SensorState>>,
session: &MijiaSession,
mac_address: &MacAddress,
) -> Result<(), eyre::Report> {
let (name, ids) = {
let mut state = state.lock().await;
let sensor = state.sensors.get_mut(mac_address).unwrap();
// Update the state of the sensor to `Connecting`.
println!(
"Trying to connect to {} from status: {:?}",
sensor.name, sensor.connection_status
);
sensor.connection_status = ConnectionStatus::Connecting {
reserved_until: Instant::now() + SENSOR_CONNECT_RESERVATION_TIMEOUT,
};
(sensor.name.clone(), sensor.ids.clone())
};
let result = connect_and_subscribe_sensor_or_disconnect(session, &name, ids).await;
let state = &mut *state.lock().await;
let sensor = state.sensors.get_mut(mac_address).unwrap();
match result {
Ok(id) => {
println!("Connected to {} and started notifications", sensor.name);
sensor.mark_connected(&mut state.homie, id).await?;
sensor.last_update_timestamp = Instant::now();
}
Err(e) => {
println!("Failed to connect to {}: {:?}", sensor.name, e);
sensor.connection_status = ConnectionStatus::Disconnected;
}
}
Ok(())
}
/// Try to connect to the ids in turn, and get the first one that succeeds. If they all fail then
/// return an error.
async fn try_connect_all(
session: &BluetoothSession,
ids: Vec<DeviceId>,
) -> Result<DeviceId, Vec<BluetoothError>> {
let mut errors = vec![];
for id in ids {
if let Err(e) = session.connect(&id).await {
errors.push(e);
} else {
return Ok(id);
}
}
Err(errors)
}
async fn connect_and_subscribe_sensor_or_disconnect(
session: &MijiaSession,
name: &str,
ids: Vec<DeviceId>,
) -> Result<DeviceId, eyre::Report> {
let id = try_connect_all(&session.bt_session, ids)
.await
.map_err(|e| eyre!("Error connecting to {}: {:?}", name, e))?;
// We managed to connect to the sensor via some id, now try to start notifications for readings.
retry(
ExponentialBackoff {
max_elapsed_time: Some(SENSOR_CONNECT_RETRY_TIMEOUT),
..Default::default()
},
|| session.start_notify_sensor(&id).map_err(Into::into),
)
.or_else(|e| async {
session
.bt_session
.disconnect(&id)
.await
.wrap_err_with(|| format!("Disconnecting from {} ({})", name, id))?;
Err(Report::new(e).wrap_err(format!("Starting notifications on {} ({})", name, id)))
})
.await?;
Ok(id)
}
/// If the sensor hasn't sent any updates in a while, disconnect it so we will try to reconnect.
async fn check_for_stale_sensor(
state: Arc<Mutex<SensorState>>,
session: &MijiaSession,
mac_address: &MacAddress,
id: &DeviceId,
) -> Result<(), eyre::Report> {
let state = &mut *state.lock().await;
let sensor = state.sensors.get_mut(mac_address).unwrap();
let now = Instant::now();
if now - sensor.last_update_timestamp > UPDATE_TIMEOUT {
println!(
"No update from {} for {:?}, reconnecting",
sensor.name,
now - sensor.last_update_timestamp
);
sensor.connection_status = ConnectionStatus::Disconnected;
state.homie.remove_node(&sensor.node_id()).await?;
// We could drop our state lock at this point, if it ends up taking
// too long. As it is, it's quite nice that we can't attempt to connect
// while we're in the middle of disconnecting.
session
.bt_session
.disconnect(id)
.await
.wrap_err_with(|| format!("disconnecting from {}", id))?;
}
Ok(())
}
async fn service_bluetooth_event_queue(
state: Arc<Mutex<SensorState>>,
session: &MijiaSession,
) -> Result<(), eyre::Report> {
println!("Subscribing to events");
let mut events = session.event_stream().await?;
println!("Processing events");
while let Some(event) = events.next().await {
handle_bluetooth_event(state.clone(), event).await?
}
// This should be unreachable, because the events Stream should never end,
// unless something has gone horribly wrong.
panic!("no more events");
}
async fn handle_bluetooth_event(
state: Arc<Mutex<SensorState>>,
event: MijiaEvent,
) -> Result<(), eyre::Report> {
let state = &mut *state.lock().await;
let homie = &mut state.homie;
let sensors = &mut state.sensors;
match event {
MijiaEvent::Readings { id, readings } => {
if let Some(sensor) = get_mut_sensor_by_id(sensors, &id) {
sensor
.publish_readings(homie, &readings, state.min_update_period)
.await?;
match &sensor.connection_status {
ConnectionStatus::Connected { id: connected_id } => {
if id != *connected_id {
log::info!(
"Got update from device on unexpected id {} (expected {})",
id,
connected_id,
);
}
}
ConnectionStatus::Connecting { .. } => {}
_ => {
println!("Got update from disconnected device {}. Connecting.", id);
sensor.mark_connected(homie, id).await?;
// TODO: Make sure the connection interval is set.
}
}
} else {
println!("Got update from unknown device {}.", id);
}
}
MijiaEvent::Disconnected { id } => {
if let Some(sensor) = get_mut_sensor_by_id(sensors, &id) {
if let ConnectionStatus::Connected { id: connected_id } = &sensor.connection_status
{
if id == *connected_id {
println!("{} disconnected", sensor.name);
sensor.connection_status = ConnectionStatus::MarkedDisconnected;
homie.remove_node(&sensor.node_id()).await?;
} else {
println!(
"{} ({}) disconnected but was connected as {}.",
sensor.name, id, connected_id
);
}
} else {
println!(
"{} ({}) disconnected but wasn't known to be connected.",
sensor.name, id
);
}
} else {
println!("Unknown device {} disconnected.", id);
}
}
_ => {}
};
Ok(())
}
| 35.345083 | 100 | 0.568947 |
ffd3d792f9fdc360abf3a0ef1168b412758e77ad
| 3,484 |
use dialoguer::{theme::ColorfulTheme, Confirm, Input, Select};
use std::collections::HashMap;
/// The result of the questioning process.
#[derive(Debug, Default)]
pub struct SurveyResults {
pub commit_type: String,
pub scope: Option<String>,
pub short_msg: String,
pub long_msg: Option<String>,
pub breaking_changes_desc: Option<String>,
pub affected_open_issues: Option<Vec<String>>,
}
impl SurveyResults {
/// Creates a default `SurveyResult`.
pub fn new() -> Self {
Self::default()
}
}
/// Asks the user all needed questions.
///
/// # Arguments
///
/// - `types`: A `HashMap` whose keys are the commit types and values are the
/// descriptions of the type.
///
/// # Returns
///
/// A `SurveyResult`.
pub fn ask(types: HashMap<&str, &str>) -> SurveyResults {
let mut results = SurveyResults::new();
// Select the scope of the commit.
let type_options = types
.iter()
.map(|(name, desc)| (name, desc))
.collect::<Vec<_>>();
let items = type_options
.iter()
.map(|(name, desc)| format!("{}: {}", name, desc))
.collect::<Vec<_>>();
let selected_index = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Select the type of change that you're committing:")
.default(0)
.items(&items)
.interact()
.unwrap();
let selected_commit_type = &type_options[selected_index];
results.commit_type = (*selected_commit_type.0).to_string();
let scope = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Denote the scope of this change (compiler, runtime, stdlib, etc.):")
.allow_empty(true)
.interact()
.ok()
.filter(|v: &String| !v.is_empty());
results.scope = scope;
let short_msg: String = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Write a short, imperative tense description of the change:")
.allow_empty(true)
.interact()
.unwrap();
results.short_msg = short_msg;
let long_msg: Option<String> = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Provide a longer description of the change:")
.allow_empty(true)
.interact()
.ok()
.filter(|v: &String| !v.is_empty());
results.long_msg = long_msg;
let is_breaking_change = Confirm::with_theme(&ColorfulTheme::default())
.with_prompt("Are there any breaking changes?")
.default(false)
.interact()
.unwrap();
if is_breaking_change {
let breaking_changes_desc = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Describe the breaking changes:")
.interact()
.ok();
results.breaking_changes_desc = breaking_changes_desc;
}
let are_issues_affected = Confirm::with_theme(&ColorfulTheme::default())
.with_prompt("Does this change affect any open issues?")
.default(false)
.interact()
.unwrap();
if are_issues_affected {
let affected_open_issues: Option<String> = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Add issue references (space-separated, e.g. \"#123\" or \"12 13\"):")
.interact()
.ok();
results.affected_open_issues = match affected_open_issues {
Some(s) => Some(s.split(' ').map(|e| e.to_string()).collect()),
None => None,
};
}
results
}
| 31.672727 | 95 | 0.611653 |
d558b5760c7da9fe83db68f4dc03369c42222a26
| 1,182 |
/*
* The Jira Cloud platform REST API
*
* Jira Cloud platform REST API documentation
*
* The version of the OpenAPI document: 1001.0.0-SNAPSHOT
* Contact: [email protected]
* Generated by: https://openapi-generator.tech
*/
/// VersionUnresolvedIssuesCount : Count of a version's unresolved issues.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VersionUnresolvedIssuesCount {
/// The URL of these count details.
#[serde(rename = "self", skip_serializing_if = "Option::is_none")]
pub _self: Option<String>,
/// Count of unresolved issues.
#[serde(
rename = "issuesUnresolvedCount",
skip_serializing_if = "Option::is_none"
)]
pub issues_unresolved_count: Option<i64>,
/// Count of issues.
#[serde(rename = "issuesCount", skip_serializing_if = "Option::is_none")]
pub issues_count: Option<i64>,
}
impl VersionUnresolvedIssuesCount {
/// Count of a version's unresolved issues.
pub fn new() -> VersionUnresolvedIssuesCount {
VersionUnresolvedIssuesCount {
_self: None,
issues_unresolved_count: None,
issues_count: None,
}
}
}
| 30.307692 | 77 | 0.675973 |
11e705e8aeac83fa033a01621311b79d74d4d7bf
| 43,217 |
/*!
# trajgen
**trajgen** is a minimum trajectory generation library written for Rust - given a set of 3D points,
desired times, and type of minimum trajectory, the library will calculate the appropriate order
polynomials to ensure a smooth path (as well as smooth derivatives) through the points.
## Features
* minimum trajectory generation for velocity, acceleration, jerk and snap
* calculate desired position, velocity, acceleration and further derivatives given time
## Using **trajgen**
Simply add the following to your `Cargo.toml` file:
```ignore
[dependencies]
trajgen = "*"
```
and now you can generate and use trajectories:
```
use trajgen::{TrajectoryGenerator, TrajectoryType, Point};
fn main() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Snap);
// add waypoints for the trajectory
let waypoints: Vec<Point> = vec![Point {x: 1., y: 2., z: 3., t: 0.},
Point {x: 2., y: 3., z: 4., t: 1.},
Point {x: 3., y: 4., z: 5., t: 2.}];
// solve for given waypoints
traj_gen.generate(&waypoints);
// use the individual values in real-time, perhaps to control a robot
let t = 0.24;
let pos = traj_gen.get_position(t).unwrap();
print!("Current desired position for time {} is {}", t, pos);
let vel = traj_gen.get_velocity(t).unwrap();
print!("Current desired velocity for time {} is {}", t, vel);
let acc = traj_gen.get_acceleration(t).unwrap();
print!("Current desired acceleration for time {} is {}", t, acc);
// or get values for a range of times, perhaps to plot
let path = traj_gen.get_positions(0.25, 0.75, 0.1);
}
```
## Derivation
For the derivation of the minimum trajectories this library implements, please see
the following [Jupyter notebook](https://github.com/tristeng/control/blob/master/notebooks/trajector-generator.ipynb).
*/
use log::{info};
use std::fmt;
use std::cmp::Ordering;
use nalgebra::{Matrix, Dynamic, VecStorage, U1, Vector, RowVector};
use std::fmt::Formatter;
// Define the dynamic matrix we use to solve
type DMatrixf32 = Matrix<f32, Dynamic, Dynamic, VecStorage<f32, Dynamic, Dynamic>>;
type DColVectorf32 = Vector<f32, Dynamic, VecStorage<f32, Dynamic, U1>>;
type DRowVectorf32 = RowVector<f32, Dynamic, VecStorage<f32, U1, Dynamic>>;
/// a point in 3D space-time
#[derive(Debug, Copy, Clone)]
pub struct Point {
pub x: f32,
pub y: f32,
pub z: f32,
pub t: f32,
}
impl Point {
/// Creates a point in 3D space-time
///
/// # Arguments
///
/// `x` - value along the x-axis
/// `y` - value along the y-axis
/// `z` - value along the z-axis
/// `t` - value along the time axis
///
/// # Examples
/// ```
/// use trajgen::Point;
/// let p3d = Point::new(5.2, -6.75, 0.23, 1.43);
/// ```
pub fn new(x: f32, y: f32, z: f32, t: f32) -> Point {
Point { x, y, z, t }
}
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Point(x: {}, y: {}, z: {}, t: {})", self.x, self.y, self.z, self.t)
}
}
/// a polynomial represented by its coefficients
#[derive(Debug, Clone)]
pub struct Polynomial {
coeffs: Vec<f32>,
}
impl Polynomial {
/// Returns an initialized polynomial
///
/// # Arguments
///
/// `coeffs` - vector of coefficients where index corresponds to power
///
/// # Examples
///
/// ```
/// use trajgen::Polynomial;
/// // f(t) = 7 - 2x + 3x^2
/// let poly = Polynomial::new(&vec![7.0f32, -2.0f32, 3.0f32]);
/// ```
pub fn new(coeffs: &Vec<f32>) -> Polynomial {
if coeffs.is_empty() {
panic!("Cannot initialize Polynomial with empty coefficients!");
}
let coeffs = coeffs.clone();
Polynomial { coeffs }
}
/// Returns the solution to f(t) at a given t
///
/// # Arguments
///
/// `t` - the value of t
///
/// # Examples
///
/// ```
/// use trajgen::Polynomial;
/// // f(t) = 7 - 2t + 3t^2
/// let poly = Polynomial::new(&vec![7.0f32, -2.0f32, 3.0f32]);
/// let ans = poly.eval(1.56);
/// ```
pub fn eval(&self, t: f32) -> f32 {
let mut val = self.coeffs[0];
let mut tt = t;
for idx in 1..self.coeffs.len() {
val = val + tt * self.coeffs[idx];
tt *= t;
}
val
}
/// Returns the derivative of the polynomial
///
/// # Examples
///
/// ```
/// use trajgen::Polynomial;
/// // f(t) = 7 - 2t + 3t^2
/// let poly = Polynomial::new(&vec![7.0f32, -2.0f32, 3.0f32]);
/// // f'(t) = 2 + 6t
/// let der = poly.derivative();
/// ```
pub fn derivative(&self) -> Polynomial {
// special case when we are down to a single coefficient
if self.coeffs.len() == 1 {
return Polynomial::new(&vec![0.]);
}
let mut newcoeffs = Vec::new();
// drop coefficient at index 0, and multiply coefficients by power
for idx in 1..self.coeffs.len() {
newcoeffs.push(self.coeffs[idx] * idx as f32);
}
Polynomial::new(&newcoeffs)
}
}
impl fmt::Display for Polynomial {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut s = String::from("f(t) = ");
for idx in 0..self.coeffs.len() {
let coeff: String = match self.coeffs[idx].partial_cmp(&0.0)
.expect("Found a coefficient that is NaN!") {
Ordering::Less => format!("- {}", -self.coeffs[idx]),
Ordering::Greater => format!("+ {}", self.coeffs[idx]),
Ordering::Equal => String::new(),
};
// check if the coefficient is 0 - if so, just continue
if coeff.len() == 0 {
continue;
}
// append on the coefficient
s.push_str(&coeff);
// append on the x and it's power
if idx > 0 {
let x = if idx > 1 {format!("t^{} ", idx)} else {String::from("t ")};
s.push_str(&x);
} else {
s.push(' ');
}
}
write!(f, "{}", s.trim())
}
}
/// The different types of supported trajectories
#[derive(Debug, PartialEq)]
pub enum TrajectoryType {
Velocity,
Acceleration,
Jerk,
Snap,
}
/// returns the number of coefficients required to solve for the given trajectory type
fn num_coeffs(traj_type: &TrajectoryType) -> usize {
match traj_type {
TrajectoryType::Velocity => 2,
TrajectoryType::Acceleration => 4,
TrajectoryType::Jerk => 6,
TrajectoryType::Snap => 8,
}
}
/// Trajectory Generator
#[derive(Debug)]
pub struct TrajectoryGenerator {
traj_type: TrajectoryType,
x_polys: Vec<Polynomial>,
y_polys: Vec<Polynomial>,
z_polys: Vec<Polynomial>,
points: Vec<Point>,
}
impl TrajectoryGenerator {
pub fn new(traj_type: TrajectoryType) -> TrajectoryGenerator {
TrajectoryGenerator {
traj_type,
x_polys: Vec::new(),
y_polys: Vec::new(),
z_polys: Vec::new(),
points: Vec::new(),
}
}
/// Returns coefficients for position and time derivatives evaulated at a point in time
/// Evaulates equations: c0*t^0 + c1*t^1 + ... + cn*t^n at some time t
///
/// # Arguments
///
/// `eqs` - position equation and time derivatives
/// `t` - the time to evaulate at
/// evaulates equations: c0*t^0 + c1*t^1 + ... + cn*t^n at some time t
fn coeffs_at_time(&self, eqs: Vec<Polynomial>, t: f32) -> DMatrixf32 {
let numcoeffs = num_coeffs(&self.traj_type);
let mut retval = DMatrixf32::zeros(eqs.len(), numcoeffs);
for ii in 0..eqs.len() {
let mut row = DRowVectorf32::zeros(numcoeffs);
let eq = &eqs[ii];
// since the time derivatives will have less coefficients calculate an offset into the
// resulting array to preserve the coefficients power
let offset = numcoeffs - eq.coeffs.len();
for jj in 0..eq.coeffs.len() {
row[jj+offset] = eq.coeffs[jj] * t.powi(jj as i32);
}
retval.set_row(ii, &row);
}
retval
}
/// Generates the polynomials that will give a smooth path through the given points
///
/// # Arguments
///
/// `points` - list of trajectory waypoints ordered by time ascending
///
/// # Examples
///
/// ```
/// use trajgen::{TrajectoryGenerator, TrajectoryType, Point};
/// let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Jerk);
/// // generates minimum jerk polynomials for a single segment trajectory
/// let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.), Point::new(2., 3., 4., 1.)];
/// traj_gen.generate(&points);
/// ```
pub fn generate(&mut self, points: &Vec<Point>) {
self.x_polys.clear();
self.y_polys.clear();
self.z_polys.clear();
self.points.clear();
self.points = points.clone();
// make sure we have at least 2 points
if points.len() < 2 {
panic!("At least 2 points are required to generate a trajectory");
}
// check that times are incrementing
for idx in 0..points.len()-1 {
if points[idx+1].t <= points[idx].t {
panic!("Time at index {} is less than or equal to time at index {}", idx+1, idx);
}
}
info!("Generating trajectory using {} waypoints", points.len());
let numcoeffs = num_coeffs(&self.traj_type);
// use the polynomial class to create our coefficient equations and time derivatives
// we want numcoeffs-1 equations total
let mut eqs: Vec<Polynomial> = Vec::new();
let poscoeffs:Vec<f32> = vec![1.0; numcoeffs];
let poly = Polynomial::new(&poscoeffs);
eqs.push(poly);
while eqs.len() < numcoeffs - 1 {
eqs.push(eqs.last().unwrap().derivative());
}
// create the A matrix
let n= numcoeffs * (points.len() - 1);
let mut a = DMatrixf32::zeros(n, n);
// create b vectors for each of x, y, and z
let mut bx = DColVectorf32::zeros(n);
let mut by = DColVectorf32::zeros(n);
let mut bz = DColVectorf32::zeros(n);
let mut rowidx: usize = 0;
let numeqs = (numcoeffs - 2) / 2;
// fill in equations for first segment - time derivatives of position are all equal to 0 at start time
let coeffs = self.coeffs_at_time(Vec::from(&eqs[1..1+numeqs]), points[0].t);
let mut m = a.slice_mut((rowidx, 0), (numeqs, numcoeffs));
for (idx, row) in coeffs.row_iter().enumerate() {
let rowvec = DRowVectorf32::from(row);
m.set_row(idx, &rowvec);
}
rowidx += numeqs;
// fill in equations for last segment - time derivatives of position are all equal to 0 at end time
let coeffs = self.coeffs_at_time(Vec::from(&eqs[1..1+numeqs]), points.last().unwrap().t);
let mut m = a.slice_mut((rowidx, n - numcoeffs), (numeqs, numcoeffs));
for (idx, row) in coeffs.row_iter().enumerate() {
let rowvec = DRowVectorf32::from(row);
m.set_row(idx, &rowvec);
}
rowidx += numeqs;
// for each segment...
for idx in 0..points.len()-1 {
let startp = points[idx];
let endp = points[idx+1];
let startt = points[idx].t;
let endt = points[idx+1].t;
// fill in 2 equations for start and end point passing through the poly
// start point
let col = idx * numcoeffs;
let coeffs = self.coeffs_at_time(Vec::from(&eqs[0..1]), startt);
let rowvec = DRowVectorf32::from(coeffs.row(0));
a.slice_mut((rowidx, col), (1, numcoeffs)).set_row(0, &rowvec);
// set the b vector values
bx[rowidx] = startp.x;
by[rowidx] = startp.y;
bz[rowidx] = startp.z;
rowidx += 1;
// end point
let coeffs = self.coeffs_at_time(Vec::from(&eqs[0..1]), endt);
let rowvec = DRowVectorf32::from(coeffs.row(0));
a.slice_mut((rowidx, col), (1, numcoeffs)).set_row(0, &rowvec);
// set the b vector values
bx[rowidx] = endp.x;
by[rowidx] = endp.y;
bz[rowidx] = endp.z;
rowidx += 1;
}
// for all segments, except last...
for idx in 0..points.len()-2 {
let endt = points[idx+1].t;
let mut col = idx * numcoeffs;
let mut coeffs = self.coeffs_at_time(Vec::from(&eqs[1..numcoeffs-1]), endt);
let mut m = a.slice_mut((rowidx, col), (numcoeffs-2, numcoeffs));
// fill in required equations for time derivatives to ensure they are the same through
// the transition point
for (ii, row) in coeffs.row_iter().enumerate() {
let rowvec = DRowVectorf32::from(row);
m.set_row(ii, &rowvec);
}
col += numcoeffs;
// negate endt coefficients since we move everything to the lhs
coeffs.neg_mut();
let mut m = a.slice_mut((rowidx, col), (numcoeffs-2, numcoeffs));
for (ii, row) in coeffs.row_iter().enumerate() {
let rowvec = DRowVectorf32::from(row);
m.set_row(ii, &rowvec);
}
rowidx += numeqs;
}
// invert the A matrix to solve the linear system Ax=b
let ainv = a.try_inverse()
.expect("Failed to invert A matrix!");
let ansx = &ainv * bx;
let ansy = &ainv * by;
let ansz = &ainv * bz;
// add a polynomial for each segment
for idx in 0..points.len()-1 {
let offset = idx * numcoeffs;
// wasn't able to get this to work with slices...so this is a little ugly
let mut arrx: Vec<f32> = Vec::new();
let mut arry: Vec<f32> = Vec::new();
let mut arrz: Vec<f32> = Vec::new();
for ii in offset..offset+numcoeffs {
arrx.push(ansx[(ii, 0)]);
arry.push(ansy[(ii, 0)]);
arrz.push(ansz[(ii, 0)]);
}
self.x_polys.push(Polynomial::new(&Vec::from(arrx)));
self.y_polys.push(Polynomial::new(&Vec::from(arry)));
self.z_polys.push(Polynomial::new(&Vec::from(arrz)));
}
info!("Finished generating trajectory using {} waypoints", points.len());
}
/// returns the index of the appropriate polygon to evaluate the value at time t
fn poly_index(&self, t: f32) -> Option<usize> {
if self.points.is_empty() {
None
} else {
if t < self.points[0].t {
Some(0)
} else if t > self.points.last().unwrap().t {
Some(self.x_polys.len() - 1)
} else {
let mut idx= 0;
for ii in 0..self.points.len()-1 {
let startp = self.points[ii];
let endp = self.points[ii+1];
if t >= startp.t && t <= endp.t {
idx = ii;
break;
}
}
Some(idx)
}
}
}
/// Returns a `Point` structure with the value for the trajectory at time t
///
/// # Arguments
///
/// `t` - time
/// `derivative` - derivative order, 0 for position, 1 for velocity, etc.
///
/// # Examples
///
/// ```
/// use trajgen::{TrajectoryGenerator, TrajectoryType, Point};
/// let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Jerk);
/// let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.), Point::new(2., 3., 4., 1.)];
/// traj_gen.generate(&points);
/// // get the position at t = 0.45
/// let point = traj_gen.get_value(0.45, 0);
/// ```
pub fn get_value(&self, t: f32, derivative: u8) -> Option<Point> {
let idx = self.poly_index(t)
.expect("A trajectory must be generated first");
let mut t = t;
if t < self.points.first().unwrap().t {
// if t is before start point time, clamp it to start time
t = self.points.first().unwrap().t;
} else if t > self.points.last().unwrap().t {
// if t is after end point time, clamp it to end time
t = self.points.last().unwrap().t;
}
let mut x_poly = self.x_polys[idx].clone();
let mut y_poly = self.y_polys[idx].clone();
let mut z_poly = self.z_polys[idx].clone();
let mut derivative = derivative;
loop {
if derivative == 0 {
break;
}
x_poly = x_poly.derivative();
y_poly = y_poly.derivative();
z_poly = z_poly.derivative();
derivative -= 1;
}
// return the point evaluated at time t with the appropriate polynomial and derivative
Some(Point{
x: x_poly.eval(t),
y: y_poly.eval(t),
z: z_poly.eval(t),
t
})
}
/// Convenience function to return the position on the current trajectory
pub fn get_position(&self, t: f32) -> Option<Point> {
return self.get_value(t, 0);
}
/// Convenience function to return the velocity on the current trajectory
pub fn get_velocity(&self, t: f32) -> Option<Point> {
return self.get_value(t, 1);
}
/// Convenience function to return the accleration on the current trajectory
pub fn get_acceleration(&self, t: f32) -> Option<Point> {
return self.get_value(t, 2);
}
/// Convenience function to return the jerk on the current trajectory
pub fn get_jerk(&self, t: f32) -> Option<Point> {
return self.get_value(t, 3);
}
/// Returns an array of `Point` structures covering the input time range and step
///
/// # Arguments
///
/// `start` - start time
/// `end` - end time
/// `step` - time step
/// `derivative` - derivative order, 0 for position, 1 for velocity, etc.
///
/// # Examples
///
/// ```
/// use trajgen::{TrajectoryGenerator, TrajectoryType, Point};
/// let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Jerk);
/// let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.), Point::new(2., 3., 4., 1.)];
/// traj_gen.generate(&points);
/// // get position values for time range [0, 1] using step of 0.1
/// let positions = traj_gen.get_values(0., 1., 0.1, 0);
/// ```
pub fn get_values(&self, start: f32, end: f32, step: f32, derivative: u8) -> Vec<Point> {
if end <= start {
panic!("End must not be before start");
}
if step <= 0. {
panic!("Step must be non-zero");
}
let mut values: Vec<Point> = Vec::new();
let mut t = start;
loop {
values.push(self.get_value(t, derivative).unwrap());
t += step;
if t > end {
break;
}
}
values
}
/// Convenience function to sample positions on the current trajectory
pub fn get_positions(&self, start: f32, end: f32, step: f32) -> Vec<Point> {
return self.get_values(start, end, step, 0);
}
/// Convenience function to sample velocities on the current trajectory
pub fn get_velocities(&self, start: f32, end: f32, step: f32) -> Vec<Point> {
return self.get_values(start, end, step, 1);
}
/// Convenience function to sample accelerations on the current trajectory
pub fn get_accelerations(&self, start: f32, end: f32, step: f32) -> Vec<Point> {
return self.get_values(start, end, step, 2);
}
/// Convenience function to sample jerks on the current trajectory
pub fn get_jerks(&self, start: f32, end: f32, step: f32) -> Vec<Point> {
return self.get_values(start, end, step, 3);
}
}
#[cfg(test)]
mod tests {
use super::*;
use assert::close;
#[test]
fn point_new() {
let point = Point::new(5.2, -6.75, 0.23, 2.32);
assert_eq!(5.2, point.x);
assert_eq!(-6.75, point.y);
assert_eq!(0.23, point.z);
assert_eq!(2.32, point.t);
}
#[test]
fn point_fmt() {
let point = Point::new(5.2, -6.75, 0.23, 2.32);
assert_eq!("Point(x: 5.2, y: -6.75, z: 0.23, t: 2.32)", format!("{}", point))
}
#[test]
fn coeffs_for_traj_type() {
assert_eq!(2, num_coeffs(&TrajectoryType::Velocity));
assert_eq!(4, num_coeffs(&TrajectoryType::Acceleration));
assert_eq!(6, num_coeffs(&TrajectoryType::Jerk));
assert_eq!(8, num_coeffs(&TrajectoryType::Snap));
}
#[test]
fn poly_new() {
// f(t) = 7 - 2t + 3t^2
let poly = Polynomial::new(&vec![7.0f32, -2.0f32, 3.0f32]);
// make sure it initialized correctly
assert_eq!(3, poly.coeffs.len());
assert_eq!(7.0, poly.coeffs[0]);
assert_eq!(-2.0, poly.coeffs[1]);
assert_eq!(3.0, poly.coeffs[2]);
}
#[test]
#[should_panic]
fn poly_new_invalid() {
Polynomial::new(&Vec::new());
}
#[test]
fn poly_eval() {
// f(t) = 7 - 2t + 3t^2 - 4t^3
let poly = Polynomial::new(&vec![7., -2., 3., -4.]);
// f(0) = 7.0
assert_eq!(7.0, poly.eval(0.0));
// f(1) = 4.0
assert_eq!(4.0, poly.eval(1.0));
// f(7.26) = -1380.0261
assert_eq!(-1380.0261, poly.eval(7.26));
}
#[test]
fn poly_derivative() {
// f(t) = 7 - 2t + 3t^2
let poly = Polynomial::new(&vec![7.0f32, -2.0f32, 3.0f32]);
let poly = poly.derivative();
// f'(t) = -2 + 6t
assert_eq!(2, poly.coeffs.len());
assert_eq!(-2.0, poly.coeffs[0]);
assert_eq!(6.0, poly.coeffs[1]);
let poly = poly.derivative();
// f''(t) = 6
assert_eq!(1, poly.coeffs.len());
assert_eq!(6.0, poly.coeffs[0]);
let poly = poly.derivative();
// f'''(t) = 0
assert_eq!(1, poly.coeffs.len());
assert_eq!(0.0, poly.coeffs[0]);
}
#[test]
fn poly_print() {
// f(t) = 7 - 2t + 3t^2
let poly = Polynomial::new(&vec![7.0f32, -2.0f32, 3.0f32]);
assert_eq!(poly.to_string(), "f(t) = + 7 - 2t + 3t^2");
// f'(t) = -2 + 6t
let poly = poly.derivative();
assert_eq!(poly.to_string(), "f(t) = - 2 + 6t");
// set a middle coefficient to 0
// f(t) = 7 + 3t^2
let poly = Polynomial::new(&vec![7.0f32, 0.0f32, 3.0f32]);
assert_eq!(poly.to_string(), "f(t) = + 7 + 3t^2");
// set the first coefficient to 0
// f(t) = -2.1t + 3.9t^2
let poly = Polynomial::new(&vec![0.0f32, -2.1f32, 3.9f32]);
assert_eq!(poly.to_string(), "f(t) = - 2.1t + 3.9t^2");
// set all coefficients to 0
let poly = Polynomial::new(&vec![0.0f32, 0.0f32, 0.0f32]);
assert_eq!(poly.to_string(), "f(t) =");
}
fn assert_poly_close(expected: Vec<f32>, actual: &Polynomial, delta: f32) {
assert_eq!(expected.len(), actual.coeffs.len());
for idx in 0..expected.len() {
close(expected[idx], actual.coeffs[idx], delta);
}
}
#[test]
fn traj_gen_new() {
let traj_gen = TrajectoryGenerator::new(TrajectoryType::Jerk);
assert_eq!(TrajectoryType::Jerk, traj_gen.traj_type);
assert_eq!(0, traj_gen.x_polys.len());
assert_eq!(0, traj_gen.y_polys.len());
assert_eq!(0, traj_gen.z_polys.len());
assert_eq!(0, traj_gen.points.len());
}
#[test]
#[should_panic]
fn traj_generate_empty_inputs() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Jerk);
let points: Vec<Point> = Vec::new();
traj_gen.generate(&points);
}
#[test]
#[should_panic]
fn traj_generate_single_point() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Jerk);
// only 1 point and 2 times
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.)];
traj_gen.generate(&points);
}
#[test]
fn traj_generate_two_points_velocity() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Velocity);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.),
Point::new(2., 3., 4., 1.)];
traj_gen.generate(&points);
// 2 points will only generate a single segment
assert_eq!(1, traj_gen.x_polys.len());
assert_eq!(1, traj_gen.y_polys.len());
assert_eq!(1, traj_gen.z_polys.len());
// check that each poly is close to what we expect
let delta = 1e-9;
assert_poly_close(vec![1., 1.], &traj_gen.x_polys[0], delta);
assert_poly_close(vec![2., 1.], &traj_gen.y_polys[0], delta);
assert_poly_close(vec![3., 1.], &traj_gen.z_polys[0], delta);
// ensure that the trajectory passes through the input points
close(1., traj_gen.x_polys[0].eval(0.), delta);
close(2., traj_gen.y_polys[0].eval(0.), delta);
close(3., traj_gen.z_polys[0].eval(0.), delta);
close(2., traj_gen.x_polys[0].eval(1.), delta);
close(3., traj_gen.y_polys[0].eval(1.), delta);
close(4., traj_gen.z_polys[0].eval(1.), delta);
}
#[test]
fn traj_generate_two_points_acceleration() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Acceleration);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.), Point::new(2., 3., 4., 1.)];
traj_gen.generate(&points);
// 2 points will only generate a single segment
assert_eq!(1, traj_gen.x_polys.len());
assert_eq!(1, traj_gen.y_polys.len());
assert_eq!(1, traj_gen.z_polys.len());
// check that each poly is close to what we expect
let delta = 1e-9;
assert_poly_close(vec![1., 0., 3., -2.], &traj_gen.x_polys[0], delta);
assert_poly_close(vec![2., 0., 3., -2.], &traj_gen.y_polys[0], delta);
assert_poly_close(vec![3., 0., 3., -2.], &traj_gen.z_polys[0], delta);
// ensure that the trajectory passes through the input points
close(1., traj_gen.x_polys[0].eval(0.), delta);
close(2., traj_gen.y_polys[0].eval(0.), delta);
close(3., traj_gen.z_polys[0].eval(0.), delta);
close(2., traj_gen.x_polys[0].eval(1.), delta);
close(3., traj_gen.y_polys[0].eval(1.), delta);
close(4., traj_gen.z_polys[0].eval(1.), delta);
}
#[test]
fn traj_generate_two_points_jerk() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Jerk);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.), Point::new(2., 3., 4., 1.)];
traj_gen.generate(&points);
// 2 points will only generate a single segment
assert_eq!(1, traj_gen.x_polys.len());
assert_eq!(1, traj_gen.y_polys.len());
assert_eq!(1, traj_gen.z_polys.len());
// check that each poly is close to what we expect
let delta = 1e-4;
assert_poly_close(vec![1., 0., 0., 10., -15., 6.], &traj_gen.x_polys[0], delta);
assert_poly_close(vec![2., 0., 0., 10., -15., 6.], &traj_gen.y_polys[0], delta);
assert_poly_close(vec![3., 0., 0., 10., -15., 6.], &traj_gen.z_polys[0], delta);
// ensure that the trajectory passes through the input points
close(1., traj_gen.x_polys[0].eval(0.), delta);
close(2., traj_gen.y_polys[0].eval(0.), delta);
close(3., traj_gen.z_polys[0].eval(0.), delta);
close(2., traj_gen.x_polys[0].eval(1.), delta);
close(3., traj_gen.y_polys[0].eval(1.), delta);
close(4., traj_gen.z_polys[0].eval(1.), delta);
}
#[test]
fn traj_generate_two_points_snap() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Snap);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.), Point::new(2., 3., 4., 1.)];
traj_gen.generate(&points);
// 2 points will only generate a single segment
assert_eq!(1, traj_gen.x_polys.len());
assert_eq!(1, traj_gen.y_polys.len());
assert_eq!(1, traj_gen.z_polys.len());
// check that each poly is close to what we expect
let delta = 1e-2;
assert_poly_close(vec![1., 0., 0., 0., 35., -84., 70., -20.], &traj_gen.x_polys[0], delta);
assert_poly_close(vec![2., 0., 0., 0., 35., -84., 70., -20.], &traj_gen.y_polys[0], delta);
assert_poly_close(vec![3., 0., 0., 0., 35., -84., 70., -20.], &traj_gen.z_polys[0], delta);
// ensure that the trajectory passes through the input points
close(1., traj_gen.x_polys[0].eval(0.), delta);
close(2., traj_gen.y_polys[0].eval(0.), delta);
close(3., traj_gen.z_polys[0].eval(0.), delta);
close(2., traj_gen.x_polys[0].eval(1.), delta);
close(3., traj_gen.y_polys[0].eval(1.), delta);
close(4., traj_gen.z_polys[0].eval(1.), delta);
}
#[test]
fn traj_generate_multi_points_velocity() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Velocity);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.),
Point::new(2., 3., 4., 1.),
Point::new(3., 4., 5., 2.)];
traj_gen.generate(&points);
// should be 2 segments since we have 3 points
assert_eq!(2, traj_gen.x_polys.len());
assert_eq!(2, traj_gen.y_polys.len());
assert_eq!(2, traj_gen.z_polys.len());
// check that each poly is close to what we expect
let delta = 1e-9;
assert_poly_close(vec![1., 1.], &traj_gen.x_polys[0], delta);
assert_poly_close(vec![1., 1.], &traj_gen.x_polys[1], delta);
assert_poly_close(vec![2., 1.], &traj_gen.y_polys[0], delta);
assert_poly_close(vec![2., 1.], &traj_gen.y_polys[1], delta);
assert_poly_close(vec![3., 1.], &traj_gen.z_polys[0], delta);
assert_poly_close(vec![3., 1.], &traj_gen.z_polys[1], delta);
// ensure that the trajectory passes through the input points and that the intermediary
// point works for both polynomials
close(1., traj_gen.x_polys[0].eval(0.), delta);
close(2., traj_gen.y_polys[0].eval(0.), delta);
close(3., traj_gen.z_polys[0].eval(0.), delta);
close(2., traj_gen.x_polys[0].eval(1.), delta);
close(3., traj_gen.y_polys[0].eval(1.), delta);
close(4., traj_gen.z_polys[0].eval(1.), delta);
close(2., traj_gen.x_polys[1].eval(1.), delta);
close(3., traj_gen.y_polys[1].eval(1.), delta);
close(4., traj_gen.z_polys[1].eval(1.), delta);
close(3., traj_gen.x_polys[1].eval(2.), delta);
close(4., traj_gen.y_polys[1].eval(2.), delta);
close(5., traj_gen.z_polys[1].eval(2.), delta);
}
#[test]
fn traj_generate_multi_points_acceleration() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Acceleration);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.),
Point::new(2., 3., 4., 1.),
Point::new(3., 4., 5., 2.)];
traj_gen.generate(&points);
// should be 2 segments since we have 3 points
assert_eq!(2, traj_gen.x_polys.len());
assert_eq!(2, traj_gen.y_polys.len());
assert_eq!(2, traj_gen.z_polys.len());
// check that each poly is close to what we expect
let delta = 1e-4;
assert_poly_close(vec![1., 0., 1.5, -0.5], &traj_gen.x_polys[0], delta);
assert_poly_close(vec![1., 0., 1.5, -0.5], &traj_gen.x_polys[1], delta);
assert_poly_close(vec![2., 0., 1.5, -0.5], &traj_gen.y_polys[0], delta);
assert_poly_close(vec![2., 0., 1.5, -0.5], &traj_gen.y_polys[1], delta);
assert_poly_close(vec![3., 0., 1.5, -0.5], &traj_gen.z_polys[0], delta);
assert_poly_close(vec![3., 0., 1.5, -0.5], &traj_gen.z_polys[1], delta);
// ensure that the trajectory passes through the input points and that the intermediary
// point works for both polynomials
close(1., traj_gen.x_polys[0].eval(0.), delta);
close(2., traj_gen.y_polys[0].eval(0.), delta);
close(3., traj_gen.z_polys[0].eval(0.), delta);
close(2., traj_gen.x_polys[0].eval(1.), delta);
close(3., traj_gen.y_polys[0].eval(1.), delta);
close(4., traj_gen.z_polys[0].eval(1.), delta);
close(2., traj_gen.x_polys[1].eval(1.), delta);
close(3., traj_gen.y_polys[1].eval(1.), delta);
close(4., traj_gen.z_polys[1].eval(1.), delta);
close(3., traj_gen.x_polys[1].eval(2.), delta);
close(4., traj_gen.y_polys[1].eval(2.), delta);
close(5., traj_gen.z_polys[1].eval(2.), delta);
}
#[test]
fn traj_generate_multi_points_jerk() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Jerk);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.),
Point::new(2., 3., 4., 1.),
Point::new(3., 4., 5., 2.)];
traj_gen.generate(&points);
// should be 2 segments since we have 3 points
assert_eq!(2, traj_gen.x_polys.len());
assert_eq!(2, traj_gen.y_polys.len());
assert_eq!(2, traj_gen.z_polys.len());
// check that each poly is close to what we expect
let delta = 1e-4;
assert_poly_close(vec![1., 0., 0., 2.5, -1.875, 0.375], &traj_gen.x_polys[0], delta);
assert_poly_close(vec![1., 0., 0., 2.5, -1.875, 0.375], &traj_gen.x_polys[1], delta);
assert_poly_close(vec![2., 0., 0., 2.5, -1.875, 0.375], &traj_gen.y_polys[0], delta);
assert_poly_close(vec![2., 0., 0., 2.5, -1.875, 0.375], &traj_gen.y_polys[1], delta);
assert_poly_close(vec![3., 0., 0., 2.5, -1.875, 0.375], &traj_gen.z_polys[0], delta);
assert_poly_close(vec![3., 0., 0., 2.5, -1.875, 0.375], &traj_gen.z_polys[1], delta);
// ensure that the trajectory passes through the input points and that the intermediary
// point works for both polynomials
close(1., traj_gen.x_polys[0].eval(0.), delta);
close(2., traj_gen.y_polys[0].eval(0.), delta);
close(3., traj_gen.z_polys[0].eval(0.), delta);
close(2., traj_gen.x_polys[0].eval(1.), delta);
close(3., traj_gen.y_polys[0].eval(1.), delta);
close(4., traj_gen.z_polys[0].eval(1.), delta);
close(2., traj_gen.x_polys[1].eval(1.), delta);
close(3., traj_gen.y_polys[1].eval(1.), delta);
close(4., traj_gen.z_polys[1].eval(1.), delta);
close(3., traj_gen.x_polys[1].eval(2.), delta);
close(4., traj_gen.y_polys[1].eval(2.), delta);
close(5., traj_gen.z_polys[1].eval(2.), delta);
}
#[test]
fn traj_generate_multi_points_snap() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Snap);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.),
Point::new(2., 3., 4., 1.),
Point::new(3., 4., 5., 2.)];
traj_gen.generate(&points);
// should be 2 segments since we have 3 points
assert_eq!(2, traj_gen.x_polys.len());
assert_eq!(2, traj_gen.y_polys.len());
assert_eq!(2, traj_gen.z_polys.len());
// check that each poly is close to what we expect
let delta = 1e-2;
assert_poly_close(vec![1., 0., 0., 0., 4.375, -5.25, 2.1875, -0.3125], &traj_gen.x_polys[0], delta);
assert_poly_close(vec![1., 0., 0., 0., 4.375, -5.25, 2.1875, -0.3125], &traj_gen.x_polys[1], delta);
assert_poly_close(vec![2., 0., 0., 0., 4.375, -5.25, 2.1875, -0.3125], &traj_gen.y_polys[0], delta);
assert_poly_close(vec![2., 0., 0., 0., 4.375, -5.25, 2.1875, -0.3125], &traj_gen.y_polys[1], delta);
assert_poly_close(vec![3., 0., 0., 0., 4.375, -5.25, 2.1875, -0.3125], &traj_gen.z_polys[0], delta);
assert_poly_close(vec![3., 0., 0., 0., 4.375, -5.25, 2.1875, -0.3125], &traj_gen.z_polys[1], delta);
// ensure that the trajectory passes through the input points and that the intermediary
// point works for both polynomials
close(1., traj_gen.x_polys[0].eval(0.), delta);
close(2., traj_gen.y_polys[0].eval(0.), delta);
close(3., traj_gen.z_polys[0].eval(0.), delta);
close(2., traj_gen.x_polys[0].eval(1.), delta);
close(3., traj_gen.y_polys[0].eval(1.), delta);
close(4., traj_gen.z_polys[0].eval(1.), delta);
close(2., traj_gen.x_polys[1].eval(1.), delta);
close(3., traj_gen.y_polys[1].eval(1.), delta);
close(4., traj_gen.z_polys[1].eval(1.), delta);
close(3., traj_gen.x_polys[1].eval(2.), delta);
close(4., traj_gen.y_polys[1].eval(2.), delta);
close(5., traj_gen.z_polys[1].eval(2.), delta);
}
#[test]
#[should_panic]
fn traj_poly_index_invalid() {
let traj_gen = TrajectoryGenerator::new(TrajectoryType::Snap);
traj_gen.poly_index(1.23).expect("This should fail");
}
#[test]
fn traj_poly_index() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Snap);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.),
Point::new(2., 3., 4., 1.),
Point::new(3., 4., 5., 2.)];
traj_gen.generate(&points);
// before start time
assert_eq!(0, traj_gen.poly_index(-1.23).unwrap());
// after start time
assert_eq!(1, traj_gen.poly_index(5.23).unwrap());
// between points 1-2
assert_eq!(0, traj_gen.poly_index(0.5).unwrap());
// between points 2-3
assert_eq!(1, traj_gen.poly_index(1.5).unwrap());
// on the start point time
assert_eq!(0, traj_gen.poly_index(0.).unwrap());
// on the middle point time
assert_eq!(0, traj_gen.poly_index(1.).unwrap());
// on the end point time
assert_eq!(1, traj_gen.poly_index(2.).unwrap());
}
#[test]
fn traj_get_value() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Snap);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.),
Point::new(2., 3., 4., 1.),
Point::new(3., 4., 5., 2.)];
traj_gen.generate(&points);
let delta = 1e-3;
// position
close(1., traj_gen.get_value(0., 0).unwrap().x, delta);
close(2., traj_gen.get_value(0., 0).unwrap().y, delta);
close(3., traj_gen.get_value(0., 0).unwrap().z, delta);
close(2., traj_gen.get_value(1., 0).unwrap().x, delta);
close(3., traj_gen.get_value(1., 0).unwrap().y, delta);
close(4., traj_gen.get_value(1., 0).unwrap().z, delta);
close(3., traj_gen.get_value(2., 0).unwrap().x, delta);
close(4., traj_gen.get_value(2., 0).unwrap().y, delta);
close(5., traj_gen.get_value(2., 0).unwrap().z, delta);
// velocity
close(2.187, traj_gen.get_value(1., 1).unwrap().x, delta);
close(2.187, traj_gen.get_value(1., 1).unwrap().y, delta);
close(2.187, traj_gen.get_value(1., 1).unwrap().z, delta);
// acceleration should be zero at the midpoint for this trajectory
close(0., traj_gen.get_value(1., 2).unwrap().x, delta);
close(0., traj_gen.get_value(1., 2).unwrap().y, delta);
close(0., traj_gen.get_value(1., 2).unwrap().z, delta);
}
#[test]
fn traj_convenience() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Snap);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.),
Point::new(2., 3., 4., 1.),
Point::new(3., 4., 5., 2.)];
traj_gen.generate(&points);
let delta = 1e-2;
close(3., traj_gen.get_position(1.).unwrap().y, delta);
// higher derivatives should have zero value at start and end
close(0., traj_gen.get_velocity(0.).unwrap().y, delta);
close(0., traj_gen.get_acceleration(0.).unwrap().z, delta);
close(0., traj_gen.get_jerk(0.).unwrap().x, delta);
close(0., traj_gen.get_velocity(2.).unwrap().y, delta);
close(0., traj_gen.get_acceleration(2.).unwrap().z, delta);
close(0., traj_gen.get_jerk(2.).unwrap().x, delta);
}
#[test]
fn traj_get_values() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Snap);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.),
Point::new(2., 3., 4., 1.),
Point::new(3., 4., 5., 2.)];
traj_gen.generate(&points);
let points = traj_gen.get_values(0., 2., 0.2, 0);
assert_eq!(10, points.len());
// should also be able to sample outside of the range with no issues
let points = traj_gen.get_values(-1., 3., 0.2, 0);
assert_eq!(20, points.len());
}
#[test]
#[should_panic]
fn traj_get_values_bad_range() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Snap);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.),
Point::new(2., 3., 4., 1.),
Point::new(3., 4., 5., 2.)];
traj_gen.generate(&points);
traj_gen.get_values(2., 1., 0.2, 0);
}
#[test]
#[should_panic]
fn traj_get_values_bad_step() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Snap);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.),
Point::new(2., 3., 4., 1.),
Point::new(3., 4., 5., 2.)];
traj_gen.generate(&points);
traj_gen.get_values(2., 1., -0.2, 0);
}
#[test]
fn traj_convenience_sample() {
let mut traj_gen = TrajectoryGenerator::new(TrajectoryType::Snap);
let points: Vec<Point> = vec![Point::new(1., 2., 3., 0.),
Point::new(2., 3., 4., 1.),
Point::new(3., 4., 5., 2.)];
traj_gen.generate(&points);
assert_eq!(10, traj_gen.get_positions(0., 2., 0.2).len());
assert_eq!(10, traj_gen.get_velocities(0., 2., 0.2).len());
assert_eq!(10, traj_gen.get_accelerations(0., 2., 0.2).len());
assert_eq!(10, traj_gen.get_jerks(0., 2., 0.2).len());
}
}
| 37.384948 | 118 | 0.549066 |
1d35c78dda68c63639194d130cc03a217925ad82
| 2,024 |
extern crate switch_hal;
use switch_hal::mock;
mod active_high_switch {
use super::*;
use embedded_hal::digital::v2::InputPin;
use switch_hal::{ActiveHigh, OutputSwitch, Switch};
#[test]
fn when_on_pin_is_high() {
let pin = mock::Pin::new();
let mut led = Switch::<_, ActiveHigh>::new(pin);
led.on().unwrap();
let pin = led.into_pin();
assert_eq!(true, pin.is_high().unwrap());
}
#[test]
fn when_off_pin_is_low() {
let pin = mock::Pin::new();
let mut led = Switch::<_, ActiveHigh>::new(pin);
led.off().unwrap();
let pin = led.into_pin();
assert_eq!(true, pin.is_low().unwrap());
}
#[test]
fn is_toggleable() {
use switch_hal::ToggleableOutputSwitch;
let pin = mock::Pin::new();
let mut led = Switch::<_, ActiveHigh>::new(pin);
led.off().unwrap();
led.toggle().unwrap();
let pin = led.into_pin();
assert_eq!(true, pin.is_high().unwrap());
}
}
mod active_low_switch {
use super::*;
use embedded_hal::digital::v2::InputPin;
use switch_hal::{ActiveLow, OutputSwitch, Switch};
#[test]
fn when_on_pin_is_low() {
let pin = mock::Pin::new();
let mut led = Switch::<_, ActiveLow>::new(pin);
led.on().unwrap();
let pin = led.into_pin();
assert_eq!(true, pin.is_low().unwrap());
}
#[test]
fn when_off_pin_is_high() {
let pin = mock::Pin::new();
let mut led = Switch::<_, ActiveLow>::new(pin);
led.off().unwrap();
let pin = led.into_pin();
assert_eq!(true, pin.is_high().unwrap());
}
#[test]
fn is_toggleable() {
use switch_hal::ToggleableOutputSwitch;
let pin = mock::Pin::new();
let mut led = Switch::<_, ActiveLow>::new(pin);
led.off().unwrap();
led.toggle().unwrap();
let pin = led.into_pin();
assert_eq!(true, pin.is_low().unwrap());
}
}
| 22.488889 | 56 | 0.546443 |
ebae550fc3f11d5571e1fc6257d6742c509dfb98
| 5,706 |
use proptest::prelude::*;
use wiggle::{GuestMemory, GuestPtr};
use wiggle_test::{impl_errno, HostMemory, MemArea, WasiCtx};
wiggle::from_witx!({
witx: ["$CARGO_MANIFEST_DIR/tests/pointers.witx"],
ctx: WasiCtx,
});
impl_errno!(types::Errno, types::GuestErrorConversion);
impl<'a> pointers::Pointers for WasiCtx<'a> {
fn pointers_and_enums<'b>(
&self,
input1: types::Excuse,
input2_ptr: &GuestPtr<'b, types::Excuse>,
input3_ptr: &GuestPtr<'b, types::Excuse>,
input4_ptr_ptr: &GuestPtr<'b, GuestPtr<'b, types::Excuse>>,
) -> Result<(), types::Errno> {
println!("BAZ input1 {:?}", input1);
let input2: types::Excuse = input2_ptr.read().map_err(|e| {
eprintln!("input2_ptr error: {}", e);
types::Errno::InvalidArg
})?;
println!("input2 {:?}", input2);
// Read enum value from immutable ptr:
let input3 = input3_ptr.read().map_err(|e| {
eprintln!("input3_ptr error: {}", e);
types::Errno::InvalidArg
})?;
println!("input3 {:?}", input3);
// Write enum to mutable ptr:
input2_ptr.write(input3).map_err(|e| {
eprintln!("input2_ptr error: {}", e);
types::Errno::InvalidArg
})?;
println!("wrote to input2_ref {:?}", input3);
// Read ptr value from mutable ptr:
let input4_ptr: GuestPtr<types::Excuse> = input4_ptr_ptr.read().map_err(|e| {
eprintln!("input4_ptr_ptr error: {}", e);
types::Errno::InvalidArg
})?;
// Read enum value from that ptr:
let input4: types::Excuse = input4_ptr.read().map_err(|e| {
eprintln!("input4_ptr error: {}", e);
types::Errno::InvalidArg
})?;
println!("input4 {:?}", input4);
// Write ptr value to mutable ptr:
input4_ptr_ptr.write(*input2_ptr).map_err(|e| {
eprintln!("input4_ptr_ptr error: {}", e);
types::Errno::InvalidArg
})?;
Ok(())
}
}
fn excuse_strat() -> impl Strategy<Value = types::Excuse> {
prop_oneof![
Just(types::Excuse::DogAte),
Just(types::Excuse::Traffic),
Just(types::Excuse::Sleeping),
]
.boxed()
}
#[derive(Debug)]
struct PointersAndEnumsExercise {
pub input1: types::Excuse,
pub input2: types::Excuse,
pub input2_loc: MemArea,
pub input3: types::Excuse,
pub input3_loc: MemArea,
pub input4: types::Excuse,
pub input4_loc: MemArea,
pub input4_ptr_loc: MemArea,
}
impl PointersAndEnumsExercise {
pub fn strat() -> BoxedStrategy<Self> {
(
excuse_strat(),
excuse_strat(),
HostMemory::mem_area_strat(4),
excuse_strat(),
HostMemory::mem_area_strat(4),
excuse_strat(),
HostMemory::mem_area_strat(4),
HostMemory::mem_area_strat(4),
)
.prop_map(
|(
input1,
input2,
input2_loc,
input3,
input3_loc,
input4,
input4_loc,
input4_ptr_loc,
)| PointersAndEnumsExercise {
input1,
input2,
input2_loc,
input3,
input3_loc,
input4,
input4_loc,
input4_ptr_loc,
},
)
.prop_filter("non-overlapping pointers", |e| {
MemArea::non_overlapping_set(&[
e.input2_loc,
e.input3_loc,
e.input4_loc,
e.input4_ptr_loc,
])
})
.boxed()
}
pub fn test(&self) {
let ctx = WasiCtx::new();
let host_memory = HostMemory::new();
host_memory
.ptr(self.input2_loc.ptr)
.write(self.input2)
.expect("input2 ref_mut");
host_memory
.ptr(self.input3_loc.ptr)
.write(self.input3)
.expect("input3 ref_mut");
host_memory
.ptr(self.input4_loc.ptr)
.write(self.input4)
.expect("input4 ref_mut");
host_memory
.ptr(self.input4_ptr_loc.ptr)
.write(self.input4_loc.ptr)
.expect("input4 ptr ref_mut");
let e = pointers::pointers_and_enums(
&ctx,
&host_memory,
self.input1 as i32,
self.input2_loc.ptr as i32,
self.input3_loc.ptr as i32,
self.input4_ptr_loc.ptr as i32,
);
assert_eq!(e, Ok(types::Errno::Ok as i32), "errno");
// Implementation of pointers_and_enums writes input3 to the input2_loc:
let written_to_input2_loc: i32 = host_memory
.ptr(self.input2_loc.ptr)
.read()
.expect("input2 ref");
assert_eq!(
written_to_input2_loc, self.input3 as i32,
"pointers_and_enums written to input2"
);
// Implementation of pointers_and_enums writes input2_loc to input4_ptr_loc:
let written_to_input4_ptr: u32 = host_memory
.ptr(self.input4_ptr_loc.ptr)
.read()
.expect("input4_ptr_loc ref");
assert_eq!(
written_to_input4_ptr, self.input2_loc.ptr,
"pointers_and_enums written to input4_ptr"
);
}
}
proptest! {
#[test]
fn pointers_and_enums(e in PointersAndEnumsExercise::strat()) {
e.test();
}
}
| 29.874346 | 85 | 0.520855 |
16453786ea9c55be48cd4db7f0b8b72834ac0622
| 7,797 |
#[cfg(not(lib_build))]
#[macro_use]
extern crate log;
macro_rules! all_log_macros {
($($arg:tt)*) => ({
trace!($($arg)*);
debug!($($arg)*);
info!($($arg)*);
warn!($($arg)*);
error!($($arg)*);
});
}
#[test]
fn no_args() {
for lvl in log::Level::iter() {
log!(lvl, "hello");
log!(lvl, "hello",);
log!(target: "my_target", lvl, "hello");
log!(target: "my_target", lvl, "hello",);
log!(lvl, "hello");
log!(lvl, "hello",);
}
all_log_macros!("hello");
all_log_macros!("hello",);
all_log_macros!(target: "my_target", "hello");
all_log_macros!(target: "my_target", "hello",);
}
#[test]
fn anonymous_args() {
for lvl in log::Level::iter() {
log!(lvl, "hello {}", "world");
log!(lvl, "hello {}", "world",);
log!(target: "my_target", lvl, "hello {}", "world");
log!(target: "my_target", lvl, "hello {}", "world",);
log!(lvl, "hello {}", "world");
log!(lvl, "hello {}", "world",);
}
all_log_macros!("hello {}", "world");
all_log_macros!("hello {}", "world",);
all_log_macros!(target: "my_target", "hello {}", "world");
all_log_macros!(target: "my_target", "hello {}", "world",);
}
#[test]
fn named_args() {
for lvl in log::Level::iter() {
log!(lvl, "hello {world}", world = "world");
log!(lvl, "hello {world}", world = "world",);
log!(target: "my_target", lvl, "hello {world}", world = "world");
log!(target: "my_target", lvl, "hello {world}", world = "world",);
log!(lvl, "hello {world}", world = "world");
log!(lvl, "hello {world}", world = "world",);
}
all_log_macros!("hello {world}", world = "world");
all_log_macros!("hello {world}", world = "world",);
all_log_macros!(target: "my_target", "hello {world}", world = "world");
all_log_macros!(target: "my_target", "hello {world}", world = "world",);
}
#[test]
fn enabled() {
for lvl in log::Level::iter() {
let _enabled = if log_enabled!(target: "my_target", lvl) {
true
} else {
false
};
}
}
#[test]
fn expr() {
for lvl in log::Level::iter() {
let _ = log!(lvl, "hello");
}
}
#[test]
#[cfg(feature = "kv_unstable")]
fn kv_no_args() {
for lvl in log::Level::iter() {
log!(target: "my_target", lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello");
log!(lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello");
}
all_log_macros!(target: "my_target", cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello");
all_log_macros!(target = "my_target", cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello");
all_log_macros!(cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello");
}
#[test]
#[cfg(feature = "kv_unstable")]
fn kv_expr_args() {
for lvl in log::Level::iter() {
log!(target: "my_target", lvl, cat_math = { let mut x = 0; x += 1; x + 1 }; "hello");
log!(lvl, target = "my_target", cat_math = { let mut x = 0; x += 1; x + 1 }; "hello");
log!(lvl, cat_math = { let mut x = 0; x += 1; x + 1 }; "hello");
}
all_log_macros!(target: "my_target", cat_math = { let mut x = 0; x += 1; x + 1 }; "hello");
all_log_macros!(target = "my_target", cat_math = { let mut x = 0; x += 1; x + 1 }; "hello");
all_log_macros!(cat_math = { let mut x = 0; x += 1; x + 1 }; "hello");
}
#[test]
#[cfg(feature = "kv_unstable")]
fn kv_anonymous_args() {
for lvl in log::Level::iter() {
log!(target: "my_target", lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {}", "world");
log!(lvl, target = "my_target", cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {}", "world");
log!(lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {}", "world");
}
all_log_macros!(target: "my_target", cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {}", "world");
all_log_macros!(target = "my_target", cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {}", "world");
all_log_macros!(cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {}", "world");
}
#[test]
#[cfg(feature = "kv_unstable")]
fn kv_named_args() {
for lvl in log::Level::iter() {
log!(target: "my_target", lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}", world = "world");
log!(lvl, target = "my_target", cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}", world = "world");
log!(lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}", world = "world");
}
all_log_macros!(target: "my_target", cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}", world = "world");
all_log_macros!(target = "my_target", cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}", world = "world");
all_log_macros!(cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}", world = "world");
}
#[test]
#[cfg(feature = "kv_unstable")]
fn kv_expr_context() {
match "chashu" {
cat_1 => {
info!(target: "target", cat_1 = cat_1, cat_2 = "nori"; "hello {}", "cats")
}
};
}
#[test]
fn implicit_named_args() {
#[rustversion::since(1.58)]
fn _check() {
let world = "world";
for lvl in log::Level::iter() {
log!(lvl, "hello {world}");
log!(lvl, "hello {world}",);
log!(target: "my_target", lvl, "hello {world}");
log!(target: "my_target", lvl, "hello {world}",);
log!(lvl, "hello {world}");
log!(lvl, "hello {world}",);
}
all_log_macros!("hello {world}");
all_log_macros!("hello {world}",);
all_log_macros!(target: "my_target", "hello {world}");
all_log_macros!(target: "my_target", "hello {world}",);
all_log_macros!(target = "my_target"; "hello {world}");
all_log_macros!(target = "my_target"; "hello {world}",);
}
}
#[test]
#[cfg(feature = "kv_unstable")]
fn kv_implicit_named_args() {
#[rustversion::since(1.58)]
fn _check() {
let world = "world";
for lvl in log::Level::iter() {
log!(target: "my_target", lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}");
log!(lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}");
}
all_log_macros!(target: "my_target", cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}");
all_log_macros!(target = "my_target", cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}");
all_log_macros!(cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}");
}
}
#[test]
#[cfg(feature = "kv_unstable")]
fn kv_string_keys() {
for lvl in log::Level::iter() {
log!(target: "my_target", lvl, "also dogs" = "Fílos", "key/that-can't/be/an/ident" = "hi"; "hello {world}", world = "world");
}
all_log_macros!(target: "my_target", "also dogs" = "Fílos", "key/that-can't/be/an/ident" = "hi"; "hello {world}", world = "world");
}
#[test]
#[cfg(feature = "kv_unstable")]
fn kv_common_value_types() {
all_log_macros!(
u8 = 42u8,
u16 = 42u16,
u32 = 42u32,
u64 = 42u64,
u128 = 42u128,
i8 = -42i8,
i16 = -42i16,
i32 = -42i32,
i64 = -42i64,
i128 = -42i128,
f32 = 4.2f32,
f64 = -4.2f64,
bool = true,
str = "string";
"hello world"
);
}
/// Some and None (from Option) are used in the macros.
#[derive(Debug)]
enum Type {
Some,
None,
}
#[test]
fn regression_issue_494() {
use self::Type::*;
all_log_macros!("some message: {:?}, {:?}", None, Some);
}
| 30.818182 | 135 | 0.536745 |
d9ee01bd1ef25bb6af058cdcbd588311897abcb3
| 5,395 |
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{anyhow, bail, Context, Result};
struct DocData<'a> {
topic: &'a str,
subtopic: &'a str,
root: &'a Path,
}
fn index_html(doc: &DocData<'_>, wpath: &Path) -> Option<PathBuf> {
let indexhtml = wpath.join("index.html");
match &doc.root.join(&indexhtml).exists() {
true => Some(indexhtml),
false => None,
}
}
fn dir_into_vec(dir: &Path) -> Result<Vec<OsString>> {
let entries = fs::read_dir(dir).with_context(|| format!("Failed to read_dir {:?}", dir))?;
let mut v = Vec::new();
for entry in entries {
let entry = entry?;
v.push(entry.file_name());
}
Ok(v)
}
fn search_path(doc: &DocData<'_>, wpath: &Path, keywords: &[&str]) -> Result<PathBuf> {
let dir = &doc.root.join(&wpath);
if dir.is_dir() {
let entries = dir_into_vec(dir)?;
for k in keywords {
let filename = &format!("{}.{}.html", k, doc.subtopic);
if entries.contains(&OsString::from(filename)) {
return Ok(dir.join(filename));
}
}
}
Err(anyhow!(format!("No document for '{}'", doc.topic)))
}
pub fn local_path(root: &Path, topic: &str) -> Result<PathBuf> {
// The ORDER of keywords_top is used for the default search and should not
// be changed.
// https://github.com/rust-lang/rustup/issues/2076#issuecomment-546613036
let keywords_top = vec!["keyword", "primitive", "macro"];
let keywords_mod = ["fn", "struct", "trait", "enum", "type", "constant"];
let topic_vec: Vec<&str> = topic.split("::").collect();
let work_path = topic_vec.iter().fold(PathBuf::new(), |acc, e| acc.join(e));
let mut subtopic = topic_vec[topic_vec.len() - 1];
let mut forced_keyword = None;
if topic_vec.len() == 1 {
let split: Vec<&str> = topic.splitn(2, ':').collect();
if split.len() == 2 {
forced_keyword = Some(vec![split[0]]);
subtopic = split[1];
}
}
let doc = DocData {
topic,
subtopic,
root,
};
/**************************
* Please ensure tests/mock/topical_doc_data.rs is UPDATED to reflect
* any change in functionality.
Argument File directory
# len() == 1 Return index.html
std std/index.html root/std
core core/index.html root/core
alloc alloc/index.html root/core
KKK std/keyword.KKK.html root/std
PPP std/primitive.PPP.html root/std
MMM std/macro.MMM.html root/std
# len() == 2 not ending in ::
MMM std/macro.MMM.html root/std
KKK std/keyword.KKK.html root/std
PPP std/primitive.PPP.html root/std
MMM core/macro.MMM.html root/core
MMM alloc/macro.MMM.html root/alloc
# If above fail, try module
std::module std/module/index.html root/std/module
core::module core/module/index.html root/core/module
alloc::module alloc/module/index.html alloc/core/module
# len() == 2, ending with ::
std::module std/module/index.html root/std/module
core::module core/module/index.html root/core/module
alloc::module alloc/module/index.html alloc/core/module
# len() > 2
# search for index.html in rel_path
std::AAA::MMM std/AAA/MMM/index.html root/std/AAA/MMM
# OR check if parent() dir exists and search for fn/sturct/etc
std::AAA::FFF std/AAA/fn.FFF9.html root/std/AAA
std::AAA::SSS std/AAA/struct.SSS.html root/std/AAA
core:AAA::SSS std/AAA/struct.SSS.html root/coreAAA
alloc:AAA::SSS std/AAA/struct.SSS.html root/coreAAA
std::AAA::TTT std/2222/trait.TTT.html root/std/AAA
std::AAA::EEE std/2222/enum.EEE.html root/std/AAA
std::AAA::TTT std/2222/type.TTT.html root/std/AAA
std::AAA::CCC std/2222/constant.CCC.html root/std/AAA
**************************/
// topic.split.count cannot be 0
let subpath_os_path = match topic_vec.len() {
1 => match topic {
"std" | "core" | "alloc" => match index_html(&doc, &work_path) {
Some(f) => f,
None => bail!(format!("No document for '{}'", doc.topic)),
},
_ => {
let std = PathBuf::from("std");
let search_keywords = match forced_keyword {
Some(k) => k,
None => keywords_top,
};
search_path(&doc, &std, &search_keywords)?
}
},
2 => match index_html(&doc, &work_path) {
Some(f) => f,
None => {
let parent = work_path.parent().unwrap();
search_path(&doc, parent, &keywords_top)?
}
},
_ => match index_html(&doc, &work_path) {
Some(f) => f,
None => {
// len > 2, guaranteed to have a parent, safe to unwrap
let parent = work_path.parent().unwrap();
search_path(&doc, parent, &keywords_mod)?
}
},
};
// The path and filename were validated to be existing on the filesystem.
// It should be safe to unwrap, or worth panicking.
Ok(subpath_os_path)
}
| 35.032468 | 94 | 0.549583 |
61e63ecf624a66ac8ec1433a1ccd0c5d11b3615a
| 3,486 |
#[doc = r" Value read from the register"]
pub struct R {
bits: u16,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u16,
}
impl super::PACKET_RAM_1_179 {
#[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 LSBYTER {
bits: u8,
}
impl LSBYTER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct MSBYTER {
bits: u8,
}
impl MSBYTER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _LSBYTEW<'a> {
w: &'a mut W,
}
impl<'a> _LSBYTEW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 255;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u16) << OFFSET);
self.w.bits |= ((value & MASK) as u16) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _MSBYTEW<'a> {
w: &'a mut W,
}
impl<'a> _MSBYTEW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 255;
const OFFSET: u8 = 8;
self.w.bits &= !((MASK as u16) << OFFSET);
self.w.bits |= ((value & MASK) as u16) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u16 {
self.bits
}
#[doc = "Bits 0:7 - LSBYTE"]
#[inline]
pub fn lsbyte(&self) -> LSBYTER {
let bits = {
const MASK: u8 = 255;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u16) as u8
};
LSBYTER { bits }
}
#[doc = "Bits 8:15 - MSBYTE"]
#[inline]
pub fn msbyte(&self) -> MSBYTER {
let bits = {
const MASK: u8 = 255;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u16) as u8
};
MSBYTER { 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: u16) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:7 - LSBYTE"]
#[inline]
pub fn lsbyte(&mut self) -> _LSBYTEW {
_LSBYTEW { w: self }
}
#[doc = "Bits 8:15 - MSBYTE"]
#[inline]
pub fn msbyte(&mut self) -> _MSBYTEW {
_MSBYTEW { w: self }
}
}
| 23.714286 | 59 | 0.49082 |
f702fcd031c6a574c8319ed4078b223b96468f3a
| 85,421 |
use auxil::ShaderStage;
use hal::{
adapter::MemoryProperties, buffer, device, format, image, memory, pass, pool, pso,
pso::VertexInputRate, query, queue::QueueFamilyId, window,
};
use winapi::{
shared::{dxgi, dxgiformat, dxgitype, minwindef::TRUE, windef::HWND, winerror},
um::{d3d11, d3d11_1, d3d11sdklayers, d3dcommon},
};
use wio::com::ComPtr;
use std::{
fmt, mem,
ops::Range,
ptr,
sync::{Arc, Weak},
};
use parking_lot::{Condvar, Mutex, RwLock};
use crate::{
conv,
debug::{set_debug_name, set_debug_name_with_suffix, verify_debug_ascii},
internal, shader, Backend, Buffer, BufferView, CommandBuffer, CommandPool, ComputePipeline,
DescriptorContent, DescriptorIndex, DescriptorPool, DescriptorSet, DescriptorSetInfo,
DescriptorSetLayout, Fence, Framebuffer, GraphicsPipeline, Image, ImageView, InternalBuffer,
InternalImage, Memory, MultiStageData, PipelineLayout, QueryPool, RawFence,
RegisterAccumulator, RegisterData, RenderPass, ResourceIndex, Sampler, Semaphore, ShaderModule,
SubpassDesc, ViewInfo,
};
//TODO: expose coherent type 0x2 when it's properly supported
const BUFFER_TYPE_MASK: u32 = 0x1 | 0x4;
struct InputLayout {
raw: ComPtr<d3d11::ID3D11InputLayout>,
required_bindings: u32,
max_vertex_bindings: u32,
topology: d3d11::D3D11_PRIMITIVE_TOPOLOGY,
vertex_strides: Vec<u32>,
}
#[derive(Clone)]
pub struct DepthStencilState {
pub raw: ComPtr<d3d11::ID3D11DepthStencilState>,
pub stencil_ref: pso::State<pso::StencilValue>,
pub read_only: bool,
}
pub struct Device {
raw: ComPtr<d3d11::ID3D11Device>,
raw1: Option<ComPtr<d3d11_1::ID3D11Device1>>,
pub(crate) context: ComPtr<d3d11::ID3D11DeviceContext>,
features: hal::Features,
memory_properties: MemoryProperties,
pub(crate) internal: Arc<internal::Internal>,
}
impl fmt::Debug for Device {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("Device")
}
}
impl Drop for Device {
fn drop(&mut self) {
if let Ok(debug) = self.raw.cast::<d3d11sdklayers::ID3D11Debug>() {
unsafe {
debug.ReportLiveDeviceObjects(d3d11sdklayers::D3D11_RLDO_DETAIL);
}
}
}
}
unsafe impl Send for Device {}
unsafe impl Sync for Device {}
impl Device {
pub fn new(
device: ComPtr<d3d11::ID3D11Device>,
device1: Option<ComPtr<d3d11_1::ID3D11Device1>>,
context: ComPtr<d3d11::ID3D11DeviceContext>,
features: hal::Features,
downlevel: hal::DownlevelProperties,
memory_properties: MemoryProperties,
feature_level: u32,
) -> Self {
Device {
internal: Arc::new(internal::Internal::new(&device, features, feature_level, downlevel)),
raw: device,
raw1: device1,
context,
features,
memory_properties,
}
}
pub fn as_raw(&self) -> *mut d3d11::ID3D11Device {
self.raw.as_raw()
}
fn create_rasterizer_state(
&self,
rasterizer_desc: &pso::Rasterizer,
multisampling_desc: &Option<pso::Multisampling>,
) -> Result<ComPtr<d3d11::ID3D11RasterizerState>, pso::CreationError> {
let mut rasterizer = ptr::null_mut();
let desc = conv::map_rasterizer_desc(rasterizer_desc, multisampling_desc);
let hr = unsafe {
self.raw
.CreateRasterizerState(&desc, &mut rasterizer as *mut *mut _ as *mut *mut _)
};
if winerror::SUCCEEDED(hr) {
Ok(unsafe { ComPtr::from_raw(rasterizer) })
} else {
Err(pso::CreationError::Other)
}
}
fn create_blend_state(
&self,
blend_desc: &pso::BlendDesc,
multisampling: &Option<pso::Multisampling>,
) -> Result<ComPtr<d3d11::ID3D11BlendState>, pso::CreationError> {
let mut blend = ptr::null_mut();
let desc = conv::map_blend_desc(blend_desc, multisampling);
let hr = unsafe {
self.raw
.CreateBlendState(&desc, &mut blend as *mut *mut _ as *mut *mut _)
};
if winerror::SUCCEEDED(hr) {
Ok(unsafe { ComPtr::from_raw(blend) })
} else {
Err(pso::CreationError::Other)
}
}
fn create_depth_stencil_state(
&self,
depth_desc: &pso::DepthStencilDesc,
) -> Result<DepthStencilState, pso::CreationError> {
let mut depth = ptr::null_mut();
let (desc, stencil_ref, read_only) = conv::map_depth_stencil_desc(depth_desc);
let hr = unsafe {
self.raw
.CreateDepthStencilState(&desc, &mut depth as *mut *mut _ as *mut *mut _)
};
if winerror::SUCCEEDED(hr) {
Ok(DepthStencilState {
raw: unsafe { ComPtr::from_raw(depth) },
stencil_ref,
read_only,
})
} else {
Err(pso::CreationError::Other)
}
}
fn create_input_layout(
&self,
vs: ComPtr<d3dcommon::ID3DBlob>,
vertex_buffers: &[pso::VertexBufferDesc],
attributes: &[pso::AttributeDesc],
input_assembler: &pso::InputAssemblerDesc,
vertex_semantic_remapping: auxil::FastHashMap<u32, Option<(u32, u32)>>,
) -> Result<InputLayout, pso::CreationError> {
let mut layout = ptr::null_mut();
let mut vertex_strides = Vec::new();
let mut required_bindings = 0u32;
let mut max_vertex_bindings = 0u32;
for buffer in vertex_buffers {
required_bindings |= 1 << buffer.binding as u32;
max_vertex_bindings = max_vertex_bindings.max(1u32 + buffer.binding as u32);
while vertex_strides.len() <= buffer.binding as usize {
vertex_strides.push(0);
}
vertex_strides[buffer.binding as usize] = buffer.stride;
}
// See [`shader::introspect_spirv_vertex_semantic_remapping`] for details of why this is needed.
let semantics: Vec<_> = attributes
.iter()
.map(
|attrib| match vertex_semantic_remapping.get(&attrib.location) {
Some(Some((major, minor))) => {
let name = std::borrow::Cow::Owned(format!("TEXCOORD{}_\0", major));
let location = *minor;
(name, location)
}
_ => {
let name = std::borrow::Cow::Borrowed("TEXCOORD\0");
let location = attrib.location;
(name, location)
}
},
)
.collect();
let input_elements = attributes
.iter()
.zip(semantics.iter())
.filter_map(|(attrib, (semantic_name, semantic_index))| {
let buffer_desc = match vertex_buffers
.iter()
.find(|buffer_desc| buffer_desc.binding == attrib.binding)
{
Some(buffer_desc) => buffer_desc,
None => {
// TODO:
// error!("Couldn't find associated vertex buffer description {:?}", attrib.binding);
return Some(Err(pso::CreationError::Other));
}
};
let (slot_class, step_rate) = match buffer_desc.rate {
VertexInputRate::Vertex => (d3d11::D3D11_INPUT_PER_VERTEX_DATA, 0),
VertexInputRate::Instance(divisor) => {
(d3d11::D3D11_INPUT_PER_INSTANCE_DATA, divisor)
}
};
let format = attrib.element.format;
Some(Ok(d3d11::D3D11_INPUT_ELEMENT_DESC {
SemanticName: semantic_name.as_ptr() as *const _, // Semantic name used by SPIRV-Cross
SemanticIndex: *semantic_index,
Format: match conv::map_format(format) {
Some(fm) => fm,
None => {
// TODO:
// error!("Unable to find DXGI format for {:?}", format);
return Some(Err(pso::CreationError::Other));
}
},
InputSlot: attrib.binding as _,
AlignedByteOffset: attrib.element.offset,
InputSlotClass: slot_class,
InstanceDataStepRate: step_rate as _,
}))
})
.collect::<Result<Vec<_>, _>>()?;
let hr = unsafe {
self.raw.CreateInputLayout(
input_elements.as_ptr(),
input_elements.len() as _,
vs.GetBufferPointer(),
vs.GetBufferSize(),
&mut layout as *mut *mut _ as *mut *mut _,
)
};
if winerror::SUCCEEDED(hr) {
let topology = conv::map_topology(input_assembler);
Ok(InputLayout {
raw: unsafe { ComPtr::from_raw(layout) },
required_bindings,
max_vertex_bindings,
topology,
vertex_strides,
})
} else {
error!("CreateInputLayout error 0x{:X}", hr);
Err(pso::CreationError::Other)
}
}
fn create_vertex_shader(
&self,
blob: ComPtr<d3dcommon::ID3DBlob>,
) -> Result<ComPtr<d3d11::ID3D11VertexShader>, pso::CreationError> {
let mut vs = ptr::null_mut();
let hr = unsafe {
self.raw.CreateVertexShader(
blob.GetBufferPointer(),
blob.GetBufferSize(),
ptr::null_mut(),
&mut vs as *mut *mut _ as *mut *mut _,
)
};
if winerror::SUCCEEDED(hr) {
Ok(unsafe { ComPtr::from_raw(vs) })
} else {
Err(pso::CreationError::ShaderCreationError(
pso::ShaderStageFlags::VERTEX,
String::from("Failed to create a vertex shader"),
))
}
}
fn create_pixel_shader(
&self,
blob: ComPtr<d3dcommon::ID3DBlob>,
) -> Result<ComPtr<d3d11::ID3D11PixelShader>, pso::CreationError> {
let mut ps = ptr::null_mut();
let hr = unsafe {
self.raw.CreatePixelShader(
blob.GetBufferPointer(),
blob.GetBufferSize(),
ptr::null_mut(),
&mut ps as *mut *mut _ as *mut *mut _,
)
};
if winerror::SUCCEEDED(hr) {
Ok(unsafe { ComPtr::from_raw(ps) })
} else {
Err(pso::CreationError::ShaderCreationError(
pso::ShaderStageFlags::FRAGMENT,
String::from("Failed to create a pixel shader"),
))
}
}
fn create_geometry_shader(
&self,
blob: ComPtr<d3dcommon::ID3DBlob>,
) -> Result<ComPtr<d3d11::ID3D11GeometryShader>, pso::CreationError> {
let mut gs = ptr::null_mut();
let hr = unsafe {
self.raw.CreateGeometryShader(
blob.GetBufferPointer(),
blob.GetBufferSize(),
ptr::null_mut(),
&mut gs as *mut *mut _ as *mut *mut _,
)
};
if winerror::SUCCEEDED(hr) {
Ok(unsafe { ComPtr::from_raw(gs) })
} else {
Err(pso::CreationError::ShaderCreationError(
pso::ShaderStageFlags::GEOMETRY,
String::from("Failed to create a geometry shader"),
))
}
}
fn create_hull_shader(
&self,
blob: ComPtr<d3dcommon::ID3DBlob>,
) -> Result<ComPtr<d3d11::ID3D11HullShader>, pso::CreationError> {
let mut hs = ptr::null_mut();
let hr = unsafe {
self.raw.CreateHullShader(
blob.GetBufferPointer(),
blob.GetBufferSize(),
ptr::null_mut(),
&mut hs as *mut *mut _ as *mut *mut _,
)
};
if winerror::SUCCEEDED(hr) {
Ok(unsafe { ComPtr::from_raw(hs) })
} else {
Err(pso::CreationError::ShaderCreationError(
pso::ShaderStageFlags::HULL,
String::from("Failed to create a hull shader"),
))
}
}
fn create_domain_shader(
&self,
blob: ComPtr<d3dcommon::ID3DBlob>,
) -> Result<ComPtr<d3d11::ID3D11DomainShader>, pso::CreationError> {
let mut ds = ptr::null_mut();
let hr = unsafe {
self.raw.CreateDomainShader(
blob.GetBufferPointer(),
blob.GetBufferSize(),
ptr::null_mut(),
&mut ds as *mut *mut _ as *mut *mut _,
)
};
if winerror::SUCCEEDED(hr) {
Ok(unsafe { ComPtr::from_raw(ds) })
} else {
Err(pso::CreationError::ShaderCreationError(
pso::ShaderStageFlags::DOMAIN,
String::from("Failed to create a domain shader"),
))
}
}
fn create_compute_shader(
&self,
blob: ComPtr<d3dcommon::ID3DBlob>,
) -> Result<ComPtr<d3d11::ID3D11ComputeShader>, pso::CreationError> {
let mut cs = ptr::null_mut();
let hr = unsafe {
self.raw.CreateComputeShader(
blob.GetBufferPointer(),
blob.GetBufferSize(),
ptr::null_mut(),
&mut cs as *mut *mut _ as *mut *mut _,
)
};
if winerror::SUCCEEDED(hr) {
Ok(unsafe { ComPtr::from_raw(cs) })
} else {
Err(pso::CreationError::ShaderCreationError(
pso::ShaderStageFlags::COMPUTE,
String::from("Failed to create a compute shader"),
))
}
}
// TODO: fix return type..
fn extract_entry_point(
stage: ShaderStage,
source: &pso::EntryPoint<Backend>,
layout: &PipelineLayout,
features: &hal::Features,
device_feature_level: u32,
) -> Result<Option<ComPtr<d3dcommon::ID3DBlob>>, pso::CreationError> {
// TODO: entrypoint stuff
match *source.module {
ShaderModule::Dxbc(ref _shader) => Err(pso::CreationError::ShaderCreationError(
pso::ShaderStageFlags::ALL,
String::from("DXBC modules are not supported yet"),
)),
ShaderModule::Spirv(ref raw_data) => Ok(shader::compile_spirv_entrypoint(
raw_data,
stage,
source,
layout,
features,
device_feature_level,
)?),
}
}
fn view_image_as_shader_resource(
&self,
info: &ViewInfo,
) -> Result<ComPtr<d3d11::ID3D11ShaderResourceView>, image::ViewCreationError> {
let mut desc: d3d11::D3D11_SHADER_RESOURCE_VIEW_DESC = unsafe { mem::zeroed() };
desc.Format = info.format;
if desc.Format == dxgiformat::DXGI_FORMAT_D32_FLOAT_S8X24_UINT {
desc.Format = dxgiformat::DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
}
#[allow(non_snake_case)]
let MostDetailedMip = info.levels.start as _;
#[allow(non_snake_case)]
let MipLevels = (info.levels.end - info.levels.start) as _;
#[allow(non_snake_case)]
let FirstArraySlice = info.layers.start as _;
#[allow(non_snake_case)]
let ArraySize = (info.layers.end - info.layers.start) as _;
match info.view_kind {
image::ViewKind::D1 => {
desc.ViewDimension = d3dcommon::D3D11_SRV_DIMENSION_TEXTURE1D;
*unsafe { desc.u.Texture1D_mut() } = d3d11::D3D11_TEX1D_SRV {
MostDetailedMip,
MipLevels,
}
}
image::ViewKind::D1Array => {
desc.ViewDimension = d3dcommon::D3D11_SRV_DIMENSION_TEXTURE1DARRAY;
*unsafe { desc.u.Texture1DArray_mut() } = d3d11::D3D11_TEX1D_ARRAY_SRV {
MostDetailedMip,
MipLevels,
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D2 if info.kind.num_samples() > 1 => {
desc.ViewDimension = d3dcommon::D3D11_SRV_DIMENSION_TEXTURE2DMS;
*unsafe { desc.u.Texture2DMS_mut() } = d3d11::D3D11_TEX2DMS_SRV {
UnusedField_NothingToDefine: 0,
}
}
image::ViewKind::D2 => {
desc.ViewDimension = d3dcommon::D3D11_SRV_DIMENSION_TEXTURE2D;
*unsafe { desc.u.Texture2D_mut() } = d3d11::D3D11_TEX2D_SRV {
MostDetailedMip,
MipLevels,
}
}
image::ViewKind::D2Array if info.kind.num_samples() > 1 => {
desc.ViewDimension = d3dcommon::D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY;
*unsafe { desc.u.Texture2DMSArray_mut() } = d3d11::D3D11_TEX2DMS_ARRAY_SRV {
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D2Array => {
desc.ViewDimension = d3dcommon::D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
*unsafe { desc.u.Texture2DArray_mut() } = d3d11::D3D11_TEX2D_ARRAY_SRV {
MostDetailedMip,
MipLevels,
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D3 => {
desc.ViewDimension = d3dcommon::D3D11_SRV_DIMENSION_TEXTURE3D;
*unsafe { desc.u.Texture3D_mut() } = d3d11::D3D11_TEX3D_SRV {
MostDetailedMip,
MipLevels,
}
}
image::ViewKind::Cube => {
desc.ViewDimension = d3dcommon::D3D11_SRV_DIMENSION_TEXTURECUBE;
*unsafe { desc.u.TextureCube_mut() } = d3d11::D3D11_TEXCUBE_SRV {
MostDetailedMip,
MipLevels,
}
}
image::ViewKind::CubeArray => {
desc.ViewDimension = d3dcommon::D3D11_SRV_DIMENSION_TEXTURECUBEARRAY;
*unsafe { desc.u.TextureCubeArray_mut() } = d3d11::D3D11_TEXCUBE_ARRAY_SRV {
MostDetailedMip,
MipLevels,
First2DArrayFace: FirstArraySlice,
NumCubes: ArraySize / 6,
}
}
}
let mut srv = ptr::null_mut();
let hr = unsafe {
self.raw.CreateShaderResourceView(
info.resource,
&desc,
&mut srv as *mut *mut _ as *mut *mut _,
)
};
if winerror::SUCCEEDED(hr) {
Ok(unsafe { ComPtr::from_raw(srv) })
} else {
Err(image::ViewCreationError::Unsupported)
}
}
fn view_image_as_unordered_access(
&self,
info: &ViewInfo,
) -> Result<ComPtr<d3d11::ID3D11UnorderedAccessView>, image::ViewCreationError> {
let mut desc: d3d11::D3D11_UNORDERED_ACCESS_VIEW_DESC = unsafe { mem::zeroed() };
desc.Format = info.format;
#[allow(non_snake_case)]
let MipSlice = info.levels.start as _;
#[allow(non_snake_case)]
let FirstArraySlice = info.layers.start as _;
#[allow(non_snake_case)]
let ArraySize = (info.layers.end - info.layers.start) as _;
match info.view_kind {
image::ViewKind::D1 => {
desc.ViewDimension = d3d11::D3D11_UAV_DIMENSION_TEXTURE1D;
*unsafe { desc.u.Texture1D_mut() } = d3d11::D3D11_TEX1D_UAV {
MipSlice: info.levels.start as _,
}
}
image::ViewKind::D1Array => {
desc.ViewDimension = d3d11::D3D11_UAV_DIMENSION_TEXTURE1DARRAY;
*unsafe { desc.u.Texture1DArray_mut() } = d3d11::D3D11_TEX1D_ARRAY_UAV {
MipSlice,
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D2 => {
desc.ViewDimension = d3d11::D3D11_UAV_DIMENSION_TEXTURE2D;
*unsafe { desc.u.Texture2D_mut() } = d3d11::D3D11_TEX2D_UAV {
MipSlice: info.levels.start as _,
}
}
image::ViewKind::D2Array => {
desc.ViewDimension = d3d11::D3D11_UAV_DIMENSION_TEXTURE2DARRAY;
*unsafe { desc.u.Texture2DArray_mut() } = d3d11::D3D11_TEX2D_ARRAY_UAV {
MipSlice,
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D3 => {
desc.ViewDimension = d3d11::D3D11_UAV_DIMENSION_TEXTURE3D;
*unsafe { desc.u.Texture3D_mut() } = d3d11::D3D11_TEX3D_UAV {
MipSlice,
FirstWSlice: FirstArraySlice,
WSize: ArraySize,
}
}
_ => unimplemented!(),
}
let mut uav = ptr::null_mut();
let hr = unsafe {
self.raw.CreateUnorderedAccessView(
info.resource,
&desc,
&mut uav as *mut *mut _ as *mut *mut _,
)
};
if winerror::SUCCEEDED(hr) {
Ok(unsafe { ComPtr::from_raw(uav) })
} else {
error!("CreateUnorderedAccessView failed: 0x{:x}", hr);
Err(image::ViewCreationError::Unsupported)
}
}
pub(crate) fn view_image_as_render_target(
&self,
info: &ViewInfo,
) -> Result<ComPtr<d3d11::ID3D11RenderTargetView>, image::ViewCreationError> {
let mut desc: d3d11::D3D11_RENDER_TARGET_VIEW_DESC = unsafe { mem::zeroed() };
desc.Format = info.format;
#[allow(non_snake_case)]
let MipSlice = info.levels.start as _;
#[allow(non_snake_case)]
let FirstArraySlice = info.layers.start as _;
#[allow(non_snake_case)]
let ArraySize = (info.layers.end - info.layers.start) as _;
match info.view_kind {
image::ViewKind::D1 => {
desc.ViewDimension = d3d11::D3D11_RTV_DIMENSION_TEXTURE1D;
*unsafe { desc.u.Texture1D_mut() } = d3d11::D3D11_TEX1D_RTV { MipSlice }
}
image::ViewKind::D1Array => {
desc.ViewDimension = d3d11::D3D11_RTV_DIMENSION_TEXTURE1DARRAY;
*unsafe { desc.u.Texture1DArray_mut() } = d3d11::D3D11_TEX1D_ARRAY_RTV {
MipSlice,
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D2 => {
if info.kind.num_samples() > 1 {
desc.ViewDimension = d3d11::D3D11_RTV_DIMENSION_TEXTURE2DMS;
*unsafe { desc.u.Texture2DMS_mut() } = d3d11::D3D11_TEX2DMS_RTV {
UnusedField_NothingToDefine: 0,
}
} else {
desc.ViewDimension = d3d11::D3D11_RTV_DIMENSION_TEXTURE2D;
*unsafe { desc.u.Texture2D_mut() } = d3d11::D3D11_TEX2D_RTV { MipSlice }
}
}
image::ViewKind::D2Array => {
if info.kind.num_samples() > 1 {
desc.ViewDimension = d3d11::D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY;
*unsafe { desc.u.Texture2DMSArray_mut() } = d3d11::D3D11_TEX2DMS_ARRAY_RTV {
FirstArraySlice,
ArraySize,
}
} else {
desc.ViewDimension = d3d11::D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
*unsafe { desc.u.Texture2DArray_mut() } = d3d11::D3D11_TEX2D_ARRAY_RTV {
MipSlice,
FirstArraySlice,
ArraySize,
}
}
}
image::ViewKind::D3 => {
desc.ViewDimension = d3d11::D3D11_RTV_DIMENSION_TEXTURE3D;
*unsafe { desc.u.Texture3D_mut() } = d3d11::D3D11_TEX3D_RTV {
MipSlice,
FirstWSlice: FirstArraySlice,
WSize: ArraySize,
}
}
_ => unimplemented!(),
}
let mut rtv = ptr::null_mut();
let hr = unsafe {
self.raw.CreateRenderTargetView(
info.resource,
&desc,
&mut rtv as *mut *mut _ as *mut *mut _,
)
};
if winerror::SUCCEEDED(hr) {
Ok(unsafe { ComPtr::from_raw(rtv) })
} else {
error!("CreateRenderTargetView failed: 0x{:x}", hr);
Err(image::ViewCreationError::Unsupported)
}
}
fn view_image_as_depth_stencil(
&self,
info: &ViewInfo,
read_only_stencil: Option<bool>,
) -> Result<ComPtr<d3d11::ID3D11DepthStencilView>, image::ViewCreationError> {
#![allow(non_snake_case)]
let MipSlice = info.levels.start as _;
let FirstArraySlice = info.layers.start as _;
let ArraySize = (info.layers.end - info.layers.start) as _;
assert_eq!(info.levels.start + 1, info.levels.end);
assert!(info.layers.end <= info.kind.num_layers());
let mut desc: d3d11::D3D11_DEPTH_STENCIL_VIEW_DESC = unsafe { mem::zeroed() };
desc.Format = info.format;
if let Some(stencil) = read_only_stencil {
desc.Flags = match stencil {
true => d3d11::D3D11_DSV_READ_ONLY_DEPTH | d3d11::D3D11_DSV_READ_ONLY_STENCIL,
false => d3d11::D3D11_DSV_READ_ONLY_DEPTH,
}
}
match info.view_kind {
image::ViewKind::D2 => {
if info.kind.num_samples() > 1 {
desc.ViewDimension = d3d11::D3D11_DSV_DIMENSION_TEXTURE2DMS;
*unsafe { desc.u.Texture2DMS_mut() } = d3d11::D3D11_TEX2DMS_DSV {
UnusedField_NothingToDefine: 0,
}
} else {
desc.ViewDimension = d3d11::D3D11_DSV_DIMENSION_TEXTURE2D;
*unsafe { desc.u.Texture2D_mut() } = d3d11::D3D11_TEX2D_DSV { MipSlice }
}
}
image::ViewKind::D2Array => {
if info.kind.num_samples() > 1 {
desc.ViewDimension = d3d11::D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY;
*unsafe { desc.u.Texture2DMSArray_mut() } = d3d11::D3D11_TEX2DMS_ARRAY_DSV {
FirstArraySlice,
ArraySize,
}
} else {
desc.ViewDimension = d3d11::D3D11_DSV_DIMENSION_TEXTURE2DARRAY;
*unsafe { desc.u.Texture2DArray_mut() } = d3d11::D3D11_TEX2D_ARRAY_DSV {
MipSlice,
FirstArraySlice,
ArraySize,
}
}
}
_ => unimplemented!(),
}
let mut dsv = ptr::null_mut();
let hr = unsafe {
self.raw.CreateDepthStencilView(
info.resource,
&desc,
&mut dsv as *mut *mut _ as *mut *mut _,
)
};
if winerror::SUCCEEDED(hr) {
Ok(unsafe { ComPtr::from_raw(dsv) })
} else {
error!("CreateDepthStencilView failed: 0x{:x}", hr);
Err(image::ViewCreationError::Unsupported)
}
}
pub(crate) fn create_swapchain_impl(
&self,
config: &window::SwapchainConfig,
window_handle: HWND,
factory: ComPtr<dxgi::IDXGIFactory>,
) -> Result<(ComPtr<dxgi::IDXGISwapChain>, dxgiformat::DXGI_FORMAT), window::SwapchainError>
{
// TODO: use IDXGIFactory2 for >=11.1
// TODO: this function should be able to fail (Result)?
debug!("{:#?}", config);
let non_srgb_format = conv::map_format_nosrgb(config.format).unwrap();
let mut desc = dxgi::DXGI_SWAP_CHAIN_DESC {
BufferDesc: dxgitype::DXGI_MODE_DESC {
Width: config.extent.width,
Height: config.extent.height,
// TODO: should this grab max value of all monitor hz? vsync
// will clamp to current monitor anyways?
RefreshRate: dxgitype::DXGI_RATIONAL {
Numerator: 1,
Denominator: 60,
},
Format: non_srgb_format,
ScanlineOrdering: dxgitype::DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED,
Scaling: dxgitype::DXGI_MODE_SCALING_UNSPECIFIED,
},
SampleDesc: dxgitype::DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
BufferUsage: dxgitype::DXGI_USAGE_RENDER_TARGET_OUTPUT,
BufferCount: config.image_count,
OutputWindow: window_handle,
// TODO:
Windowed: TRUE,
// TODO:
SwapEffect: dxgi::DXGI_SWAP_EFFECT_DISCARD,
Flags: 0,
};
let dxgi_swapchain = {
let mut swapchain: *mut dxgi::IDXGISwapChain = ptr::null_mut();
let hr = unsafe {
factory.CreateSwapChain(
self.raw.as_raw() as *mut _,
&mut desc as *mut _,
&mut swapchain as *mut *mut _ as *mut *mut _,
)
};
assert_eq!(hr, winerror::S_OK);
unsafe { ComPtr::from_raw(swapchain) }
};
Ok((dxgi_swapchain, non_srgb_format))
}
}
impl device::Device<Backend> for Device {
unsafe fn allocate_memory(
&self,
mem_type: hal::MemoryTypeId,
size: u64,
) -> Result<Memory, device::AllocationError> {
let properties = self.memory_properties.memory_types[mem_type.0].properties;
let host_ptr = if properties.contains(hal::memory::Properties::CPU_VISIBLE) {
let mut data = vec![0u8; size as usize];
let ptr = data.as_mut_ptr();
mem::forget(data);
ptr
} else {
ptr::null_mut()
};
Ok(Memory {
properties,
size,
host_ptr,
local_buffers: Arc::new(RwLock::new(thunderdome::Arena::new())),
})
}
unsafe fn create_command_pool(
&self,
_family: QueueFamilyId,
_create_flags: pool::CommandPoolCreateFlags,
) -> Result<CommandPool, device::OutOfMemory> {
// TODO:
Ok(CommandPool {
device: self.raw.clone(),
device1: self.raw1.clone(),
internal: Arc::clone(&self.internal),
})
}
unsafe fn destroy_command_pool(&self, _pool: CommandPool) {
// automatic
}
unsafe fn create_render_pass<'a, Ia, Is, Id>(
&self,
attachments: Ia,
subpasses: Is,
_dependencies: Id,
) -> Result<RenderPass, device::OutOfMemory>
where
Ia: Iterator<Item = pass::Attachment>,
Is: Iterator<Item = pass::SubpassDesc<'a>>,
{
Ok(RenderPass {
attachments: attachments.collect(),
subpasses: subpasses
.map(|desc| SubpassDesc {
color_attachments: desc.colors.to_vec(),
depth_stencil_attachment: desc.depth_stencil.cloned(),
input_attachments: desc.inputs.to_vec(),
resolve_attachments: desc.resolves.to_vec(),
})
.collect(),
})
}
unsafe fn create_pipeline_layout<'a, Is, Ic>(
&self,
set_layouts: Is,
_push_constant_ranges: Ic,
) -> Result<PipelineLayout, device::OutOfMemory>
where
Is: Iterator<Item = &'a DescriptorSetLayout>,
Ic: Iterator<Item = (pso::ShaderStageFlags, Range<u32>)>,
{
let mut res_offsets = MultiStageData::<RegisterData<RegisterAccumulator>>::default();
let mut sets = Vec::new();
for set_layout in set_layouts {
sets.push(DescriptorSetInfo {
bindings: Arc::clone(&set_layout.bindings),
registers: res_offsets.advance(&set_layout.pool_mapping),
});
}
res_offsets.map_other(|data| {
// These use <= because this tells us the _next_ register, so maximum usage will be equal to the limit.
//
// Leave one slot for push constants
assert!(
data.c.res_index as u32
<= d3d11::D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1,
"{} bound constant buffers exceeds limit of {}",
data.c.res_index as u32,
d3d11::D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1,
);
assert!(
data.s.res_index as u32 <= d3d11::D3D11_COMMONSHADER_SAMPLER_REGISTER_COUNT,
"{} bound samplers exceeds limit of {}",
data.s.res_index as u32,
d3d11::D3D11_COMMONSHADER_SAMPLER_REGISTER_COUNT,
);
assert!(
data.t.res_index as u32 <= d3d11::D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_COUNT,
"{} bound sampled textures and read-only buffers exceeds limit of {}",
data.t.res_index as u32,
d3d11::D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_COUNT,
);
assert!(
data.u.res_index as u32 <= d3d11::D3D11_PS_CS_UAV_REGISTER_COUNT,
"{} bound storage textures and read-write buffers exceeds limit of {}",
data.u.res_index as u32,
d3d11::D3D11_PS_CS_UAV_REGISTER_COUNT,
);
});
Ok(PipelineLayout { sets })
}
unsafe fn create_pipeline_cache(
&self,
_data: Option<&[u8]>,
) -> Result<(), device::OutOfMemory> {
Ok(())
}
unsafe fn get_pipeline_cache_data(&self, _cache: &()) -> Result<Vec<u8>, device::OutOfMemory> {
//empty
Ok(Vec::new())
}
unsafe fn destroy_pipeline_cache(&self, _: ()) {
//empty
}
unsafe fn merge_pipeline_caches<'a, I>(
&self,
_: &mut (),
_: I,
) -> Result<(), device::OutOfMemory>
where
I: Iterator<Item = &'a ()>,
{
//empty
Ok(())
}
unsafe fn create_graphics_pipeline<'a>(
&self,
desc: &pso::GraphicsPipelineDesc<'a, Backend>,
_cache: Option<&()>,
) -> Result<GraphicsPipeline, pso::CreationError> {
let features = &self.features;
let build_shader =
|stage: ShaderStage, source: Option<&pso::EntryPoint<'a, Backend>>| match source {
Some(src) => Self::extract_entry_point(
stage,
src,
desc.layout,
features,
self.internal.device_feature_level,
),
None => Ok(None),
};
let (layout, vs, gs, hs, ds) = match desc.primitive_assembler {
pso::PrimitiveAssemblerDesc::Vertex {
buffers,
attributes,
ref input_assembler,
ref vertex,
ref tessellation,
ref geometry,
} => {
let vertex_semantic_remapping = match vertex.module {
ShaderModule::Spirv(spirv) => {
shader::introspect_spirv_vertex_semantic_remapping(spirv)?
}
_ => unimplemented!(),
};
let vs = build_shader(ShaderStage::Vertex, Some(&vertex))?.unwrap();
let gs = build_shader(ShaderStage::Geometry, geometry.as_ref())?;
let layout = self.create_input_layout(
vs.clone(),
buffers,
attributes,
input_assembler,
vertex_semantic_remapping,
)?;
let vs = self.create_vertex_shader(vs)?;
let gs = if let Some(blob) = gs {
Some(self.create_geometry_shader(blob)?)
} else {
None
};
let (hs, ds) = if let Some(ts) = tessellation {
let hs = build_shader(ShaderStage::Hull, Some(&ts.0))?.unwrap();
let ds = build_shader(ShaderStage::Domain, Some(&ts.1))?.unwrap();
(
Some(self.create_hull_shader(hs)?),
Some(self.create_domain_shader(ds)?),
)
} else {
(None, None)
};
(layout, vs, gs, hs, ds)
}
pso::PrimitiveAssemblerDesc::Mesh { .. } => {
return Err(pso::CreationError::UnsupportedPipeline)
}
};
let ps = build_shader(ShaderStage::Fragment, desc.fragment.as_ref())?;
let ps = if let Some(blob) = ps {
Some(self.create_pixel_shader(blob)?)
} else {
None
};
let rasterizer_state =
self.create_rasterizer_state(&desc.rasterizer, &desc.multisampling)?;
let blend_state = self.create_blend_state(&desc.blender, &desc.multisampling)?;
let depth_stencil_state = Some(self.create_depth_stencil_state(&desc.depth_stencil)?);
match desc.label {
Some(label) if verify_debug_ascii(label) => {
let mut name = label.to_string();
set_debug_name_with_suffix(&blend_state, &mut name, " -- Blend State");
set_debug_name_with_suffix(&rasterizer_state, &mut name, " -- Rasterizer State");
set_debug_name_with_suffix(&layout.raw, &mut name, " -- Input Layout");
if let Some(ref dss) = depth_stencil_state {
set_debug_name_with_suffix(&dss.raw, &mut name, " -- Depth Stencil State");
}
}
_ => {}
}
Ok(GraphicsPipeline {
vs,
gs,
ds,
hs,
ps,
topology: layout.topology,
input_layout: layout.raw,
rasterizer_state,
blend_state,
depth_stencil_state,
baked_states: desc.baked_states.clone(),
required_bindings: layout.required_bindings,
max_vertex_bindings: layout.max_vertex_bindings,
strides: layout.vertex_strides,
})
}
unsafe fn create_compute_pipeline<'a>(
&self,
desc: &pso::ComputePipelineDesc<'a, Backend>,
_cache: Option<&()>,
) -> Result<ComputePipeline, pso::CreationError> {
let features = &self.features;
let build_shader =
|stage: ShaderStage, source: Option<&pso::EntryPoint<'a, Backend>>| match source {
Some(src) => Self::extract_entry_point(
stage,
src,
desc.layout,
features,
self.internal.device_feature_level,
),
None => Ok(None),
};
let cs = build_shader(ShaderStage::Compute, Some(&desc.shader))?.unwrap();
let cs = self.create_compute_shader(cs)?;
Ok(ComputePipeline { cs })
}
unsafe fn create_framebuffer<I>(
&self,
_renderpass: &RenderPass,
_attachments: I,
extent: image::Extent,
) -> Result<Framebuffer, device::OutOfMemory> {
Ok(Framebuffer {
layers: extent.depth as _,
})
}
unsafe fn create_shader_module(
&self,
raw_data: &[u32],
) -> Result<ShaderModule, device::ShaderError> {
Ok(ShaderModule::Spirv(raw_data.into()))
}
unsafe fn create_buffer(
&self,
size: u64,
usage: buffer::Usage,
_sparse: memory::SparseFlags,
) -> Result<Buffer, buffer::CreationError> {
use buffer::Usage;
let mut bind = 0;
if usage.contains(Usage::UNIFORM) {
bind |= d3d11::D3D11_BIND_CONSTANT_BUFFER;
}
if usage.contains(Usage::VERTEX) {
bind |= d3d11::D3D11_BIND_VERTEX_BUFFER;
}
if usage.contains(Usage::INDEX) {
bind |= d3d11::D3D11_BIND_INDEX_BUFFER;
}
// TODO: >=11.1
if usage.intersects(
Usage::UNIFORM_TEXEL | Usage::STORAGE_TEXEL | Usage::TRANSFER_SRC | Usage::STORAGE,
) {
bind |= d3d11::D3D11_BIND_SHADER_RESOURCE;
}
if usage.intersects(Usage::TRANSFER_DST | Usage::STORAGE) {
bind |= d3d11::D3D11_BIND_UNORDERED_ACCESS;
}
// if `D3D11_BIND_CONSTANT_BUFFER` intersects with any other bind flag, we need to handle
// it by creating two buffers. one with `D3D11_BIND_CONSTANT_BUFFER` and one with the rest
let needs_disjoint_cb = bind & d3d11::D3D11_BIND_CONSTANT_BUFFER != 0
&& bind != d3d11::D3D11_BIND_CONSTANT_BUFFER;
if needs_disjoint_cb {
bind ^= d3d11::D3D11_BIND_CONSTANT_BUFFER;
}
fn up_align(x: u64, alignment: u64) -> u64 {
(x + alignment - 1) & !(alignment - 1)
}
// constant buffer size need to be divisible by 16
let size = if usage.contains(Usage::UNIFORM) {
up_align(size, 16)
} else {
up_align(size, 4)
};
Ok(Buffer {
internal: InternalBuffer {
raw: ptr::null_mut(),
disjoint_cb: if needs_disjoint_cb {
Some(ptr::null_mut())
} else {
None
},
srv: None,
uav: None,
usage,
debug_name: None,
},
bound_range: 0..0,
local_memory_arena: Weak::new(),
memory_index: None,
is_coherent: false,
memory_ptr: ptr::null_mut(),
bind,
requirements: memory::Requirements {
size,
alignment: 4,
type_mask: BUFFER_TYPE_MASK,
},
})
}
unsafe fn get_buffer_requirements(&self, buffer: &Buffer) -> memory::Requirements {
buffer.requirements
}
unsafe fn bind_buffer_memory(
&self,
memory: &Memory,
offset: u64,
buffer: &mut Buffer,
) -> Result<(), device::BindError> {
debug!(
"usage={:?}, props={:b}",
buffer.internal.usage, memory.properties
);
#[allow(non_snake_case)]
let mut MiscFlags = if buffer.bind
& (d3d11::D3D11_BIND_SHADER_RESOURCE | d3d11::D3D11_BIND_UNORDERED_ACCESS)
!= 0
{
d3d11::D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS
} else {
0
};
if buffer.internal.usage.contains(buffer::Usage::INDIRECT) {
MiscFlags |= d3d11::D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS;
}
let initial_data = if memory.host_ptr.is_null() {
None
} else {
Some(d3d11::D3D11_SUBRESOURCE_DATA {
pSysMem: memory.host_ptr.offset(offset as isize) as *const _,
SysMemPitch: 0,
SysMemSlicePitch: 0,
})
};
//TODO: check `memory.properties.contains(memory::Properties::DEVICE_LOCAL)` ?
let raw = {
// device local memory
let desc = d3d11::D3D11_BUFFER_DESC {
ByteWidth: buffer.requirements.size as _,
Usage: d3d11::D3D11_USAGE_DEFAULT,
BindFlags: buffer.bind,
CPUAccessFlags: 0,
MiscFlags,
StructureByteStride: if buffer.internal.usage.contains(buffer::Usage::TRANSFER_SRC)
{
4
} else {
0
},
};
let mut raw: *mut d3d11::ID3D11Buffer = ptr::null_mut();
let hr = self.raw.CreateBuffer(
&desc,
initial_data.as_ref().map_or(ptr::null_mut(), |id| id),
&mut raw as *mut *mut _ as *mut *mut _,
);
if !winerror::SUCCEEDED(hr) {
return Err(device::BindError::WrongMemory);
}
if let Some(ref mut name) = buffer.internal.debug_name {
set_debug_name(&*raw, name);
}
ComPtr::from_raw(raw)
};
let disjoint_cb = if buffer.internal.disjoint_cb.is_some() {
let desc = d3d11::D3D11_BUFFER_DESC {
ByteWidth: buffer.requirements.size as _,
Usage: d3d11::D3D11_USAGE_DEFAULT,
BindFlags: d3d11::D3D11_BIND_CONSTANT_BUFFER,
CPUAccessFlags: 0,
MiscFlags: 0,
StructureByteStride: 0,
};
let mut disjoint_raw: *mut d3d11::ID3D11Buffer = ptr::null_mut();
let hr = self.raw.CreateBuffer(
&desc,
initial_data.as_ref().map_or(ptr::null_mut(), |id| id),
&mut disjoint_raw as *mut *mut _ as *mut *mut _,
);
if !winerror::SUCCEEDED(hr) {
return Err(device::BindError::WrongMemory);
}
if let Some(ref mut name) = buffer.internal.debug_name {
set_debug_name_with_suffix(&*disjoint_raw, name, " -- Constant Buffer");
}
Some(disjoint_raw)
} else {
None
};
let srv = if buffer.bind & d3d11::D3D11_BIND_SHADER_RESOURCE != 0 {
let mut desc = mem::zeroed::<d3d11::D3D11_SHADER_RESOURCE_VIEW_DESC>();
desc.Format = dxgiformat::DXGI_FORMAT_R32_TYPELESS;
desc.ViewDimension = d3dcommon::D3D11_SRV_DIMENSION_BUFFEREX;
*desc.u.BufferEx_mut() = d3d11::D3D11_BUFFEREX_SRV {
FirstElement: 0,
NumElements: buffer.requirements.size as u32 / 4,
Flags: d3d11::D3D11_BUFFEREX_SRV_FLAG_RAW,
};
let mut srv: *mut d3d11::ID3D11ShaderResourceView = ptr::null_mut();
let hr = self.raw.CreateShaderResourceView(
raw.as_raw() as *mut _,
&desc,
&mut srv as *mut *mut _ as *mut *mut _,
);
if !winerror::SUCCEEDED(hr) {
error!("CreateShaderResourceView failed: 0x{:x}", hr);
return Err(device::BindError::WrongMemory);
}
if let Some(ref mut name) = buffer.internal.debug_name {
set_debug_name_with_suffix(&*srv, name, " -- SRV");
}
Some(srv)
} else {
None
};
let uav = if buffer.bind & d3d11::D3D11_BIND_UNORDERED_ACCESS != 0 {
let mut desc = mem::zeroed::<d3d11::D3D11_UNORDERED_ACCESS_VIEW_DESC>();
desc.Format = dxgiformat::DXGI_FORMAT_R32_TYPELESS;
desc.ViewDimension = d3d11::D3D11_UAV_DIMENSION_BUFFER;
*desc.u.Buffer_mut() = d3d11::D3D11_BUFFER_UAV {
FirstElement: 0,
NumElements: buffer.requirements.size as u32 / 4,
Flags: d3d11::D3D11_BUFFER_UAV_FLAG_RAW,
};
let mut uav: *mut d3d11::ID3D11UnorderedAccessView = ptr::null_mut();
let hr = self.raw.CreateUnorderedAccessView(
raw.as_raw() as *mut _,
&desc,
&mut uav as *mut *mut _ as *mut *mut _,
);
if !winerror::SUCCEEDED(hr) {
error!("CreateUnorderedAccessView failed: 0x{:x}", hr);
return Err(device::BindError::WrongMemory);
}
if let Some(ref mut name) = buffer.internal.debug_name {
set_debug_name_with_suffix(&*uav, name, " -- UAV");
}
Some(uav)
} else {
None
};
let internal = InternalBuffer {
raw: raw.into_raw(),
disjoint_cb,
srv,
uav,
usage: buffer.internal.usage,
debug_name: buffer.internal.debug_name.take(),
};
let range = offset..offset + buffer.requirements.size;
let memory_index = memory.bind_buffer(range.clone(), internal.clone());
buffer.internal = internal;
buffer.is_coherent = memory
.properties
.contains(hal::memory::Properties::COHERENT);
buffer.memory_ptr = memory.host_ptr;
buffer.bound_range = range;
buffer.local_memory_arena = Arc::downgrade(&memory.local_buffers);
buffer.memory_index = Some(memory_index);
Ok(())
}
unsafe fn create_buffer_view(
&self,
_buffer: &Buffer,
_format: Option<format::Format>,
_range: buffer::SubRange,
) -> Result<BufferView, buffer::ViewCreationError> {
unimplemented!()
}
unsafe fn create_image(
&self,
kind: image::Kind,
mip_levels: image::Level,
format: format::Format,
_tiling: image::Tiling,
usage: image::Usage,
_sparse: memory::SparseFlags,
view_caps: image::ViewCapabilities,
) -> Result<Image, image::CreationError> {
let surface_desc = format.base_format().0.desc();
let bytes_per_texel = surface_desc.bits / 8;
let ext = kind.extent();
let size = (ext.width * ext.height * ext.depth) as u64 * bytes_per_texel as u64;
let bind = conv::map_image_usage(usage, surface_desc, self.internal.device_feature_level);
debug!("{:b}", bind);
Ok(Image {
internal: InternalImage {
raw: ptr::null_mut(),
copy_srv: None,
srv: None,
unordered_access_views: Vec::new(),
depth_stencil_views: Vec::new(),
render_target_views: Vec::new(),
debug_name: None,
},
decomposed_format: conv::DecomposedDxgiFormat::UNKNOWN,
kind,
mip_levels,
format,
usage,
view_caps,
bind,
requirements: memory::Requirements {
size: size,
alignment: 4,
type_mask: 0x1, // device-local only
},
})
}
unsafe fn get_image_requirements(&self, image: &Image) -> memory::Requirements {
image.requirements
}
unsafe fn get_image_subresource_footprint(
&self,
_image: &Image,
_sub: image::Subresource,
) -> image::SubresourceFootprint {
unimplemented!()
}
unsafe fn bind_image_memory(
&self,
memory: &Memory,
_offset: u64,
image: &mut Image,
) -> Result<(), device::BindError> {
use image::Usage;
use memory::Properties;
let base_format = image.format.base_format();
let format_desc = base_format.0.desc();
let compressed = format_desc.is_compressed();
let depth = image.format.is_depth();
let stencil = image.format.is_stencil();
let (bind, usage, cpu) = if memory.properties == Properties::DEVICE_LOCAL {
(image.bind, d3d11::D3D11_USAGE_DEFAULT, 0)
} else if memory.properties
== (Properties::DEVICE_LOCAL | Properties::CPU_VISIBLE | Properties::CPU_CACHED)
{
(
image.bind,
d3d11::D3D11_USAGE_DYNAMIC,
d3d11::D3D11_CPU_ACCESS_WRITE,
)
} else if memory.properties == (Properties::CPU_VISIBLE | Properties::CPU_CACHED) {
(
0,
d3d11::D3D11_USAGE_STAGING,
d3d11::D3D11_CPU_ACCESS_READ | d3d11::D3D11_CPU_ACCESS_WRITE,
)
} else {
unimplemented!()
};
let dxgi_format = conv::map_format(image.format).unwrap();
let decomposed = conv::DecomposedDxgiFormat::from_dxgi_format(dxgi_format);
assert!(
memory.host_ptr.is_null(),
"Images can only be allocated from device-local memory"
);
let initial_data_ptr = ptr::null_mut();
let mut resource = ptr::null_mut();
let view_kind = match image.kind {
image::Kind::D1(width, layers) => {
let desc = d3d11::D3D11_TEXTURE1D_DESC {
Width: width,
MipLevels: image.mip_levels as _,
ArraySize: layers as _,
Format: decomposed.typeless,
Usage: usage,
BindFlags: bind,
CPUAccessFlags: cpu,
MiscFlags: 0,
};
let hr = self.raw.CreateTexture1D(
&desc,
initial_data_ptr,
&mut resource as *mut *mut _ as *mut *mut _,
);
if !winerror::SUCCEEDED(hr) {
error!("CreateTexture1D failed: 0x{:x}", hr);
return Err(device::BindError::WrongMemory);
}
image::ViewKind::D1Array
}
image::Kind::D2(width, height, layers, samples) => {
let desc = d3d11::D3D11_TEXTURE2D_DESC {
Width: width,
Height: height,
MipLevels: image.mip_levels as _,
ArraySize: layers as _,
Format: decomposed.typeless,
SampleDesc: dxgitype::DXGI_SAMPLE_DESC {
Count: samples as _,
Quality: 0,
},
Usage: usage,
BindFlags: bind,
CPUAccessFlags: cpu,
MiscFlags: {
let mut flags = 0;
if image.view_caps.contains(image::ViewCapabilities::KIND_CUBE) {
flags |= d3d11::D3D11_RESOURCE_MISC_TEXTURECUBE;
}
flags
},
};
let hr = self.raw.CreateTexture2D(
&desc,
initial_data_ptr,
&mut resource as *mut *mut _ as *mut *mut _,
);
if !winerror::SUCCEEDED(hr) {
error!("CreateTexture2D failed: 0x{:x}", hr);
return Err(device::BindError::WrongMemory);
}
image::ViewKind::D2Array
}
image::Kind::D3(width, height, depth) => {
let desc = d3d11::D3D11_TEXTURE3D_DESC {
Width: width,
Height: height,
Depth: depth,
MipLevels: image.mip_levels as _,
Format: decomposed.typeless,
Usage: usage,
BindFlags: bind,
CPUAccessFlags: cpu,
MiscFlags: 0,
};
let hr = self.raw.CreateTexture3D(
&desc,
initial_data_ptr,
&mut resource as *mut *mut _ as *mut *mut _,
);
if !winerror::SUCCEEDED(hr) {
error!("CreateTexture3D failed: 0x{:x}", hr);
return Err(device::BindError::WrongMemory);
}
image::ViewKind::D3
}
};
let mut unordered_access_views = Vec::new();
if image.usage.contains(Usage::TRANSFER_DST)
&& !compressed
&& !depth
&& self.internal.downlevel.storage_images
{
for mip in 0..image.mip_levels {
let view = ViewInfo {
resource: resource,
kind: image.kind,
caps: image::ViewCapabilities::empty(),
view_kind,
// TODO: we should be using `uav_format` rather than `copy_uav_format`, and share
// the UAVs when the formats are identical
format: decomposed.copy_uav.unwrap(),
levels: mip..(mip + 1),
layers: 0..image.kind.num_layers(),
};
let uav = self
.view_image_as_unordered_access(&view)
.map_err(|_| device::BindError::WrongMemory)?;
if let Some(ref name) = image.internal.debug_name {
set_debug_name(&uav, &format!("{} -- UAV Mip {}", name, mip));
}
unordered_access_views.push(uav);
}
}
let (copy_srv, srv) = if image.usage.contains(image::Usage::TRANSFER_SRC) {
let mut view = ViewInfo {
resource: resource,
kind: image.kind,
caps: image::ViewCapabilities::empty(),
view_kind,
format: decomposed.copy_srv.unwrap(),
levels: 0..image.mip_levels,
layers: 0..image.kind.num_layers(),
};
let copy_srv = if !compressed {
Some(
self.view_image_as_shader_resource(&view)
.map_err(|_| device::BindError::WrongMemory)?,
)
} else {
None
};
view.format = decomposed.srv.unwrap();
let srv = if !depth && !stencil {
Some(
self.view_image_as_shader_resource(&view)
.map_err(|_| device::BindError::WrongMemory)?,
)
} else {
None
};
(copy_srv, srv)
} else {
(None, None)
};
let mut render_target_views = Vec::new();
if (image.usage.contains(image::Usage::COLOR_ATTACHMENT)
|| image.usage.contains(image::Usage::TRANSFER_DST))
&& !compressed
&& !depth
{
for layer in 0..image.kind.num_layers() {
for mip in 0..image.mip_levels {
let view = ViewInfo {
resource,
kind: image.kind,
caps: image::ViewCapabilities::empty(),
view_kind,
format: decomposed.rtv.unwrap(),
levels: mip..(mip + 1),
layers: layer..(layer + 1),
};
let rtv = self
.view_image_as_render_target(&view)
.map_err(|_| device::BindError::WrongMemory)?;
if let Some(ref name) = image.internal.debug_name {
set_debug_name(
&rtv,
&format!("{} -- RTV Mip {} Layer {}", name, mip, layer),
);
}
render_target_views.push(rtv);
}
}
};
let mut depth_stencil_views = Vec::new();
if depth {
for layer in 0..image.kind.num_layers() {
for mip in 0..image.mip_levels {
let view = ViewInfo {
resource,
kind: image.kind,
caps: image::ViewCapabilities::empty(),
view_kind,
format: decomposed.dsv.unwrap(),
levels: mip..(mip + 1),
layers: layer..(layer + 1),
};
let dsv = self
.view_image_as_depth_stencil(&view, None)
.map_err(|_| device::BindError::WrongMemory)?;
if let Some(ref name) = image.internal.debug_name {
set_debug_name(
&dsv,
&format!("{} -- DSV Mip {} Layer {}", name, mip, layer),
);
}
depth_stencil_views.push(dsv);
}
}
}
if let Some(ref mut name) = image.internal.debug_name {
set_debug_name(&*resource, name);
if let Some(ref copy_srv) = copy_srv {
set_debug_name_with_suffix(copy_srv, name, " -- Copy SRV");
}
if let Some(ref srv) = srv {
set_debug_name_with_suffix(srv, name, " -- SRV");
}
}
let internal = InternalImage {
raw: resource,
copy_srv,
srv,
unordered_access_views,
depth_stencil_views,
render_target_views,
debug_name: image.internal.debug_name.take(),
};
image.decomposed_format = decomposed;
image.internal = internal;
Ok(())
}
unsafe fn create_image_view(
&self,
image: &Image,
view_kind: image::ViewKind,
format: format::Format,
_swizzle: format::Swizzle,
range: image::SubresourceRange,
) -> Result<ImageView, image::ViewCreationError> {
let is_array = image.kind.num_layers() > 1;
let num_levels = range.resolve_level_count(image.mip_levels);
let num_layers = range.resolve_layer_count(image.kind.num_layers());
let info = ViewInfo {
resource: image.internal.raw,
kind: image.kind,
caps: image.view_caps,
// D3D11 doesn't allow looking at a single slice of an array as a non-array
view_kind: if is_array && view_kind == image::ViewKind::D2 {
image::ViewKind::D2Array
} else if is_array && view_kind == image::ViewKind::D1 {
image::ViewKind::D1Array
} else {
view_kind
},
format: conv::map_format(format).ok_or(image::ViewCreationError::BadFormat(format))?,
levels: range.level_start..range.level_start + num_levels,
layers: range.layer_start..range.layer_start + num_layers,
};
let srv_info = ViewInfo {
format: conv::viewable_format(info.format),
..info.clone()
};
let mut debug_name = image.internal.debug_name.clone();
Ok(ImageView {
subresource: d3d11::D3D11CalcSubresource(
0,
range.layer_start as _,
range.level_start as _,
),
format,
srv_handle: if image.usage.intersects(image::Usage::SAMPLED) {
let srv = self.view_image_as_shader_resource(&srv_info)?;
if let Some(ref mut name) = debug_name {
set_debug_name_with_suffix(&srv, name, " -- SRV");
}
Some(srv.into_raw())
} else {
None
},
rtv_handle: if image.usage.contains(image::Usage::COLOR_ATTACHMENT) {
let rtv = self.view_image_as_render_target(&info)?;
if let Some(ref mut name) = debug_name {
set_debug_name_with_suffix(&rtv, name, " -- RTV");
}
Some(rtv.into_raw())
} else {
None
},
uav_handle: if image.usage.contains(image::Usage::STORAGE) {
let uav = self.view_image_as_unordered_access(&info)?;
if let Some(ref mut name) = debug_name {
set_debug_name_with_suffix(&uav, name, " -- UAV");
}
Some(uav.into_raw())
} else {
None
},
dsv_handle: if image.usage.contains(image::Usage::DEPTH_STENCIL_ATTACHMENT) {
let dsv = self.view_image_as_depth_stencil(&info, None)?;
if let Some(ref mut name) = debug_name {
set_debug_name_with_suffix(&dsv, name, " -- DSV");
}
Some(dsv.into_raw())
} else {
None
},
rodsv_handle: if image.usage.contains(image::Usage::DEPTH_STENCIL_ATTACHMENT)
&& self.internal.downlevel.read_only_depth_stencil
{
let rodsv =
self.view_image_as_depth_stencil(&info, Some(image.format.is_stencil()))?;
if let Some(ref mut name) = debug_name {
set_debug_name_with_suffix(&rodsv, name, " -- DSV");
}
Some(rodsv.into_raw())
} else {
None
},
owned: true,
})
}
unsafe fn create_sampler(
&self,
info: &image::SamplerDesc,
) -> Result<Sampler, device::AllocationError> {
assert!(info.normalized);
let op = match info.comparison {
Some(_) => d3d11::D3D11_FILTER_REDUCTION_TYPE_COMPARISON,
None => d3d11::D3D11_FILTER_REDUCTION_TYPE_STANDARD,
};
let desc = d3d11::D3D11_SAMPLER_DESC {
Filter: conv::map_filter(
info.min_filter,
info.mag_filter,
info.mip_filter,
op,
info.anisotropy_clamp,
),
AddressU: conv::map_wrapping(info.wrap_mode.0),
AddressV: conv::map_wrapping(info.wrap_mode.1),
AddressW: conv::map_wrapping(info.wrap_mode.2),
MipLODBias: info.lod_bias.0,
MaxAnisotropy: info.anisotropy_clamp.map_or(0, |aniso| aniso as u32),
ComparisonFunc: info.comparison.map_or(0, |comp| conv::map_comparison(comp)),
BorderColor: info.border.into(),
MinLOD: info.lod_range.start.0,
MaxLOD: info.lod_range.end.0,
};
let mut sampler = ptr::null_mut();
let hr = self
.raw
.CreateSamplerState(&desc, &mut sampler as *mut *mut _ as *mut *mut _);
assert_eq!(true, winerror::SUCCEEDED(hr));
Ok(Sampler {
sampler_handle: ComPtr::from_raw(sampler),
})
}
unsafe fn create_descriptor_pool<I>(
&self,
_max_sets: usize,
ranges: I,
_flags: pso::DescriptorPoolCreateFlags,
) -> Result<DescriptorPool, device::OutOfMemory>
where
I: Iterator<Item = pso::DescriptorRangeDesc>,
{
let mut total = RegisterData::default();
for range in ranges {
let content = DescriptorContent::from(range.ty);
total.add_content_many(content, range.count as DescriptorIndex);
}
let max_stages = 6;
let count = total.sum() * max_stages;
Ok(DescriptorPool::with_capacity(count))
}
unsafe fn create_descriptor_set_layout<'a, I, J>(
&self,
layout_bindings: I,
_immutable_samplers: J,
) -> Result<DescriptorSetLayout, device::OutOfMemory>
where
I: Iterator<Item = pso::DescriptorSetLayoutBinding>,
J: Iterator<Item = &'a Sampler>,
{
let mut total = MultiStageData::<RegisterData<_>>::default();
let mut bindings = layout_bindings.collect::<Vec<_>>();
for binding in bindings.iter() {
let content = DescriptorContent::from(binding.ty);
// If this binding is used by the graphics pipeline and is a UAV, it belongs to the "Output Merger"
// stage, so we only put them in the fragment stage to save redundant descriptor allocations.
let stage_flags = if content.contains(DescriptorContent::UAV)
&& binding
.stage_flags
.intersects(pso::ShaderStageFlags::ALL - pso::ShaderStageFlags::COMPUTE)
{
let mut stage_flags = pso::ShaderStageFlags::FRAGMENT;
stage_flags.set(
pso::ShaderStageFlags::COMPUTE,
binding.stage_flags.contains(pso::ShaderStageFlags::COMPUTE),
);
stage_flags
} else {
binding.stage_flags
};
total.add_content_many(content, stage_flags, binding.count as _);
}
bindings.sort_by_key(|a| a.binding);
let accum = total.map_register(|count| RegisterAccumulator {
res_index: *count as ResourceIndex,
});
Ok(DescriptorSetLayout {
bindings: Arc::new(bindings),
pool_mapping: accum.to_mapping(),
})
}
unsafe fn write_descriptor_set<'a, I>(&self, op: pso::DescriptorSetWrite<'a, Backend, I>)
where
I: Iterator<Item = pso::Descriptor<'a, Backend>>,
{
// Get baseline mapping
let mut mapping = op
.set
.layout
.pool_mapping
.map_register(|mapping| mapping.offset);
// Iterate over layout bindings until the first binding is found.
let binding_start = op
.set
.layout
.bindings
.iter()
.position(|binding| binding.binding == op.binding)
.unwrap();
// If we've skipped layout bindings, we need to add them to get the correct binding offset
for binding in &op.set.layout.bindings[..binding_start] {
let content = DescriptorContent::from(binding.ty);
mapping.add_content_many(content, binding.stage_flags, binding.count as _);
}
// We start at the given binding index and array index
let mut binding_index = binding_start;
let mut array_index = op.array_offset;
// If we're skipping array indices in the current binding, we need to add them to get the correct binding offset
if array_index > 0 {
let binding: &pso::DescriptorSetLayoutBinding = &op.set.layout.bindings[binding_index];
let content = DescriptorContent::from(binding.ty);
mapping.add_content_many(content, binding.stage_flags, array_index as _);
}
// Iterate over the descriptors, figuring out the corresponding binding, and adding
// it to the set of bindings.
//
// When we hit the end of an array of descriptors and there are still descriptors left
// over, we will spill into writing the next binding.
for descriptor in op.descriptors {
let binding: &pso::DescriptorSetLayoutBinding = &op.set.layout.bindings[binding_index];
let handles = match descriptor {
pso::Descriptor::Buffer(buffer, ref _sub) => RegisterData {
c: match buffer.internal.disjoint_cb {
Some(dj_buf) => dj_buf as *mut _,
None => buffer.internal.raw as *mut _,
},
t: buffer.internal.srv.map_or(ptr::null_mut(), |p| p as *mut _),
u: buffer.internal.uav.map_or(ptr::null_mut(), |p| p as *mut _),
s: ptr::null_mut(),
},
pso::Descriptor::Image(image, _layout) => RegisterData {
c: ptr::null_mut(),
t: image.srv_handle.map_or(ptr::null_mut(), |h| h as *mut _),
u: image.uav_handle.map_or(ptr::null_mut(), |h| h as *mut _),
s: ptr::null_mut(),
},
pso::Descriptor::Sampler(sampler) => RegisterData {
c: ptr::null_mut(),
t: ptr::null_mut(),
u: ptr::null_mut(),
s: sampler.sampler_handle.as_raw() as *mut _,
},
pso::Descriptor::CombinedImageSampler(image, _layout, sampler) => RegisterData {
c: ptr::null_mut(),
t: image.srv_handle.map_or(ptr::null_mut(), |h| h as *mut _),
u: image.uav_handle.map_or(ptr::null_mut(), |h| h as *mut _),
s: sampler.sampler_handle.as_raw() as *mut _,
},
pso::Descriptor::TexelBuffer(_buffer_view) => unimplemented!(),
};
let content = DescriptorContent::from(binding.ty);
if content.contains(DescriptorContent::CBV) {
let offsets = mapping.map_other(|map| map.c);
op.set
.assign_stages(&offsets, binding.stage_flags, handles.c);
};
if content.contains(DescriptorContent::SRV) {
let offsets = mapping.map_other(|map| map.t);
op.set
.assign_stages(&offsets, binding.stage_flags, handles.t);
};
if content.contains(DescriptorContent::UAV) {
// If this binding is used by the graphics pipeline and is a UAV, it belongs to the "Output Merger"
// stage, so we only put them in the fragment stage to save redundant descriptor allocations.
let stage_flags = if binding
.stage_flags
.intersects(pso::ShaderStageFlags::ALL - pso::ShaderStageFlags::COMPUTE)
{
let mut stage_flags = pso::ShaderStageFlags::FRAGMENT;
stage_flags.set(
pso::ShaderStageFlags::COMPUTE,
binding.stage_flags.contains(pso::ShaderStageFlags::COMPUTE),
);
stage_flags
} else {
binding.stage_flags
};
let offsets = mapping.map_other(|map| map.u);
op.set.assign_stages(&offsets, stage_flags, handles.u);
};
if content.contains(DescriptorContent::SAMPLER) {
let offsets = mapping.map_other(|map| map.s);
op.set
.assign_stages(&offsets, binding.stage_flags, handles.s);
};
mapping.add_content_many(content, binding.stage_flags, 1);
array_index += 1;
if array_index >= binding.count {
// We've run out of array to write to, we should overflow to the next binding.
array_index = 0;
binding_index += 1;
}
}
}
unsafe fn copy_descriptor_set<'a>(&self, _op: pso::DescriptorSetCopy<'a, Backend>) {
unimplemented!()
/*
for offset in 0 .. copy.count {
let (dst_ty, dst_handle_offset, dst_second_handle_offset) = copy
.dst_set
.get_handle_offset(copy.dst_binding + offset as u32);
let (src_ty, src_handle_offset, src_second_handle_offset) = copy
.src_set
.get_handle_offset(copy.src_binding + offset as u32);
assert_eq!(dst_ty, src_ty);
let dst_handle = copy.dst_set.handles.offset(dst_handle_offset as isize);
let src_handle = copy.dst_set.handles.offset(src_handle_offset as isize);
match dst_ty {
pso::DescriptorType::Image {
ty: pso::ImageDescriptorType::Sampled { with_sampler: true }
} => {
let dst_second_handle = copy
.dst_set
.handles
.offset(dst_second_handle_offset as isize);
let src_second_handle = copy
.dst_set
.handles
.offset(src_second_handle_offset as isize);
*dst_handle = *src_handle;
*dst_second_handle = *src_second_handle;
}
_ => *dst_handle = *src_handle,
}
}*/
}
unsafe fn map_memory(
&self,
memory: &mut Memory,
segment: memory::Segment,
) -> Result<*mut u8, device::MapError> {
Ok(memory.host_ptr.offset(segment.offset as isize))
}
unsafe fn unmap_memory(&self, _memory: &mut Memory) {
// persistent mapping FTW
}
unsafe fn flush_mapped_memory_ranges<'a, I>(&self, ranges: I) -> Result<(), device::OutOfMemory>
where
I: Iterator<Item = (&'a Memory, memory::Segment)>,
{
let _scope = debug_scope!(&self.context, "FlushMappedRanges");
// go through every range we wrote to
for (memory, ref segment) in ranges {
let range = memory.resolve(segment);
let _scope = debug_scope!(&self.context, "Range({:?})", range);
memory.flush(&self.context, range);
}
Ok(())
}
unsafe fn invalidate_mapped_memory_ranges<'a, I>(
&self,
ranges: I,
) -> Result<(), device::OutOfMemory>
where
I: Iterator<Item = (&'a Memory, memory::Segment)>,
{
let _scope = debug_scope!(&self.context, "InvalidateMappedRanges");
// go through every range we want to read from
for (memory, ref segment) in ranges {
let range = memory.resolve(segment);
let _scope = debug_scope!(&self.context, "Range({:?})", range);
memory.invalidate(
&self.context,
range,
self.internal.working_buffer.clone(),
self.internal.working_buffer_size,
);
}
Ok(())
}
fn create_semaphore(&self) -> Result<Semaphore, device::OutOfMemory> {
// TODO:
Ok(Semaphore)
}
fn create_fence(&self, signalled: bool) -> Result<Fence, device::OutOfMemory> {
Ok(Arc::new(RawFence {
mutex: Mutex::new(signalled),
condvar: Condvar::new(),
}))
}
unsafe fn reset_fence(&self, fence: &mut Fence) -> Result<(), device::OutOfMemory> {
*fence.mutex.lock() = false;
Ok(())
}
unsafe fn wait_for_fence(
&self,
fence: &Fence,
timeout_ns: u64,
) -> Result<bool, device::WaitError> {
use std::time::{Duration, Instant};
debug!("wait_for_fence {:?} for {} ns", fence, timeout_ns);
let mut guard = fence.mutex.lock();
match timeout_ns {
0 => Ok(*guard),
0xFFFFFFFFFFFFFFFF => {
while !*guard {
fence.condvar.wait(&mut guard);
}
Ok(true)
}
_ => {
let total = Duration::from_nanos(timeout_ns as u64);
let now = Instant::now();
while !*guard {
let duration = match total.checked_sub(now.elapsed()) {
Some(dur) => dur,
None => return Ok(false),
};
let result = fence.condvar.wait_for(&mut guard, duration);
if result.timed_out() {
return Ok(false);
}
}
Ok(true)
}
}
}
unsafe fn get_fence_status(&self, fence: &Fence) -> Result<bool, device::DeviceLost> {
Ok(*fence.mutex.lock())
}
fn create_event(&self) -> Result<(), device::OutOfMemory> {
unimplemented!()
}
unsafe fn get_event_status(&self, _event: &()) -> Result<bool, device::WaitError> {
unimplemented!()
}
unsafe fn set_event(&self, _event: &mut ()) -> Result<(), device::OutOfMemory> {
unimplemented!()
}
unsafe fn reset_event(&self, _event: &mut ()) -> Result<(), device::OutOfMemory> {
unimplemented!()
}
unsafe fn free_memory(&self, mut memory: Memory) {
if !memory.host_ptr.is_null() {
let _vec =
Vec::from_raw_parts(memory.host_ptr, memory.size as usize, memory.size as usize);
// let it drop
memory.host_ptr = ptr::null_mut();
}
for (_, (_range, mut internal)) in memory.local_buffers.write().drain() {
internal.release_resources()
}
}
unsafe fn create_query_pool(
&self,
_query_ty: query::Type,
_count: query::Id,
) -> Result<QueryPool, query::CreationError> {
unimplemented!()
}
unsafe fn destroy_query_pool(&self, _pool: QueryPool) {
unimplemented!()
}
unsafe fn get_query_pool_results(
&self,
_pool: &QueryPool,
_queries: Range<query::Id>,
_data: &mut [u8],
_stride: buffer::Stride,
_flags: query::ResultFlags,
) -> Result<bool, device::WaitError> {
unimplemented!()
}
unsafe fn destroy_shader_module(&self, _shader_lib: ShaderModule) {}
unsafe fn destroy_render_pass(&self, _rp: RenderPass) {
//unimplemented!()
}
unsafe fn destroy_pipeline_layout(&self, _layout: PipelineLayout) {
//unimplemented!()
}
unsafe fn destroy_graphics_pipeline(&self, _pipeline: GraphicsPipeline) {}
unsafe fn destroy_compute_pipeline(&self, _pipeline: ComputePipeline) {}
unsafe fn destroy_framebuffer(&self, _fb: Framebuffer) {}
unsafe fn destroy_buffer(&self, buffer: Buffer) {
let mut internal = buffer.internal;
if internal.raw.is_null() {
return;
}
let arena_arc = match buffer.local_memory_arena.upgrade() {
Some(arena) => arena,
// Memory is destroyed before the buffer, we've already been destroyed.
None => return,
};
let mut arena = arena_arc.write();
let memory_index = buffer.memory_index.expect("Buffer's memory index unset");
// Drop the internal stored by the arena on the floor, it owns nothing.
let _ = arena.remove(memory_index);
// Release all memory owned by this buffer
internal.release_resources();
}
unsafe fn destroy_buffer_view(&self, _view: BufferView) {
//unimplemented!()
}
unsafe fn destroy_image(&self, mut image: Image) {
image.internal.release_resources();
}
unsafe fn destroy_image_view(&self, _view: ImageView) {
//unimplemented!()
}
unsafe fn destroy_sampler(&self, _sampler: Sampler) {}
unsafe fn destroy_descriptor_pool(&self, _pool: DescriptorPool) {
//unimplemented!()
}
unsafe fn destroy_descriptor_set_layout(&self, _layout: DescriptorSetLayout) {
//unimplemented!()
}
unsafe fn destroy_fence(&self, _fence: Fence) {
// unimplemented!()
}
unsafe fn destroy_semaphore(&self, _semaphore: Semaphore) {
//unimplemented!()
}
unsafe fn destroy_event(&self, _event: ()) {
//unimplemented!()
}
fn wait_idle(&self) -> Result<(), device::OutOfMemory> {
Ok(())
// unimplemented!()
}
unsafe fn set_image_name(&self, image: &mut Image, name: &str) {
if !verify_debug_ascii(name) {
return;
}
image.internal.debug_name = Some(name.to_string());
}
unsafe fn set_buffer_name(&self, buffer: &mut Buffer, name: &str) {
if !verify_debug_ascii(name) {
return;
}
buffer.internal.debug_name = Some(name.to_string());
}
unsafe fn set_command_buffer_name(&self, command_buffer: &mut CommandBuffer, name: &str) {
if !verify_debug_ascii(name) {
return;
}
command_buffer.debug_name = Some(name.to_string());
}
unsafe fn set_semaphore_name(&self, _semaphore: &mut Semaphore, _name: &str) {
// TODO
}
unsafe fn set_fence_name(&self, _fence: &mut Fence, _name: &str) {
// TODO
}
unsafe fn set_framebuffer_name(&self, _framebuffer: &mut Framebuffer, _name: &str) {
// TODO
}
unsafe fn set_render_pass_name(&self, _render_pass: &mut RenderPass, _name: &str) {
// TODO
}
unsafe fn set_descriptor_set_name(&self, _descriptor_set: &mut DescriptorSet, _name: &str) {
// TODO
}
unsafe fn set_descriptor_set_layout_name(
&self,
_descriptor_set_layout: &mut DescriptorSetLayout,
_name: &str,
) {
// TODO
}
unsafe fn set_pipeline_layout_name(&self, _pipeline_layout: &mut PipelineLayout, _name: &str) {
// TODO
}
}
| 35.008607 | 120 | 0.520071 |
fe0de59677540a3ffa2a905e9b0360c8f79faf90
| 324 |
use all_test_types::only_bench::*;
use criterion::{criterion_group, criterion_main, Criterion};
fn check_speed(c: &mut Criterion) {
c.bench_function("some_fn", |b| {
b.iter(|| only_ran_in_benches(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
});
}
criterion_group!(benches, check_speed);
criterion_main!(benches);
| 27 | 75 | 0.67284 |
6792ccfa8ed670cabca4fe31261f2c68d3cb8581
| 201,154 |
use std::collections::HashMap;
use std::cell::RefCell;
use std::borrow::BorrowMut;
use std::default::Default;
use std::collections::BTreeMap;
use serde_json as json;
use std::io;
use std::fs;
use std::mem;
use std::thread::sleep;
use crate::client;
// ##############
// UTILITIES ###
// ############
/// Identifies the an OAuth2 authorization scope.
/// A scope is needed when requesting an
/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
#[derive(PartialEq, Eq, Hash)]
pub enum Scope {
/// Create, edit, organize, and delete all your tasks
Full,
/// View your tasks
Readonly,
}
impl AsRef<str> for Scope {
fn as_ref(&self) -> &str {
match *self {
Scope::Full => "https://www.googleapis.com/auth/tasks",
Scope::Readonly => "https://www.googleapis.com/auth/tasks.readonly",
}
}
}
impl Default for Scope {
fn default() -> Scope {
Scope::Readonly
}
}
// ########
// HUB ###
// ######
/// Central instance to access all TasksHub related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_tasks1 as tasks1;
/// use tasks1::{Result, Error};
/// # async fn dox() {
/// use std::default::Default;
/// use oauth2;
/// use tasks1::TasksHub;
///
/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
/// // `client_secret`, among other things.
/// let secret: oauth2::ApplicationSecret = Default::default();
/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
/// // unless you replace `None` with the desired Flow.
/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
/// // retrieve them from storage.
/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// ).build().await.unwrap();
/// let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasks().list("tasklist")
/// .updated_min("ipsum")
/// .show_hidden(true)
/// .show_deleted(true)
/// .show_completed(false)
/// .page_token("Lorem")
/// .max_results(-25)
/// .due_min("labore")
/// .due_max("sed")
/// .completed_min("duo")
/// .completed_max("sed")
/// .doit().await;
///
/// match result {
/// Err(e) => match e {
/// // The Error enum provides details about what exactly happened.
/// // You can also just use its `Debug`, `Display` or `Error` traits
/// Error::HttpError(_)
/// |Error::Io(_)
/// |Error::MissingAPIKey
/// |Error::MissingToken(_)
/// |Error::Cancelled
/// |Error::UploadSizeLimitExceeded(_, _)
/// |Error::Failure(_)
/// |Error::BadRequest(_)
/// |Error::FieldClash(_)
/// |Error::JsonDecodeError(_, _) => println!("{}", e),
/// },
/// Ok(res) => println!("Success: {:?}", res),
/// }
/// # }
/// ```
pub struct TasksHub<C> {
client: RefCell<C>,
auth: RefCell<oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>>,
_user_agent: String,
_base_url: String,
_root_url: String,
}
impl<'a, C> client::Hub for TasksHub<C> {}
impl<'a, C> TasksHub<C>
where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
pub fn new(client: C, authenticator: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>) -> TasksHub<C> {
TasksHub {
client: RefCell::new(client),
auth: RefCell::new(authenticator),
_user_agent: "google-api-rust-client/2.0.0".to_string(),
_base_url: "https://tasks.googleapis.com/".to_string(),
_root_url: "https://tasks.googleapis.com/".to_string(),
}
}
pub fn tasklists(&'a self) -> TasklistMethods<'a, C> {
TasklistMethods { hub: &self }
}
pub fn tasks(&'a self) -> TaskMethods<'a, C> {
TaskMethods { hub: &self }
}
/// Set the user-agent header field to use in all requests to the server.
/// It defaults to `google-api-rust-client/2.0.0`.
///
/// Returns the previously set user-agent.
pub fn user_agent(&mut self, agent_name: String) -> String {
mem::replace(&mut self._user_agent, agent_name)
}
/// Set the base url to use in all requests to the server.
/// It defaults to `https://tasks.googleapis.com/`.
///
/// Returns the previously set base url.
pub fn base_url(&mut self, new_base_url: String) -> String {
mem::replace(&mut self._base_url, new_base_url)
}
/// Set the root url to use in all requests to the server.
/// It defaults to `https://tasks.googleapis.com/`.
///
/// Returns the previously set root url.
pub fn root_url(&mut self, new_root_url: String) -> String {
mem::replace(&mut self._root_url, new_root_url)
}
}
// ############
// SCHEMAS ###
// ##########
/// There is no detailed description.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [clear tasks](TaskClearCall) (none)
/// * [delete tasks](TaskDeleteCall) (none)
/// * [get tasks](TaskGetCall) (response)
/// * [insert tasks](TaskInsertCall) (request|response)
/// * [list tasks](TaskListCall) (none)
/// * [move tasks](TaskMoveCall) (response)
/// * [patch tasks](TaskPatchCall) (request|response)
/// * [update tasks](TaskUpdateCall) (request|response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Task {
/// Completion date of the task (as a RFC 3339 timestamp). This field is omitted if the task has not been completed.
pub completed: Option<String>,
/// Flag indicating whether the task has been deleted. The default is False.
pub deleted: Option<bool>,
/// Due date of the task (as a RFC 3339 timestamp). Optional. The due date only records date information; the time portion of the timestamp is discarded when setting the due date. It isn't possible to read or write the time that a task is due via the API.
pub due: Option<String>,
/// ETag of the resource.
pub etag: Option<String>,
/// Flag indicating whether the task is hidden. This is the case if the task had been marked completed when the task list was last cleared. The default is False. This field is read-only.
pub hidden: Option<bool>,
/// Task identifier.
pub id: Option<String>,
/// Type of the resource. This is always "tasks#task".
pub kind: Option<String>,
/// Collection of links. This collection is read-only.
pub links: Option<Vec<TaskLinks>>,
/// Notes describing the task. Optional.
pub notes: Option<String>,
/// Parent task identifier. This field is omitted if it is a top-level task. This field is read-only. Use the "move" method to move the task under a different parent or to the top level.
pub parent: Option<String>,
/// String indicating the position of the task among its sibling tasks under the same parent task or at the top level. If this string is greater than another task's corresponding position string according to lexicographical ordering, the task is positioned after the other task under the same parent task (or at the top level). This field is read-only. Use the "move" method to move the task to another position.
pub position: Option<String>,
/// URL pointing to this task. Used to retrieve, update, or delete this task.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
/// Status of the task. This is either "needsAction" or "completed".
pub status: Option<String>,
/// Title of the task.
pub title: Option<String>,
/// Last modification time of the task (as a RFC 3339 timestamp).
pub updated: Option<String>,
}
impl client::RequestValue for Task {}
impl client::Resource for Task {}
impl client::ResponseResult for Task {}
/// There is no detailed description.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [get tasklists](TasklistGetCall) (response)
/// * [insert tasklists](TasklistInsertCall) (request|response)
/// * [patch tasklists](TasklistPatchCall) (request|response)
/// * [update tasklists](TasklistUpdateCall) (request|response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TaskList {
/// ETag of the resource.
pub etag: Option<String>,
/// Task list identifier.
pub id: Option<String>,
/// Type of the resource. This is always "tasks#taskList".
pub kind: Option<String>,
/// URL pointing to this task list. Used to retrieve, update, or delete this task list.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
/// Title of the task list.
pub title: Option<String>,
/// Last modification time of the task list (as a RFC 3339 timestamp).
pub updated: Option<String>,
}
impl client::RequestValue for TaskList {}
impl client::Resource for TaskList {}
impl client::ResponseResult for TaskList {}
/// There is no detailed description.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list tasklists](TasklistListCall) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TaskLists {
/// ETag of the resource.
pub etag: Option<String>,
/// Collection of task lists.
pub items: Option<Vec<TaskList>>,
/// Type of the resource. This is always "tasks#taskLists".
pub kind: Option<String>,
/// Token that can be used to request the next page of this result.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
}
impl client::ResponseResult for TaskLists {}
/// There is no detailed description.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list tasks](TaskListCall) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Tasks {
/// ETag of the resource.
pub etag: Option<String>,
/// Collection of tasks.
pub items: Option<Vec<Task>>,
/// Type of the resource. This is always "tasks#tasks".
pub kind: Option<String>,
/// Token used to access the next page of this result.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
}
impl client::ResponseResult for Tasks {}
/// Collection of links. This collection is read-only.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TaskLinks {
/// The description. In HTML speak: Everything between <a> and </a>.
pub description: Option<String>,
/// The URL.
pub link: Option<String>,
/// Type of the link, e.g. "email".
#[serde(rename="type")]
pub type_: Option<String>,
}
impl client::NestedType for TaskLinks {}
impl client::Part for TaskLinks {}
// ###################
// MethodBuilders ###
// #################
/// A builder providing access to all methods supported on *tasklist* resources.
/// It is not used directly, but through the `TasksHub` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_tasks1 as tasks1;
///
/// # async fn dox() {
/// use std::default::Default;
/// use oauth2;
/// use tasks1::TasksHub;
///
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// ).build().await.unwrap();
/// let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.tasklists();
/// # }
/// ```
pub struct TasklistMethods<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
}
impl<'a, C> client::MethodsBuilder for TasklistMethods<'a, C> {}
impl<'a, C> TasklistMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Deletes the authenticated user's specified task list.
///
/// # Arguments
///
/// * `tasklist` - Task list identifier.
pub fn delete(&self, tasklist: &str) -> TasklistDeleteCall<'a, C> {
TasklistDeleteCall {
hub: self.hub,
_tasklist: tasklist.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns the authenticated user's specified task list.
///
/// # Arguments
///
/// * `tasklist` - Task list identifier.
pub fn get(&self, tasklist: &str) -> TasklistGetCall<'a, C> {
TasklistGetCall {
hub: self.hub,
_tasklist: tasklist.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a new task list and adds it to the authenticated user's task lists.
///
/// # Arguments
///
/// * `request` - No description provided.
pub fn insert(&self, request: TaskList) -> TasklistInsertCall<'a, C> {
TasklistInsertCall {
hub: self.hub,
_request: request,
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns all the authenticated user's task lists.
pub fn list(&self) -> TasklistListCall<'a, C> {
TasklistListCall {
hub: self.hub,
_page_token: Default::default(),
_max_results: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates the authenticated user's specified task list. This method supports patch semantics.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `tasklist` - Task list identifier.
pub fn patch(&self, request: TaskList, tasklist: &str) -> TasklistPatchCall<'a, C> {
TasklistPatchCall {
hub: self.hub,
_request: request,
_tasklist: tasklist.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates the authenticated user's specified task list.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `tasklist` - Task list identifier.
pub fn update(&self, request: TaskList, tasklist: &str) -> TasklistUpdateCall<'a, C> {
TasklistUpdateCall {
hub: self.hub,
_request: request,
_tasklist: tasklist.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *task* resources.
/// It is not used directly, but through the `TasksHub` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_tasks1 as tasks1;
///
/// # async fn dox() {
/// use std::default::Default;
/// use oauth2;
/// use tasks1::TasksHub;
///
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// ).build().await.unwrap();
/// let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `clear(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `move_(...)`, `patch(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.tasks();
/// # }
/// ```
pub struct TaskMethods<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
}
impl<'a, C> client::MethodsBuilder for TaskMethods<'a, C> {}
impl<'a, C> TaskMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Clears all completed tasks from the specified task list. The affected tasks will be marked as 'hidden' and no longer be returned by default when retrieving all tasks for a task list.
///
/// # Arguments
///
/// * `tasklist` - Task list identifier.
pub fn clear(&self, tasklist: &str) -> TaskClearCall<'a, C> {
TaskClearCall {
hub: self.hub,
_tasklist: tasklist.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Deletes the specified task from the task list.
///
/// # Arguments
///
/// * `tasklist` - Task list identifier.
/// * `task` - Task identifier.
pub fn delete(&self, tasklist: &str, task: &str) -> TaskDeleteCall<'a, C> {
TaskDeleteCall {
hub: self.hub,
_tasklist: tasklist.to_string(),
_task: task.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns the specified task.
///
/// # Arguments
///
/// * `tasklist` - Task list identifier.
/// * `task` - Task identifier.
pub fn get(&self, tasklist: &str, task: &str) -> TaskGetCall<'a, C> {
TaskGetCall {
hub: self.hub,
_tasklist: tasklist.to_string(),
_task: task.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a new task on the specified task list.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `tasklist` - Task list identifier.
pub fn insert(&self, request: Task, tasklist: &str) -> TaskInsertCall<'a, C> {
TaskInsertCall {
hub: self.hub,
_request: request,
_tasklist: tasklist.to_string(),
_previous: Default::default(),
_parent: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns all tasks in the specified task list.
///
/// # Arguments
///
/// * `tasklist` - Task list identifier.
pub fn list(&self, tasklist: &str) -> TaskListCall<'a, C> {
TaskListCall {
hub: self.hub,
_tasklist: tasklist.to_string(),
_updated_min: Default::default(),
_show_hidden: Default::default(),
_show_deleted: Default::default(),
_show_completed: Default::default(),
_page_token: Default::default(),
_max_results: Default::default(),
_due_min: Default::default(),
_due_max: Default::default(),
_completed_min: Default::default(),
_completed_max: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Moves the specified task to another position in the task list. This can include putting it as a child task under a new parent and/or move it to a different position among its sibling tasks.
///
/// # Arguments
///
/// * `tasklist` - Task list identifier.
/// * `task` - Task identifier.
pub fn move_(&self, tasklist: &str, task: &str) -> TaskMoveCall<'a, C> {
TaskMoveCall {
hub: self.hub,
_tasklist: tasklist.to_string(),
_task: task.to_string(),
_previous: Default::default(),
_parent: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates the specified task. This method supports patch semantics.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `tasklist` - Task list identifier.
/// * `task` - Task identifier.
pub fn patch(&self, request: Task, tasklist: &str, task: &str) -> TaskPatchCall<'a, C> {
TaskPatchCall {
hub: self.hub,
_request: request,
_tasklist: tasklist.to_string(),
_task: task.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates the specified task.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `tasklist` - Task list identifier.
/// * `task` - Task identifier.
pub fn update(&self, request: Task, tasklist: &str, task: &str) -> TaskUpdateCall<'a, C> {
TaskUpdateCall {
hub: self.hub,
_request: request,
_tasklist: tasklist.to_string(),
_task: task.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
// ###################
// CallBuilders ###
// #################
/// Deletes the authenticated user's specified task list.
///
/// A builder for the *delete* method supported by a *tasklist* resource.
/// It is not used directly, but through a `TasklistMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasklists().delete("tasklist")
/// .doit().await;
/// # }
/// ```
pub struct TasklistDeleteCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_tasklist: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TasklistDeleteCall<'a, C> {}
impl<'a, C> TasklistDeleteCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasklists.delete",
http_method: hyper::Method::DELETE });
let mut params: Vec<(&str, String)> = Vec::with_capacity(2 + self._additional_params.len());
params.push(("tasklist", self._tasklist.to_string()));
for &field in ["tasklist"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
let mut url = self.hub._base_url.clone() + "tasks/v1/users/@me/lists/{tasklist}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Full.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{tasklist}", "tasklist")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["tasklist"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.body(hyper::body::Body::empty());
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = res;
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Task list identifier.
///
/// Sets the *tasklist* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn tasklist(mut self, new_value: &str) -> TasklistDeleteCall<'a, C> {
self._tasklist = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TasklistDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TasklistDeleteCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Full`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TasklistDeleteCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Returns the authenticated user's specified task list.
///
/// A builder for the *get* method supported by a *tasklist* resource.
/// It is not used directly, but through a `TasklistMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasklists().get("tasklist")
/// .doit().await;
/// # }
/// ```
pub struct TasklistGetCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_tasklist: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TasklistGetCall<'a, C> {}
impl<'a, C> TasklistGetCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, TaskList)> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasklists.get",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
params.push(("tasklist", self._tasklist.to_string()));
for &field in ["alt", "tasklist"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "tasks/v1/users/@me/lists/{tasklist}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{tasklist}", "tasklist")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["tasklist"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.body(hyper::body::Body::empty());
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Task list identifier.
///
/// Sets the *tasklist* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn tasklist(mut self, new_value: &str) -> TasklistGetCall<'a, C> {
self._tasklist = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TasklistGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TasklistGetCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Readonly`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TasklistGetCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Creates a new task list and adds it to the authenticated user's task lists.
///
/// A builder for the *insert* method supported by a *tasklist* resource.
/// It is not used directly, but through a `TasklistMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// use tasks1::api::TaskList;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = TaskList::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasklists().insert(req)
/// .doit().await;
/// # }
/// ```
pub struct TasklistInsertCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_request: TaskList,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TasklistInsertCall<'a, C> {}
impl<'a, C> TasklistInsertCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, TaskList)> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasklists.insert",
http_method: hyper::Method::POST });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
for &field in ["alt"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "tasks/v1/users/@me/lists";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Full.as_ref().to_string(), ());
}
let url = url::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
client::remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::POST).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
.header(CONTENT_LENGTH, request_size as u64)
.body(hyper::body::Body::from(request_value_reader.get_ref().clone()));
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: TaskList) -> TasklistInsertCall<'a, C> {
self._request = new_value;
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TasklistInsertCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TasklistInsertCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Full`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TasklistInsertCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Returns all the authenticated user's task lists.
///
/// A builder for the *list* method supported by a *tasklist* resource.
/// It is not used directly, but through a `TasklistMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasklists().list()
/// .page_token("kasd")
/// .max_results(-24)
/// .doit().await;
/// # }
/// ```
pub struct TasklistListCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_page_token: Option<String>,
_max_results: Option<i32>,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TasklistListCall<'a, C> {}
impl<'a, C> TasklistListCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, TaskLists)> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasklists.list",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
if let Some(value) = self._page_token {
params.push(("pageToken", value.to_string()));
}
if let Some(value) = self._max_results {
params.push(("maxResults", value.to_string()));
}
for &field in ["alt", "pageToken", "maxResults"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "tasks/v1/users/@me/lists";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
}
let url = url::Url::parse_with_params(&url, params).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.body(hyper::body::Body::empty());
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Token specifying the result page to return. Optional.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> TasklistListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Maximum number of task lists returned on one page. Optional. The default is 20 (max allowed: 100).
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: i32) -> TasklistListCall<'a, C> {
self._max_results = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TasklistListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TasklistListCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Readonly`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TasklistListCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Updates the authenticated user's specified task list. This method supports patch semantics.
///
/// A builder for the *patch* method supported by a *tasklist* resource.
/// It is not used directly, but through a `TasklistMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// use tasks1::api::TaskList;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = TaskList::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasklists().patch(req, "tasklist")
/// .doit().await;
/// # }
/// ```
pub struct TasklistPatchCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_request: TaskList,
_tasklist: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TasklistPatchCall<'a, C> {}
impl<'a, C> TasklistPatchCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, TaskList)> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasklists.patch",
http_method: hyper::Method::PATCH });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("tasklist", self._tasklist.to_string()));
for &field in ["alt", "tasklist"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "tasks/v1/users/@me/lists/{tasklist}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Full.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{tasklist}", "tasklist")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["tasklist"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
client::remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::PATCH).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
.header(CONTENT_LENGTH, request_size as u64)
.body(hyper::body::Body::from(request_value_reader.get_ref().clone()));
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: TaskList) -> TasklistPatchCall<'a, C> {
self._request = new_value;
self
}
/// Task list identifier.
///
/// Sets the *tasklist* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn tasklist(mut self, new_value: &str) -> TasklistPatchCall<'a, C> {
self._tasklist = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TasklistPatchCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TasklistPatchCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Full`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TasklistPatchCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Updates the authenticated user's specified task list.
///
/// A builder for the *update* method supported by a *tasklist* resource.
/// It is not used directly, but through a `TasklistMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// use tasks1::api::TaskList;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = TaskList::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasklists().update(req, "tasklist")
/// .doit().await;
/// # }
/// ```
pub struct TasklistUpdateCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_request: TaskList,
_tasklist: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TasklistUpdateCall<'a, C> {}
impl<'a, C> TasklistUpdateCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, TaskList)> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasklists.update",
http_method: hyper::Method::PUT });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("tasklist", self._tasklist.to_string()));
for &field in ["alt", "tasklist"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "tasks/v1/users/@me/lists/{tasklist}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Full.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{tasklist}", "tasklist")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["tasklist"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
client::remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
.header(CONTENT_LENGTH, request_size as u64)
.body(hyper::body::Body::from(request_value_reader.get_ref().clone()));
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: TaskList) -> TasklistUpdateCall<'a, C> {
self._request = new_value;
self
}
/// Task list identifier.
///
/// Sets the *tasklist* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn tasklist(mut self, new_value: &str) -> TasklistUpdateCall<'a, C> {
self._tasklist = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TasklistUpdateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TasklistUpdateCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Full`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TasklistUpdateCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Clears all completed tasks from the specified task list. The affected tasks will be marked as 'hidden' and no longer be returned by default when retrieving all tasks for a task list.
///
/// A builder for the *clear* method supported by a *task* resource.
/// It is not used directly, but through a `TaskMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasks().clear("tasklist")
/// .doit().await;
/// # }
/// ```
pub struct TaskClearCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_tasklist: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TaskClearCall<'a, C> {}
impl<'a, C> TaskClearCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasks.clear",
http_method: hyper::Method::POST });
let mut params: Vec<(&str, String)> = Vec::with_capacity(2 + self._additional_params.len());
params.push(("tasklist", self._tasklist.to_string()));
for &field in ["tasklist"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
let mut url = self.hub._base_url.clone() + "tasks/v1/lists/{tasklist}/clear";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Full.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{tasklist}", "tasklist")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["tasklist"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::POST).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.body(hyper::body::Body::empty());
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = res;
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Task list identifier.
///
/// Sets the *tasklist* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn tasklist(mut self, new_value: &str) -> TaskClearCall<'a, C> {
self._tasklist = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TaskClearCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TaskClearCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Full`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TaskClearCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Deletes the specified task from the task list.
///
/// A builder for the *delete* method supported by a *task* resource.
/// It is not used directly, but through a `TaskMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasks().delete("tasklist", "task")
/// .doit().await;
/// # }
/// ```
pub struct TaskDeleteCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_tasklist: String,
_task: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TaskDeleteCall<'a, C> {}
impl<'a, C> TaskDeleteCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<hyper::Response<hyper::body::Body>> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasks.delete",
http_method: hyper::Method::DELETE });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
params.push(("tasklist", self._tasklist.to_string()));
params.push(("task", self._task.to_string()));
for &field in ["tasklist", "task"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
let mut url = self.hub._base_url.clone() + "tasks/v1/lists/{tasklist}/tasks/{task}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Full.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{tasklist}", "tasklist"), ("{task}", "task")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["task", "tasklist"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::DELETE).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.body(hyper::body::Body::empty());
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = res;
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Task list identifier.
///
/// Sets the *tasklist* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn tasklist(mut self, new_value: &str) -> TaskDeleteCall<'a, C> {
self._tasklist = new_value.to_string();
self
}
/// Task identifier.
///
/// Sets the *task* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn task(mut self, new_value: &str) -> TaskDeleteCall<'a, C> {
self._task = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TaskDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TaskDeleteCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Full`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TaskDeleteCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Returns the specified task.
///
/// A builder for the *get* method supported by a *task* resource.
/// It is not used directly, but through a `TaskMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasks().get("tasklist", "task")
/// .doit().await;
/// # }
/// ```
pub struct TaskGetCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_tasklist: String,
_task: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TaskGetCall<'a, C> {}
impl<'a, C> TaskGetCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Task)> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasks.get",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("tasklist", self._tasklist.to_string()));
params.push(("task", self._task.to_string()));
for &field in ["alt", "tasklist", "task"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "tasks/v1/lists/{tasklist}/tasks/{task}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{tasklist}", "tasklist"), ("{task}", "task")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["task", "tasklist"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.body(hyper::body::Body::empty());
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Task list identifier.
///
/// Sets the *tasklist* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn tasklist(mut self, new_value: &str) -> TaskGetCall<'a, C> {
self._tasklist = new_value.to_string();
self
}
/// Task identifier.
///
/// Sets the *task* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn task(mut self, new_value: &str) -> TaskGetCall<'a, C> {
self._task = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TaskGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TaskGetCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Readonly`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TaskGetCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Creates a new task on the specified task list.
///
/// A builder for the *insert* method supported by a *task* resource.
/// It is not used directly, but through a `TaskMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// use tasks1::api::Task;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Task::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasks().insert(req, "tasklist")
/// .previous("et")
/// .parent("voluptua.")
/// .doit().await;
/// # }
/// ```
pub struct TaskInsertCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_request: Task,
_tasklist: String,
_previous: Option<String>,
_parent: Option<String>,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TaskInsertCall<'a, C> {}
impl<'a, C> TaskInsertCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Task)> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasks.insert",
http_method: hyper::Method::POST });
let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
params.push(("tasklist", self._tasklist.to_string()));
if let Some(value) = self._previous {
params.push(("previous", value.to_string()));
}
if let Some(value) = self._parent {
params.push(("parent", value.to_string()));
}
for &field in ["alt", "tasklist", "previous", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "tasks/v1/lists/{tasklist}/tasks";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Full.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{tasklist}", "tasklist")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["tasklist"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
client::remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::POST).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
.header(CONTENT_LENGTH, request_size as u64)
.body(hyper::body::Body::from(request_value_reader.get_ref().clone()));
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Task) -> TaskInsertCall<'a, C> {
self._request = new_value;
self
}
/// Task list identifier.
///
/// Sets the *tasklist* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn tasklist(mut self, new_value: &str) -> TaskInsertCall<'a, C> {
self._tasklist = new_value.to_string();
self
}
/// Previous sibling task identifier. If the task is created at the first position among its siblings, this parameter is omitted. Optional.
///
/// Sets the *previous* query property to the given value.
pub fn previous(mut self, new_value: &str) -> TaskInsertCall<'a, C> {
self._previous = Some(new_value.to_string());
self
}
/// Parent task identifier. If the task is created at the top level, this parameter is omitted. Optional.
///
/// Sets the *parent* query property to the given value.
pub fn parent(mut self, new_value: &str) -> TaskInsertCall<'a, C> {
self._parent = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TaskInsertCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TaskInsertCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Full`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TaskInsertCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Returns all tasks in the specified task list.
///
/// A builder for the *list* method supported by a *task* resource.
/// It is not used directly, but through a `TaskMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasks().list("tasklist")
/// .updated_min("consetetur")
/// .show_hidden(false)
/// .show_deleted(true)
/// .show_completed(false)
/// .page_token("Stet")
/// .max_results(-99)
/// .due_min("duo")
/// .due_max("vero")
/// .completed_min("vero")
/// .completed_max("invidunt")
/// .doit().await;
/// # }
/// ```
pub struct TaskListCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_tasklist: String,
_updated_min: Option<String>,
_show_hidden: Option<bool>,
_show_deleted: Option<bool>,
_show_completed: Option<bool>,
_page_token: Option<String>,
_max_results: Option<i32>,
_due_min: Option<String>,
_due_max: Option<String>,
_completed_min: Option<String>,
_completed_max: Option<String>,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TaskListCall<'a, C> {}
impl<'a, C> TaskListCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Tasks)> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasks.list",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(13 + self._additional_params.len());
params.push(("tasklist", self._tasklist.to_string()));
if let Some(value) = self._updated_min {
params.push(("updatedMin", value.to_string()));
}
if let Some(value) = self._show_hidden {
params.push(("showHidden", value.to_string()));
}
if let Some(value) = self._show_deleted {
params.push(("showDeleted", value.to_string()));
}
if let Some(value) = self._show_completed {
params.push(("showCompleted", value.to_string()));
}
if let Some(value) = self._page_token {
params.push(("pageToken", value.to_string()));
}
if let Some(value) = self._max_results {
params.push(("maxResults", value.to_string()));
}
if let Some(value) = self._due_min {
params.push(("dueMin", value.to_string()));
}
if let Some(value) = self._due_max {
params.push(("dueMax", value.to_string()));
}
if let Some(value) = self._completed_min {
params.push(("completedMin", value.to_string()));
}
if let Some(value) = self._completed_max {
params.push(("completedMax", value.to_string()));
}
for &field in ["alt", "tasklist", "updatedMin", "showHidden", "showDeleted", "showCompleted", "pageToken", "maxResults", "dueMin", "dueMax", "completedMin", "completedMax"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "tasks/v1/lists/{tasklist}/tasks";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Readonly.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{tasklist}", "tasklist")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["tasklist"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.body(hyper::body::Body::empty());
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Task list identifier.
///
/// Sets the *tasklist* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn tasklist(mut self, new_value: &str) -> TaskListCall<'a, C> {
self._tasklist = new_value.to_string();
self
}
/// Lower bound for a task's last modification time (as a RFC 3339 timestamp) to filter by. Optional. The default is not to filter by last modification time.
///
/// Sets the *updated min* query property to the given value.
pub fn updated_min(mut self, new_value: &str) -> TaskListCall<'a, C> {
self._updated_min = Some(new_value.to_string());
self
}
/// Flag indicating whether hidden tasks are returned in the result. Optional. The default is False.
///
/// Sets the *show hidden* query property to the given value.
pub fn show_hidden(mut self, new_value: bool) -> TaskListCall<'a, C> {
self._show_hidden = Some(new_value);
self
}
/// Flag indicating whether deleted tasks are returned in the result. Optional. The default is False.
///
/// Sets the *show deleted* query property to the given value.
pub fn show_deleted(mut self, new_value: bool) -> TaskListCall<'a, C> {
self._show_deleted = Some(new_value);
self
}
/// Flag indicating whether completed tasks are returned in the result. Optional. The default is True. Note that showHidden must also be True to show tasks completed in first party clients, such as the web UI and Google's mobile apps.
///
/// Sets the *show completed* query property to the given value.
pub fn show_completed(mut self, new_value: bool) -> TaskListCall<'a, C> {
self._show_completed = Some(new_value);
self
}
/// Token specifying the result page to return. Optional.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> TaskListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Maximum number of task lists returned on one page. Optional. The default is 20 (max allowed: 100).
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: i32) -> TaskListCall<'a, C> {
self._max_results = Some(new_value);
self
}
/// Lower bound for a task's due date (as a RFC 3339 timestamp) to filter by. Optional. The default is not to filter by due date.
///
/// Sets the *due min* query property to the given value.
pub fn due_min(mut self, new_value: &str) -> TaskListCall<'a, C> {
self._due_min = Some(new_value.to_string());
self
}
/// Upper bound for a task's due date (as a RFC 3339 timestamp) to filter by. Optional. The default is not to filter by due date.
///
/// Sets the *due max* query property to the given value.
pub fn due_max(mut self, new_value: &str) -> TaskListCall<'a, C> {
self._due_max = Some(new_value.to_string());
self
}
/// Lower bound for a task's completion date (as a RFC 3339 timestamp) to filter by. Optional. The default is not to filter by completion date.
///
/// Sets the *completed min* query property to the given value.
pub fn completed_min(mut self, new_value: &str) -> TaskListCall<'a, C> {
self._completed_min = Some(new_value.to_string());
self
}
/// Upper bound for a task's completion date (as a RFC 3339 timestamp) to filter by. Optional. The default is not to filter by completion date.
///
/// Sets the *completed max* query property to the given value.
pub fn completed_max(mut self, new_value: &str) -> TaskListCall<'a, C> {
self._completed_max = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TaskListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TaskListCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Readonly`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TaskListCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Moves the specified task to another position in the task list. This can include putting it as a child task under a new parent and/or move it to a different position among its sibling tasks.
///
/// A builder for the *move* method supported by a *task* resource.
/// It is not used directly, but through a `TaskMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasks().move_("tasklist", "task")
/// .previous("elitr")
/// .parent("Lorem")
/// .doit().await;
/// # }
/// ```
pub struct TaskMoveCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_tasklist: String,
_task: String,
_previous: Option<String>,
_parent: Option<String>,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TaskMoveCall<'a, C> {}
impl<'a, C> TaskMoveCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Task)> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasks.move",
http_method: hyper::Method::POST });
let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
params.push(("tasklist", self._tasklist.to_string()));
params.push(("task", self._task.to_string()));
if let Some(value) = self._previous {
params.push(("previous", value.to_string()));
}
if let Some(value) = self._parent {
params.push(("parent", value.to_string()));
}
for &field in ["alt", "tasklist", "task", "previous", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "tasks/v1/lists/{tasklist}/tasks/{task}/move";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Full.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{tasklist}", "tasklist"), ("{task}", "task")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["task", "tasklist"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::POST).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.body(hyper::body::Body::empty());
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Task list identifier.
///
/// Sets the *tasklist* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn tasklist(mut self, new_value: &str) -> TaskMoveCall<'a, C> {
self._tasklist = new_value.to_string();
self
}
/// Task identifier.
///
/// Sets the *task* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn task(mut self, new_value: &str) -> TaskMoveCall<'a, C> {
self._task = new_value.to_string();
self
}
/// New previous sibling task identifier. If the task is moved to the first position among its siblings, this parameter is omitted. Optional.
///
/// Sets the *previous* query property to the given value.
pub fn previous(mut self, new_value: &str) -> TaskMoveCall<'a, C> {
self._previous = Some(new_value.to_string());
self
}
/// New parent task identifier. If the task is moved to the top level, this parameter is omitted. Optional.
///
/// Sets the *parent* query property to the given value.
pub fn parent(mut self, new_value: &str) -> TaskMoveCall<'a, C> {
self._parent = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TaskMoveCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TaskMoveCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Full`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TaskMoveCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Updates the specified task. This method supports patch semantics.
///
/// A builder for the *patch* method supported by a *task* resource.
/// It is not used directly, but through a `TaskMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// use tasks1::api::Task;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Task::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasks().patch(req, "tasklist", "task")
/// .doit().await;
/// # }
/// ```
pub struct TaskPatchCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_request: Task,
_tasklist: String,
_task: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TaskPatchCall<'a, C> {}
impl<'a, C> TaskPatchCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Task)> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasks.patch",
http_method: hyper::Method::PATCH });
let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
params.push(("tasklist", self._tasklist.to_string()));
params.push(("task", self._task.to_string()));
for &field in ["alt", "tasklist", "task"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "tasks/v1/lists/{tasklist}/tasks/{task}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Full.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{tasklist}", "tasklist"), ("{task}", "task")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["task", "tasklist"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
client::remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::PATCH).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
.header(CONTENT_LENGTH, request_size as u64)
.body(hyper::body::Body::from(request_value_reader.get_ref().clone()));
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Task) -> TaskPatchCall<'a, C> {
self._request = new_value;
self
}
/// Task list identifier.
///
/// Sets the *tasklist* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn tasklist(mut self, new_value: &str) -> TaskPatchCall<'a, C> {
self._tasklist = new_value.to_string();
self
}
/// Task identifier.
///
/// Sets the *task* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn task(mut self, new_value: &str) -> TaskPatchCall<'a, C> {
self._task = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TaskPatchCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TaskPatchCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Full`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TaskPatchCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Updates the specified task.
///
/// A builder for the *update* method supported by a *task* resource.
/// It is not used directly, but through a `TaskMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_tasks1 as tasks1;
/// use tasks1::api::Task;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use tasks1::TasksHub;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = TasksHub::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Task::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.tasks().update(req, "tasklist", "task")
/// .doit().await;
/// # }
/// ```
pub struct TaskUpdateCall<'a, C>
where C: 'a {
hub: &'a TasksHub<C>,
_request: Task,
_tasklist: String,
_task: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C> client::CallBuilder for TaskUpdateCall<'a, C> {}
impl<'a, C> TaskUpdateCall<'a, C> where C: BorrowMut<hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Task)> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "tasks.tasks.update",
http_method: hyper::Method::PUT });
let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
params.push(("tasklist", self._tasklist.to_string()));
params.push(("task", self._task.to_string()));
for &field in ["alt", "tasklist", "task"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "tasks/v1/lists/{tasklist}/tasks/{task}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Full.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{tasklist}", "tasklist"), ("{task}", "task")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["task", "tasklist"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
client::remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let authenticator = self.hub.auth.borrow_mut();
let token = match authenticator.token(&self._scopes.keys().collect::<Vec<_>>()[..]).await {
Ok(token) => token.clone(),
Err(err) => {
match dlg.token(&err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(client::Error::MissingToken(err))
}
}
}
};
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::PUT).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone()) .header(AUTHORIZATION, format!("Bearer {}", token.as_str()));
let request = req_builder
.header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
.header(CONTENT_LENGTH, request_size as u64)
.body(hyper::body::Body::from(request_value_reader.get_ref().clone()));
client.borrow_mut().request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Task) -> TaskUpdateCall<'a, C> {
self._request = new_value;
self
}
/// Task list identifier.
///
/// Sets the *tasklist* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn tasklist(mut self, new_value: &str) -> TaskUpdateCall<'a, C> {
self._tasklist = new_value.to_string();
self
}
/// Task identifier.
///
/// Sets the *task* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn task(mut self, new_value: &str) -> TaskUpdateCall<'a, C> {
self._task = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TaskUpdateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> TaskUpdateCall<'a, C>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::Full`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> TaskUpdateCall<'a, C>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
| 43.70063 | 416 | 0.560213 |
cc7b47e9742a88d624fab86c46996623c1e78c42
| 9,495 |
// Copyright 2020, The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use std::convert::TryInto;
use futures::{stream::FuturesUnordered, Stream, StreamExt};
use log::*;
use tari_comms::{
connectivity::ConnectivityError,
peer_manager::{NodeDistance, NodeId, Peer, PeerFeatures},
PeerConnection,
PeerManager,
};
use super::{
state_machine::{DhtNetworkDiscoveryRoundInfo, DiscoveryParams, NetworkDiscoveryContext, StateEvent},
NetworkDiscoveryError,
};
use crate::{peer_validator::PeerValidator, proto::rpc::GetPeersRequest, rpc, DhtConfig};
const LOG_TARGET: &str = "comms::dht::network_discovery";
#[derive(Debug)]
pub(super) struct Discovering {
params: DiscoveryParams,
context: NetworkDiscoveryContext,
stats: DhtNetworkDiscoveryRoundInfo,
neighbourhood_threshold: NodeDistance,
}
impl Discovering {
pub fn new(params: DiscoveryParams, context: NetworkDiscoveryContext) -> Self {
Self {
params,
context,
stats: Default::default(),
neighbourhood_threshold: NodeDistance::max_distance(),
}
}
async fn initialize(&mut self) -> Result<(), NetworkDiscoveryError> {
if self.params.peers.is_empty() {
return Err(NetworkDiscoveryError::NoSyncPeers);
}
// The neighbourhood threshold is used to determine how many new neighbours we're receiving from a peer or
// peers. When "bootstrapping" from a seed node, receiving many new neighbours is expected and acceptable.
// However during a normal non-bootstrap sync receiving all new neighbours is a bit "fishy" and should be
// treated as suspicious.
self.neighbourhood_threshold = self
.context
.peer_manager
.calc_region_threshold(
self.context.node_identity.node_id(),
self.config().num_neighbouring_nodes,
PeerFeatures::COMMUNICATION_NODE,
)
.await?;
Ok(())
}
pub async fn next_event(&mut self) -> StateEvent {
debug!(
target: LOG_TARGET,
"Starting network discovery with params {}", self.params
);
if let Err(err) = self.initialize().await {
return err.into();
}
let mut dial_stream = self.dial_all_candidates();
while let Some(result) = dial_stream.next().await {
match result {
Ok(conn) => {
let peer_node_id = conn.peer_node_id().clone();
self.stats.sync_peers.push(peer_node_id.clone());
debug!(target: LOG_TARGET, "Attempting to sync from peer `{}`", peer_node_id);
match self.request_from_peers(conn).await {
Ok(_) => {
self.stats.num_succeeded += 1;
},
Err(err) => {
debug!(
target: LOG_TARGET,
"Failed to request peers from `{}`: {}", peer_node_id, err
);
},
}
},
Err(err) => {
debug!(target: LOG_TARGET, "Failed to connect to sync peer candidate: {}", err);
},
}
}
StateEvent::DiscoveryComplete(self.stats.clone())
}
async fn request_from_peers(&mut self, mut conn: PeerConnection) -> Result<(), NetworkDiscoveryError> {
let client = conn.connect_rpc::<rpc::DhtClient>().await?;
let peer_node_id = conn.peer_node_id();
debug!(
target: LOG_TARGET,
"Established RPC connection to peer `{}`", peer_node_id
);
self.request_peers(peer_node_id, client).await?;
Ok(())
}
async fn request_peers(
&mut self,
sync_peer: &NodeId,
mut client: rpc::DhtClient,
) -> Result<(), NetworkDiscoveryError> {
debug!(
target: LOG_TARGET,
"Requesting {} peers from `{}`",
self.params
.num_peers_to_request
.as_ref()
.map(ToString::to_string)
.unwrap_or_else(|| "∞".into()),
sync_peer
);
match client
.get_peers(GetPeersRequest {
n: self.params.num_peers_to_request.map(|v| v as u32).unwrap_or_default(),
include_clients: true,
})
.await
{
Ok(mut stream) => {
while let Some(resp) = stream.next().await {
match resp {
Ok(resp) => match resp.peer.and_then(|peer| peer.try_into().ok()) {
Some(peer) => {
self.validate_and_add_peer(sync_peer, peer).await?;
},
None => {
debug!(target: LOG_TARGET, "Invalid response from peer `{}`", sync_peer);
},
},
Err(err) => {
debug!(target: LOG_TARGET, "Error response from peer `{}`: {}", sync_peer, err);
},
}
}
},
Err(err) => {
debug!(
target: LOG_TARGET,
"Failed to request for peers from peer `{}`: {}", sync_peer, err
);
},
}
Ok(())
}
async fn validate_and_add_peer(&mut self, sync_peer: &NodeId, new_peer: Peer) -> Result<(), NetworkDiscoveryError> {
if self.context.node_identity.node_id() == &new_peer.node_id {
debug!(target: LOG_TARGET, "Received our own node from peer sync. Ignoring.");
return Ok(());
}
let new_peer_node_id = new_peer.node_id.clone();
let peer_validator = PeerValidator::new(self.peer_manager(), self.config());
let peer_dist = new_peer.node_id.distance(self.context.node_identity.node_id());
let is_neighbour = peer_dist <= self.neighbourhood_threshold;
match peer_validator.validate_and_add_peer(new_peer).await {
Ok(true) => {
if is_neighbour {
self.stats.num_new_neighbours += 1;
}
self.stats.num_new_peers += 1;
Ok(())
},
Ok(false) => {
self.stats.num_duplicate_peers += 1;
Ok(())
},
Err(err) => {
warn!(
target: LOG_TARGET,
"Received invalid peer from sync peer '{}': {}. Banning sync peer.", sync_peer, err
);
self.context
.connectivity
.ban_peer(
sync_peer.clone(),
format!("Network discovery peer sent invalid peer '{}'", new_peer_node_id),
)
.await?;
Err(err.into())
},
}
}
fn config(&self) -> &DhtConfig {
&self.context.config
}
fn peer_manager(&self) -> &PeerManager {
&self.context.peer_manager
}
fn dial_all_candidates(&self) -> impl Stream<Item = Result<PeerConnection, ConnectivityError>> + 'static {
let pending_dials = self
.params
.peers
.iter()
.map(|peer| {
let connectivity = self.context.connectivity.clone();
let peer = peer.clone();
async move { connectivity.dial_peer(peer).await }
})
.collect::<FuturesUnordered<_>>();
debug!(
target: LOG_TARGET,
"Dialing {} candidate peer(s) for peer sync",
pending_dials.len()
);
pending_dials
}
}
| 37.529644 | 120 | 0.549868 |
71117c62eef5ed98d7585ceda0507816c509f6ba
| 313 |
#![feature(test)]
extern crate test;
extern crate wire;
extern crate identifiers;
extern crate db;
extern crate auth as auth_lib;
extern crate diesel;
//extern crate migrations_internals;
extern crate chrono;
extern crate uuid;
mod calls;
extern crate testing_common as common;
extern crate testing_fixtures;
| 17.388889 | 38 | 0.795527 |
dd9b592e319777e363b97bcb73303d6335377775
| 22,508 |
use token_vesting::instruction;
use spl_token::instruction::{initialize_mint, mint_to};
use std::{convert::TryInto, str::FromStr};
use spl_associated_token_account::{get_associated_token_address, create_associated_token_account};
use solana_program::{hash::Hash, instruction::Instruction, pubkey::Pubkey, rent::Rent, system_program, sysvar};
use honggfuzz::fuzz;
use solana_program_test::{BanksClient, ProgramTest, processor};
use solana_sdk::{signature::Keypair, signature::Signer, system_instruction, transaction::Transaction, transport::TransportError};
use arbitrary::Arbitrary;
use std::collections::HashMap;
use token_vesting::{instruction::{Schedule, VestingInstruction}, processor::Processor};
use token_vesting::instruction::{init, unlock, change_destination, create};
use solana_sdk::{account::Account, instruction::InstructionError, transaction::TransactionError};
struct TokenVestingEnv {
system_program_id: Pubkey,
token_program_id: Pubkey,
sysvarclock_program_id: Pubkey,
rent_program_id: Pubkey,
vesting_program_id: Pubkey,
mint_authority: Keypair
}
#[derive(Debug, Arbitrary, Clone)]
struct FuzzInstruction {
vesting_account_key: AccountId,
vesting_token_account_key: AccountId,
source_token_account_owner_key: AccountId,
source_token_account_key: AccountId,
source_token_amount: u64,
destination_token_owner_key: AccountId,
destination_token_key: AccountId,
new_destination_token_key: AccountId,
mint_key: AccountId,
schedules: Vec<Schedule>,
payer_key: AccountId,
vesting_program_account: AccountId,
seeds:[u8; 32],
number_of_schedules: u8,
instruction: instruction::VestingInstruction,
// This flag decides wether the instruction will be executed with inputs that should
// not provoke any errors. (The accounts and contracts will be set up before if needed)
correct_inputs: bool
}
/// Use u8 as an account id to simplify the address space and re-use accounts
/// more often.
type AccountId = u8;
fn main() {
let rt = tokio::runtime::Runtime::new().unwrap();
// Set up the fixed test environment
let token_vesting_testenv = TokenVestingEnv {
system_program_id: system_program::id(),
sysvarclock_program_id: sysvar::clock::id(),
rent_program_id: sysvar::rent::id(),
token_program_id: spl_token::id(),
vesting_program_id: Pubkey::from_str("C4twuLidmxnWNX7NfUMECE8exXoC3ZNiUxokLG5vWEiM").unwrap(),
mint_authority: Keypair::new()
};
loop {
fuzz!(|fuzz_instructions: Vec<FuzzInstruction>| {
// Initialize and start the test network
let mut program_test = ProgramTest::new(
"token_vesting",
token_vesting_testenv.vesting_program_id,
processor!(Processor::process_instruction),
);
program_test.add_account(token_vesting_testenv.mint_authority.pubkey(), Account {
lamports: u32::MAX as u64,
..Account::default()
});
let mut test_state = rt.block_on(program_test.start_with_context());
rt.block_on(run_fuzz_instructions(&token_vesting_testenv, &mut test_state.banks_client, fuzz_instructions, &test_state.payer, test_state.last_blockhash));
});
}
}
async fn run_fuzz_instructions(
token_vesting_testenv: &TokenVestingEnv,
banks_client: &mut BanksClient,
fuzz_instructions: Vec<FuzzInstruction>,
correct_payer: &Keypair,
recent_blockhash: Hash
) {
// keep track of all accounts
let mut vesting_account_keys: HashMap<AccountId, Pubkey> = HashMap::new();
let mut vesting_token_account_keys: HashMap<AccountId, Pubkey> = HashMap::new();
let mut source_token_account_owner_keys: HashMap<AccountId, Keypair> = HashMap::new();
let mut destination_token_owner_keys: HashMap<AccountId, Keypair> = HashMap::new();
let mut destination_token_keys: HashMap<AccountId, Pubkey> = HashMap::new();
let mut new_destination_token_keys: HashMap<AccountId, Pubkey> = HashMap::new();
let mut mint_keys: HashMap<AccountId, Keypair> = HashMap::new();
let mut payer_keys: HashMap<AccountId, Keypair> = HashMap::new();
let mut global_output_instructions = vec![];
let mut global_signer_keys = vec![];
for fuzz_instruction in fuzz_instructions {
// Add accounts
vesting_account_keys
.entry(fuzz_instruction.vesting_account_key)
.or_insert_with(|| Pubkey::new_unique());
vesting_token_account_keys
.entry(fuzz_instruction.vesting_token_account_key)
.or_insert_with(|| Pubkey::new_unique());
source_token_account_owner_keys
.entry(fuzz_instruction.source_token_account_owner_key)
.or_insert_with(|| Keypair::new());
destination_token_owner_keys
.entry(fuzz_instruction.destination_token_owner_key)
.or_insert_with(|| Keypair::new());
destination_token_keys
.entry(fuzz_instruction.destination_token_key)
.or_insert_with(|| Pubkey::new_unique());
new_destination_token_keys
.entry(fuzz_instruction.new_destination_token_key)
.or_insert_with(|| Pubkey::new_unique());
mint_keys
.entry(fuzz_instruction.mint_key)
.or_insert_with(|| Keypair::new());
payer_keys
.entry(fuzz_instruction.payer_key)
.or_insert_with(|| Keypair::new());
let (mut output_instructions, mut signer_keys) = run_fuzz_instruction(
&token_vesting_testenv,
&fuzz_instruction,
&correct_payer,
mint_keys.get(&fuzz_instruction.mint_key).unwrap(),
vesting_account_keys.get(&fuzz_instruction.vesting_account_key).unwrap(),
vesting_token_account_keys.get(&fuzz_instruction.vesting_token_account_key).unwrap(),
source_token_account_owner_keys.get(
&fuzz_instruction.source_token_account_owner_key
).unwrap(),
destination_token_owner_keys.get(
&fuzz_instruction.destination_token_owner_key
).unwrap(),
destination_token_keys.get(
&fuzz_instruction.destination_token_key
).unwrap(),
new_destination_token_keys.get(
&fuzz_instruction.new_destination_token_key
).unwrap(),
payer_keys.get(&fuzz_instruction.payer_key).unwrap()
);
global_output_instructions.append(&mut output_instructions);
global_signer_keys.append(&mut signer_keys);
}
// Process transaction on test network
let mut transaction = Transaction::new_with_payer(
&global_output_instructions,
Some(&correct_payer.pubkey()),
);
let signers = [correct_payer].iter().map(|&v| v).chain(global_signer_keys.iter()).collect::<Vec<&Keypair>>();
transaction.partial_sign(
&signers,
recent_blockhash
);
banks_client.process_transaction(transaction).await.unwrap_or_else(|e| {
if let TransportError::TransactionError(te) = e {
match te {
TransactionError::InstructionError(_, ie) => {
match ie {
InstructionError::InvalidArgument
| InstructionError::InvalidInstructionData
| InstructionError::InvalidAccountData
| InstructionError::InsufficientFunds
| InstructionError::AccountAlreadyInitialized
| InstructionError::InvalidSeeds
| InstructionError::Custom(0) => {},
_ => {
print!("{:?}", ie);
Err(ie).unwrap()
}
}
},
TransactionError::SignatureFailure
| TransactionError::InvalidAccountForFee
| TransactionError::InsufficientFundsForFee => {},
_ => {
print!("{:?}", te);
panic!()
}
}
} else {
print!("{:?}", e);
panic!()
}
});
}
fn run_fuzz_instruction(
token_vesting_testenv: &TokenVestingEnv,
fuzz_instruction: &FuzzInstruction,
correct_payer: &Keypair,
mint_key: &Keypair,
vesting_account_key: &Pubkey,
vesting_token_account_key: &Pubkey,
source_token_account_owner_key: &Keypair,
destination_token_owner_key: &Keypair,
destination_token_key: &Pubkey,
new_destination_token_key: &Pubkey,
payer_key: &Keypair
) -> (Vec<Instruction>, Vec<Keypair>) {
// Execute the fuzzing in a more restrained way in order to go deeper into the program branches.
// For each possible fuzz instruction we first instantiate the needed accounts for the instruction
if fuzz_instruction.correct_inputs {
let mut correct_seeds = fuzz_instruction.seeds;
let (correct_vesting_account_key, bump) = Pubkey::find_program_address(
&[&correct_seeds[..31]],
&token_vesting_testenv.vesting_program_id
);
correct_seeds[31] = bump;
let correct_vesting_token_key = get_associated_token_address(
&correct_vesting_account_key,
&mint_key.pubkey()
);
let correct_source_token_account_key = get_associated_token_address(
&source_token_account_owner_key.pubkey(),
&mint_key.pubkey()
);
match fuzz_instruction {
FuzzInstruction {
instruction: VestingInstruction::Init{ .. },
..
} => {
return (vec![init(
&token_vesting_testenv.system_program_id,
&token_vesting_testenv.rent_program_id,
&token_vesting_testenv.vesting_program_id,
&correct_payer.pubkey(),
&correct_vesting_account_key,
correct_seeds,
fuzz_instruction.number_of_schedules as u32
).unwrap()], vec![]);
},
FuzzInstruction {
instruction: VestingInstruction::Create { .. },
..
} => {
let mut instructions_acc = vec![init(
&token_vesting_testenv.system_program_id,
&token_vesting_testenv.rent_program_id,
&token_vesting_testenv.vesting_program_id,
&correct_payer.pubkey(),
&correct_vesting_account_key,
correct_seeds,
fuzz_instruction.number_of_schedules as u32
).unwrap()];
let mut create_instructions = create_fuzzinstruction(
token_vesting_testenv,
fuzz_instruction,
correct_payer,
&correct_source_token_account_key,
source_token_account_owner_key,
destination_token_key,
&destination_token_owner_key.pubkey(),
&correct_vesting_account_key,
&correct_vesting_token_key,
correct_seeds,
mint_key,
fuzz_instruction.source_token_amount
);
instructions_acc.append(&mut create_instructions);
return (instructions_acc, vec![clone_keypair(mint_key),
clone_keypair(&token_vesting_testenv.mint_authority),
clone_keypair(source_token_account_owner_key)]);
},
FuzzInstruction {
instruction: VestingInstruction::Unlock{ .. },
..
} => {
let mut instructions_acc = vec![init(
&token_vesting_testenv.system_program_id,
&token_vesting_testenv.rent_program_id,
&token_vesting_testenv.vesting_program_id,
&correct_payer.pubkey(),
&correct_vesting_account_key,
correct_seeds,
fuzz_instruction.number_of_schedules as u32
).unwrap()];
let mut create_instructions = create_fuzzinstruction(
token_vesting_testenv,
fuzz_instruction,
correct_payer,
&correct_source_token_account_key,
source_token_account_owner_key,
destination_token_key,
&destination_token_owner_key.pubkey(),
&correct_vesting_account_key,
&correct_vesting_token_key,
correct_seeds,
mint_key,
fuzz_instruction.source_token_amount
);
instructions_acc.append(&mut create_instructions);
let unlock_instruction = unlock(
&token_vesting_testenv.vesting_program_id,
&token_vesting_testenv.token_program_id,
&token_vesting_testenv.sysvarclock_program_id,
&correct_vesting_account_key,
&correct_vesting_token_key,
destination_token_key,
correct_seeds
).unwrap();
instructions_acc.push(unlock_instruction);
return (instructions_acc, vec![
clone_keypair(mint_key),
clone_keypair(&token_vesting_testenv.mint_authority),
clone_keypair(source_token_account_owner_key),
]);
},
FuzzInstruction {
instruction: VestingInstruction::ChangeDestination{ .. },
..
} => {
let mut instructions_acc = vec![init(
&token_vesting_testenv.system_program_id,
&token_vesting_testenv.rent_program_id,
&token_vesting_testenv.vesting_program_id,
&correct_payer.pubkey(),
&correct_vesting_account_key,
correct_seeds,
fuzz_instruction.number_of_schedules as u32
).unwrap()];
let mut create_instructions = create_fuzzinstruction(
token_vesting_testenv,
fuzz_instruction,
correct_payer,
&correct_source_token_account_key,
source_token_account_owner_key,
destination_token_key,
&destination_token_owner_key.pubkey(),
&correct_vesting_account_key,
&correct_vesting_token_key,
correct_seeds,
mint_key,
fuzz_instruction.source_token_amount
);
instructions_acc.append(&mut create_instructions);
let new_destination_instruction = create_associated_token_account(
&correct_payer.pubkey(),
&Pubkey::new_unique(), // Arbitrary
&mint_key.pubkey()
);
instructions_acc.push(new_destination_instruction);
let change_instruction = change_destination(
&token_vesting_testenv.vesting_program_id,
&correct_vesting_account_key,
&destination_token_owner_key.pubkey(),
&destination_token_key,
new_destination_token_key,
correct_seeds
).unwrap();
instructions_acc.push(change_instruction);
return (instructions_acc, vec![
clone_keypair(mint_key),
clone_keypair(&token_vesting_testenv.mint_authority),
clone_keypair(source_token_account_owner_key),
clone_keypair(destination_token_owner_key),
]);
}
};
// Execute a more random input fuzzing (these should give an error almost surely)
} else {
match fuzz_instruction {
FuzzInstruction {
instruction: VestingInstruction::Init{ .. },
..
} => {
return (vec![init(
&token_vesting_testenv.system_program_id,
&token_vesting_testenv.rent_program_id,
&token_vesting_testenv.vesting_program_id,
&payer_key.pubkey(),
vesting_account_key,
fuzz_instruction.seeds,
fuzz_instruction.number_of_schedules as u32
).unwrap()], vec![]);
},
FuzzInstruction {
instruction: VestingInstruction::Create { .. },
..
} => {
let create_instructions = create(
&token_vesting_testenv.vesting_program_id,
&token_vesting_testenv.token_program_id,
vesting_account_key,
vesting_token_account_key,
&source_token_account_owner_key.pubkey(),
&destination_token_owner_key.pubkey(),
destination_token_key,
&mint_key.pubkey(),
fuzz_instruction.schedules.clone(),
fuzz_instruction.seeds
).unwrap();
return (
vec![create_instructions],
vec![clone_keypair(source_token_account_owner_key)]
);
},
FuzzInstruction {
instruction: VestingInstruction::Unlock{ .. },
..
} => {
let unlock_instruction = unlock(
&token_vesting_testenv.vesting_program_id,
&token_vesting_testenv.token_program_id,
&token_vesting_testenv.sysvarclock_program_id,
vesting_account_key,
vesting_token_account_key,
destination_token_key,
fuzz_instruction.seeds,
).unwrap();
return (
vec![unlock_instruction],
vec![]
);
},
FuzzInstruction {
instruction: VestingInstruction::ChangeDestination{ .. },
..
} => {
let change_instruction = change_destination(
&token_vesting_testenv.vesting_program_id,
vesting_account_key,
&destination_token_owner_key.pubkey(),
&destination_token_key,
new_destination_token_key,
fuzz_instruction.seeds,
).unwrap();
return (
vec![change_instruction],
vec![clone_keypair(destination_token_owner_key)]
);
}
};
}
}
// A correct vesting create fuzz instruction
fn create_fuzzinstruction(
token_vesting_testenv: &TokenVestingEnv,
fuzz_instruction: &FuzzInstruction,
payer: &Keypair,
correct_source_token_account_key: &Pubkey,
source_token_account_owner_key: &Keypair,
destination_token_key: &Pubkey,
destination_token_owner_key: &Pubkey,
correct_vesting_account_key: &Pubkey,
correct_vesting_token_key: &Pubkey,
correct_seeds: [u8; 32],
mint_key: &Keypair,
source_amount: u64
) -> Vec<Instruction> {
// Initialize the token mint account
let mut instructions_acc = mint_init_instruction(
&payer,
&mint_key,
&token_vesting_testenv.mint_authority
);
// Create the associated token accounts
let source_instruction = create_associated_token_account(
&payer.pubkey(),
&source_token_account_owner_key.pubkey(),
&mint_key.pubkey()
);
instructions_acc.push(source_instruction);
let vesting_instruction = create_associated_token_account(
&payer.pubkey(),
&correct_vesting_account_key,
&mint_key.pubkey()
);
instructions_acc.push(vesting_instruction);
let destination_instruction = create_associated_token_account(
&payer.pubkey(),
&destination_token_owner_key,
&mint_key.pubkey()
);
instructions_acc.push(destination_instruction);
// Credit the source account
let setup_instruction = mint_to(
&spl_token::id(),
&mint_key.pubkey(),
&correct_source_token_account_key,
&token_vesting_testenv.mint_authority.pubkey(),
&[],
source_amount
).unwrap();
instructions_acc.push(setup_instruction);
let used_number_of_schedules = fuzz_instruction.number_of_schedules.min(
fuzz_instruction.schedules.len().try_into().unwrap_or(u8::MAX)
);
// Initialize the vesting program account
let create_instruction = create(
&token_vesting_testenv.vesting_program_id,
&token_vesting_testenv.token_program_id,
&correct_vesting_account_key,
&correct_vesting_token_key,
&source_token_account_owner_key.pubkey(),
&correct_source_token_account_key,
&destination_token_key,
&mint_key.pubkey(),
fuzz_instruction.schedules.clone()[..used_number_of_schedules.into()].into(),
correct_seeds,
).unwrap();
instructions_acc.push(create_instruction);
return instructions_acc;
}
// Helper functions
fn mint_init_instruction(
payer: &Keypair,
mint:&Keypair,
mint_authority: &Keypair) -> Vec<Instruction> {
let instructions = vec![
system_instruction::create_account(
&payer.pubkey(),
&mint.pubkey(),
Rent::default().minimum_balance(82),
82,
&spl_token::id()
),
initialize_mint(
&spl_token::id(),
&mint.pubkey(),
&mint_authority.pubkey(),
None,
0
).unwrap(),
];
return instructions;
}
fn clone_keypair(keypair: &Keypair) -> Keypair {
return Keypair::from_bytes(&keypair.to_bytes().clone()).unwrap();
}
| 39.144348 | 166 | 0.592589 |
c190c314d7fbc787a217eede9daba375ab1de459
| 32,261 |
use super::runtime::*;
use super::{CFunctionArtifact, ContextArtifact, FunctionArtifact, ModuleArtifact};
use crate::emitter::ir::*;
use derive_new::new;
use llvm::prelude::*;
use std::collections::HashMap;
pub fn run<'ctx: 'm, 'm>(
function: &FunctionArtifact<'ctx, 'm>,
def: &Function,
module: &mut ModuleArtifact<'ctx, 'm>,
ctx: &ContextArtifact<'ctx>,
) {
let entry_bb = function.value.append_block("entry");
let builder = LLVMBuilder::new(entry_bb);
let mut values = HashMap::new();
let (ret_pointer, env_param, params) = {
let mut params = function.value.params();
let ret_pointer = if function.symbol.kind.returns_by_pointer_store() {
Some(params.remove(0))
} else {
None
};
let env_param = if function.symbol.kind.takes_env_as_argument() {
Some(params.remove(0))
} else {
None
};
(ret_pointer, env_param, params)
};
// Bind arguments
for (p, param) in def.params.iter().zip(¶ms) {
values.insert(p.id, *param);
}
if let (Some(env_param), Some(env)) = (env_param, &def.env) {
// Bind an environment argument
values.insert(env.id, env_param);
let env_param = builder.build_bit_cast(env_param, {
let elem_tys = ctx.llvm_type_all(env.elems.iter().map(|p| &p.ty));
llvm_type!(*ctx, (ptr (struct ...{elem_tys})))
});
// Bind the environment argument elements
for (index, elem) in env.elems.iter().enumerate() {
let param = builder.build_struct_gep(env_param, index as u32);
let param = builder.build_load(param);
values.insert(elem.id, param);
}
}
if function.symbol.kind.is_main() {
let llrt_init = module.capture_c_function(
"llrt_init",
ctx,
|| llvm_type!(*ctx, (function(i32 (ptr (ptr u8))) void)),
);
builder.build_call(llrt_init.value, ¶ms);
}
let mut codegen = Codegen::new(ctx, module, builder, ret_pointer, values, HashMap::new());
if let Some(ret) = codegen.eval(&def.body) {
codegen.eval_return(ret);
}
}
#[derive(new)]
struct Codegen<'a, 'ctx: 'm, 'm> {
ctx: &'a ContextArtifact<'ctx>,
module: &'a mut ModuleArtifact<'ctx, 'm>,
builder: LLVMBox<LLVMBuilder<'ctx, 'm>>,
ret_pointer: Option<LLVMValue<'ctx, 'm>>,
local_values: HashMap<RtId, LLVMValue<'ctx, 'm>>,
local_conts: HashMap<RtId, Cont<'ctx, 'm>>,
}
impl<'a, 'ctx: 'm, 'm> Codegen<'a, 'ctx, 'm> {
fn eval(&mut self, rt: &Rt) -> Option<LLVMValue<'ctx, 'm>> {
match rt {
Rt::Local(id) => match self.local_values.get(id) {
Some(value) => Some(*value),
None => panic!("Undefined variable: {}", id),
},
Rt::LocalFun(_, _) => {
panic!("Found Rt::LocalFun at Codegen, this should be erased by emitter")
}
Rt::StaticFun(Ct::Id(id), env) => {
let fp = self.module.capture_function(*id, self.ctx).value;
let env = match env {
Some(env) => self.eval(env)?,
None => {
let ty = self.ctx.llvm_type(&Ct::Env).as_type_of().unwrap();
llvm_constant!(*self.ctx, (nullptr { ty })).as_value()
}
};
let value = llvm_constant!(*self.ctx, (undef (struct (typeof fp) (typeof env))));
let value = self.builder.build_insert_value(value, fp, 0);
let value = self.builder.build_insert_value(value, env, 1);
Some(value)
}
Rt::StaticFun(ct, _) => {
panic!("Unresolved Ct: {}, this should be resolved by emitter", ct)
}
Rt::Const(c) => Some(self.llvm_constant(c).as_value()),
Rt::Call(call) => {
let clos = self.eval(&call.0)?;
let args = self.eval_all(&call.1)?;
Some(self.eval_call(clos, &args))
}
Rt::CCall(c_call) => {
let args = self.eval_all(&c_call.2)?;
let ctx = self.ctx;
let f = self
.module
.capture_c_function(&c_call.0, ctx, || match c_call.1 {
Ct::Clos(ref clos) => {
let params = ctx.llvm_type_all(&clos.0);
let ret = match clos.1 {
Ct::Unit => llvm_type!(*ctx, void).as_type(),
ref ty => ctx.llvm_type(ty),
};
llvm_type!(*ctx, (function(...{params}) {ret}))
}
ref ty => panic!("CCall type is not a function type: {}", ty),
});
Some(self.eval_c_call(f, &args))
}
Rt::Nullary(nullary) => {
use Nullary::*;
Some(match nullary {
Uninitialized(ty) => {
let ty = self.ctx.llvm_type(ty);
llvm_constant!(*self.ctx, (undef { ty })).as_value()
}
Null(ty) => {
let ty = self.ctx.llvm_type(ty);
llvm_constant!(*self.ctx, (nullptr(ptr { ty }))).as_value()
}
GenId => RtString::build_genid(&self.builder, self.module),
SizeOf(ty) => {
let ty = self.ctx.llvm_type(ty);
let size = self.ctx.data_layout().type_alloc_size(ty);
llvm_constant!(*self.ctx, (u64 { size })).as_value()
}
AlignOf(ty) => {
let ty = self.ctx.llvm_type(ty);
let align = self.ctx.data_layout().abi_type_alignment(ty);
llvm_constant!(*self.ctx, (u64 { align })).as_value()
}
})
}
Rt::Unary(unary) => {
use Unary::*;
let x = self.eval(&unary.1)?;
Some(match &unary.0 {
Not => self.builder.build_not(x),
Load => self.builder.build_load(x),
StructElem(_, i) => self.builder.build_extract_value(x, *i as u32),
Reinterpret(a, b) => {
let a = self.ctx.llvm_type(a);
let b = self.ctx.llvm_type(b);
self.eval_reinterpret(a, b, x)
}
SyntaxBody(ty) => {
let ty = self.ctx.llvm_type(ty);
RtSyntax::build_syntax_body(ty, x, &self.builder, self.module)
}
Panic => {
build_panic(x, &self.builder, self.module);
return None;
}
BitCast(ty) => {
let ty = self.ctx.llvm_type(ty);
self.builder.build_bit_cast(x, ty)
}
PtrToI => self.builder.build_ptr_to_int(x, llvm_type!(*self.ctx, u64)),
IToPtr(ty) => {
let ty = self.ctx.llvm_type(ty);
self.builder
.build_int_to_ptr(x, llvm_type!(*self.ctx, (ptr { ty })))
}
IComplement => {
let int_ty = x
.get_type()
.as_type_of::<LLVMIntegerType>()
.expect("Integer type");
let y = LLVMConstantInt::get(int_ty, -1i64 as u64, true);
self.builder.build_xor(x, y)
}
ITrunc(ty) => {
let ty = self.ctx.llvm_type(ty);
self.builder.build_trunc(x, ty)
}
IPopCount => {
let int_ty = x
.get_type()
.as_type_of::<LLVMIntegerType>()
.expect("Integer type");
let function = match int_ty.bit_width() {
8 => self.module.ctpop_i8(),
16 => self.module.ctpop_i16(),
32 => self.module.ctpop_i32(),
64 => self.module.ctpop_i64(),
_ => panic!("popcount is not defined for type: {}", int_ty),
};
self.builder.build_call(function, &[x])
}
SExt(ty) => {
let ty = self.ctx.llvm_type(ty);
self.builder.build_sext(x, ty)
}
SToF(ty) => {
let ty = self.ctx.llvm_type(ty);
self.builder.build_si_to_fp(x, ty)
}
UExt(ty) => {
let ty = self.ctx.llvm_type(ty);
self.builder.build_zext(x, ty)
}
UToF(ty) => {
let ty = self.ctx.llvm_type(ty);
self.builder.build_ui_to_fp(x, ty)
}
FToS(ty) => {
let ty = self.ctx.llvm_type(ty);
self.builder.build_fp_to_si(x, ty)
}
FToU(ty) => {
let ty = self.ctx.llvm_type(ty);
self.builder.build_fp_to_ui(x, ty)
}
FTrunc(ty) => {
let ty = self.ctx.llvm_type(ty);
self.builder.build_fptrunc(x, ty)
}
FExt(ty) => {
let ty = self.ctx.llvm_type(ty);
self.builder.build_fpext(x, ty)
}
RealCeil | RealFloor | RealTrunc | RealRound => {
use llvm::TypeKind::*;
let function = match (&unary.0, x.get_type().kind()) {
(RealCeil, LLVMFloatTypeKind) => self.module.ceil_f32(),
(RealCeil, LLVMDoubleTypeKind) => self.module.ceil_f64(),
(RealFloor, LLVMFloatTypeKind) => self.module.floor_f32(),
(RealFloor, LLVMDoubleTypeKind) => self.module.floor_f64(),
(RealTrunc, LLVMFloatTypeKind) => self.module.trunc_f32(),
(RealTrunc, LLVMDoubleTypeKind) => self.module.trunc_f64(),
(RealRound, LLVMFloatTypeKind) => self.module.round_f32(),
(RealRound, LLVMDoubleTypeKind) => self.module.round_f64(),
(op, _) => panic!("{} is not defined for type: {}", op, x.get_type()),
};
self.builder.build_call(function, &[x])
}
MathSqrt | MathSin | MathCos | MathExp | MathLog => {
use llvm::TypeKind::*;
let function = match (&unary.0, x.get_type().kind()) {
(MathSqrt, LLVMFloatTypeKind) => self.module.sqrt_f32(),
(MathSqrt, LLVMDoubleTypeKind) => self.module.sqrt_f64(),
(MathSin, LLVMFloatTypeKind) => self.module.sin_f32(),
(MathSin, LLVMDoubleTypeKind) => self.module.sin_f64(),
(MathCos, LLVMFloatTypeKind) => self.module.cos_f32(),
(MathCos, LLVMDoubleTypeKind) => self.module.cos_f64(),
(MathExp, LLVMFloatTypeKind) => self.module.exp_f32(),
(MathExp, LLVMDoubleTypeKind) => self.module.exp_f64(),
(MathLog, LLVMFloatTypeKind) => self.module.log_f32(),
(MathLog, LLVMDoubleTypeKind) => self.module.log_f64(),
(op, _) => panic!("{} is not defined for type: {}", op, x.get_type()),
};
self.builder.build_call(function, &[x])
}
StringPtr => RtString::build_getptr(x, &self.builder),
StringLength => RtString::build_getlen(x, &self.builder),
ArrayPtr => RtArray::build_getptr(x, &self.builder),
ArrayLength => RtArray::build_getlen(x, &self.builder),
})
}
Rt::Binary(binary) => {
use Binary::*;
let x = self.eval(&binary.1)?;
let y = self.eval(&binary.2)?;
Some(match &binary.0 {
Store => {
self.builder.build_store(x, y);
self.llvm_constant(&Const::Unit).as_value()
}
Offset => self.builder.build_gep(y, &[x]),
PtrEq => self.builder.build_eq(x, y),
PtrLt => self.builder.build_ult(x, y),
PtrLe => self.builder.build_ule(x, y),
PtrGt => self.builder.build_ugt(x, y),
PtrGe => self.builder.build_uge(x, y),
IEq => self.builder.build_eq(x, y),
IShl => self.builder.build_shl(x, y),
IAShr => self.builder.build_ashr(x, y),
ILShr => self.builder.build_lshr(x, y),
IAnd => self.builder.build_and(x, y),
IOr => self.builder.build_or(x, y),
IXor => self.builder.build_xor(x, y),
SLt => self.builder.build_slt(x, y),
SLe => self.builder.build_sle(x, y),
SGt => self.builder.build_sgt(x, y),
SGe => self.builder.build_sge(x, y),
SAdd => self.builder.build_nswadd(x, y),
SSub => self.builder.build_nswsub(x, y),
SMul => self.builder.build_nswmul(x, y),
SDiv => self.builder.build_sdiv(x, y),
SRem => self.builder.build_srem(x, y),
ULt => self.builder.build_ult(x, y),
ULe => self.builder.build_ule(x, y),
UGt => self.builder.build_ugt(x, y),
UGe => self.builder.build_uge(x, y),
UAdd => self.builder.build_add(x, y),
USub => self.builder.build_sub(x, y),
UMul => self.builder.build_mul(x, y),
UDiv => self.builder.build_udiv(x, y),
URem => self.builder.build_urem(x, y),
FEq => self.builder.build_feq(x, y),
FLt => self.builder.build_flt(x, y),
FLe => self.builder.build_fle(x, y),
FGt => self.builder.build_fgt(x, y),
FGe => self.builder.build_fge(x, y),
FAdd => self.builder.build_fadd(x, y),
FSub => self.builder.build_fsub(x, y),
FMul => self.builder.build_fmul(x, y),
FDiv => self.builder.build_fdiv(x, y),
FRem => self.builder.build_frem(x, y),
MathPow => {
let function = match x.get_type().kind() {
llvm::TypeKind::LLVMFloatTypeKind => self.module.pow_f32(),
llvm::TypeKind::LLVMDoubleTypeKind => self.module.pow_f64(),
_ => panic!("{} is not defined for type: {}", MathPow, x.get_type()),
};
self.builder.build_call(function, &[x, y])
}
StringConstruct => RtString::build_construct(x, y, &self.builder),
StringEq => RtString::build_eq(x, y, &self.builder, self.module),
StringCmp => RtString::build_cmp(x, y, &self.builder, self.module),
StringConcat => RtString::build_concat(x, y, &self.builder, self.module),
CharEq => RtChar::build_eq(x, y, &self.builder),
ArrayConstruct => RtArray::build_construct(x, y, &self.builder),
ArrayLoad => RtArray::build_load(x, y, &self.builder),
})
}
Rt::Ternary(ternary) => {
use Ternary::*;
let x = self.eval(&ternary.1)?;
let y = self.eval(&ternary.2)?;
let z = self.eval(&ternary.3)?;
Some(match &ternary.0 {
PtrCopy | PtrMove => {
let f = match &ternary.0 {
PtrCopy => self.module.memcpy_i64(),
_ => self.module.memmove_i64(),
};
let ptr_ty = llvm_type!(*self.ctx, (ptr i8));
let value_ty = x
.get_type()
.as_type_of::<LLVMPointerType>()
.unwrap()
.element_type();
let src = self.builder.build_bit_cast(x, ptr_ty);
let len = self.ctx.data_layout().type_alloc_size(value_ty);
let len = llvm_constant!(*self.ctx, (u64 { len })).as_value();
let len = self.builder.build_mul(len, y);
let dest = self.builder.build_bit_cast(z, ptr_ty);
let is_volatile = llvm_constant!(*self.ctx, (bool false)).as_value();
self.builder.build_call(f, &[dest, src, len, is_volatile]);
self.llvm_constant(&Const::Unit).as_value()
}
ArrayStore => {
RtArray::build_store(x, y, z, &self.builder);
self.llvm_constant(&Const::Unit).as_value()
}
})
}
Rt::Alloc(alloc) => {
let a = self.eval(&alloc.1)?;
let ptr = self.eval_alloc(alloc.0, a.get_type());
self.builder.build_store(a, ptr);
Some(ptr)
}
Rt::AllocArray(alloc) => {
let ty = self.ctx.llvm_type(&alloc.1);
let len = self.eval(&alloc.2)?;
let ptr = self.eval_array_alloc(alloc.0, ty, len);
Some(RtArray::build_construct(ptr, len, &self.builder))
}
Rt::ConstructEnv(con) => {
let elems = self.eval_all(&con.1)?;
let ptr = self.eval_alloc(con.0, {
let elem_tys = elems.iter().map(|v| v.get_type()).collect::<Vec<_>>();
llvm_type!(*self.ctx, (struct ...{elem_tys}))
});
for (index, elem) in elems.iter().enumerate() {
let elem_ptr = self.builder.build_struct_gep(ptr, index as u32);
self.builder.build_store(*elem, elem_ptr);
}
let env_ty = self.ctx.llvm_type(&Ct::Env);
Some(self.builder.build_bit_cast(ptr, env_ty))
}
Rt::ConstructData(_) => {
panic!("Found Rt::ConstructData at Codegen, this should be erased by emitter")
}
Rt::ConstructStruct(con) => {
let mut result = LLVMConstant::undef(self.ctx.llvm_type(&con.0)).as_value();
for (index, field) in con.1.iter().enumerate() {
let value = self.eval(field)?;
result = self.builder.build_insert_value(result, value, index as u32);
}
Some(result)
}
Rt::ConstructSyntax(con) => {
let x = self.eval(&con.1)?;
let x = RtSyntax::build_construct_syntax(con.0, x, &self.builder, self.module);
Some(x)
}
Rt::Seq(seq) => {
for stmt in seq.0.iter() {
self.eval(stmt)?;
}
self.eval(&seq.1)
}
Rt::If(if_) => self.eval_if(&if_.0, &if_.1, &if_.2),
Rt::While(while_) => self.eval_while(&while_.0, &while_.1),
Rt::And(_) => {
panic!("Found Rt::And at Codegen, this should be erased by emitter")
}
Rt::Or(_) => {
panic!("Found Rt::Or at Codegen, this should be erased by emitter")
}
Rt::Match(_) => {
panic!("Found Rt::Match at Codegen, this should be erased by emitter")
}
Rt::Return(ret) => {
let ret = self.eval(ret)?;
self.eval_return(ret);
None
}
Rt::Cont(id, args) => {
let args = self.eval_all(args)?;
match self.local_conts.remove(id) {
Some(mut cont) => {
cont.enter(args, self);
self.local_conts.insert(*id, cont);
None
}
// NOTE: Continuation recursion is unsupported at the moment
None => panic!("Undefined continuation: {}", id),
}
}
Rt::Never => {
self.builder.build_unreachable();
None
}
Rt::LetFunction(_) => {
panic!("Found Rt::LetFunction at Codegen, this should be erased by emitter")
}
Rt::LetVar(let_) => self.eval_let_var(&let_.0, &let_.1),
Rt::LetCont(let_) => self.eval_let_cont(&let_.0, &let_.1),
}
}
fn eval_all<'b>(
&mut self,
rts: impl IntoIterator<Item = &'b Rt>,
) -> Option<Vec<LLVMValue<'ctx, 'm>>> {
rts.into_iter().map(|arg| self.eval(arg)).collect()
}
fn eval_call(
&mut self,
clos: impl LLVMAnyValue<'ctx, 'm>,
args: &[LLVMValue<'ctx, 'm>],
) -> LLVMValue<'ctx, 'm> {
let fp = self.builder.build_extract_value(clos, 0);
let env = self.builder.build_extract_value(clos, 1);
let args = std::iter::once(env)
.chain(args.iter().copied())
.collect::<Vec<_>>();
self.builder.build_call(fp, &args)
}
fn eval_c_call(
&mut self,
cfun: CFunctionArtifact<'ctx, 'm>,
args: &[LLVMValue<'ctx, 'm>],
) -> LLVMValue<'ctx, 'm> {
if cfun.return_by_pointer_store {
let ret_param = cfun.value.params()[0];
let ret_ptr = self.builder.build_entry_alloca(
"rettmp",
ret_param
.get_type()
.as_type_of::<LLVMPointerType>()
.unwrap()
.element_type(),
);
let args = std::iter::once(ret_ptr)
.chain(args.iter().copied())
.collect::<Vec<_>>();
self.builder.build_call(cfun.value, &args);
self.builder.build_load(ret_ptr)
} else {
let ret = self.builder.build_call(cfun.value, args);
if ret.get_type().is_sized() {
ret
} else {
self.llvm_constant(&Const::Unit).as_value()
}
}
}
fn eval_if(&mut self, cond: &Rt, then: &Rt, else_: &Rt) -> Option<LLVMValue<'ctx, 'm>> {
let cond = self.eval(cond)?;
let then_bb = self.builder.append_block("then");
let else_bb = self.builder.append_block("else");
self.builder.build_cond_br(cond, then_bb, else_bb);
let mut merge = Cont::new("merge", |phis, _| Some(phis[0].as_value()));
self.builder.set_insert_point(then_bb, true);
if let Some(then) = self.eval(then) {
merge.enter(vec![then], self);
}
self.builder.set_insert_point(else_bb, true);
if let Some(else_) = self.eval(else_) {
merge.enter(vec![else_], self);
}
merge.continue_(self)
}
fn eval_while(&mut self, cond: &Rt, body: &Rt) -> Option<LLVMValue<'ctx, 'm>> {
let cond_bb = self.builder.append_block("cond");
self.builder.build_br(cond_bb);
self.builder.set_insert_point(cond_bb, true);
let cond = self.eval(cond)?;
let then_bb = self.builder.append_block("then");
let else_bb = self.builder.append_block("else");
self.builder.build_cond_br(cond, then_bb, else_bb);
self.builder.set_insert_point(then_bb, true);
if let Some(_) = self.eval(body) {
self.builder.build_br(cond_bb);
}
self.builder.set_insert_point(else_bb, true);
Some(self.llvm_constant(&Const::Unit).as_value())
}
fn eval_let_var(&mut self, vars: &Vec<RtVar>, body: &Rt) -> Option<LLVMValue<'ctx, 'm>> {
for var in vars {
let init = self.eval(&var.init)?;
self.local_values.insert(var.id, init);
}
self.eval(body)
}
fn eval_let_cont(&mut self, conts: &Vec<RtCont>, body: &Rt) -> Option<LLVMValue<'ctx, 'm>> {
for cont in conts {
self.local_conts.insert(cont.id, {
let params = cont.params.iter().map(|p| p.id).collect::<Vec<_>>();
let body = cont.body.clone();
Cont::boxed("cont", move |args, self_| {
assert_eq!(args.len(), params.len());
for (param, arg) in params.iter().zip(args) {
self_.local_values.insert(*param, arg.as_value());
}
self_.eval(&body)
})
});
}
let mut merge = Cont::new("merge", |phis, _| Some(phis[0].as_value()));
if let Some(ret) = self.eval(body) {
merge.enter(vec![ret], self);
}
for cont in conts {
let cont = self.local_conts.remove(&cont.id).unwrap();
if let Some(ret) = cont.continue_(self) {
merge.enter(vec![ret], self);
}
}
merge.continue_(self)
}
fn eval_alloc(&mut self, loc: Location, ty: impl LLVMAnyType<'ctx>) -> LLVMValue<'ctx, 'm> {
match loc {
Location::Heap => build_heap_alloc(ty, &self.builder, self.module),
Location::Stack => self.builder.build_alloca("", ty),
}
}
fn eval_array_alloc(
&mut self,
loc: Location,
ty: impl LLVMAnyType<'ctx>,
num: impl LLVMAnyValue<'ctx, 'm>,
) -> LLVMValue<'ctx, 'm> {
match loc {
Location::Heap => build_heap_array_alloc(ty, num, &self.builder, self.module),
Location::Stack => self.builder.build_array_alloca("", ty, num),
}
}
fn eval_reinterpret(
&mut self,
a: impl LLVMAnyType<'ctx>,
b: impl LLVMAnyType<'ctx>,
x: impl LLVMAnyValue<'ctx, 'm>,
) -> LLVMValue<'ctx, 'm> {
let a_size = self.ctx.data_layout().type_alloc_size(a);
let b_size = self.ctx.data_layout().type_alloc_size(b);
if a_size < b_size {
let ptr = self.builder.build_entry_alloca("reinterpret", b);
let a_ptr = self.builder.build_bit_cast(ptr, LLVMPointerType::get(a, 0));
self.builder.build_store(x, a_ptr);
self.builder.build_load(ptr)
} else {
let ptr = self.builder.build_entry_alloca("reinterpret", a);
self.builder.build_store(x, ptr);
let b_ptr = self.builder.build_bit_cast(ptr, LLVMPointerType::get(b, 0));
self.builder.build_load(b_ptr)
}
}
fn eval_return(&mut self, x: impl LLVMAnyValue<'ctx, 'm>) {
match self.ret_pointer {
Some(ptr) => {
self.builder.build_store(x, ptr);
self.builder.build_ret_void();
}
None => {
self.builder.build_ret(x);
}
}
}
pub fn llvm_constant(&self, c: &Const) -> LLVMConstant<'ctx, 'm> {
match c {
Const::Integer(ty, signed, value) => match ty {
Ct::F32 | Ct::F64 => LLVMConstantFP::get(
self.ctx.llvm_type(ty).as_type_of().unwrap(),
if *signed {
*value as i64 as f64
} else {
*value as f64
},
)
.as_constant(),
_ => LLVMConstantInt::get(
self.ctx.llvm_type(ty).as_type_of().unwrap(),
*value,
*signed,
)
.as_constant(),
},
Const::FPNumber(ty, value) => LLVMConstantFP::get(
self.ctx.llvm_type(ty).as_type_of().unwrap(),
value.into_inner(),
)
.as_constant(),
Const::String(s) => RtString::llvm_constant(s, self.module.module()),
Const::Char(c) => RtChar::llvm_constant(c, self.module.module()),
Const::SyntaxSexp(_, s) => RtSyntax::<RtSexp>::llvm_constant(s, self.module.module()),
Const::Unit => llvm_constant!(*self.ctx, (struct)).as_constant(),
}
}
}
#[derive(Debug)]
enum Cont<
'ctx: 'p,
'p,
F = Box<
dyn FnOnce(
&[LLVMPhiNode<'ctx, 'p>],
&mut Codegen<'_, 'ctx, 'p>,
) -> Option<LLVMValue<'ctx, 'p>>,
>,
> {
Never(&'static str, F),
Reach(
LLVMBasicBlock<'ctx, 'p>,
Vec<LLVMPhiNode<'ctx, 'p>>,
Option<(LLVMBasicBlock<'ctx, 'p>, LLVMValue<'ctx, 'p>)>,
),
}
impl<'ctx: 'p, 'p, F> Cont<'ctx, 'p, F>
where
F: FnOnce(&[LLVMPhiNode<'ctx, 'p>], &mut Codegen<'_, 'ctx, 'p>) -> Option<LLVMValue<'ctx, 'p>>,
{
fn new(name: &'static str, f: F) -> Self {
Self::Never(name, f)
}
fn boxed(name: &'static str, f: F) -> Cont<'ctx, 'p>
where
F: 'static,
{
Cont::Never(name, Box::new(f))
}
fn enter(&mut self, args: Vec<LLVMValue<'ctx, 'p>>, b: &mut Codegen<'_, 'ctx, 'p>) {
let current_bb = b.builder.insert_point();
if let Self::Never(name, _) = self {
let cont_bb = current_bb.parent().append_block(name);
b.builder.set_insert_point(cont_bb, true);
let phis = args
.iter()
.map(|arg| b.builder.build_phi(arg.get_type()))
.collect::<Vec<_>>();
let f = match std::mem::replace(self, Self::Reach(cont_bb, phis, None)) {
Self::Never(_, f) => f,
_ => unreachable!(),
};
match self {
Self::Reach(_, phis, ret) => {
*ret = f(phis, b).map(|value| (b.builder.insert_point(), value));
}
_ => unreachable!(),
}
b.builder.set_insert_point(current_bb, true);
}
match self {
Self::Reach(bb, phis, _) => {
b.builder.build_br(*bb);
for (phi, arg) in phis.iter().zip(args) {
phi.add_incoming(arg, current_bb);
}
}
_ => unreachable!(),
}
}
fn continue_(&self, b: &mut Codegen<'_, 'ctx, 'p>) -> Option<LLVMValue<'ctx, 'p>> {
match self {
Self::Never(_, _) => None,
Self::Reach(_, _, None) => None,
Self::Reach(_, _, Some((bb, value))) => {
b.builder.set_insert_point(*bb, true);
Some(*value)
}
}
}
}
| 41.78886 | 99 | 0.456619 |
381393fd0fe7f19ff64e250794a877cbfdffea1d
| 26,525 |
use syntax::ast::token::*;
use syntax::ast::expr::*;
use syntax::ast::constant::*;
use syntax::ast::op::*;
use syntax::ast::punc::*;
use syntax::ast::keyword::*;
use std::collections::btree_map::BTreeMap;
use std::fmt;
use std::vec::Vec;
use self::TokenData::*;
use syntax::ast::constant::Const::{CBool, CString, CNum, CNull, CUndefined};
use syntax::ast::expr::ExprDef::{ThrowExpr, ConstExpr, ArrayDeclExpr, ObjectDeclExpr, BlockExpr, GetConstFieldExpr, BinOpExpr};
use syntax::ast::op::UnaryOp::{UnaryNot, UnaryPlus, UnaryMinus, UnaryIncrementPre, UnaryIncrementPost, UnaryDecrementPost, UnaryDecrementPre};
use syntax::ast::expr::ExprDef::{WhileLoopExpr, TypeOfExpr, VarDeclExpr, ReturnExpr, ConstructExpr, SwitchExpr, FunctionDeclExpr, CallExpr, IfExpr, GetFieldExpr, AssignExpr, UnaryOpExpr, LocalExpr};
use syntax::ast::op::CompOp::{
CompStrictEqual,
CompEqual,
CompStrictNotEqual,
CompNotEqual,
CompGreaterThan,
CompLessThan,
CompLessThanOrEqual,
CompGreaterThanOrEqual};
use syntax::ast::op::BinOp::{BinNum, BinBit, BinLog, BinComp};
use syntax::ast::op::BitOp::{BitShr, BitShl, BitOr, BitAnd, BitXor};
use syntax::ast::op::LogOp::{LogOr, LogAnd};
use syntax::ast::op::NumOp::{OpMul, OpAdd, OpDiv, OpMod, OpSub};
use syntax::ast::expr::ExprDef::ArrowFunctionDeclExpr;
use syntax::parser::ParseError::{UnexpectedKeyword, AbruptEnd, Expected, ExpectedExpr};
use syntax::ast::punc::Punctuator::{POpenParen, PNot, POpenBlock, PNeg, PArrow, PCloseBlock, PCloseParen, PComma, PCloseBracket, PColon, PSemicolon};
use syntax::ast::keyword::Keyword::{KCase, KElse, KDefault};
macro_rules! mk (
($this:expr, $def:expr) => (
Expr::new($def, try!($this.get_token($this.pos - 1)).pos, try!($this.get_token($this.pos - 1)).pos)
);
($this:expr, $def:expr, $first:expr) => (
Expr::new($def, $first.pos, try!($this.get_token($this.pos - 1)).pos)
);
);
#[derive(Clone, PartialEq)]
/// An error encountered during parsing an expression
pub enum ParseError {
/// When it expected a certain kind of token, but got another as part of something
Expected(Vec<TokenData>, Token, &'static str),
/// When it expected a certain expression, but got another
ExpectedExpr(&'static str, Expr),
/// When it didn't expect this keyword
UnexpectedKeyword(Keyword),
/// When there is an abrupt end to the parsing
AbruptEnd
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Expected(ref wanted, ref got, ref routine) if wanted.len() == 0 => write!(f, "{}:{}: Expected expression for {}, got {}", got.pos.line_number, got.pos.column_number, routine, got.data),
Expected(ref wanted, ref got, ref routine) => {
try!(write!(f, "{}:{}: ", got.pos.line_number, got.pos.column_number));
try!(write!(f, "Expected "));
let last = wanted.last().unwrap();
for wanted_token in wanted.iter() {
try!(write!(f, "'{}'{}", wanted_token, if wanted_token == last {""} else {", "}));
}
try!(write!(f, " for {}", routine));
write!(f, " but got {}", got.data)
},
UnexpectedKeyword(ref key) => {
write!(f, "Unexpected {}", key)
}
ExpectedExpr(ref wanted, ref got) => {
write!(f, "Expected {}, but got {}", wanted, got)
},
AbruptEnd => {
write!(f, "Abrupt end")
}
}
}
}
pub type ParseResult = Result<Expr, ParseError>;
/// A Javascript parser
pub struct Parser {
/// The tokens being input
tokens: Vec<Token>,
/// The current position within the tokens
pos: u64
}
impl Parser {
#[inline(always)]
/// Creates a new parser, using `tokens` as input
pub fn new(tokens: Vec<Token>) -> Parser {
Parser {tokens: tokens, pos: 0}
}
/// Parse all expressions in the token array
pub fn parse_all(&mut self) -> ParseResult {
let mut exprs = Vec::new();
while self.pos < self.tokens.len() {
let result = try!(self.parse());
exprs.push(result);
}
Ok(mk!(self, BlockExpr(exprs)))
}
fn parse_struct(&mut self, keyword:Keyword) -> ParseResult {
match keyword {
KThrow => {
let thrown = try!(self.parse());
Ok(mk!(self, ThrowExpr(box thrown)))
},
KVar => {
let mut vars = Vec::new();
loop {
let name = match self.get_token(self.pos) {
Ok(Token { data: TIdentifier(ref name), ..}) => name.clone(),
Ok(tok) => return Err(Expected(vec!(TIdentifier("identifier".into_string())), tok, "var statement")),
Err(AbruptEnd) => break,
Err(e) => return Err(e)
};
self.pos += 1;
match self.get_token(self.pos) {
Ok(Token {data: TPunctuator(PAssign), ..}) => {
self.pos += 1;
let val = try!(self.parse());
vars.push((name, Some(val)));
match self.get_token(self.pos) {
Ok(Token {data: TPunctuator(PComma), ..}) => self.pos += 1,
_ => break
}
},
Ok(Token {data: TPunctuator(PComma), ..}) => {
self.pos += 1;
vars.push((name, None));
},
_ => {
vars.push((name, None));
break;
}
}
}
Ok(mk!(self, VarDeclExpr(vars)))
},
KReturn => Ok(mk!(self, ReturnExpr(Some(box try!(self.parse()).clone())))),
KNew => {
let call = try!(self.parse());
match call.def {
CallExpr(ref func, ref args) => Ok(mk!(self, ConstructExpr(func.clone(), args.clone()))),
_ => Err(ExpectedExpr("constructor", call))
}
},
KTypeOf => Ok(mk!(self, TypeOfExpr(box try!(self.parse())))),
KIf => {
try!(self.expect_punc(POpenParen, "if block"));
let cond = try!(self.parse());
try!(self.expect_punc(PCloseParen, "if block"));
let expr = try!(self.parse());
let next = self.get_token(self.pos + 1);
Ok(mk!(self, IfExpr(box cond, box expr, if next.is_ok() && next.unwrap().data == TKeyword(KElse) {
self.pos += 2;
Some(box try!(self.parse()))
} else {
None
})))
},
KWhile => {
try!(self.expect_punc(POpenParen, "while condition"));
let cond = try!(self.parse());
try!(self.expect_punc(PCloseParen, "while condition"));
let expr = try!(self.parse());
Ok(mk!(self, WhileLoopExpr(box cond, box expr)))
},
KSwitch => {
try!(self.expect_punc(POpenParen, "switch value"));
let value = self.parse();
try!(self.expect_punc(PCloseParen, "switch value"));
try!(self.expect_punc(POpenBlock, "switch block"));
let mut cases = Vec::new();
let mut default = None;
while self.pos + 1 < self.tokens.len() {
let tok = try!(self.get_token(self.pos));
self.pos += 1;
match tok.data {
TKeyword(KCase) => {
let cond = self.parse();
let mut block = Vec::new();
try!(self.expect_punc(PColon, "switch case"));
loop {
match try!(self.get_token(self.pos)).data {
TKeyword(KCase) | TKeyword(KDefault) => break,
TPunctuator(PCloseBlock) => break,
_ => block.push(try!(self.parse()))
}
}
cases.push((cond.unwrap(), block));
},
TKeyword(KDefault) => {
let mut block = Vec::new();
try!(self.expect_punc(PColon, "default switch case"));
loop {
match try!(self.get_token(self.pos)).data {
TKeyword(KCase) | TKeyword(KDefault) => break,
TPunctuator(PCloseBlock) => break,
_ => block.push(try!(self.parse()))
}
}
default = Some(mk!(self, BlockExpr(block)));
},
TPunctuator(PCloseBlock) => break,
_ => return Err(Expected(vec!(TKeyword(KCase), TKeyword(KDefault), TPunctuator(PCloseBlock)), tok, "switch block"))
}
}
try!(self.expect_punc(PCloseBlock, "switch block"));
Ok(mk!(self, SwitchExpr(box value.unwrap(), cases, match default {
Some(v) => Some(box v),
None => None
})))
},
KFunction => {
let tk = try!(self.get_token(self.pos));
let name = match tk.data {
TIdentifier(ref name) => {
self.pos += 1;
Some(name.clone())
},
TPunctuator(POpenParen) => None,
_ => return Err(Expected(vec!(TIdentifier("identifier".into_string())), tk.clone(), "function name"))
};
try!(self.expect_punc(POpenParen, "function"));
let mut args:Vec<String> = Vec::new();
let mut tk = try!(self.get_token(self.pos));
while tk.data != TPunctuator(PCloseParen) {
match tk.data {
TIdentifier(ref id) => args.push(id.clone()),
_ => return Err(Expected(vec!(TIdentifier("identifier".into_string())), tk.clone(), "function arguments"))
}
self.pos += 1;
if try!(self.get_token(self.pos)).data == TPunctuator(PComma) {
self.pos += 1;
}
tk = try!(self.get_token(self.pos));
}
self.pos += 1;
let block = try!(self.parse());
Ok(mk!(self, FunctionDeclExpr(name, args, box block)))
},
_ => Err(UnexpectedKeyword(keyword))
}
}
/// Parse a single expression
pub fn parse(&mut self) -> ParseResult {
if self.pos > self.tokens.len() {
return Err(AbruptEnd);
}
let token = try!(self.get_token(self.pos));
self.pos += 1;
let expr : Expr = match token.data {
TPunctuator(PSemicolon) | TComment(_) if self.pos < self.tokens.len() => try!(self.parse()),
TPunctuator(PSemicolon) | TComment(_) => mk!(self, ConstExpr(CUndefined)),
TNumericLiteral(num) =>
mk!(self, ConstExpr(CNum(num))),
TNullLiteral =>
mk!(self, ConstExpr(CNull)),
TStringLiteral(text) =>
mk!(self, ConstExpr(CString(text))),
TBooleanLiteral(val) =>
mk!(self, ConstExpr(CBool(val))),
TIdentifier(ref s) if s.as_slice() == "undefined" =>
mk!(self, ConstExpr(CUndefined)),
TIdentifier(s) =>
mk!(self, LocalExpr(s)),
TKeyword(keyword) =>
try!(self.parse_struct(keyword)),
TPunctuator(POpenParen) => {
match try!(self.get_token(self.pos)).data {
TPunctuator(PCloseParen) if try!(self.get_token(self.pos + 1)).data == TPunctuator(PArrow) => {
self.pos += 2;
let expr = try!(self.parse());
mk!(self, ArrowFunctionDeclExpr(Vec::new(), box expr), token)
},
_ => {
let next = try!(self.parse());
let next_tok = try!(self.get_token(self.pos));
self.pos += 1;
match next_tok.data {
TPunctuator(PCloseParen) => next,
TPunctuator(PComma) => { // at this point it's probably gonna be an arrow function
let mut args = vec!(match next.def {
LocalExpr(name) => name,
_ => "".into_string()
}, match try!(self.get_token(self.pos)).data {
TIdentifier(ref id) => id.clone(),
_ => "".into_string()
});
let mut expect_ident = true;
loop {
self.pos += 1;
let curr_tk = try!(self.get_token(self.pos));
match curr_tk.data {
TIdentifier(ref id) if expect_ident => {
args.push(id.clone());
expect_ident = false;
},
TPunctuator(PComma) => {
expect_ident = true;
},
TPunctuator(PCloseParen) => {
self.pos += 1;
break;
},
_ if expect_ident => return Err(Expected(vec!(TIdentifier("identifier".into_string())), curr_tk, "arrow function")),
_ => return Err(Expected(vec!(TPunctuator(PComma), TPunctuator(PCloseParen)), curr_tk, "arrow function"))
}
}
try!(self.expect(TPunctuator(PArrow), "arrow function"));
let expr = try!(self.parse());
mk!(self, ArrowFunctionDeclExpr(args, box expr), token)
}
_ => return Err(Expected(vec!(TPunctuator(PCloseParen)), next_tok, "brackets"))
}
}
}
},
TPunctuator(POpenBracket) => {
let mut array : Vec<Expr> = Vec::new();
let mut expect_comma_or_end = try!(self.get_token(self.pos)).data == TPunctuator(PCloseBracket);
loop {
let token = try!(self.get_token(self.pos));
if token.data == TPunctuator(PCloseBracket) && expect_comma_or_end {
self.pos += 1;
break;
} else if token.data == TPunctuator(PComma) && expect_comma_or_end {
expect_comma_or_end = false;
} else if token.data == TPunctuator(PComma) && !expect_comma_or_end {
array.push(mk!(self, ConstExpr(CNull)));
expect_comma_or_end = false;
} else if expect_comma_or_end {
return Err(Expected(vec!(TPunctuator(PComma), TPunctuator(PCloseBracket)), token.clone(), "array declaration"));
} else {
let parsed = try!(self.parse());
self.pos -= 1;
array.push(parsed);
expect_comma_or_end = true;
}
self.pos += 1;
}
mk!(self, ArrayDeclExpr(array), token)
},
TPunctuator(POpenBlock) if try!(self.get_token(self.pos)).data == TPunctuator(PCloseBlock) => {
self.pos += 1;
mk!(self, ObjectDeclExpr(box BTreeMap::new()), token)
},
TPunctuator(POpenBlock) if try!(self.get_token(self.pos + 1)).data == TPunctuator(PColon) => {
let mut map = box BTreeMap::new();
while try!(self.get_token(self.pos - 1)).data == TPunctuator(PComma) || map.len() == 0 {
let tk = try!(self.get_token(self.pos));
let name = match tk.data {
TIdentifier(ref id) => id.clone(),
TStringLiteral(ref str) => str.clone(),
_ => return Err(vec!(TIdentifier("identifier".into_string()), TStringLiteral("string".into_string()), tk, "object declaration"))
};
self.pos += 1;
try!(self.expect(TPunctuator(PColon), "object declaration"));
let value = try!(self.parse());
map.insert(name, value);
self.pos += 1;
}
mk!(self, ObjectDeclExpr(map), token)
},
TPunctuator(POpenBlock) => {
let mut exprs = Vec::new();
loop {
if try!(self.get_token(self.pos)).data == TPunctuator(PCloseBlock) {
break;
} else {
exprs.push(try!(self.parse()));
}
}
self.pos += 1;
mk!(self, BlockExpr(exprs), token)
},
TPunctuator(PSub) =>
mk!(self, UnaryOpExpr(UnaryMinus, box try!(self.parse()))),
TPunctuator(PAdd) =>
mk!(self, UnaryOpExpr(UnaryPlus, box try!(self.parse()))),
TPunctuator(PNot) =>
mk!(self, UnaryOpExpr(UnaryNot, box try!(self.parse()))),
TPunctuator(PInc) =>
mk!(self, UnaryOpExpr(UnaryIncrementPre, box try!(self.parse()))),
TPunctuator(PDec) =>
mk!(self, UnaryOpExpr(UnaryDecrementPre, box try!(self.parse()))),
_ => return Err(Expected(Vec::new(), token.clone(), "script"))
};
if self.pos >= self.tokens.len() {
Ok(expr)
} else {
self.parse_next(expr)
}
}
fn get_token(&self, pos:u64) -> Result<Token, ParseError> {
if pos < self.tokens.len() {
Ok(self.tokens[pos].clone())
} else {
Err(AbruptEnd)
}
}
fn parse_next(&mut self, expr:Expr) -> ParseResult {
let next = try!(self.get_token(self.pos));
let mut carry_on = true;
let mut result = expr.clone();
match next.data {
TPunctuator(PDot) => {
self.pos += 1;
let tk = try!(self.get_token(self.pos));
match tk.data {
TIdentifier(ref s) => result = mk!(self, GetConstFieldExpr(box expr, s.to_string())),
_ => return Err(Expected(vec!(TIdentifier("identifier".into_string())), tk, "field access"))
}
self.pos += 1;
},
TPunctuator(POpenParen) => {
let mut args = Vec::new();
let mut expect_comma_or_end = try!(self.get_token(self.pos + 1)).data == TPunctuator(PCloseParen);
loop {
self.pos += 1;
let token = try!(self.get_token(self.pos));
if token.data == TPunctuator(PCloseParen) && expect_comma_or_end {
self.pos += 1;
break;
} else if token.data == TPunctuator(PComma) && expect_comma_or_end {
expect_comma_or_end = false;
} else if expect_comma_or_end {
return Err(Expected(vec!(TPunctuator(PComma), TPunctuator(PCloseParen)), token, "function call arguments"));
} else {
let parsed = try!(self.parse());
self.pos -= 1;
args.push(parsed);
expect_comma_or_end = true;
}
}
result = mk!(self, CallExpr(box expr, args));
},
TPunctuator(PQuestion) => {
self.pos += 1;
let if_e = try!(self.parse());
try!(self.expect(TPunctuator(PColon), "if expression"));
let else_e = try!(self.parse());
result = mk!(self, IfExpr(box expr, box if_e, Some(box else_e)));
},
TPunctuator(POpenBracket) => {
self.pos += 1;
let index = try!(self.parse());
try!(self.expect(TPunctuator(PCloseBracket), "array index"));
result = mk!(self, GetFieldExpr(box expr, box index));
},
TPunctuator(PSemicolon) | TComment(_) => {
self.pos += 1;
},
TPunctuator(PAssign) => {
self.pos += 1;
let next = try!(self.parse());
result = mk!(self, AssignExpr(box expr, box next));
},
TPunctuator(PArrow) => {
self.pos += 1;
let mut args = Vec::with_capacity(1);
match result.def {
LocalExpr(name) => args.push(name),
_ => return Err(ExpectedExpr("identifier", result))
}
let next = try!(self.parse());
result = mk!(self, ArrowFunctionDeclExpr(args, box next));
},
TPunctuator(PAdd) =>
result = try!(self.binop(BinNum(OpAdd), expr)),
TPunctuator(PSub) =>
result = try!(self.binop(BinNum(OpSub), expr)),
TPunctuator(PMul) =>
result = try!(self.binop(BinNum(OpMul), expr)),
TPunctuator(PDiv) =>
result = try!(self.binop(BinNum(OpDiv), expr)),
TPunctuator(PMod) =>
result = try!(self.binop(BinNum(OpMod), expr)),
TPunctuator(PBoolAnd) =>
result = try!(self.binop(BinLog(LogAnd), expr)),
TPunctuator(PBoolOr) =>
result = try!(self.binop(BinLog(LogOr), expr)),
TPunctuator(PAnd) =>
result = try!(self.binop(BinBit(BitAnd), expr)),
TPunctuator(POr) =>
result = try!(self.binop(BinBit(BitOr), expr)),
TPunctuator(PXor) =>
result = try!(self.binop(BinBit(BitXor), expr)),
TPunctuator(PLeftSh) =>
result = try!(self.binop(BinBit(BitShl), expr)),
TPunctuator(PRightSh) =>
result = try!(self.binop(BinBit(BitShr), expr)),
TPunctuator(PEq) =>
result = try!(self.binop(BinComp(CompEqual), expr)),
TPunctuator(PNotEq) =>
result = try!(self.binop(BinComp(CompNotEqual), expr)),
TPunctuator(PStrictEq) =>
result = try!(self.binop(BinComp(CompStrictEqual), expr)),
TPunctuator(PStrictNotEq) =>
result = try!(self.binop(BinComp(CompStrictNotEqual), expr)),
TPunctuator(PLessThan) =>
result = try!(self.binop(BinComp(CompLessThan), expr)),
TPunctuator(PLessThanOrEq) =>
result = try!(self.binop(BinComp(CompLessThanOrEqual), expr)),
TPunctuator(PGreaterThan) =>
result = try!(self.binop(BinComp(CompGreaterThan), expr)),
TPunctuator(PGreaterThanOrEq) =>
result = try!(self.binop(BinComp(CompGreaterThanOrEqual), expr)),
TPunctuator(PInc) =>
result = mk!(self, UnaryOpExpr(UnaryIncrementPost, box try!(self.parse()))),
TPunctuator(PDec) =>
result = mk!(self, UnaryOpExpr(UnaryDecrementPost, box try!(self.parse()))),
_ => carry_on = false
};
if carry_on && self.pos < self.tokens.len() {
self.parse_next(result)
} else {
Ok(result)
}
}
fn binop(&mut self, op:BinOp, orig:Expr) -> Result<Expr, ParseError> {
let (precedence, assoc) = op.get_precedence_and_assoc();
self.pos += 1;
let next = try!(self.parse());
Ok(match next.def {
BinOpExpr(ref op2, ref a, ref b) => {
let other_precedence = op2.get_precedence();
if precedence < other_precedence || (precedence == other_precedence && !assoc) {
mk!(self, BinOpExpr(*op2, b.clone(), box mk!(self, BinOpExpr(op.clone(), box orig, a.clone()))))
} else {
mk!(self, BinOpExpr(op, box orig, box next.clone()))
}
},
_ => mk!(self, BinOpExpr(op, box orig, box next))
})
}
/// Returns an error if the next symbol is not `tk`
fn expect(&mut self, tk:TokenData, routine:&'static str) -> Result<(), ParseError> {
self.pos += 1;
let curr_tk = try!(self.get_token(self.pos - 1));
if curr_tk.data != tk {
Err(Expected(vec!(tk), curr_tk, routine))
} else {
Ok(())
}
}
/// Returns an error if the next symbol is not the punctuator `p`
#[inline(always)]
fn expect_punc(&mut self, p:Punctuator, routine:&'static str) -> Result<(), ParseError> {
self.expect(TPunctuator(p), routine)
}
}
| 47.879061 | 198 | 0.464279 |
26bb6d62b5acde0a77e1e4a056eb7b12990fdcf1
| 8,053 |
use super::Actor;
use std::mem;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct ActorToken(pub char);
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct ActorPosition(pub i32, pub i32);
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct ActorIndex {
pub id: usize,
pub generation: usize,
}
#[derive(Debug)]
pub struct NextIndex(ActorIndex);
impl NextIndex {
pub fn index(&self) -> ActorIndex {
self.0
}
}
enum Slot<A: ?Sized> {
Free { next_free: Option<usize> },
Full { actor: Box<A>, generation: usize },
}
/// Manages all the actors for the game by hashing actors by id
pub struct ActorManager<A: Actor + ?Sized> {
slots: Vec<Slot<A>>,
free_top: Option<usize>,
generation: usize,
size: usize,
}
impl<A: Actor + ?Sized> Default for ActorManager<A> {
fn default() -> ActorManager<A> {
ActorManager::new()
}
}
impl<A: Actor + ?Sized> ActorManager<A> {
pub fn new() -> ActorManager<A> {
ActorManager {
slots: Vec::new(),
free_top: None,
generation: 0,
size: 0,
}
}
pub fn with_capacity(capacity: usize) -> ActorManager<A> {
ActorManager {
slots: Vec::with_capacity(capacity),
free_top: None,
generation: 0,
size: 0,
}
}
/// Removes the next index from the manager and returns it.
pub fn next_index(&mut self) -> NextIndex {
let id = match self.free_top.take() {
Some(top) => top,
None => self.slots.len(),
};
NextIndex(ActorIndex {
id,
generation: self.generation,
})
}
/// Adds a new actor into the manager.
///
/// The index passed in must be the result of next_index().
pub fn add(&mut self, NextIndex(index): NextIndex, actor: Box<A>) {
let actor_slot = Slot::Full {
actor,
generation: index.generation,
};
let id = index.id;
if id == self.slots.len() {
self.slots.push(actor_slot);
} else {
if let Some(Slot::Free { next_free }) = self.slots.get(id) {
self.free_top = *next_free;
}
mem::replace(&mut self.slots[id], actor_slot);
}
self.size += 1;
}
/// Removes an actor from the manager.
pub fn remove(&mut self, index: ActorIndex) {
let id = index.id;
match self.slots.get(id) {
Some(Slot::Free { .. }) => return,
Some(Slot::Full { generation, .. }) if *generation != index.generation => return,
None => return,
_ => {}
}
mem::replace(
&mut self.slots[id],
Slot::Free {
next_free: self.free_top.take(),
},
);
self.free_top = Some(id);
self.generation += 1;
self.size -= 1;
}
pub fn values_mut(&mut self) -> impl Iterator<Item = &mut A> {
self.slots.iter_mut().filter_map(|slot| match slot {
Slot::Full { actor, .. } => Some(&mut **actor),
_ => None,
})
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (ActorIndex, &mut A)> {
self.slots
.iter_mut()
.enumerate()
.filter_map(|(id, slot)| match slot {
Slot::Full { actor, generation } => Some((
ActorIndex {
id,
generation: *generation,
},
&mut **actor,
)),
_ => None,
})
}
/// Get a mutable reference to an actor given the id
pub fn get_mut(&mut self, index: ActorIndex) -> Option<&mut A> {
match self.slots.get_mut(index.id) {
Some(Slot::Full { actor, generation }) if *generation == index.generation => {
Some(&mut **actor)
}
_ => None,
}
}
pub fn len(&self) -> usize {
self.size
}
pub fn capacity(&self) -> usize {
self.slots.capacity()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Attempts to send a message to an actor and returns either
/// the response or a given default message if the actor can't be found
pub fn apply_message(
&mut self,
actor_id: ActorIndex,
msg: &A::Message,
none: A::Message,
) -> A::Message {
self.get_mut(actor_id)
.map_or(none, |actor| actor.handle_message(msg))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::collision::CollisionSide;
use crate::context::Context;
use crate::vector::PositionChange;
use crate::viewport::Viewport;
use crate::ActorData;
use sdl2::rect::Rect;
use sdl2::render::Renderer;
use std::error::Error;
#[derive(Debug, Clone, PartialEq)]
struct TestActor(ActorIndex);
impl Actor for TestActor {
type Type = ();
type Message = ();
fn handle_message(&mut self, _message: &()) -> () {
()
}
fn collides_with(&mut self, _other: &ActorData<()>) -> Option<CollisionSide> {
None
}
fn update(&mut self, _context: &mut Context, _elapsed: f64) -> PositionChange {
PositionChange {
x: 0,
y: 0,
w: 0,
h: 0,
}
}
fn render(
&mut self,
_context: &mut Context,
_viewport: &mut Viewport,
_elapsed: f64,
) -> Result<(), Box<Error>> {
Ok(())
}
fn data(&mut self) -> ActorData<Self::Type> {
ActorData {
index: self.0,
state: 0,
damage: 0,
collision_filter: 0,
resolves_collisions: false,
rect: Rect::new(0, 0, 0, 0),
bounding_box: None,
actor_type: (),
}
}
}
fn actor_from_token(
_token: ActorToken,
index: ActorIndex,
_position: ActorPosition,
_renderer: &mut Renderer,
) -> Box<Actor<Type = (), Message = ()>> {
Box::new(TestActor(index))
}
#[test]
fn test_insert_and_remove() {
let mut manager = ActorManager::with_capacity(100);
let mut indexes = Vec::new();
for _ in 0..100 {
let next_index = manager.next_index();
let index = next_index.index();
manager.add(next_index, Box::new(TestActor(index)));
indexes.push(index);
}
for i in indexes.iter().take(50) {
assert!(manager.get_mut(*i).is_some());
manager.remove(*i);
assert_eq!(manager.get_mut(*i), None);
}
for _ in 0..50 {
let next_index = manager.next_index();
let index = next_index.index();
manager.add(next_index, Box::new(TestActor(index)));
}
assert_eq!(manager.len(), 100);
assert_eq!(manager.capacity(), 100);
let mut count = 0;
manager.values_mut().for_each(|_| count += 1);
assert_eq!(count, 100);
}
#[test]
fn test_stale_index() {
let mut manager = ActorManager::new();
let index;
let next_index = manager.next_index();
index = next_index.index();
manager.add(next_index, Box::new(TestActor(index)));
assert!(manager.get_mut(index).is_some());
// After replacing the value, you shouldn't be able to read
// from the old index.
manager.remove(index);
let next_index = manager.next_index();
let new_index = next_index.index();
assert_eq!(index.id, new_index.id);
manager.add(next_index, Box::new(TestActor(new_index)));
assert!(manager.get_mut(new_index).is_some());
assert_eq!(manager.get_mut(index), None);
}
}
| 27.578767 | 93 | 0.513597 |
eb0226e5052440dc451665748b5a3708bf0ae65b
| 8,618 |
//! Generic ASN.1 decoding framework.
use alloc::{boxed::Box, vec::Vec};
use core::convert::TryInto;
use crate::types::{self, AsnType, Tag};
pub use nom::Needed;
pub use rasn_derive::Decode;
/// A **data type** that can decoded from any ASN.1 format.
pub trait Decode: Sized + AsnType {
/// Decode this value from a given ASN.1 decoder.
///
/// **Note for implementors** You typically do not need to implement this.
/// The default implementation will call `Decode::decode_with_tag` with
/// your types associated `AsnType::TAG`. You should only ever need to
/// implement this if you have a type that *cannot* be implicitly tagged,
/// such as a `CHOICE` type, which case you want to implement the decoding
/// in `decode`.
fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, D::Error> {
Self::decode_with_tag(decoder, Self::TAG)
}
/// Decode this value implicitly tagged with `tag` from a given ASN.1 decoder.
///
/// **Note** For `CHOICE` and other types that cannot be implicitly tagged
/// this will **explicitly tag** the value, for all other types, it will
/// **implicitly** tag the value.
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error>;
}
/// A **data format** decode any ASN.1 data type.
pub trait Decoder: Sized {
type Error: Error;
/// Peek at the next available tag.
fn peek_tag(&self) -> Result<Tag, Self::Error>;
/// Decode a unknown ASN.1 value identified by `tag` from the available input.
fn decode_any(&mut self, tag: Tag) -> Result<Vec<u8>, Self::Error>;
/// Decode a `BIT STRING` identified by `tag` from the available input.
fn decode_bit_string(&mut self, tag: Tag) -> Result<types::BitString, Self::Error>;
/// Decode a `BOOL` identified by `tag` from the available input.
fn decode_bool(&mut self, tag: Tag) -> Result<bool, Self::Error>;
/// Decode an enumerated enum's discriminant identified by `tag` from the available input.
fn decode_enumerated(&mut self, tag: Tag) -> Result<types::Integer, Self::Error>;
/// Decode a `INTEGER` identified by `tag` from the available input.
fn decode_integer(&mut self, tag: Tag) -> Result<types::Integer, Self::Error>;
/// Decode `NULL` identified by `tag` from the available input.
fn decode_null(&mut self, tag: Tag) -> Result<(), Self::Error>;
/// Decode a `OBJECT IDENTIFIER` identified by `tag` from the available input.
fn decode_object_identifier(
&mut self,
tag: Tag,
) -> Result<types::ObjectIdentifier, Self::Error>;
/// Decode a `SEQUENCE` identified by `tag` from the available input. Returning
/// a new `Decoder` containing the sequence's contents to be decoded.
fn decode_sequence<D, F>(&mut self, tag: Tag, decode_fn: F) -> Result<D, Self::Error>
where
F: FnOnce(&mut Self) -> Result<D, Self::Error>;
/// Decode a `SEQUENCE OF D` where `D: Decode` identified by `tag` from the available input.
fn decode_sequence_of<D: Decode>(&mut self, tag: Tag) -> Result<Vec<D>, Self::Error>;
/// Decode a `OCTET STRING` identified by `tag` from the available input.
fn decode_octet_string(&mut self, tag: Tag) -> Result<Vec<u8>, Self::Error>;
/// Decode a `UTF8 STRING` identified by `tag` from the available input.
fn decode_utf8_string(&mut self, tag: Tag) -> Result<types::Utf8String, Self::Error>;
/// Decode an ASN.1 value that has been explicitly prefixed with `tag` from the available input.
fn decode_explicit_prefix<D: Decode>(&mut self, tag: Tag) -> Result<D, Self::Error>;
/// Decode a `UtcTime` identified by `tag` from the available input.
fn decode_utc_time(&mut self, tag: Tag) -> Result<types::UtcTime, Self::Error>;
/// Decode a `GeneralizedTime` identified by `tag` from the available input.
fn decode_generalized_time(&mut self, tag: Tag) -> Result<types::GeneralizedTime, Self::Error>;
/// Decode a `OBJECT IDENTIFIER` identified by `tag` from the available input.
/// This is a specialisation of [`Self::decode_object_identifier`] for
/// formats where you can zero copy the input.
fn decode_oid<'de>(&'de mut self, _tag: Tag) -> Result<&'de types::Oid, Self::Error> {
Err(Self::Error::custom(
"This format does not support losslessly decoding object identifiers.",
))
}
}
/// A generic error that can occur while decoding ASN.1.
pub trait Error: core::fmt::Display {
/// Creates a new general error using `msg` when decoding ASN.1.
fn custom<D: core::fmt::Display>(msg: D) -> Self;
/// Creates a new error about needing more data to finish parsing.
fn incomplete(needed: Needed) -> Self;
/// Creates a new error about exceeding the maximum allowed data for a type.
fn exceeds_max_length(length: usize) -> Self;
}
impl Decode for () {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
decoder.decode_null(tag)
}
}
impl<D: Decode> Decode for Option<D> {
fn decode_with_tag<DE: Decoder>(decoder: &mut DE, tag: Tag) -> Result<Self, DE::Error> {
if decoder.peek_tag().map_or(false, |t| t == tag) {
D::decode_with_tag(decoder, tag).map(Some)
} else {
Ok(None)
}
}
}
impl Decode for bool {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
decoder.decode_bool(tag)
}
}
macro_rules! impl_integers {
($($int:ty),+ $(,)?) => {
$(
impl Decode for $int {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
core::convert::TryInto::try_into(decoder.decode_integer(tag)?)
.map_err(Error::custom)
}
}
)+
}
}
impl_integers! {
i8,
i16,
i32,
i64,
i128,
isize,
u8,
u16,
u32,
u64,
u128,
usize,
}
impl<T: Decode> Decode for Box<T> {
fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, D::Error> {
T::decode(decoder).map(Box::new)
}
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
T::decode_with_tag(decoder, tag).map(Box::new)
}
}
impl Decode for types::Integer {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
decoder.decode_integer(tag)
}
}
impl Decode for types::OctetString {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
decoder.decode_octet_string(tag).map(Self::from)
}
}
impl Decode for types::ObjectIdentifier {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
decoder.decode_object_identifier(tag)
}
}
impl Decode for types::BitString {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
decoder.decode_bit_string(tag)
}
}
impl Decode for types::Utf8String {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
decoder.decode_utf8_string(tag)
}
}
impl Decode for types::UtcTime {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
decoder.decode_utc_time(tag)
}
}
impl Decode for types::GeneralizedTime {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
decoder.decode_generalized_time(tag)
}
}
impl<T: Decode> Decode for alloc::vec::Vec<T> {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
decoder.decode_sequence_of(tag)
}
}
impl<T: Decode + Default, const N: usize> Decode for [T; N] {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
let sequence = decoder.decode_sequence_of(tag)?;
sequence.try_into().map_err(|seq: Vec<_>| {
Error::custom(alloc::format!(
"Incorrect number of items provided. Expected {}, Actual {}.",
N,
seq.len()
))
})
}
}
impl<T: AsnType, V: Decode> Decode for types::Implicit<T, V> {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
Ok(Self::new(V::decode_with_tag(decoder, tag)?))
}
}
impl<T: AsnType, V: Decode> Decode for types::Explicit<T, V> {
fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
Ok(Self::new(decoder.decode_explicit_prefix(tag)?))
}
}
| 37.798246 | 100 | 0.634254 |
08d2a048528d39d13a5fa4b965263d4fde78b21b
| 745 |
// F32
#[inline]
pub extern "C" fn ceilf32(x: f32) -> f32 {
x.ceil()
}
#[inline]
pub extern "C" fn floorf32(x: f32) -> f32 {
x.floor()
}
#[inline]
pub extern "C" fn truncf32(x: f32) -> f32 {
x.trunc()
}
#[inline]
pub extern "C" fn nearbyintf32(x: f32) -> f32 {
x.round()
}
// F64
#[inline]
pub extern "C" fn ceilf64(x: f64) -> f64 {
x.ceil()
}
#[inline]
pub extern "C" fn floorf64(x: f64) -> f64 {
x.floor()
}
#[inline]
pub extern "C" fn truncf64(x: f64) -> f64 {
x.trunc()
}
#[inline]
pub extern "C" fn nearbyintf64(x: f64) -> f64 {
x.round()
}
/// A declaration for the stack probe function in Rust's standard library, for
/// catching callstack overflow.
extern "C" {
pub fn __rust_probestack();
}
| 15.520833 | 78 | 0.586577 |
f8c6624d179fc5a5197314438d859b7c1a353ef4
| 1,473 |
use std::cmp;
use std::fmt;
use std::ops;
use num;
use math::common::LinearInterpolate;
pub type IntScalar = i32;
#[cfg(not(feature = "float64"))]
pub type FloatScalar = f32;
#[cfg(feature = "float64")]
pub type FloatScalar = f64;
pub trait BaseNum where
Self: Copy + Clone + fmt::Debug + cmp::PartialOrd,
Self: num::Num + num::NumCast + num::ToPrimitive,
Self: ops::AddAssign + ops::SubAssign + ops::MulAssign + ops::DivAssign {}
pub trait BaseFloat: BaseNum + num::Float + num::Signed {}
pub trait BaseInt: BaseNum {}
impl BaseNum for i8 {}
impl BaseNum for i16 {}
impl BaseNum for i32 {}
impl BaseNum for i64 {}
impl BaseNum for isize {}
impl BaseNum for u8 {}
impl BaseNum for u16 {}
impl BaseNum for u32 {}
impl BaseNum for u64 {}
impl BaseNum for usize {}
impl BaseNum for f32 {}
impl BaseNum for f64 {}
impl BaseInt for i8 {}
impl BaseInt for i16 {}
impl BaseInt for i32 {}
impl BaseInt for i64 {}
impl BaseInt for isize {}
impl BaseInt for u8 {}
impl BaseInt for u16 {}
impl BaseInt for u32 {}
impl BaseInt for u64 {}
impl BaseInt for usize {}
impl BaseFloat for f32 {}
impl BaseFloat for f64 {}
pub fn partial_min<T: cmp::PartialOrd>(a: T, b: T) -> T {
if a < b {
a
} else {
b
}
}
pub fn partial_max<T: cmp::PartialOrd>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
impl LinearInterpolate for f32 {
type Scalar = f32;
}
impl LinearInterpolate for f64 {
type Scalar = f64;
}
| 19.905405 | 78 | 0.644942 |
4b8671df32736c3576b865d23d062d64fef69915
| 37,554 |
#[doc = "Register `FIFO` reader"]
pub struct R(crate::R<FIFO_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<FIFO_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<FIFO_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<FIFO_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `FIFO` writer"]
pub struct W(crate::W<FIFO_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<FIFO_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<FIFO_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<FIFO_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Receive FIFO. Buffer Depth\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum RXFIFOSIZE_A {
#[doc = "0: Receive FIFO/Buffer depth = 1 dataword."]
_000 = 0,
#[doc = "1: Receive FIFO/Buffer depth = 4 datawords."]
_001 = 1,
#[doc = "2: Receive FIFO/Buffer depth = 8 datawords."]
_010 = 2,
#[doc = "3: Receive FIFO/Buffer depth = 16 datawords."]
_011 = 3,
#[doc = "4: Receive FIFO/Buffer depth = 32 datawords."]
_100 = 4,
#[doc = "5: Receive FIFO/Buffer depth = 64 datawords."]
_101 = 5,
#[doc = "6: Receive FIFO/Buffer depth = 128 datawords."]
_110 = 6,
#[doc = "7: Receive FIFO/Buffer depth = 256 datawords."]
_111 = 7,
}
impl From<RXFIFOSIZE_A> for u8 {
#[inline(always)]
fn from(variant: RXFIFOSIZE_A) -> Self {
variant as _
}
}
#[doc = "Field `RXFIFOSIZE` reader - Receive FIFO. Buffer Depth"]
pub struct RXFIFOSIZE_R(crate::FieldReader<u8, RXFIFOSIZE_A>);
impl RXFIFOSIZE_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
RXFIFOSIZE_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RXFIFOSIZE_A {
match self.bits {
0 => RXFIFOSIZE_A::_000,
1 => RXFIFOSIZE_A::_001,
2 => RXFIFOSIZE_A::_010,
3 => RXFIFOSIZE_A::_011,
4 => RXFIFOSIZE_A::_100,
5 => RXFIFOSIZE_A::_101,
6 => RXFIFOSIZE_A::_110,
7 => RXFIFOSIZE_A::_111,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `_000`"]
#[inline(always)]
pub fn is_000(&self) -> bool {
**self == RXFIFOSIZE_A::_000
}
#[doc = "Checks if the value of the field is `_001`"]
#[inline(always)]
pub fn is_001(&self) -> bool {
**self == RXFIFOSIZE_A::_001
}
#[doc = "Checks if the value of the field is `_010`"]
#[inline(always)]
pub fn is_010(&self) -> bool {
**self == RXFIFOSIZE_A::_010
}
#[doc = "Checks if the value of the field is `_011`"]
#[inline(always)]
pub fn is_011(&self) -> bool {
**self == RXFIFOSIZE_A::_011
}
#[doc = "Checks if the value of the field is `_100`"]
#[inline(always)]
pub fn is_100(&self) -> bool {
**self == RXFIFOSIZE_A::_100
}
#[doc = "Checks if the value of the field is `_101`"]
#[inline(always)]
pub fn is_101(&self) -> bool {
**self == RXFIFOSIZE_A::_101
}
#[doc = "Checks if the value of the field is `_110`"]
#[inline(always)]
pub fn is_110(&self) -> bool {
**self == RXFIFOSIZE_A::_110
}
#[doc = "Checks if the value of the field is `_111`"]
#[inline(always)]
pub fn is_111(&self) -> bool {
**self == RXFIFOSIZE_A::_111
}
}
impl core::ops::Deref for RXFIFOSIZE_R {
type Target = crate::FieldReader<u8, RXFIFOSIZE_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Receive FIFO Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RXFE_A {
#[doc = "0: Receive FIFO is not enabled. Buffer is depth 1. (Legacy support)"]
_0 = 0,
#[doc = "1: Receive FIFO is enabled. Buffer is depth indicted by RXFIFOSIZE."]
_1 = 1,
}
impl From<RXFE_A> for bool {
#[inline(always)]
fn from(variant: RXFE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `RXFE` reader - Receive FIFO Enable"]
pub struct RXFE_R(crate::FieldReader<bool, RXFE_A>);
impl RXFE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
RXFE_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RXFE_A {
match self.bits {
false => RXFE_A::_0,
true => RXFE_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
**self == RXFE_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
**self == RXFE_A::_1
}
}
impl core::ops::Deref for RXFE_R {
type Target = crate::FieldReader<bool, RXFE_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `RXFE` writer - Receive FIFO Enable"]
pub struct RXFE_W<'a> {
w: &'a mut W,
}
impl<'a> RXFE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RXFE_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Receive FIFO is not enabled. Buffer is depth 1. (Legacy support)"]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(RXFE_A::_0)
}
#[doc = "Receive FIFO is enabled. Buffer is depth indicted by RXFIFOSIZE."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(RXFE_A::_1)
}
#[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 = "Transmit FIFO. Buffer Depth\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum TXFIFOSIZE_A {
#[doc = "0: Transmit FIFO/Buffer depth = 1 dataword."]
_000 = 0,
#[doc = "1: Transmit FIFO/Buffer depth = 4 datawords."]
_001 = 1,
#[doc = "2: Transmit FIFO/Buffer depth = 8 datawords."]
_010 = 2,
#[doc = "3: Transmit FIFO/Buffer depth = 16 datawords."]
_011 = 3,
#[doc = "4: Transmit FIFO/Buffer depth = 32 datawords."]
_100 = 4,
#[doc = "5: Transmit FIFO/Buffer depth = 64 datawords."]
_101 = 5,
#[doc = "6: Transmit FIFO/Buffer depth = 128 datawords."]
_110 = 6,
#[doc = "7: Transmit FIFO/Buffer depth = 256 datawords"]
_111 = 7,
}
impl From<TXFIFOSIZE_A> for u8 {
#[inline(always)]
fn from(variant: TXFIFOSIZE_A) -> Self {
variant as _
}
}
#[doc = "Field `TXFIFOSIZE` reader - Transmit FIFO. Buffer Depth"]
pub struct TXFIFOSIZE_R(crate::FieldReader<u8, TXFIFOSIZE_A>);
impl TXFIFOSIZE_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
TXFIFOSIZE_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TXFIFOSIZE_A {
match self.bits {
0 => TXFIFOSIZE_A::_000,
1 => TXFIFOSIZE_A::_001,
2 => TXFIFOSIZE_A::_010,
3 => TXFIFOSIZE_A::_011,
4 => TXFIFOSIZE_A::_100,
5 => TXFIFOSIZE_A::_101,
6 => TXFIFOSIZE_A::_110,
7 => TXFIFOSIZE_A::_111,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `_000`"]
#[inline(always)]
pub fn is_000(&self) -> bool {
**self == TXFIFOSIZE_A::_000
}
#[doc = "Checks if the value of the field is `_001`"]
#[inline(always)]
pub fn is_001(&self) -> bool {
**self == TXFIFOSIZE_A::_001
}
#[doc = "Checks if the value of the field is `_010`"]
#[inline(always)]
pub fn is_010(&self) -> bool {
**self == TXFIFOSIZE_A::_010
}
#[doc = "Checks if the value of the field is `_011`"]
#[inline(always)]
pub fn is_011(&self) -> bool {
**self == TXFIFOSIZE_A::_011
}
#[doc = "Checks if the value of the field is `_100`"]
#[inline(always)]
pub fn is_100(&self) -> bool {
**self == TXFIFOSIZE_A::_100
}
#[doc = "Checks if the value of the field is `_101`"]
#[inline(always)]
pub fn is_101(&self) -> bool {
**self == TXFIFOSIZE_A::_101
}
#[doc = "Checks if the value of the field is `_110`"]
#[inline(always)]
pub fn is_110(&self) -> bool {
**self == TXFIFOSIZE_A::_110
}
#[doc = "Checks if the value of the field is `_111`"]
#[inline(always)]
pub fn is_111(&self) -> bool {
**self == TXFIFOSIZE_A::_111
}
}
impl core::ops::Deref for TXFIFOSIZE_R {
type Target = crate::FieldReader<u8, TXFIFOSIZE_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Transmit FIFO Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TXFE_A {
#[doc = "0: Transmit FIFO is not enabled. Buffer is depth 1. (Legacy support)."]
_0 = 0,
#[doc = "1: Transmit FIFO is enabled. Buffer is depth indicated by TXFIFOSIZE."]
_1 = 1,
}
impl From<TXFE_A> for bool {
#[inline(always)]
fn from(variant: TXFE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `TXFE` reader - Transmit FIFO Enable"]
pub struct TXFE_R(crate::FieldReader<bool, TXFE_A>);
impl TXFE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
TXFE_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TXFE_A {
match self.bits {
false => TXFE_A::_0,
true => TXFE_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
**self == TXFE_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
**self == TXFE_A::_1
}
}
impl core::ops::Deref for TXFE_R {
type Target = crate::FieldReader<bool, TXFE_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `TXFE` writer - Transmit FIFO Enable"]
pub struct TXFE_W<'a> {
w: &'a mut W,
}
impl<'a> TXFE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TXFE_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Transmit FIFO is not enabled. Buffer is depth 1. (Legacy support)."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(TXFE_A::_0)
}
#[doc = "Transmit FIFO is enabled. Buffer is depth indicated by TXFIFOSIZE."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(TXFE_A::_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | ((value as u32 & 0x01) << 7);
self.w
}
}
#[doc = "Receive FIFO Underflow Interrupt Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RXUFE_A {
#[doc = "0: RXUF flag does not generate an interrupt to the host."]
_0 = 0,
#[doc = "1: RXUF flag generates an interrupt to the host."]
_1 = 1,
}
impl From<RXUFE_A> for bool {
#[inline(always)]
fn from(variant: RXUFE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `RXUFE` reader - Receive FIFO Underflow Interrupt Enable"]
pub struct RXUFE_R(crate::FieldReader<bool, RXUFE_A>);
impl RXUFE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
RXUFE_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RXUFE_A {
match self.bits {
false => RXUFE_A::_0,
true => RXUFE_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
**self == RXUFE_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
**self == RXUFE_A::_1
}
}
impl core::ops::Deref for RXUFE_R {
type Target = crate::FieldReader<bool, RXUFE_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `RXUFE` writer - Receive FIFO Underflow Interrupt Enable"]
pub struct RXUFE_W<'a> {
w: &'a mut W,
}
impl<'a> RXUFE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RXUFE_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "RXUF flag does not generate an interrupt to the host."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(RXUFE_A::_0)
}
#[doc = "RXUF flag generates an interrupt to the host."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(RXUFE_A::_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | ((value as u32 & 0x01) << 8);
self.w
}
}
#[doc = "Transmit FIFO Overflow Interrupt Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TXOFE_A {
#[doc = "0: TXOF flag does not generate an interrupt to the host."]
_0 = 0,
#[doc = "1: TXOF flag generates an interrupt to the host."]
_1 = 1,
}
impl From<TXOFE_A> for bool {
#[inline(always)]
fn from(variant: TXOFE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `TXOFE` reader - Transmit FIFO Overflow Interrupt Enable"]
pub struct TXOFE_R(crate::FieldReader<bool, TXOFE_A>);
impl TXOFE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
TXOFE_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TXOFE_A {
match self.bits {
false => TXOFE_A::_0,
true => TXOFE_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
**self == TXOFE_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
**self == TXOFE_A::_1
}
}
impl core::ops::Deref for TXOFE_R {
type Target = crate::FieldReader<bool, TXOFE_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `TXOFE` writer - Transmit FIFO Overflow Interrupt Enable"]
pub struct TXOFE_W<'a> {
w: &'a mut W,
}
impl<'a> TXOFE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TXOFE_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "TXOF flag does not generate an interrupt to the host."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(TXOFE_A::_0)
}
#[doc = "TXOF flag generates an interrupt to the host."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(TXOFE_A::_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | ((value as u32 & 0x01) << 9);
self.w
}
}
#[doc = "Receiver Idle Empty Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum RXIDEN_A {
#[doc = "0: Disable RDRF assertion due to partially filled FIFO when receiver is idle."]
_000 = 0,
#[doc = "1: Enable RDRF assertion due to partially filled FIFO when receiver is idle for 1 character."]
_001 = 1,
#[doc = "2: Enable RDRF assertion due to partially filled FIFO when receiver is idle for 2 characters."]
_010 = 2,
#[doc = "3: Enable RDRF assertion due to partially filled FIFO when receiver is idle for 4 characters."]
_011 = 3,
#[doc = "4: Enable RDRF assertion due to partially filled FIFO when receiver is idle for 8 characters."]
_100 = 4,
#[doc = "5: Enable RDRF assertion due to partially filled FIFO when receiver is idle for 16 characters."]
_101 = 5,
#[doc = "6: Enable RDRF assertion due to partially filled FIFO when receiver is idle for 32 characters."]
_110 = 6,
#[doc = "7: Enable RDRF assertion due to partially filled FIFO when receiver is idle for 64 characters."]
_111 = 7,
}
impl From<RXIDEN_A> for u8 {
#[inline(always)]
fn from(variant: RXIDEN_A) -> Self {
variant as _
}
}
#[doc = "Field `RXIDEN` reader - Receiver Idle Empty Enable"]
pub struct RXIDEN_R(crate::FieldReader<u8, RXIDEN_A>);
impl RXIDEN_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
RXIDEN_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RXIDEN_A {
match self.bits {
0 => RXIDEN_A::_000,
1 => RXIDEN_A::_001,
2 => RXIDEN_A::_010,
3 => RXIDEN_A::_011,
4 => RXIDEN_A::_100,
5 => RXIDEN_A::_101,
6 => RXIDEN_A::_110,
7 => RXIDEN_A::_111,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `_000`"]
#[inline(always)]
pub fn is_000(&self) -> bool {
**self == RXIDEN_A::_000
}
#[doc = "Checks if the value of the field is `_001`"]
#[inline(always)]
pub fn is_001(&self) -> bool {
**self == RXIDEN_A::_001
}
#[doc = "Checks if the value of the field is `_010`"]
#[inline(always)]
pub fn is_010(&self) -> bool {
**self == RXIDEN_A::_010
}
#[doc = "Checks if the value of the field is `_011`"]
#[inline(always)]
pub fn is_011(&self) -> bool {
**self == RXIDEN_A::_011
}
#[doc = "Checks if the value of the field is `_100`"]
#[inline(always)]
pub fn is_100(&self) -> bool {
**self == RXIDEN_A::_100
}
#[doc = "Checks if the value of the field is `_101`"]
#[inline(always)]
pub fn is_101(&self) -> bool {
**self == RXIDEN_A::_101
}
#[doc = "Checks if the value of the field is `_110`"]
#[inline(always)]
pub fn is_110(&self) -> bool {
**self == RXIDEN_A::_110
}
#[doc = "Checks if the value of the field is `_111`"]
#[inline(always)]
pub fn is_111(&self) -> bool {
**self == RXIDEN_A::_111
}
}
impl core::ops::Deref for RXIDEN_R {
type Target = crate::FieldReader<u8, RXIDEN_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `RXIDEN` writer - Receiver Idle Empty Enable"]
pub struct RXIDEN_W<'a> {
w: &'a mut W,
}
impl<'a> RXIDEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RXIDEN_A) -> &'a mut W {
self.bits(variant.into())
}
#[doc = "Disable RDRF assertion due to partially filled FIFO when receiver is idle."]
#[inline(always)]
pub fn _000(self) -> &'a mut W {
self.variant(RXIDEN_A::_000)
}
#[doc = "Enable RDRF assertion due to partially filled FIFO when receiver is idle for 1 character."]
#[inline(always)]
pub fn _001(self) -> &'a mut W {
self.variant(RXIDEN_A::_001)
}
#[doc = "Enable RDRF assertion due to partially filled FIFO when receiver is idle for 2 characters."]
#[inline(always)]
pub fn _010(self) -> &'a mut W {
self.variant(RXIDEN_A::_010)
}
#[doc = "Enable RDRF assertion due to partially filled FIFO when receiver is idle for 4 characters."]
#[inline(always)]
pub fn _011(self) -> &'a mut W {
self.variant(RXIDEN_A::_011)
}
#[doc = "Enable RDRF assertion due to partially filled FIFO when receiver is idle for 8 characters."]
#[inline(always)]
pub fn _100(self) -> &'a mut W {
self.variant(RXIDEN_A::_100)
}
#[doc = "Enable RDRF assertion due to partially filled FIFO when receiver is idle for 16 characters."]
#[inline(always)]
pub fn _101(self) -> &'a mut W {
self.variant(RXIDEN_A::_101)
}
#[doc = "Enable RDRF assertion due to partially filled FIFO when receiver is idle for 32 characters."]
#[inline(always)]
pub fn _110(self) -> &'a mut W {
self.variant(RXIDEN_A::_110)
}
#[doc = "Enable RDRF assertion due to partially filled FIFO when receiver is idle for 64 characters."]
#[inline(always)]
pub fn _111(self) -> &'a mut W {
self.variant(RXIDEN_A::_111)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 10)) | ((value as u32 & 0x07) << 10);
self.w
}
}
#[doc = "Receive FIFO/Buffer Flush\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RXFLUSH_AW {
#[doc = "0: No flush operation occurs."]
_0 = 0,
#[doc = "1: All data in the receive FIFO/buffer is cleared out."]
_1 = 1,
}
impl From<RXFLUSH_AW> for bool {
#[inline(always)]
fn from(variant: RXFLUSH_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `RXFLUSH` writer - Receive FIFO/Buffer Flush"]
pub struct RXFLUSH_W<'a> {
w: &'a mut W,
}
impl<'a> RXFLUSH_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RXFLUSH_AW) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "No flush operation occurs."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(RXFLUSH_AW::_0)
}
#[doc = "All data in the receive FIFO/buffer is cleared out."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(RXFLUSH_AW::_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | ((value as u32 & 0x01) << 14);
self.w
}
}
#[doc = "Transmit FIFO/Buffer Flush\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TXFLUSH_AW {
#[doc = "0: No flush operation occurs."]
_0 = 0,
#[doc = "1: All data in the transmit FIFO/Buffer is cleared out."]
_1 = 1,
}
impl From<TXFLUSH_AW> for bool {
#[inline(always)]
fn from(variant: TXFLUSH_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `TXFLUSH` writer - Transmit FIFO/Buffer Flush"]
pub struct TXFLUSH_W<'a> {
w: &'a mut W,
}
impl<'a> TXFLUSH_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TXFLUSH_AW) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "No flush operation occurs."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(TXFLUSH_AW::_0)
}
#[doc = "All data in the transmit FIFO/Buffer is cleared out."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(TXFLUSH_AW::_1)
}
#[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 << 15)) | ((value as u32 & 0x01) << 15);
self.w
}
}
#[doc = "Receiver Buffer Underflow Flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RXUF_A {
#[doc = "0: No receive buffer underflow has occurred since the last time the flag was cleared."]
_0 = 0,
#[doc = "1: At least one receive buffer underflow has occurred since the last time the flag was cleared."]
_1 = 1,
}
impl From<RXUF_A> for bool {
#[inline(always)]
fn from(variant: RXUF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `RXUF` reader - Receiver Buffer Underflow Flag"]
pub struct RXUF_R(crate::FieldReader<bool, RXUF_A>);
impl RXUF_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
RXUF_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RXUF_A {
match self.bits {
false => RXUF_A::_0,
true => RXUF_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
**self == RXUF_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
**self == RXUF_A::_1
}
}
impl core::ops::Deref for RXUF_R {
type Target = crate::FieldReader<bool, RXUF_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `RXUF` writer - Receiver Buffer Underflow Flag"]
pub struct RXUF_W<'a> {
w: &'a mut W,
}
impl<'a> RXUF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RXUF_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "No receive buffer underflow has occurred since the last time the flag was cleared."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(RXUF_A::_0)
}
#[doc = "At least one receive buffer underflow has occurred since the last time the flag was cleared."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(RXUF_A::_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | ((value as u32 & 0x01) << 16);
self.w
}
}
#[doc = "Transmitter Buffer Overflow Flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TXOF_A {
#[doc = "0: No transmit buffer overflow has occurred since the last time the flag was cleared."]
_0 = 0,
#[doc = "1: At least one transmit buffer overflow has occurred since the last time the flag was cleared."]
_1 = 1,
}
impl From<TXOF_A> for bool {
#[inline(always)]
fn from(variant: TXOF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `TXOF` reader - Transmitter Buffer Overflow Flag"]
pub struct TXOF_R(crate::FieldReader<bool, TXOF_A>);
impl TXOF_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
TXOF_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TXOF_A {
match self.bits {
false => TXOF_A::_0,
true => TXOF_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
**self == TXOF_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
**self == TXOF_A::_1
}
}
impl core::ops::Deref for TXOF_R {
type Target = crate::FieldReader<bool, TXOF_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `TXOF` writer - Transmitter Buffer Overflow Flag"]
pub struct TXOF_W<'a> {
w: &'a mut W,
}
impl<'a> TXOF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TXOF_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "No transmit buffer overflow has occurred since the last time the flag was cleared."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(TXOF_A::_0)
}
#[doc = "At least one transmit buffer overflow has occurred since the last time the flag was cleared."]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(TXOF_A::_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | ((value as u32 & 0x01) << 17);
self.w
}
}
#[doc = "Receive Buffer/FIFO Empty\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RXEMPT_A {
#[doc = "0: Receive buffer is not empty."]
_0 = 0,
#[doc = "1: Receive buffer is empty."]
_1 = 1,
}
impl From<RXEMPT_A> for bool {
#[inline(always)]
fn from(variant: RXEMPT_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `RXEMPT` reader - Receive Buffer/FIFO Empty"]
pub struct RXEMPT_R(crate::FieldReader<bool, RXEMPT_A>);
impl RXEMPT_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
RXEMPT_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RXEMPT_A {
match self.bits {
false => RXEMPT_A::_0,
true => RXEMPT_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
**self == RXEMPT_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
**self == RXEMPT_A::_1
}
}
impl core::ops::Deref for RXEMPT_R {
type Target = crate::FieldReader<bool, RXEMPT_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Transmit Buffer/FIFO Empty\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TXEMPT_A {
#[doc = "0: Transmit buffer is not empty."]
_0 = 0,
#[doc = "1: Transmit buffer is empty."]
_1 = 1,
}
impl From<TXEMPT_A> for bool {
#[inline(always)]
fn from(variant: TXEMPT_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `TXEMPT` reader - Transmit Buffer/FIFO Empty"]
pub struct TXEMPT_R(crate::FieldReader<bool, TXEMPT_A>);
impl TXEMPT_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
TXEMPT_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TXEMPT_A {
match self.bits {
false => TXEMPT_A::_0,
true => TXEMPT_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
**self == TXEMPT_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
**self == TXEMPT_A::_1
}
}
impl core::ops::Deref for TXEMPT_R {
type Target = crate::FieldReader<bool, TXEMPT_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:2 - Receive FIFO. Buffer Depth"]
#[inline(always)]
pub fn rxfifosize(&self) -> RXFIFOSIZE_R {
RXFIFOSIZE_R::new((self.bits & 0x07) as u8)
}
#[doc = "Bit 3 - Receive FIFO Enable"]
#[inline(always)]
pub fn rxfe(&self) -> RXFE_R {
RXFE_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bits 4:6 - Transmit FIFO. Buffer Depth"]
#[inline(always)]
pub fn txfifosize(&self) -> TXFIFOSIZE_R {
TXFIFOSIZE_R::new(((self.bits >> 4) & 0x07) as u8)
}
#[doc = "Bit 7 - Transmit FIFO Enable"]
#[inline(always)]
pub fn txfe(&self) -> TXFE_R {
TXFE_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - Receive FIFO Underflow Interrupt Enable"]
#[inline(always)]
pub fn rxufe(&self) -> RXUFE_R {
RXUFE_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - Transmit FIFO Overflow Interrupt Enable"]
#[inline(always)]
pub fn txofe(&self) -> TXOFE_R {
TXOFE_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bits 10:12 - Receiver Idle Empty Enable"]
#[inline(always)]
pub fn rxiden(&self) -> RXIDEN_R {
RXIDEN_R::new(((self.bits >> 10) & 0x07) as u8)
}
#[doc = "Bit 16 - Receiver Buffer Underflow Flag"]
#[inline(always)]
pub fn rxuf(&self) -> RXUF_R {
RXUF_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - Transmitter Buffer Overflow Flag"]
#[inline(always)]
pub fn txof(&self) -> TXOF_R {
TXOF_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 22 - Receive Buffer/FIFO Empty"]
#[inline(always)]
pub fn rxempt(&self) -> RXEMPT_R {
RXEMPT_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - Transmit Buffer/FIFO Empty"]
#[inline(always)]
pub fn txempt(&self) -> TXEMPT_R {
TXEMPT_R::new(((self.bits >> 23) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 3 - Receive FIFO Enable"]
#[inline(always)]
pub fn rxfe(&mut self) -> RXFE_W {
RXFE_W { w: self }
}
#[doc = "Bit 7 - Transmit FIFO Enable"]
#[inline(always)]
pub fn txfe(&mut self) -> TXFE_W {
TXFE_W { w: self }
}
#[doc = "Bit 8 - Receive FIFO Underflow Interrupt Enable"]
#[inline(always)]
pub fn rxufe(&mut self) -> RXUFE_W {
RXUFE_W { w: self }
}
#[doc = "Bit 9 - Transmit FIFO Overflow Interrupt Enable"]
#[inline(always)]
pub fn txofe(&mut self) -> TXOFE_W {
TXOFE_W { w: self }
}
#[doc = "Bits 10:12 - Receiver Idle Empty Enable"]
#[inline(always)]
pub fn rxiden(&mut self) -> RXIDEN_W {
RXIDEN_W { w: self }
}
#[doc = "Bit 14 - Receive FIFO/Buffer Flush"]
#[inline(always)]
pub fn rxflush(&mut self) -> RXFLUSH_W {
RXFLUSH_W { w: self }
}
#[doc = "Bit 15 - Transmit FIFO/Buffer Flush"]
#[inline(always)]
pub fn txflush(&mut self) -> TXFLUSH_W {
TXFLUSH_W { w: self }
}
#[doc = "Bit 16 - Receiver Buffer Underflow Flag"]
#[inline(always)]
pub fn rxuf(&mut self) -> RXUF_W {
RXUF_W { w: self }
}
#[doc = "Bit 17 - Transmitter Buffer Overflow Flag"]
#[inline(always)]
pub fn txof(&mut self) -> TXOF_W {
TXOF_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 = "LPUART FIFO 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 [fifo](index.html) module"]
pub struct FIFO_SPEC;
impl crate::RegisterSpec for FIFO_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [fifo::R](R) reader structure"]
impl crate::Readable for FIFO_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [fifo::W](W) writer structure"]
impl crate::Writable for FIFO_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets FIFO to value 0x00c0_0011"]
impl crate::Resettable for FIFO_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0x00c0_0011
}
}
| 30.908642 | 405 | 0.567636 |
ded7f3536258a63bdcdaed547b172c49ca8f2334
| 6,232 |
//! The `ping` command performs a ping operation.
use crate::cli::util::cluster_identifiers_from;
use crate::state::State;
use crate::client::ServiceType;
use async_trait::async_trait;
use log::debug;
use nu_engine::CommandArgs;
use nu_errors::ShellError;
use nu_protocol::{Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue};
use nu_source::Tag;
use nu_stream::OutputStream;
use std::ops::Add;
use std::sync::Arc;
use tokio::runtime::Runtime;
use tokio::time::Instant;
pub struct Ping {
state: Arc<State>,
}
impl Ping {
pub fn new(state: Arc<State>) -> Self {
Self { state }
}
}
#[async_trait]
impl nu_engine::WholeStreamCommand for Ping {
fn name(&self) -> &str {
"ping"
}
fn signature(&self) -> Signature {
Signature::build("ping")
.named(
"bucket",
SyntaxShape::String,
"the name of the bucket",
None,
)
.named(
"clusters",
SyntaxShape::String,
"the clusters which should be contacted",
None,
)
}
fn usage(&self) -> &str {
"Ping available services in the cluster"
}
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
run_ping(self.state.clone(), args)
}
}
fn run_ping(state: Arc<State>, args: CommandArgs) -> Result<OutputStream, ShellError> {
let ctrl_c = args.ctrl_c();
let args = args.evaluate_once()?;
let bucket_name = match args
.call_info
.args
.get("bucket")
.map(|id| id.as_string().ok())
.flatten()
.or_else(|| state.active_cluster().active_bucket())
{
Some(v) => v,
None => {
return Err(ShellError::untagged_runtime_error(format!(
"Could not auto-select a bucket - please use --bucket instead"
)))
}
};
let cluster_identifiers = cluster_identifiers_from(&state, &args, true)?;
debug!("Running ping");
let rt = Runtime::new().unwrap();
let clusters_len = cluster_identifiers.len();
let mut results = vec![];
for identifier in cluster_identifiers {
let cluster = match state.clusters().get(&identifier) {
Some(c) => c,
None => continue, //This can't actually happen, we filter the clusters in cluster_identifiers_from
};
let deadline = Instant::now().add(cluster.timeouts().query_timeout());
let result = cluster
.cluster()
.ping_all_http_request(deadline, ctrl_c.clone());
match result {
Ok(res) => {
for ping in res {
let tag = Tag::default();
let mut collected = TaggedDictBuilder::new(&tag);
if clusters_len > 1 {
collected.insert_value("cluster", identifier.clone());
}
collected.insert_value("service", ping.service().as_string());
collected.insert_value("remote", ping.address().to_string());
collected.insert_value(
"latency",
UntaggedValue::duration(ping.latency().as_nanos()).into_untagged_value(),
);
collected.insert_value("state", ping.state().to_string());
let error = match ping.error() {
Some(e) => e.to_string(),
None => "".into(),
};
collected.insert_value("error", error);
results.push(collected.into_value());
}
}
Err(_e) => {}
};
// TODO: do this in parallel to http ops.
let kv_deadline = Instant::now().add(cluster.timeouts().data_timeout());
let mut client = match cluster.cluster().key_value_client(
cluster.username().to_string(),
cluster.password().to_string(),
bucket_name.clone(),
"".into(),
"".into(),
kv_deadline.clone(),
ctrl_c.clone(),
) {
Ok(c) => c,
Err(e) => {
let tag = Tag::default();
let mut collected = TaggedDictBuilder::new(&tag);
if clusters_len > 1 {
collected.insert_value("cluster", identifier.clone());
}
collected.insert_value("service", ServiceType::KeyValue.as_string());
collected.insert_value("remote", "".to_string());
collected.insert_value("latency", "".to_string());
collected.insert_value("state", "error".to_string());
collected.insert_value("error", e.to_string());
results.push(collected.into_value());
continue;
}
};
let kv_result = rt.block_on(client.ping_all(kv_deadline.clone(), ctrl_c.clone()));
match kv_result {
Ok(res) => {
for ping in res {
let tag = Tag::default();
let mut collected = TaggedDictBuilder::new(&tag);
if clusters_len > 1 {
collected.insert_value("cluster", identifier.clone());
}
collected.insert_value("service", ping.service().as_string());
collected.insert_value("remote", ping.address().to_string());
collected.insert_value(
"latency",
UntaggedValue::duration(ping.latency().as_nanos()).into_untagged_value(),
);
collected.insert_value("state", ping.state().to_string());
let error = match ping.error() {
Some(e) => e.to_string(),
None => "".into(),
};
collected.insert_value("error", error);
results.push(collected.into_value());
}
}
Err(_e) => {}
};
}
Ok(OutputStream::from(results))
}
| 33.869565 | 110 | 0.508504 |
d667c58fbbef59048ca1a70394339041e3c2d95a
| 104 |
#[rustfmt::skip]
#[allow(clippy::all)]
#[path = "../../gen/registry/registry.subnet.v1.rs"]
pub mod v1;
| 20.8 | 52 | 0.634615 |
f4e270be025150303d4a83662852f74bb1775a96
| 796 |
use dotenv::vars as get_all_vars;
use std::collections::HashMap;
use std::net::Ipv4Addr;
pub(crate) struct AppConfig {
pub(crate) bind_ip: Ipv4Addr,
pub(crate) bind_port: u16,
}
impl AppConfig {
pub(crate) fn load_from_env() -> Self {
let all_vars: HashMap<String, String> = get_all_vars().collect();
let bind_ip;
let bind_port;
if !all_vars.contains_key("BIND_IP") {
bind_ip = "127.0.0.1".parse().unwrap();
} else {
bind_ip = all_vars.get("BIND_IP").unwrap().parse().unwrap();
}
if !all_vars.contains_key("BIND_PORT") {
bind_port = 8080;
} else {
bind_port = all_vars.get("BIND_PORT").unwrap().parse().unwrap();
}
Self { bind_ip, bind_port }
}
}
| 25.677419 | 76 | 0.575377 |
5d0b3608ec82898458f259bede3c1225e48a2c29
| 3,487 |
use std::time::Duration;
use serde::Deserialize;
use serde_aux::field_attributes::deserialize_number_from_string;
use sqlx::{
postgres::{PgConnectOptions, PgSslMode},
ConnectOptions,
};
use crate::domain::{self, EmailAddress};
#[derive(Deserialize)]
pub struct Settings {
pub database: DatabaseSettings,
pub application: ApplicationSettings,
pub email_client: EmailClientSettings,
}
#[derive(Deserialize)]
pub struct DatabaseSettings {
pub host: String,
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16,
pub username: String,
pub password: String,
pub name: String,
#[serde(default)]
pub require_ssl: bool,
}
#[derive(Deserialize)]
pub struct ApplicationSettings {
pub host: String,
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16,
pub base_url: String,
}
#[derive(Deserialize)]
pub struct EmailClientSettings {
pub base_url: String,
pub sender_email: String,
pub authorization_token: String,
pub timeout_milliseconds: u64,
}
impl DatabaseSettings {
pub fn without_db(&self) -> PgConnectOptions {
let ssl_mode = if self.require_ssl {
PgSslMode::Require
} else {
PgSslMode::Prefer
};
PgConnectOptions::new()
.host(&self.host)
.port(self.port)
.ssl_mode(ssl_mode)
.username(&self.username)
.password(&self.password)
}
pub fn with_db(&self) -> PgConnectOptions {
let mut options = self.without_db().database(&self.name);
options.log_statements(log::LevelFilter::Trace);
options
}
}
impl ApplicationSettings {
pub fn address(&self) -> String {
format!("{}:{}", self.host, self.port)
}
}
impl EmailClientSettings {
pub fn sender(&self) -> Result<EmailAddress, domain::email_address::ParseEmailAddressError> {
self.sender_email.parse()
}
pub fn timeout(&self) -> Duration {
Duration::from_millis(self.timeout_milliseconds)
}
}
pub fn get_configuration() -> Result<Settings, config::ConfigError> {
let base_path = std::env::current_dir().expect("Failed to determine the current directory");
let configuration_directory = base_path.join("configuration");
let environment: Environment = std::env::var("APP_ENVIRONMENT")
.unwrap_or_else(|_| "local".into())
.try_into()
.expect("Failed to parse APP_ENVIRONMENT");
config::Config::builder()
.add_source(config::File::from(configuration_directory.join("base")).required(true))
.add_source(
config::File::from(configuration_directory.join(environment.as_str())).required(true),
)
.add_source(config::Environment::with_prefix("app").separator("__"))
.build()?
.try_deserialize()
}
enum Environment {
Local,
Production,
}
impl Environment {
fn as_str(&self) -> &'static str {
match self {
Environment::Local => "local",
Environment::Production => "production",
}
}
}
impl TryFrom<String> for Environment {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
match value.to_lowercase().as_str() {
"local" => Ok(Environment::Local),
"production" => Ok(Environment::Production),
other => Err(format!("{} is not a valid environment", other)),
}
}
}
| 27.031008 | 98 | 0.639805 |
ac00989ee8317a6a4d6956584fae20a9b8a751cb
| 2,747 |
//! Async Function Expression.
use crate::{
exec::Executable,
syntax::ast::node::{join_nodes, FormalParameter, Node, StatementList},
Context, Result, Value,
};
use gc::{Finalize, Trace};
use std::fmt;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// An async function expression is very similar to an async function declaration except used within
/// a wider expression (for example during an assignment).
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#prod-AsyncFunctionExpression
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
pub struct AsyncFunctionExpr {
name: Option<Box<str>>,
parameters: Box<[FormalParameter]>,
body: StatementList,
}
impl AsyncFunctionExpr {
/// Creates a new function expression
pub(in crate::syntax) fn new<N, P, B>(name: N, parameters: P, body: B) -> Self
where
N: Into<Option<Box<str>>>,
P: Into<Box<[FormalParameter]>>,
B: Into<StatementList>,
{
Self {
name: name.into(),
parameters: parameters.into(),
body: body.into(),
}
}
/// Gets the name of the function declaration.
pub fn name(&self) -> Option<&str> {
self.name.as_ref().map(Box::as_ref)
}
/// Gets the list of parameters of the function declaration.
pub fn parameters(&self) -> &[FormalParameter] {
&self.parameters
}
/// Gets the body of the function declaration.
pub fn body(&self) -> &[Node] {
self.body.statements()
}
/// Implements the display formatting with indentation.
pub(in crate::syntax::ast::node) fn display(
&self,
f: &mut fmt::Formatter<'_>,
indentation: usize,
) -> fmt::Result {
f.write_str("function")?;
if let Some(ref name) = self.name {
write!(f, " {}", name)?;
}
f.write_str("(")?;
join_nodes(f, &self.parameters)?;
f.write_str(") {{")?;
self.body.display(f, indentation + 1)?;
writeln!(f, "}}")
}
}
impl Executable for AsyncFunctionExpr {
fn run(&self, _: &mut Context) -> Result<Value> {
// TODO: Implement AsyncFunctionExpr
Ok(Value::Undefined)
}
}
impl fmt::Display for AsyncFunctionExpr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.display(f, 0)
}
}
impl From<AsyncFunctionExpr> for Node {
fn from(expr: AsyncFunctionExpr) -> Self {
Self::AsyncFunctionExpr(expr)
}
}
| 27.747475 | 101 | 0.607936 |
ffe6f8833a148ebe20695845d314d7bd0b28bc10
| 14,260 |
use chrono::offset::Utc;
use chrono::prelude::*;
use serde_derive::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};
use crate::crypto;
use crate::error::Error;
use crate::metadata::{self, Metadata};
use crate::Result;
const SPEC_VERSION: &str = "1.0";
fn parse_datetime(ts: &str) -> Result<DateTime<Utc>> {
Utc.datetime_from_str(ts, "%FT%TZ")
.map_err(|e| Error::Encoding(format!("Can't parse DateTime: {:?}", e)))
}
fn format_datetime(ts: &DateTime<Utc>) -> String {
format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
ts.year(),
ts.month(),
ts.day(),
ts.hour(),
ts.minute(),
ts.second()
)
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RootMetadata {
#[serde(rename = "_type")]
typ: metadata::Role,
spec_version: String,
version: u32,
consistent_snapshot: bool,
expires: String,
#[serde(deserialize_with = "deserialize_reject_duplicates::deserialize")]
keys: BTreeMap<crypto::KeyId, crypto::PublicKey>,
roles: RoleDefinitions,
}
impl RootMetadata {
pub fn from(meta: &metadata::RootMetadata) -> Result<Self> {
Ok(RootMetadata {
typ: metadata::Role::Root,
spec_version: SPEC_VERSION.to_string(),
version: meta.version(),
expires: format_datetime(&meta.expires()),
consistent_snapshot: meta.consistent_snapshot(),
keys: meta.keys().iter().map(|(id, key)| (id.clone(), key.clone())).collect(),
roles: RoleDefinitions {
root: meta.root().clone(),
snapshot: meta.snapshot().clone(),
targets: meta.targets().clone(),
timestamp: meta.timestamp().clone(),
},
})
}
pub fn try_into(self) -> Result<metadata::RootMetadata> {
if self.typ != metadata::Role::Root {
return Err(Error::Encoding(format!(
"Attempted to decode root metdata labeled as {:?}",
self.typ
)));
}
if self.spec_version != SPEC_VERSION {
return Err(Error::Encoding(format!("Unknown spec version {}", self.spec_version)));
}
metadata::RootMetadata::new(
self.version,
parse_datetime(&self.expires)?,
self.consistent_snapshot,
self.keys.into_iter().collect(),
self.roles.root,
self.roles.snapshot,
self.roles.targets,
self.roles.timestamp,
)
}
}
#[derive(Debug, Serialize, Deserialize)]
struct RoleDefinitions {
root: metadata::RoleDefinition,
snapshot: metadata::RoleDefinition,
targets: metadata::RoleDefinition,
timestamp: metadata::RoleDefinition,
}
#[derive(Serialize, Deserialize)]
pub struct RoleDefinition {
threshold: u32,
#[serde(rename = "keyids")]
key_ids: Vec<crypto::KeyId>,
}
impl RoleDefinition {
pub fn from(role: &metadata::RoleDefinition) -> Result<Self> {
let mut key_ids = role.key_ids().iter().cloned().collect::<Vec<crypto::KeyId>>();
key_ids.sort();
Ok(RoleDefinition { threshold: role.threshold(), key_ids })
}
pub fn try_into(mut self) -> Result<metadata::RoleDefinition> {
let vec_len = self.key_ids.len();
if vec_len < 1 {
return Err(Error::Encoding("Role defined with no assoiciated key IDs.".into()));
}
let key_ids = self.key_ids.drain(0..).collect::<HashSet<crypto::KeyId>>();
let dupes = vec_len - key_ids.len();
if dupes != 0 {
return Err(Error::Encoding(format!("Found {} duplicate key IDs.", dupes)));
}
Ok(metadata::RoleDefinition::new(self.threshold, key_ids)?)
}
}
#[derive(Serialize, Deserialize)]
pub struct TimestampMetadata {
#[serde(rename = "_type")]
typ: metadata::Role,
spec_version: String,
version: u32,
expires: String,
meta: TimestampMeta,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct TimestampMeta {
#[serde(rename = "snapshot.json")]
snapshot: metadata::MetadataDescription,
}
impl TimestampMetadata {
pub fn from(metadata: &metadata::TimestampMetadata) -> Result<Self> {
Ok(TimestampMetadata {
typ: metadata::Role::Timestamp,
spec_version: SPEC_VERSION.to_string(),
version: metadata.version(),
expires: format_datetime(metadata.expires()),
meta: TimestampMeta { snapshot: metadata.snapshot().clone() },
})
}
pub fn try_into(self) -> Result<metadata::TimestampMetadata> {
if self.typ != metadata::Role::Timestamp {
return Err(Error::Encoding(format!(
"Attempted to decode timestamp metdata labeled as {:?}",
self.typ
)));
}
if self.spec_version != SPEC_VERSION {
return Err(Error::Encoding(format!("Unknown spec version {}", self.spec_version)));
}
metadata::TimestampMetadata::new(
self.version,
parse_datetime(&self.expires)?,
self.meta.snapshot,
)
}
}
#[derive(Serialize, Deserialize)]
pub struct SnapshotMetadata {
#[serde(rename = "_type")]
typ: metadata::Role,
spec_version: String,
version: u32,
expires: String,
#[serde(deserialize_with = "deserialize_reject_duplicates::deserialize")]
meta: BTreeMap<String, metadata::MetadataDescription>,
}
impl SnapshotMetadata {
pub fn from(metadata: &metadata::SnapshotMetadata) -> Result<Self> {
Ok(SnapshotMetadata {
typ: metadata::Role::Snapshot,
spec_version: SPEC_VERSION.to_string(),
version: metadata.version(),
expires: format_datetime(&metadata.expires()),
meta: metadata.meta().iter().map(|(p, d)| (format!("{}.json", p), d.clone())).collect(),
})
}
pub fn try_into(self) -> Result<metadata::SnapshotMetadata> {
if self.typ != metadata::Role::Snapshot {
return Err(Error::Encoding(format!(
"Attempted to decode snapshot metdata labeled as {:?}",
self.typ
)));
}
if self.spec_version != SPEC_VERSION {
return Err(Error::Encoding(format!("Unknown spec version {}", self.spec_version)));
}
metadata::SnapshotMetadata::new(
self.version,
parse_datetime(&self.expires)?,
self.meta
.into_iter()
.map(|(p, d)| {
if !p.ends_with(".json") {
return Err(Error::Encoding(format!(
"Metadata does not end with .json: {}",
p
)));
}
let s = p.split_at(p.len() - ".json".len()).0.into();
let p = metadata::MetadataPath::new(s)?;
Ok((p, d))
})
.collect::<Result<_>>()?,
)
}
}
#[derive(Serialize, Deserialize)]
pub struct TargetsMetadata {
#[serde(rename = "_type")]
typ: metadata::Role,
spec_version: String,
version: u32,
expires: String,
targets: BTreeMap<metadata::VirtualTargetPath, metadata::TargetDescription>,
#[serde(skip_serializing_if = "Option::is_none")]
delegations: Option<metadata::Delegations>,
}
impl TargetsMetadata {
pub fn from(metadata: &metadata::TargetsMetadata) -> Result<Self> {
Ok(TargetsMetadata {
typ: metadata::Role::Targets,
spec_version: SPEC_VERSION.to_string(),
version: metadata.version(),
expires: format_datetime(&metadata.expires()),
targets: metadata.targets().iter().map(|(p, d)| (p.clone(), d.clone())).collect(),
delegations: metadata.delegations().cloned(),
})
}
pub fn try_into(self) -> Result<metadata::TargetsMetadata> {
if self.typ != metadata::Role::Targets {
return Err(Error::Encoding(format!(
"Attempted to decode targets metdata labeled as {:?}",
self.typ
)));
}
if self.spec_version != SPEC_VERSION {
return Err(Error::Encoding(format!("Unknown spec version {}", self.spec_version)));
}
metadata::TargetsMetadata::new(
self.version,
parse_datetime(&self.expires)?,
self.targets.into_iter().collect(),
self.delegations,
)
}
}
#[derive(Serialize, Deserialize)]
pub struct PublicKey {
keytype: crypto::KeyType,
scheme: crypto::SignatureScheme,
keyval: PublicKeyValue,
}
impl PublicKey {
pub fn new(
keytype: crypto::KeyType,
scheme: crypto::SignatureScheme,
public_key: String,
) -> Self {
PublicKey { keytype, scheme, keyval: PublicKeyValue { public: public_key } }
}
pub fn public_key(&self) -> &str {
&self.keyval.public
}
pub fn scheme(&self) -> &crypto::SignatureScheme {
&self.scheme
}
pub fn keytype(&self) -> &crypto::KeyType {
&self.keytype
}
}
#[derive(Serialize, Deserialize)]
pub struct PublicKeyValue {
public: String,
}
#[derive(Serialize, Deserialize)]
pub struct Delegation {
role: metadata::MetadataPath,
terminating: bool,
threshold: u32,
#[serde(rename = "keyids")]
key_ids: Vec<crypto::KeyId>,
paths: Vec<metadata::VirtualTargetPath>,
}
impl Delegation {
pub fn from(meta: &metadata::Delegation) -> Self {
let mut paths = meta.paths().iter().cloned().collect::<Vec<metadata::VirtualTargetPath>>();
paths.sort();
let mut key_ids = meta.key_ids().iter().cloned().collect::<Vec<crypto::KeyId>>();
key_ids.sort();
Delegation {
role: meta.role().clone(),
terminating: meta.terminating(),
threshold: meta.threshold(),
key_ids,
paths,
}
}
pub fn try_into(self) -> Result<metadata::Delegation> {
let paths = self.paths.iter().cloned().collect::<HashSet<metadata::VirtualTargetPath>>();
if paths.len() != self.paths.len() {
return Err(Error::Encoding("Non-unique delegation paths.".into()));
}
let key_ids = self.key_ids.iter().cloned().collect::<HashSet<crypto::KeyId>>();
if key_ids.len() != self.key_ids.len() {
return Err(Error::Encoding("Non-unique delegation key IDs.".into()));
}
metadata::Delegation::new(self.role, self.terminating, self.threshold, key_ids, paths)
}
}
#[derive(Serialize, Deserialize)]
pub struct Delegations {
#[serde(deserialize_with = "deserialize_reject_duplicates::deserialize")]
keys: BTreeMap<crypto::KeyId, crypto::PublicKey>,
roles: Vec<metadata::Delegation>,
}
impl Delegations {
pub fn from(delegations: &metadata::Delegations) -> Delegations {
Delegations {
keys: delegations.keys().iter().map(|(id, key)| (id.clone(), key.clone())).collect(),
roles: delegations.roles().clone(),
}
}
pub fn try_into(self) -> Result<metadata::Delegations> {
metadata::Delegations::new(self.keys.into_iter().collect(), self.roles)
}
}
#[derive(Serialize, Deserialize)]
pub struct TargetDescription {
length: u64,
hashes: BTreeMap<crypto::HashAlgorithm, crypto::HashValue>,
#[serde(default, skip_serializing_if = "Option::is_none")]
custom: Option<BTreeMap<String, serde_json::Value>>,
}
impl TargetDescription {
pub fn from(description: &metadata::TargetDescription) -> TargetDescription {
TargetDescription {
length: description.length(),
hashes: description.hashes().iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
custom: description
.custom()
.map(|custom| custom.iter().map(|(k, v)| (k.clone(), v.clone())).collect()),
}
}
pub fn try_into(self) -> Result<metadata::TargetDescription> {
metadata::TargetDescription::new(
self.length,
self.hashes.into_iter().collect(),
self.custom.map(|custom| custom.into_iter().collect()),
)
}
}
#[derive(Deserialize)]
pub struct MetadataDescription {
version: u32,
length: usize,
hashes: BTreeMap<crypto::HashAlgorithm, crypto::HashValue>,
}
impl MetadataDescription {
pub fn try_into(self) -> Result<metadata::MetadataDescription> {
metadata::MetadataDescription::new(
self.version,
self.length,
self.hashes.into_iter().collect(),
)
}
}
/// Custom deserialize to reject duplicate keys.
mod deserialize_reject_duplicates {
use serde::de::{Deserialize, Deserializer, Error, MapAccess, Visitor};
use std::collections::BTreeMap;
use std::fmt;
use std::marker::PhantomData;
use std::result::Result;
pub fn deserialize<'de, K, V, D>(deserializer: D) -> Result<BTreeMap<K, V>, D::Error>
where
K: Deserialize<'de> + Ord,
V: Deserialize<'de>,
D: Deserializer<'de>,
{
struct BTreeVisitor<K, V> {
marker: PhantomData<(K, V)>,
};
impl<'de, K, V> Visitor<'de> for BTreeVisitor<K, V>
where
K: Deserialize<'de> + Ord,
V: Deserialize<'de>,
{
type Value = BTreeMap<K, V>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("map")
}
fn visit_map<M>(self, mut access: M) -> std::result::Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut map = BTreeMap::new();
while let Some((key, value)) = access.next_entry()? {
if map.insert(key, value).is_some() {
return Err(M::Error::custom("Cannot have duplicate keys"));
}
}
Ok(map)
}
}
deserializer.deserialize_map(BTreeVisitor { marker: PhantomData })
}
}
| 30.865801 | 100 | 0.576017 |
69662cb13f1ada9dc16875328f318df008329bc4
| 1,475 |
use serde::Deserialize;
use std::path::PathBuf;
use structopt::StructOpt;
use watchman_client::prelude::*;
#[derive(Debug, StructOpt)]
#[structopt(about = "Perform a glob query for a path, using watchman")]
struct Opt {
#[structopt(default_value = ".")]
path: PathBuf,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
if let Err(err) = run().await {
// Print a prettier error than the default
eprintln!("{}", err);
std::process::exit(1);
}
Ok(())
}
async fn run() -> Result<(), Box<dyn std::error::Error>> {
let opt = Opt::from_args();
let client = Connector::new().connect().await?;
let resolved = client
.resolve_root(CanonicalPath::canonicalize(opt.path)?)
.await?;
println!("resolved watch to {:?}", resolved);
// Basic globs -> names
let files = client.glob(&resolved, &["**/*.rs"]).await?;
println!("files: {:#?}", files);
query_result_type! {
struct NameAndHash {
name: NameField,
hash: ContentSha1HexField,
}
}
let response: QueryResult<NameAndHash> = client
.query(
&resolved,
QueryRequestCommon {
glob: Some(vec!["**/*.rs".to_string()]),
expression: Some(Expr::Not(Box::new(Expr::Empty))),
..Default::default()
},
)
.await?;
println!("response: {:#?}", response);
Ok(())
}
| 25.877193 | 71 | 0.549153 |
d98c3f52c1991ca2e93968e3590b343cfa81877c
| 1,188 |
use rustler::dynamic::TermType;
// PrintableTermType is a workaround for rustler::dynamic::TermType not having the Debug trait.
pub enum PrintableTermType {
PrintTerm(TermType),
}
use std::fmt;
impl fmt::Debug for PrintableTermType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use PrintableTermType::PrintTerm;
match self {
PrintTerm(TermType::Atom) => write!(f, "Atom"),
PrintTerm(TermType::Binary) => write!(f, "Binary"),
PrintTerm(TermType::EmptyList) => write!(f, "EmptyList"),
PrintTerm(TermType::Exception) => write!(f, "Exception"),
PrintTerm(TermType::Fun) => write!(f, "Fun"),
PrintTerm(TermType::List) => write!(f, "List"),
PrintTerm(TermType::Map) => write!(f, "Map"),
PrintTerm(TermType::Number) => write!(f, "Number"),
PrintTerm(TermType::Pid) => write!(f, "Pid"),
PrintTerm(TermType::Port) => write!(f, "Port"),
PrintTerm(TermType::Ref) => write!(f, "Ref"),
PrintTerm(TermType::Tuple) => write!(f, "Tuple"),
PrintTerm(TermType::Unknown) => write!(f, "Unknown"),
}
}
}
| 40.965517 | 95 | 0.578283 |
0ee185299317a00a87ed02e9078ecf6c61faffc1
| 4,486 |
#![allow(dead_code)]
use crate::arch::x86_64::kernel::syscall_handler;
use crate::logging::*;
use crate::scheduler::task::BOOT_STACK;
use x86::controlregs::*;
use x86::cpuid::*;
use x86::io::*;
use x86::msr::*;
// MSR EFER bits
const EFER_SCE: u64 = 1 << 0;
const EFER_LME: u64 = 1 << 8;
const EFER_LMA: u64 = 1 << 10;
const EFER_NXE: u64 = 1 << 11;
const EFER_SVME: u64 = 1 << 12;
const EFER_LMSLE: u64 = 1 << 13;
const EFER_FFXSR: u64 = 1 << 14;
const EFER_TCE: u64 = 1 << 15;
static mut PHYSICAL_ADDRESS_BITS: u8 = 0;
static mut LINEAR_ADDRESS_BITS: u8 = 0;
static mut SUPPORTS_1GIB_PAGES: bool = false;
/// Force strict CPU ordering, serializes load and store operations.
#[inline(always)]
pub fn mb() {
unsafe {
asm!("mfence", options(nostack));
}
}
/// Search the most significant bit
#[inline(always)]
pub fn msb(value: u64) -> Option<u64> {
if value > 0 {
let ret: u64;
unsafe {
asm!("bsr {0}, {1}", out(reg) ret, in(reg) value, options(nostack,preserves_flags));
}
Some(ret)
} else {
None
}
}
/// Search the least significant bit
#[inline(always)]
pub fn lsb(value: u64) -> Option<u64> {
if value > 0 {
let ret: u64;
unsafe {
asm!("bsf {0}, {1}", out(reg) ret, in(reg) value, options(nostack, preserves_flags));
}
Some(ret)
} else {
None
}
}
#[inline(always)]
pub fn halt() {
unsafe {
asm!("hlt", options(nostack));
}
}
#[inline(always)]
pub fn pause() {
unsafe {
asm!("pause", options(nostack));
}
}
#[no_mangle]
pub extern "C" fn shutdown() -> ! {
// shutdown, works like Qemu's shutdown command
unsafe {
outb(0xf4, 0x00);
}
loop {
halt();
}
}
pub fn supports_1gib_pages() -> bool {
unsafe { SUPPORTS_1GIB_PAGES }
}
pub fn get_linear_address_bits() -> u8 {
unsafe { LINEAR_ADDRESS_BITS }
}
pub fn get_physical_address_bits() -> u8 {
unsafe { PHYSICAL_ADDRESS_BITS }
}
pub fn init() {
debug!("enable supported processor features");
let cpuid = CpuId::new();
let mut cr0 = unsafe { cr0() };
// be sure that AM, NE and MP is enabled
cr0 = cr0 | Cr0::CR0_ALIGNMENT_MASK;
cr0 = cr0 | Cr0::CR0_NUMERIC_ERROR;
cr0 = cr0 | Cr0::CR0_MONITOR_COPROCESSOR;
// enable cache
cr0 = cr0 & !(Cr0::CR0_CACHE_DISABLE | Cr0::CR0_NOT_WRITE_THROUGH);
debug!("set CR0 to {:?}", cr0);
unsafe { cr0_write(cr0) };
let mut cr4 = unsafe { cr4() };
let has_pge = match cpuid.get_feature_info() {
Some(finfo) => finfo.has_pge(),
None => false,
};
if has_pge {
cr4 |= Cr4::CR4_ENABLE_GLOBAL_PAGES;
}
let has_fsgsbase = match cpuid.get_extended_feature_info() {
Some(efinfo) => efinfo.has_fsgsbase(),
None => false,
};
if has_fsgsbase {
cr4 |= Cr4::CR4_ENABLE_FSGSBASE;
} else {
panic!("eduOS-rs requires the CPU feature FSGSBASE");
}
let has_mce = match cpuid.get_feature_info() {
Some(finfo) => finfo.has_mce(),
None => false,
};
if has_mce {
cr4 |= Cr4::CR4_ENABLE_MACHINE_CHECK; // enable machine check exceptions
}
// disable performance monitoring counter
// allow the usage of rdtsc in user space
cr4 &= !(Cr4::CR4_ENABLE_PPMC | Cr4::CR4_TIME_STAMP_DISABLE);
debug!("set CR4 to {:?}", cr4);
unsafe { cr4_write(cr4) };
let has_syscall = match cpuid.get_extended_function_info() {
Some(finfo) => finfo.has_syscall_sysret(),
None => false,
};
if has_syscall == false {
panic!("Syscall support is missing");
}
// enable support of syscall and sysret
unsafe {
wrmsr(IA32_EFER, rdmsr(IA32_EFER) | EFER_LMA | EFER_SCE | EFER_NXE);
wrmsr(IA32_STAR, (0x1Bu64 << 48) | (0x08u64 << 32));
wrmsr(IA32_LSTAR, syscall_handler as u64);
wrmsr(IA32_FMASK, 1 << 9); // clear IF flag during system call
// reset GS registers
wrmsr(IA32_GS_BASE, 0);
asm!("wrgsbase {}", in(reg) BOOT_STACK.top());
}
// determin processor features
let extended_function_info = cpuid
.get_extended_function_info()
.expect("CPUID Extended Function Info not available!");
unsafe {
PHYSICAL_ADDRESS_BITS = extended_function_info
.physical_address_bits()
.expect("CPUID Physical Address Bits not available!");
LINEAR_ADDRESS_BITS = extended_function_info
.linear_address_bits()
.expect("CPUID Linear Address Bits not available!");
SUPPORTS_1GIB_PAGES = extended_function_info.has_1gib_pages();
}
if supports_1gib_pages() {
info!("System supports 1GiB pages");
}
debug!("Physical address bits {}", get_physical_address_bits());
debug!("Linear address bits {}", get_linear_address_bits());
debug!("CR0: {:?}", cr0);
debug!("CR4: {:?}", cr4);
}
| 22.542714 | 88 | 0.66897 |
62c0741b6697a484385e051eeda0afcc8af4ca21
| 203 |
// aux-build:derive-bad.rs
#[macro_use]
extern crate derive_bad;
#[derive(
A
)]
//~^^ ERROR proc-macro derive produced unparseable tokens
//~| ERROR expected `:`, found `}`
struct A;
fn main() {}
| 14.5 | 57 | 0.650246 |
ed29e4ac927e7f4b078e2a68d97fd03418860b49
| 497 |
//! MIO bindings for Unix Domain Sockets
#![cfg(unix)]
#![deny(missing_docs)]
#![doc(html_root_url = "https://docs.rs/mio-uds/0.6")]
extern crate iovec;
extern crate libc;
extern crate mio;
use std::io;
mod datagram;
mod listener;
mod socket;
mod stream;
pub use stream::UnixStream;
pub use listener::UnixListener;
pub use datagram::UnixDatagram;
fn cvt(i: libc::c_int) -> io::Result<libc::c_int> {
if i == -1 {
Err(io::Error::last_os_error())
} else {
Ok(i)
}
}
| 17.137931 | 54 | 0.647887 |
79977dcdcf6f7e062f10208a3e87a1dd92f81e3a
| 2,271 |
use crate::header::AccessFlags;
use crate::reader::cpool;
use crate::reader::decoding::*;
pub type ModulePackages<'a> = DecodeCountedCopy<'a, cpool::Index<cpool::Package>, u16>;
pub type ModulePackageIter<'a> = DecodeCounted<'a, cpool::Index<cpool::Package>, u16>;
dec_structure! {
pub struct ModuleMainClass<'a> into {
main_class: cpool::Index<cpool::Class>,
}
}
dec_structure! {
pub struct Module<'a> into {
name: cpool::Index<cpool::Module>,
flags: AccessFlags,
version: Option<cpool::Index<cpool::Utf8<'static>>>,
requires: Requires<'a>,
exports: Exports<'a>,
opens: Opens<'a>,
uses: Uses<'a>,
provides: Provides<'a>,
}
}
pub type Requires<'a> = DecodeCountedCopy<'a, Require<'a>, u16>;
pub type RequireIter<'a> = DecodeCounted<'a, Require<'a>, u16>;
dec_structure! {
pub struct Require<'a> {
index: cpool::Index<cpool::Module>,
flags: AccessFlags,
version: cpool::Index<cpool::Utf8<'static>>,
}
}
pub type Exports<'a> = DecodeCountedCopy<'a, Export<'a>, u16>;
pub type ExportIter<'a> = DecodeCounted<'a, Export<'a>, u16>;
pub type ExportsToIter<'a> = DecodeCounted<'a, cpool::Index<cpool::Module>, u16>;
dec_structure! {
pub struct Export<'a> {
index: cpool::Index<cpool::Package>,
flags: AccessFlags,
exports_to: ExportsToIter<'a>,
}
}
pub type Opens<'a> = DecodeCountedCopy<'a, Open<'a>, u16>;
pub type OpenIter<'a> = DecodeCounted<'a, Open<'a>, u16>;
pub type OpensToIter<'a> = DecodeCounted<'a, cpool::Index<cpool::Module>, u16>;
dec_structure! {
pub struct Open<'a> {
index: cpool::Index<cpool::Package>,
flags: AccessFlags,
opens_to: OpensToIter<'a>,
}
}
pub type Uses<'a> = DecodeCountedCopy<'a, cpool::Index<cpool::Class>, u16>;
pub type UseIter<'a> = DecodeCounted<'a, cpool::Index<cpool::Class>, u16>;
pub type Provides<'a> = DecodeCountedCopy<'a, Provide<'a>, u16>;
pub type ProvideIter<'a> = DecodeCounted<'a, Provide<'a>, u16>;
pub type ProvidesWithIter<'a> = DecodeCounted<'a, cpool::Index<cpool::Class>, u16>;
dec_structure! {
pub struct Provide<'a> {
index: cpool::Index<cpool::Class>,
provides_with: ProvidesWithIter<'a>,
}
}
| 29.115385 | 87 | 0.636284 |
504253dbd7701324553aad9d7be1b64d29572b60
| 3,222 |
use crate::error::Error;
use crate::qrcode::decoder::error_correction_level::ErrorCorrectionLevel;
use crate::qrcode::decoder::version::Version;
pub struct DataBlock {
num_data_codewords: isize,
codewords: Vec<u8>,
}
impl DataBlock {
pub fn get_data_blocks(raw_codewords: &[u8], version: &Version, ec_level: &ErrorCorrectionLevel) -> Result<Vec<DataBlock>, Error> {
if raw_codewords.len() as isize != version.get_total_codewords() {
return Err(Error::IllegalArgumentError);
}
let ec_blocks = version.get_ec_blocks_for_level(ec_level);
let ec_block_array = ec_blocks.get_ec_blocks();
/* unused
let mut total_blocks = 0;
for ec_block in ec_block_array {
total_blocks += ec_block.get_count();
}
*/
let mut result = vec![];
let mut num_result_blocks = 0;
for ec_block in ec_block_array {
for _ in 0..ec_block.get_count() {
let num_data_codewords = ec_block.get_data_codewords();
let num_block_codewords = ec_blocks.get_ec_codewords_per_block() + num_data_codewords;
let data_block = DataBlock {
num_data_codewords: num_data_codewords,
codewords: vec![0; num_block_codewords as usize],
};
result.push(data_block);
num_result_blocks += 1;
}
}
let shoter_blocks_total_codewords = result[0].codewords.len();
let mut longer_blocks_start_at = result.len() - 1;
while longer_blocks_start_at >= 0 {
let num_codewords = result[longer_blocks_start_at].codewords.len();
if num_codewords == shoter_blocks_total_codewords {
break;
}
longer_blocks_start_at -= 1;
}
longer_blocks_start_at -= 1;
let shorter_blocks_num_data_codewords = shoter_blocks_total_codewords - ec_blocks.get_ec_codewords_per_block() as usize;
let mut raw_codewords_offset = 0;
for i in 0..shorter_blocks_num_data_codewords {
for j in 0..num_result_blocks {
result[j].codewords[i] = raw_codewords[raw_codewords_offset];
raw_codewords_offset += 1;
}
}
for j in longer_blocks_start_at..num_result_blocks {
result[j].codewords[shorter_blocks_num_data_codewords] = raw_codewords[raw_codewords_offset];
raw_codewords_offset += 1;
}
let max = result[0].codewords.len();
for i in shorter_blocks_num_data_codewords..max {
for j in 0..num_result_blocks {
let i_offset = if j < longer_blocks_start_at { i } else { i + 1};
result[j].codewords[i_offset] = raw_codewords[raw_codewords_offset];
raw_codewords_offset += 1;
}
}
return Ok(result);
}
pub const fn get_num_data_codewords(&self) -> isize {
return self.num_data_codewords;
}
pub const fn get_codewords(&self) -> &Vec<u8> {
return &self.codewords;
}
}
| 37.905882 | 136 | 0.594972 |
7695a0cec91b6d14957e7e4d3e502fd7b366ac46
| 998 |
fn main() {
// let number = 6;
// if number < 5 {
// println!("condition was true");
// } else {
// println!("condition was false");
// }
// // rustでは、ifの評価値は必ずbool型でないといけない
// // Javascriptのように、勝手にboolへは変換されない
// if number != 0 {
// println!("number was something other than zero");
// }
// if number % 4 == 0 {
// // 数値は4で割り切れます
// println!("number is divisible by 4");
// } else if number % 3 == 0 {
// // 数値は3で割り切れます
// println!("number is divisible by 3");
// } else if number % 2 == 0 {
// // 数値は2で割り切れます
// println!("number is divisible by 2");
// } else {
// // 数値は4、3、2で割り切れません
// println!("number is not divisible by 4, 3, or 2");
// }
let condition = true;
// ifを変数に代入できるが、異なる型を代入することはできない
let number = if condition {
5
} else {
// "six"
6
};
println!("The value of number is: {}", number);
}
| 23.761905 | 61 | 0.488978 |
645f2b023380031aaff0aa6796c00a00be4136f1
| 9,686 |
//! Freshening is the process of replacing unknown variables with fresh types. The idea is that
//! the type, after freshening, contains no inference variables but instead contains either a
//! value for each variable or fresh "arbitrary" types wherever a variable would have been.
//!
//! Freshening is used primarily to get a good type for inserting into a cache. The result
//! summarizes what the type inferencer knows "so far". The primary place it is used right now is
//! in the trait matching algorithm, which needs to be able to cache whether an `impl` self type
//! matches some other type X -- *without* affecting `X`. That means if that if the type `X` is in
//! fact an unbound type variable, we want the match to be regarded as ambiguous, because depending
//! on what type that type variable is ultimately assigned, the match may or may not succeed.
//!
//! To handle closures, freshened types also have to contain the signature and kind of any
//! closure in the local inference context, as otherwise the cache key might be invalidated.
//! The way this is done is somewhat hacky - the closure signature is appended to the substs,
//! as well as the closure kind "encoded" as a type. Also, special handling is needed when
//! the closure signature contains a reference to the original closure.
//!
//! Note that you should be careful not to allow the output of freshening to leak to the user in
//! error messages or in any other form. Freshening is only really useful as an internal detail.
//!
//! Because of the manipulation required to handle closures, doing arbitrary operations on
//! freshened types is not recommended. However, in addition to doing equality/hash
//! comparisons (for caching), it is possible to do a `ty::_match` operation between
//! 2 freshened types - this works even with the closure encoding.
//!
//! __An important detail concerning regions.__ The freshener also replaces *all* free regions with
//! 'erased. The reason behind this is that, in general, we do not take region relationships into
//! account when making type-overloaded decisions. This is important because of the design of the
//! region inferencer, which is not based on unification but rather on accumulating and then
//! solving a set of constraints. In contrast, the type inferencer assigns a value to each type
//! variable only once, and it does so as soon as it can, so it is reasonable to ask what the type
//! inferencer knows "so far".
use crate::mir::interpret::ConstValue;
use crate::ty::{self, Ty, TyCtxt, TypeFoldable};
use crate::ty::fold::TypeFolder;
use crate::util::nodemap::FxHashMap;
use std::collections::hash_map::Entry;
use super::InferCtxt;
use super::unify_key::ToType;
pub struct TypeFreshener<'a, 'tcx: 'a> {
infcx: &'a InferCtxt<'a, 'tcx>,
ty_freshen_count: u32,
const_freshen_count: u32,
ty_freshen_map: FxHashMap<ty::InferTy, Ty<'tcx>>,
const_freshen_map: FxHashMap<ty::InferConst<'tcx>, &'tcx ty::Const<'tcx>>,
}
impl<'a, 'tcx> TypeFreshener<'a, 'tcx> {
pub fn new(infcx: &'a InferCtxt<'a, 'tcx>) -> TypeFreshener<'a, 'tcx> {
TypeFreshener {
infcx,
ty_freshen_count: 0,
const_freshen_count: 0,
ty_freshen_map: Default::default(),
const_freshen_map: Default::default(),
}
}
fn freshen_ty<F>(
&mut self,
opt_ty: Option<Ty<'tcx>>,
key: ty::InferTy,
freshener: F,
) -> Ty<'tcx>
where
F: FnOnce(u32) -> ty::InferTy,
{
if let Some(ty) = opt_ty {
return ty.fold_with(self);
}
match self.ty_freshen_map.entry(key) {
Entry::Occupied(entry) => *entry.get(),
Entry::Vacant(entry) => {
let index = self.ty_freshen_count;
self.ty_freshen_count += 1;
let t = self.infcx.tcx.mk_ty_infer(freshener(index));
entry.insert(t);
t
}
}
}
fn freshen_const<F>(
&mut self,
opt_ct: Option<&'tcx ty::Const<'tcx>>,
key: ty::InferConst<'tcx>,
freshener: F,
ty: Ty<'tcx>,
) -> &'tcx ty::Const<'tcx>
where
F: FnOnce(u32) -> ty::InferConst<'tcx>,
{
if let Some(ct) = opt_ct {
return ct.fold_with(self);
}
match self.const_freshen_map.entry(key) {
Entry::Occupied(entry) => *entry.get(),
Entry::Vacant(entry) => {
let index = self.const_freshen_count;
self.const_freshen_count += 1;
let ct = self.infcx.tcx.mk_const_infer(freshener(index), ty);
entry.insert(ct);
ct
}
}
}
}
impl<'a, 'tcx> TypeFolder<'tcx> for TypeFreshener<'a, 'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.infcx.tcx
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
match *r {
ty::ReLateBound(..) => {
// leave bound regions alone
r
}
ty::ReStatic |
ty::ReEarlyBound(..) |
ty::ReFree(_) |
ty::ReScope(_) |
ty::ReVar(_) |
ty::RePlaceholder(..) |
ty::ReEmpty |
ty::ReErased => {
// replace all free regions with 'erased
self.tcx().lifetimes.re_erased
}
ty::ReClosureBound(..) => {
bug!(
"encountered unexpected region: {:?}",
r,
);
}
}
}
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
if !t.needs_infer() && !t.has_erasable_regions() &&
!(t.has_closure_types() && self.infcx.in_progress_tables.is_some()) {
return t;
}
let tcx = self.infcx.tcx;
match t.sty {
ty::Infer(ty::TyVar(v)) => {
let opt_ty = self.infcx.type_variables.borrow_mut().probe(v).known();
self.freshen_ty(
opt_ty,
ty::TyVar(v),
ty::FreshTy)
}
ty::Infer(ty::IntVar(v)) => {
self.freshen_ty(
self.infcx.int_unification_table.borrow_mut()
.probe_value(v)
.map(|v| v.to_type(tcx)),
ty::IntVar(v),
ty::FreshIntTy)
}
ty::Infer(ty::FloatVar(v)) => {
self.freshen_ty(
self.infcx.float_unification_table.borrow_mut()
.probe_value(v)
.map(|v| v.to_type(tcx)),
ty::FloatVar(v),
ty::FreshFloatTy)
}
ty::Infer(ty::FreshTy(ct)) |
ty::Infer(ty::FreshIntTy(ct)) |
ty::Infer(ty::FreshFloatTy(ct)) => {
if ct >= self.ty_freshen_count {
bug!("Encountered a freshend type with id {} \
but our counter is only at {}",
ct,
self.ty_freshen_count);
}
t
}
ty::Generator(..) |
ty::Bool |
ty::Char |
ty::Int(..) |
ty::Uint(..) |
ty::Float(..) |
ty::Adt(..) |
ty::Str |
ty::Error |
ty::Array(..) |
ty::Slice(..) |
ty::RawPtr(..) |
ty::Ref(..) |
ty::FnDef(..) |
ty::FnPtr(_) |
ty::Dynamic(..) |
ty::Never |
ty::Tuple(..) |
ty::Projection(..) |
ty::UnnormalizedProjection(..) |
ty::Foreign(..) |
ty::Param(..) |
ty::Closure(..) |
ty::GeneratorWitness(..) |
ty::Opaque(..) => {
t.super_fold_with(self)
}
ty::Placeholder(..) |
ty::Bound(..) => bug!("unexpected type {:?}", t),
}
}
fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
match ct.val {
ConstValue::Infer(ty::InferConst::Var(v)) => {
let opt_ct = self.infcx.const_unification_table
.borrow_mut()
.probe_value(v)
.val
.known();
return self.freshen_const(
opt_ct,
ty::InferConst::Var(v),
ty::InferConst::Fresh,
ct.ty,
);
}
ConstValue::Infer(ty::InferConst::Fresh(i)) => {
if i >= self.const_freshen_count {
bug!(
"Encountered a freshend const with id {} \
but our counter is only at {}",
i,
self.const_freshen_count,
);
}
return ct;
}
ConstValue::Infer(ty::InferConst::Canonical(..)) |
ConstValue::Placeholder(_) => {
bug!("unexpected const {:?}", ct)
}
ConstValue::Param(_) |
ConstValue::Scalar(_) |
ConstValue::Slice { .. } |
ConstValue::ByRef(..) |
ConstValue::Unevaluated(..) => {}
}
ct.super_fold_with(self)
}
}
| 35.874074 | 99 | 0.506091 |
acf8eb0e56bf0b5c6cfe7f3cca4a3516e468d192
| 299 |
fn main() {
// ANCHOR: here
{ // s no es válido aqui, no se ha declarado aun
let s = "hello"; // s es válido de aqui en adelante
// cosas a hacer con s
} // termina el alcance, y s deja de ser válida
// ANCHOR_END: here
}
| 29.9 | 73 | 0.48495 |
71336787cede2b6fdbf2529bc0d7e483c9e5fea6
| 5,057 |
//! Functions for converting between Casper types and their Protobuf equivalents.
mod ipc;
mod state;
mod transforms;
use std::{
convert::TryInto,
fmt::{self, Display, Formatter},
string::ToString,
};
use casper_execution_engine::core::{engine_state, DEPLOY_HASH_LENGTH};
use casper_types::{account::ACCOUNT_HASH_LENGTH, bytesrepr, KEY_HASH_LENGTH};
pub use transforms::TransformMap;
/// Try to convert a `Vec<u8>` to a 32-byte array.
pub(crate) fn vec_to_array(input: Vec<u8>, input_name: &str) -> Result<[u8; 32], ParsingError> {
input
.as_slice()
.try_into()
.map_err(|_| format!("{} must be 32 bytes.", input_name).into())
}
#[derive(Debug, PartialEq)]
pub enum MappingError {
InvalidStateHashLength { expected: usize, actual: usize },
InvalidAccountHashLength { expected: usize, actual: usize },
InvalidDeployHashLength { expected: usize, actual: usize },
InvalidHashLength { expected: usize, actual: usize },
Parsing(ParsingError),
InvalidStateHash(String),
MissingPayload,
TryFromSlice,
Serialization(bytesrepr::Error),
}
impl MappingError {
pub fn invalid_account_hash_length(actual: usize) -> Self {
let expected = ACCOUNT_HASH_LENGTH;
MappingError::InvalidAccountHashLength { expected, actual }
}
pub fn invalid_deploy_hash_length(actual: usize) -> Self {
let expected = KEY_HASH_LENGTH;
MappingError::InvalidDeployHashLength { expected, actual }
}
pub fn invalid_hash_length(actual: usize) -> Self {
let expected = DEPLOY_HASH_LENGTH;
MappingError::InvalidHashLength { expected, actual }
}
}
impl From<ParsingError> for MappingError {
fn from(error: ParsingError) -> Self {
MappingError::Parsing(error)
}
}
impl From<bytesrepr::Error> for MappingError {
fn from(error: bytesrepr::Error) -> Self {
Self::Serialization(error)
}
}
// This is whackadoodle, we know
impl From<MappingError> for engine_state::Error {
fn from(error: MappingError) -> Self {
match error {
MappingError::InvalidStateHashLength { expected, actual } => {
engine_state::Error::InvalidHashLength { expected, actual }
}
_ => engine_state::Error::Deploy,
}
}
}
impl Display for MappingError {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
match self {
MappingError::InvalidStateHashLength { expected, actual } => write!(
f,
"Invalid hash length: expected {}, actual {}",
expected, actual
),
MappingError::InvalidAccountHashLength { expected, actual } => write!(
f,
"Invalid public key length: expected {}, actual {}",
expected, actual
),
MappingError::InvalidDeployHashLength { expected, actual } => write!(
f,
"Invalid deploy hash length: expected {}, actual {}",
expected, actual
),
MappingError::Parsing(ParsingError(message)) => write!(f, "Parsing error: {}", message),
MappingError::InvalidStateHash(message) => write!(f, "Invalid hash: {}", message),
MappingError::MissingPayload => write!(f, "Missing payload"),
MappingError::TryFromSlice => write!(f, "Unable to convert from slice"),
MappingError::InvalidHashLength { expected, actual } => write!(
f,
"Invalid hash length: expected {}, actual {}",
expected, actual
),
MappingError::Serialization(error) => write!(f, "{}", error),
}
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct ParsingError(pub String);
impl<T: ToString> From<T> for ParsingError {
fn from(error: T) -> Self {
ParsingError(error.to_string())
}
}
#[cfg(test)]
pub mod test_utils {
use std::{any, convert::TryFrom, fmt::Debug};
/// Checks that domain object `original` can be converted into a corresponding protobuf object
/// and back, and that the conversions yield an equal object to `original`.
pub fn protobuf_round_trip<T, U>(original: T)
where
T: Clone + PartialEq + Debug + TryFrom<U>,
<T as TryFrom<U>>::Error: Debug,
U: From<T>,
{
let pb_object = U::from(original.clone());
let parsed = T::try_from(pb_object).unwrap_or_else(|_| {
panic!(
"Expected transforming {} into {} to succeed.",
any::type_name::<U>(),
any::type_name::<T>()
)
});
assert_eq!(original, parsed);
}
}
#[cfg(test)]
mod tests {
use super::vec_to_array;
#[test]
fn vec_to_array_test() {
assert_eq!([1; 32], vec_to_array(vec![1; 32], "").unwrap());
assert!(vec_to_array(vec![], "").is_err());
assert!(vec_to_array(vec![1; 31], "").is_err());
assert!(vec_to_array(vec![1; 33], "").is_err());
}
}
| 32.210191 | 100 | 0.600554 |
01c9145db217bc0fa933ac48feb75e768c787afe
| 4,284 |
//! Misc utility definitions
use byteorder::ByteOrder;
use failure::{format_err, Error};
use image::{Rgba, RgbaImage};
use num::{Integer, ToPrimitive, Unsigned};
use std::fmt::{Debug, Display};
/// A list of supported formats
///
/// Information gathered from [https://openslide.org/formats/](https://openslide.org/formats/)
///
#[derive(Clone, Debug)]
pub enum Format {
/// Single-file pyramidal tiled TIFF, with non-standard metadata and compression.
///
/// File extensions:
/// .svs, .tif
Aperio,
/// Multi-file JPEG/NGR with proprietary metadata and index file formats, and single-file
/// TIFF-like format with proprietary metadata.
///
/// File extensions:
/// .vms, .vmu, .ndpi
Hamamatsu,
/// Single-file pyramidal tiled BigTIFF with non-standard metadata.
///
/// File extensions
/// .scn
Leica,
/// Multi-file with very complicated proprietary metadata and indexes.
///
/// File extensions
/// .mrxs
Mirax,
/// Single-file pyramidal tiled TIFF or BigTIFF with non-standard metadata.
///
/// File extensions
/// .tiff
Phillips,
/// SQLite database containing pyramid tiles and metadata.
///
/// File extensions
/// .svslide
Sakura,
/// Single-file pyramidal tiled TIFF, with non-standard metadata and overlaps. Additional files
/// contain more metadata and detailed overlap info.
///
/// File extensions
/// .tif
Trestle,
/// Single-file pyramidal tiled BigTIFF, with non-standard metadata and overlaps.
///
/// File extensions
/// .bif, .tif
Ventana,
/// Single-file pyramidal tiled TIFF.
///
/// File extensions
/// .tif
GenericTiledTiff,
}
/// The different ways the u8 color values are encoded into a u32 value.
///
/// A successfull reading from OpenSlide's `read_region()` will result in a buffer of `u32` with
/// `height * width` elements, where `height` and `width` is the shape (in pixels) of the read
/// region. This `u32` value consist of four `u8` values which are the red, green, blue, and alpha
/// value of a certain pixel. This enum determines in which order to arange these channels within
/// one element.
#[derive(Clone, Debug)]
pub enum WordRepresentation {
/// From most significant bit to least significant bit: `[alpha, red, green, blue]`
BigEndian,
/// From most significant bit to least significant bit: `[blue, green, red, alpha]`
LittleEndian,
}
/// This function takes a buffer, as the one obtained from openslide::read_region, and decodes into
/// an Rgba image buffer.
pub fn decode_buffer<T: Unsigned + Integer + ToPrimitive + Debug + Display + Clone + Copy>(
buffer: &Vec<u32>,
height: T,
width: T,
word_representation: WordRepresentation,
) -> Result<RgbaImage, Error> {
let mut rgba_image = RgbaImage::new(
width
.to_u32()
.ok_or(format_err!("Conversion to primitive error"))?,
height
.to_u32()
.ok_or(format_err!("Conversion to primitive error"))?,
);
for (col, row, pixel) in rgba_image.enumerate_pixels_mut() {
let curr_pos = row
* width
.to_u32()
.ok_or(format_err!("Conversion to primitive error"))?
+ col;
let value = buffer[curr_pos as usize];
let mut buf = [0; 4];
match word_representation {
WordRepresentation::BigEndian => byteorder::BigEndian::write_u32(&mut buf, value),
WordRepresentation::LittleEndian => byteorder::BigEndian::write_u32(&mut buf, value),
};
let [alpha, mut red, mut green, mut blue] = buf;
if alpha != 0 && alpha != 255 {
red = (red as f32 * (255.0 / alpha as f32))
.round()
.max(0.0)
.min(255.0) as u8;
green = (green as f32 * (255.0 / alpha as f32))
.round()
.max(0.0)
.min(255.0) as u8;
blue = (blue as f32 * (255.0 / alpha as f32))
.round()
.max(0.0)
.min(255.0) as u8;
}
*pixel = Rgba([red, green, blue, alpha]);
}
Ok(rgba_image)
}
| 32.70229 | 99 | 0.596872 |
eb59dae619a84f33e68a525e1fb5a23c38bc0bd7
| 9,649 |
#![deny(missing_docs)]
//! # attr - static paths for Rust
use std::marker::PhantomData;
/// In case of failed traversals, this Result type is
/// returned.
pub type Result<X> = std::result::Result<X, String>;
/// Direct access to an attribute of a type.
///
/// All attributes need to be named for debugging purposes.
pub trait Attr<Type: ?Sized> {
/// The resulting value when accessing the attribute
type Output;
/// The attributes name
fn name(&self) -> &str;
/// Implementation of the retrieval
fn get(&self, i: Type) -> Self::Output;
}
/// Direct, possibly failing access to an attribute of a type.
pub trait InsecureAttr<Type: ?Sized> {
/// The resulting value when accessing the attribute
type Output;
/// The attributes name
fn name(&self) -> &str;
/// Implementation of the retrieval
fn get(&self, i: Type) -> Result<Self::Output>;
}
/// Access to a part of the attribute by index
///
/// This can be used to provide access to parts of a vector
pub trait IndexableAttr<Type: ?Sized, Idx: ?Sized> : Attr<Type>{
/// The resulting value when accessing the attribute
type Output;
/// Implementation of the indexing operation
fn at(&self, i: Type, idx: Idx) -> <Self as IndexableAttr<Type, Idx>>::Output;
}
/// Access to a part of the attribute by index, where access can fail
///
/// This can be used to provide access to parts of a vector where the exact structure
/// of vector parts is unknown.
pub trait InsecureIndexableAttr<Type: ?Sized, Idx: ?Sized> : InsecureAttr<Type> {
/// The resulting value when accessing the attribute
type Output;
/// Implementation of the indexing operation
fn at(&self, i: Type, idx: Idx) -> Result<<Self as InsecureIndexableAttr<Type, Idx>>::Output>;
}
/// Iteration over an attribute
///
/// This allows to express path that branch out, for example at a vector.
pub trait IterableAttr<'a, Type: ?Sized> : Attr<Type> {
/// The output item of the iteration
type Item: 'a;
/// Retrieval of an Iterator
fn iter(&self, i: Type) -> Box<Iterator<Item=Self::Item> + 'a>;
}
/// Insecure variant of iteration over an attribute
///
/// This allows to express path that branch out, for example at a vector.
/// This operation may fail.
pub trait InsecureIterableAttr<'a, Type: ?Sized> : Attr<Type> {
/// The output item of the iteration
type Item: 'a;
/// Retrieval of an Iterator
fn iter(&self, i: Type) -> Result<Box<Iterator<Item=Self::Item> + 'a>>;
}
/// Recursive path traversal
///
/// This trait should rarely need to be implemented yourself,
/// but is needed to express bounds when accepting paths.
pub trait Traverse<'a, 'b: 'a, X: 'b, Y: 'b> {
/// implementation of the traversal for a specific path
#[inline]
fn traverse(&'a self, val: X) -> Result<Y>;
}
/// The Identity is the end of a path and provides the point where
/// input equals output and we start returning.
/// It's necessary for recursive path traversal, but generally not
/// to be used in user code.
pub struct Identity;
/// A plain path describing how to retrieve a value at a point,
/// and then recursive down the rest of the path.
///
/// Paths are usually inferred and should not be directly used
/// in user code.
pub struct Path<Input, Output, A: Attr<Input>, Rest> {
attr: A,
next: Rest,
phantom_x: PhantomData<Input>,
phantom_z: PhantomData<Output>,
}
/// A path path describing how to retrieve a value at a point,
/// and then recursive down the rest of the path.
///
/// For InsecurePath, the retrieval operation could fail!
///
/// Paths are usually inferred and should not be directly used
/// in user code.
pub struct InsecurePath<Input, Output, A: InsecureAttr<Input>, Rest> {
attr: A,
next: Rest,
phantom_x: PhantomData<Input>,
phantom_z: PhantomData<Output>,
}
/// A path that describes a mapping operation, which later application
/// of a subpath.
///
/// Paths are usually inferred and should not be directly used
/// in user code.
pub struct MapPath<A, R> {
attr: A,
next: R,
}
/// `retrieve` is the starting point of a path that always
/// returns a value.
///
/// Note that path creation starts inside out, this
/// needs to be called with the innermost attribute.
pub fn retrieve<X, Z, A>(attr: A) -> Path<X, Z, A, Identity>
where A: Attr<X>
{
Path {
attr: attr,
next: Identity,
phantom_x: PhantomData,
phantom_z: PhantomData,
}
}
/// `retrieve_insecure` is the starting point of a path that is
/// not always present. For that reason, it returns a Result
/// indicating the success of the path operation.
pub fn retrieve_insecure<X, Z, A>(attr: A) -> InsecurePath<X, Z, A, Identity>
where A: InsecureAttr<X>
{
InsecurePath {
attr: attr,
next: Identity,
phantom_x: PhantomData,
phantom_z: PhantomData,
}
}
impl<'a, 'b: 'a, T: 'b> Traverse<'a, 'b, T, T> for Identity {
#[inline]
fn traverse(&'a self, val: T) -> Result<T> { Ok(val) }
}
impl<'a, 'b: 'a, X: 'b, Z: 'b, A: Attr<X>, R: Traverse<'a, 'b, A::Output, Z>> Traverse<'a, 'b, X, Z> for Path<X, Z, A, R> where <A as Attr<X>>::Output: 'b {
#[inline]
fn traverse(&'a self, obj: X) -> Result<Z> {
let val = self.attr.get(obj);
self.next.traverse(val)
}
}
impl<'a, 'b: 'a, X: 'b, Z: 'b, A: InsecureAttr<X>, R: Traverse<'a, 'b, A::Output, Z>> Traverse<'a, 'b, X, Z> for InsecurePath<X, Z, A, R> where <A as InsecureAttr<X>>::Output: 'b {
#[inline]
fn traverse(&'a self, obj: X) -> Result<Z> {
let val = self.attr.get(obj);
match val {
Ok(v) => self.next.traverse(v),
Err(_) => Err("Something went wrong".into())
}
}
}
impl<'a, X: 'a, Z: 'a, A: IterableAttr<'a, X>, R: Traverse<'a, 'a, A::Item, Z>> Traverse<'a, 'a, X, Box<Iterator<Item=Result<Z>> + 'a>> for MapPath<A, R> {
#[inline]
fn traverse(&'a self, obj: X) -> Result<Box<Iterator<Item=Result<Z>> + 'a>> {
let iter = self.attr.iter(obj);
let next = &self.next;
let map = iter.map(move |v| next.traverse(v) );
Ok(Box::new(map))
}
}
impl<'a, 'b: 'a, X: 'b, Z: 'b, A: Attr<X>, R: Traverse<'a, 'b, A::Output, Z>> Path<X, Z, A, R> where <A as Attr<X>>::Output: 'b {
/// Extends a path by another segment.
///
/// This needs a retrieval that always succeds
pub fn from<NX: 'b, NY: 'b, NZ: 'b, NA>(self, attr: NA) -> Path<NX, NZ, NA, Self>
where A: Attr<NY, Output=Z>,
NA: Attr<NX, Output=NY> {
Path {
attr: attr,
next: self,
phantom_x: PhantomData,
phantom_z: PhantomData,
}
}
/// Extends a path by another segment.
///
/// This assumes that the retrieval cannot always succeed.
pub fn try<NX: 'a, NY: 'a, NZ: 'a, NA>(self, attr: NA) -> InsecurePath<NX, NZ, NA, Self>
where A: Attr<NY, Output=Z>,
NA: InsecureAttr<NX, Output=NY> {
InsecurePath {
attr: attr,
next: self,
phantom_x: PhantomData,
phantom_z: PhantomData,
}
}
/// Extends a path by an iteration operation.
///
/// This assumes that the iteration is always possible
pub fn mapped<NX: 'b, NY: 'b, NZ: 'b, NA>(self, attr: NA) -> MapPath<NA, Self>
where A: Attr<X>,
R: Traverse<'a, 'b, A::Output, Z>,
NA: IterableAttr<'a, NX, Item=NY>,
Self: Traverse<'a, 'b, NY, NZ> {
MapPath {
attr: attr,
next: self,
}
}
}
impl<'a, 'b: 'a, X: 'b, Z: 'b, A: InsecureAttr<X>, R: Traverse<'a, 'b, A::Output, Z>> InsecurePath<X, Z, A, R> where <A as InsecureAttr<X>>::Output: 'b {
/// Extends a path that may fail by another segment that always succeeds.
pub fn from<NX: 'b, NY: 'b, NZ: 'b, NA>(self, attr: NA) -> Path<NX, NZ, NA, Self>
where A: InsecureAttr<NY, Output=Z>,
NA: Attr<NX, Output=NY> {
Path {
attr: attr,
next: self,
phantom_x: PhantomData,
phantom_z: PhantomData,
}
}
/// Extends a path that may fail by another segment that may fail.
pub fn try<NX: 'b, NY: 'b, NZ: 'b, NA>(self, attr: NA) -> InsecurePath<NX, NZ, NA, Self>
where A: InsecureAttr<NY, Output=Z>,
NA: InsecureAttr<NX, Output=NY> {
InsecurePath {
attr: attr,
next: self,
phantom_x: PhantomData,
phantom_z: PhantomData,
}
}
/// Extends a path that may fail by another segment that may fail.
pub fn mapped<NX: 'b, NY: 'b, NZ: 'b, NA>(self, attr: NA) -> MapPath<NA, Self>
where A: InsecureAttr<X>,
R: Traverse<'a, 'b, A::Output, Z>,
NA: IterableAttr<'a, NX, Item=NY>,
Self: Traverse<'a, 'b, NY, NZ> {
MapPath {
attr: attr,
next: self,
}
}
}
impl<A, R> MapPath<A, R> {
/// Extends a mapped path by another segment that always succeeds
pub fn from<'a, 'b: 'a, X: 'b, Y: 'b, Z: 'b, NX: 'b, NY: 'b, NA>(self, attr: NA) -> Path<NX, Box<std::iter::Iterator<Item=Result<Z>> + 'a>, NA, Self>
where A: IterableAttr<'a, X, Item=Y>,
R: Traverse<'a, 'b, Y, Z>,
NA: Attr<NX, Output=NY>,
Self: Traverse<'a, 'b, NY, Box<std::iter::Iterator<Item=Result<Z>>>>
{
Path {
attr: attr,
next: self,
phantom_x: PhantomData,
phantom_z: PhantomData,
}
}
}
| 32.708475 | 180 | 0.588662 |
4bbca0b9d641ea83bdf2e6d38c2f6a762f8032fc
| 3,208 |
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
#![allow(missing_docs)]
//! Reserved OIDs through Materialized.
pub const TYPE_LIST_OID: u32 = 16_384;
pub const TYPE_MAP_OID: u32 = 16_385;
pub const FUNC_CEIL_F32_OID: u32 = 16_386;
pub const FUNC_CONCAT_AGG_OID: u32 = 16_387;
pub const FUNC_CSV_EXTRACT_OID: u32 = 16_388;
pub const FUNC_CURRENT_TIMESTAMP_OID: u32 = 16_389;
pub const FUNC_FLOOR_F32_OID: u32 = 16_390;
pub const FUNC_LIST_APPEND_OID: u32 = 16_392;
pub const FUNC_LIST_CAT_OID: u32 = 16_393;
pub const FUNC_LIST_LENGTH_MAX_OID: u32 = 16_394;
pub const FUNC_LIST_LENGTH_OID: u32 = 16_395;
pub const FUNC_LIST_NDIMS_OID: u32 = 16_396;
pub const FUNC_LIST_PREPEND_OID: u32 = 16_397;
pub const FUNC_MAX_BOOL_OID: u32 = 16_398;
pub const FUNC_MIN_BOOL_OID: u32 = 16_399;
pub const FUNC_MZ_ALL_OID: u32 = 16_400;
pub const FUNC_MZ_ANY_OID: u32 = 16_401;
pub const FUNC_MZ_AVG_PROMOTION_DECIMAL_OID: u32 = 16_402;
pub const FUNC_MZ_AVG_PROMOTION_F32_OID: u32 = 16_403;
pub const FUNC_MZ_AVG_PROMOTION_F64_OID: u32 = 16_404;
pub const FUNC_MZ_AVG_PROMOTION_I32_OID: u32 = 16_405;
pub const FUNC_MZ_CLASSIFY_OBJECT_ID_OID: u32 = 16_406;
pub const FUNC_MZ_CLUSTER_ID_OID: u32 = 16_407;
pub const FUNC_MZ_IS_MATERIALIZED_OID: u32 = 16_408;
pub const FUNC_MZ_LOGICAL_TIMESTAMP_OID: u32 = 16_409;
pub const FUNC_MZ_RENDER_TYPEMOD_OID: u32 = 16_410;
pub const FUNC_MZ_VERSION_OID: u32 = 16_411;
pub const FUNC_REGEXP_EXTRACT_OID: u32 = 16_412;
pub const FUNC_REPEAT_OID: u32 = 16_413;
pub const FUNC_ROUND_F32_OID: u32 = 16_414;
pub const FUNC_UNNEST_LIST_OID: u32 = 16_416;
pub const OP_CONCAT_ELEMENY_LIST_OID: u32 = 16_417;
pub const OP_CONCAT_LIST_ELEMENT_OID: u32 = 16_418;
pub const OP_CONCAT_LIST_LIST_OID: u32 = 16_419;
pub const OP_CONTAINED_JSONB_STRING_OID: u32 = 16_420;
pub const OP_CONTAINED_MAP_MAP_OID: u32 = 16_421;
pub const OP_CONTAINED_STRING_JSONB_OID: u32 = 16_422;
pub const OP_CONTAINS_ALL_KEYS_MAP_OID: u32 = 16_423;
pub const OP_CONTAINS_ANY_KEYS_MAP_OID: u32 = 16_424;
pub const OP_CONTAINS_JSONB_STRING_OID: u32 = 16_425;
pub const OP_CONTAINS_KEY_MAP_OID: u32 = 16_426;
pub const OP_CONTAINS_MAP_MAP_OID: u32 = 16_427;
pub const OP_CONTAINS_STRING_JSONB_OID: u32 = 16_428;
pub const OP_GET_VALUE_MAP_OID: u32 = 16_429;
pub const OP_GET_VALUES_MAP_OID: u32 = 16_430;
pub const OP_MOD_F32_OID: u32 = 16_431;
pub const OP_MOD_F64_OID: u32 = 16_432;
pub const OP_UNARY_PLUS_OID: u32 = 16_433;
pub const FUNC_MZ_SLEEP_OID: u32 = 16_434;
pub const FUNC_MZ_SESSION_ID_OID: u32 = 16_435;
pub const FUNC_MZ_UPTIME_OID: u32 = 16_436;
pub const FUNC_MZ_WORKERS_OID: u32 = 16_437;
pub const __DEPRECATED_TYPE_APD_OID: u32 = 16_438;
pub const FUNC_LIST_EQ_OID: u32 = 16_439;
pub const FUNC_MZ_ROW_SIZE: u32 = 16_440;
pub const FUNC_MAX_NUMERIC_OID: u32 = 16_441;
pub const FUNC_MIN_NUMERIC_OID: u32 = 16_442;
pub const FUNC_MZ_AVG_PROMOTION_I16_OID: u32 = 16_443;
// next ID: 16_444
| 44.555556 | 69 | 0.802369 |
8a10377cc05f8ac584d5de96c1a317ef032bb27a
| 32,515 |
#![allow(non_snake_case)]
use crate::consts::*;
use crate::debug_manager::DebugManager;
use crate::error::*;
use crate::macos::ioapic::IoApic;
use crate::paging::*;
use crate::vm::VirtualCPU;
use burst::x86::{disassemble_64, InstructionOperation, OperandType};
use lazy_static::lazy_static;
use log::{debug, error, trace};
use std::sync::{Arc, Mutex};
use x86::controlregs::*;
use x86::cpuid::*;
use x86::msr::*;
use x86::segmentation::*;
use x86::Ring;
use xhypervisor;
use xhypervisor::consts::vmcs::*;
use xhypervisor::consts::vmx_cap::{
CPU_BASED2_APIC_REG_VIRT, CPU_BASED2_RDTSCP, CPU_BASED_MONITOR, CPU_BASED_MSR_BITMAPS,
CPU_BASED_MWAIT, CPU_BASED_SECONDARY_CTLS, CPU_BASED_TPR_SHADOW, CPU_BASED_TSC_OFFSET,
PIN_BASED_INTR, PIN_BASED_NMI, PIN_BASED_VIRTUAL_NMI, VMENTRY_GUEST_IA32E, VMENTRY_LOAD_EFER,
};
use xhypervisor::consts::vmx_exit;
use xhypervisor::{read_vmx_cap, vCPU, x86Reg};
/* desired control word constrained by hardware/hypervisor capabilities */
fn cap2ctrl(cap: u64, ctrl: u64) -> u64 {
(ctrl | (cap & 0xffffffff)) & (cap >> 32)
}
lazy_static! {
static ref CAP_PINBASED: u64 = {
let cap: u64 = { read_vmx_cap(&xhypervisor::VMXCap::PINBASED).unwrap() };
cap2ctrl(cap, PIN_BASED_INTR | PIN_BASED_NMI | PIN_BASED_VIRTUAL_NMI)
};
static ref CAP_PROCBASED: u64 =
{
let cap: u64 = { read_vmx_cap(&xhypervisor::VMXCap::PROCBASED).unwrap() };
cap2ctrl(
cap,
CPU_BASED_SECONDARY_CTLS
| CPU_BASED_MWAIT | CPU_BASED_MSR_BITMAPS
| CPU_BASED_MONITOR | CPU_BASED_TSC_OFFSET
| CPU_BASED_TPR_SHADOW,
)
};
static ref CAP_PROCBASED2: u64 = {
let cap: u64 = { read_vmx_cap(&xhypervisor::VMXCap::PROCBASED2).unwrap() };
cap2ctrl(cap, CPU_BASED2_RDTSCP | CPU_BASED2_APIC_REG_VIRT)
};
static ref CAP_ENTRY: u64 = {
let cap: u64 = { read_vmx_cap(&xhypervisor::VMXCap::ENTRY).unwrap() };
cap2ctrl(cap, VMENTRY_LOAD_EFER | VMENTRY_GUEST_IA32E)
};
static ref CAP_EXIT: u64 = {
let cap: u64 = { read_vmx_cap(&xhypervisor::VMXCap::EXIT).unwrap() };
cap2ctrl(cap, 0)
};
}
pub struct UhyveCPU {
id: u32,
kernel_path: String,
vcpu: vCPU,
vm_start: usize,
apic_base: u64,
ioapic: Arc<Mutex<IoApic>>,
pub dbg: Option<Arc<Mutex<DebugManager>>>,
}
impl UhyveCPU {
pub fn new(
id: u32,
kernel_path: String,
vm_start: usize,
ioapic: Arc<Mutex<IoApic>>,
dbg: Option<Arc<Mutex<DebugManager>>>,
) -> UhyveCPU {
UhyveCPU {
id,
kernel_path,
vcpu: vCPU::new().unwrap(),
vm_start,
apic_base: APIC_DEFAULT_BASE,
ioapic,
dbg,
}
}
fn setup_system_gdt(&mut self) -> Result<()> {
debug!("Setup GDT");
self.vcpu.write_vmcs(VMCS_GUEST_CS_LIMIT, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_CS_BASE, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_CS_AR, 0x209B)?;
self.vcpu.write_vmcs(VMCS_GUEST_SS_LIMIT, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_SS_BASE, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_SS_AR, 0x4093)?;
self.vcpu.write_vmcs(VMCS_GUEST_DS_LIMIT, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_DS_BASE, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_DS_AR, 0x4093)?;
self.vcpu.write_vmcs(VMCS_GUEST_ES_LIMIT, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_ES_BASE, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_ES_AR, 0x4093)?;
self.vcpu.write_vmcs(VMCS_GUEST_FS_LIMIT, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_FS_BASE, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_FS_AR, 0x4093)?;
self.vcpu.write_vmcs(VMCS_GUEST_GS_LIMIT, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_GS_BASE, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_GS_AR, 0x4093)?;
self.vcpu.write_vmcs(VMCS_GUEST_GDTR_BASE, BOOT_GDT)?;
self.vcpu.write_vmcs(
VMCS_GUEST_GDTR_LIMIT,
((std::mem::size_of::<u64>() * BOOT_GDT_MAX as usize) - 1) as u64,
)?;
self.vcpu.write_vmcs(VMCS_GUEST_IDTR_BASE, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_IDTR_LIMIT, 0xffff)?;
self.vcpu.write_vmcs(VMCS_GUEST_TR, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_TR_LIMIT, 0xffff)?;
self.vcpu.write_vmcs(VMCS_GUEST_TR_AR, 0x8b)?;
self.vcpu.write_vmcs(VMCS_GUEST_TR_BASE, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_LDTR, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_LDTR_LIMIT, 0xffff)?;
self.vcpu.write_vmcs(VMCS_GUEST_LDTR_AR, 0x82)?;
self.vcpu.write_vmcs(VMCS_GUEST_LDTR_BASE, 0)?;
// Reload the segment descriptors
self.vcpu.write_register(
&x86Reg::CS,
SegmentSelector::new(GDT_KERNEL_CODE as u16, Ring::Ring0).bits() as u64,
)?;
self.vcpu.write_register(
&x86Reg::DS,
SegmentSelector::new(GDT_KERNEL_DATA as u16, Ring::Ring0).bits() as u64,
)?;
self.vcpu.write_register(
&x86Reg::ES,
SegmentSelector::new(GDT_KERNEL_DATA as u16, Ring::Ring0).bits() as u64,
)?;
self.vcpu.write_register(
&x86Reg::SS,
SegmentSelector::new(GDT_KERNEL_DATA as u16, Ring::Ring0).bits() as u64,
)?;
self.vcpu.write_register(
&x86Reg::FS,
SegmentSelector::new(GDT_KERNEL_DATA as u16, Ring::Ring0).bits() as u64,
)?;
self.vcpu.write_register(
&x86Reg::GS,
SegmentSelector::new(GDT_KERNEL_DATA as u16, Ring::Ring0).bits() as u64,
)?;
Ok(())
}
fn setup_system_64bit(&mut self) -> Result<()> {
debug!("Setup 64bit mode");
let cr0 = Cr0::CR0_PROTECTED_MODE
| Cr0::CR0_ENABLE_PAGING
| Cr0::CR0_EXTENSION_TYPE
| Cr0::CR0_NUMERIC_ERROR;
let cr4 = Cr4::CR4_ENABLE_PAE | Cr4::CR4_ENABLE_VMX;
self.vcpu
.write_vmcs(VMCS_GUEST_IA32_EFER, EFER_LME | EFER_LMA)?;
self.vcpu.write_vmcs(
VMCS_CTRL_CR0_MASK,
(Cr0::CR0_CACHE_DISABLE | Cr0::CR0_NOT_WRITE_THROUGH | cr0).bits() as u64,
)?;
self.vcpu
.write_vmcs(VMCS_CTRL_CR0_SHADOW, cr0.bits() as u64)?;
self.vcpu
.write_vmcs(VMCS_CTRL_CR4_MASK, cr4.bits() as u64)?;
self.vcpu
.write_vmcs(VMCS_CTRL_CR4_SHADOW, cr4.bits() as u64)?;
self.vcpu.write_register(&x86Reg::CR0, cr0.bits() as u64)?;
self.vcpu.write_register(&x86Reg::CR4, cr4.bits() as u64)?;
self.vcpu.write_register(&x86Reg::CR3, BOOT_PML4)?;
self.vcpu.write_register(&x86Reg::DR7, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_SYSENTER_ESP, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_SYSENTER_EIP, 0)?;
Ok(())
}
fn setup_msr(&mut self) -> Result<()> {
const IA32_CSTAR: u32 = 0xc0000083;
debug!("Enable MSR registers");
self.vcpu.enable_native_msr(IA32_FS_BASE, true)?;
self.vcpu.enable_native_msr(IA32_GS_BASE, true)?;
self.vcpu.enable_native_msr(IA32_KERNEL_GSBASE, true)?;
self.vcpu.enable_native_msr(IA32_SYSENTER_CS, true)?;
self.vcpu.enable_native_msr(IA32_SYSENTER_EIP, true)?;
self.vcpu.enable_native_msr(IA32_SYSENTER_ESP, true)?;
self.vcpu.enable_native_msr(IA32_STAR, true)?;
self.vcpu.enable_native_msr(IA32_LSTAR, true)?;
self.vcpu.enable_native_msr(IA32_CSTAR, true)?;
self.vcpu.enable_native_msr(IA32_FMASK, true)?;
self.vcpu.enable_native_msr(TSC, true)?;
self.vcpu.enable_native_msr(IA32_TSC_AUX, true)?;
Ok(())
}
fn setup_capabilities(&mut self) -> Result<()> {
debug!("Setup VMX capabilities");
self.vcpu.write_vmcs(VMCS_CTRL_PIN_BASED, *CAP_PINBASED)?;
debug!(
"Pin-Based VM-Execution Controls 0x{:x}",
self.vcpu.read_vmcs(VMCS_CTRL_PIN_BASED)?
);
self.vcpu.write_vmcs(VMCS_CTRL_CPU_BASED, *CAP_PROCBASED)?;
debug!(
"Primary Processor-Based VM-Execution Controls 0x{:x}",
self.vcpu.read_vmcs(VMCS_CTRL_CPU_BASED)?
);
self.vcpu
.write_vmcs(VMCS_CTRL_CPU_BASED2, *CAP_PROCBASED2)?;
debug!(
"Secondary Processor-Based VM-Execution Controls 0x{:x}",
self.vcpu.read_vmcs(VMCS_CTRL_CPU_BASED2)?
);
self.vcpu
.write_vmcs(VMCS_CTRL_VMENTRY_CONTROLS, *CAP_ENTRY)?;
debug!(
"VM-Entry Controls 0x{:x}",
self.vcpu.read_vmcs(VMCS_CTRL_VMENTRY_CONTROLS)?
);
self.vcpu.write_vmcs(VMCS_CTRL_VMEXIT_CONTROLS, *CAP_EXIT)?;
debug!(
"VM-Exit Controls 0x{:x}",
self.vcpu.read_vmcs(VMCS_CTRL_VMEXIT_CONTROLS)?
);
Ok(())
}
fn emulate_cpuid(&mut self, rip: u64) -> Result<()> {
let len = self.vcpu.read_vmcs(VMCS_RO_VMEXIT_INSTR_LEN)?;
let rax = self.vcpu.read_register(&x86Reg::RAX)?;
let rcx = self.vcpu.read_register(&x86Reg::RCX)?;
match rax {
0x80000002 => {
// create own processor string (first part)
let mut id_reg_values: [u32; 4] = [0; 4];
let id = b"uhyve - unikerne";
unsafe {
std::ptr::copy_nonoverlapping(
id.as_ptr(),
id_reg_values.as_mut_ptr() as *mut u8,
id.len(),
);
}
self.vcpu
.write_register(&x86Reg::RAX, id_reg_values[0] as u64)?;
self.vcpu
.write_register(&x86Reg::RBX, id_reg_values[1] as u64)?;
self.vcpu
.write_register(&x86Reg::RCX, id_reg_values[2] as u64)?;
self.vcpu
.write_register(&x86Reg::RDX, id_reg_values[3] as u64)?;
}
0x80000003 => {
// create own processor string (second part)
let mut id_reg_values: [u32; 4] = [0; 4];
let id = b"l hypervisor\0";
unsafe {
std::ptr::copy_nonoverlapping(
id.as_ptr(),
id_reg_values.as_mut_ptr() as *mut u8,
id.len(),
);
}
self.vcpu
.write_register(&x86Reg::RAX, id_reg_values[0] as u64)?;
self.vcpu
.write_register(&x86Reg::RBX, id_reg_values[1] as u64)?;
self.vcpu
.write_register(&x86Reg::RCX, id_reg_values[2] as u64)?;
self.vcpu
.write_register(&x86Reg::RDX, id_reg_values[3] as u64)?;
}
0x80000004 => {
self.vcpu.write_register(&x86Reg::RAX, 0)?;
self.vcpu.write_register(&x86Reg::RBX, 0)?;
self.vcpu.write_register(&x86Reg::RCX, 0)?;
self.vcpu.write_register(&x86Reg::RDX, 0)?;
}
_ => {
let extended_features = (rax == 7) && (rcx == 0);
let processor_info = rax == 1;
let result = native_cpuid::cpuid_count(rax as u32, rcx as u32);
let rax = result.eax as u64;
let mut rbx = result.ebx as u64;
let mut rcx = result.ecx as u64;
let rdx = result.edx as u64;
if processor_info {
// inform that the kernel is running within a hypervisor
rcx |= 1 << 31;
}
if extended_features {
// disable SGX support
rbx &= !(1 << 2);
}
self.vcpu.write_register(&x86Reg::RAX, rax)?;
self.vcpu.write_register(&x86Reg::RBX, rbx)?;
self.vcpu.write_register(&x86Reg::RCX, rcx)?;
self.vcpu.write_register(&x86Reg::RDX, rdx)?;
}
}
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
Ok(())
}
fn emulate_rdmsr(&mut self, rip: u64) -> Result<()> {
let len = self.vcpu.read_vmcs(VMCS_RO_VMEXIT_INSTR_LEN)?;
let rcx = self.vcpu.read_register(&x86Reg::RCX)? & 0xFFFFFFFF;
match rcx as u32 {
IA32_EFER => {
let efer = self.vcpu.read_vmcs(VMCS_GUEST_IA32_EFER)?;
let rax = efer & 0xFFFFFFFF;
let rdx = efer >> 32;
self.vcpu.write_register(&x86Reg::RAX, rax)?;
self.vcpu.write_register(&x86Reg::RDX, rdx)?;
}
IA32_MISC_ENABLE => {
self.vcpu.write_register(&x86Reg::RAX, 0)?;
self.vcpu.write_register(&x86Reg::RDX, 0)?;
}
IA32_APIC_BASE => {
self.vcpu
.write_register(&x86Reg::RAX, self.apic_base & 0xFFFFFFFF)?;
self.vcpu
.write_register(&x86Reg::RDX, (self.apic_base >> 32) & 0xFFFFFFFF)?;
}
_ => {
error!("Unable to read msr 0x{:x}!", rcx);
return Err(Error::InternalError);
}
}
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
Ok(())
}
fn emulate_wrmsr(&mut self, rip: u64) -> Result<()> {
let len = self.vcpu.read_vmcs(VMCS_RO_VMEXIT_INSTR_LEN)?;
let rcx = self.vcpu.read_register(&x86Reg::RCX)? & 0xFFFFFFFF;
match rcx as u32 {
IA32_EFER => {
let rax = self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF;
let rdx = self.vcpu.read_register(&x86Reg::RDX)? & 0xFFFFFFFF;
let efer = ((rdx as u64) << 32) | rax as u64;
self.vcpu.write_vmcs(VMCS_GUEST_IA32_EFER, efer)?;
}
IA32_APIC_BASE => {
let rax = self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF;
let rdx = self.vcpu.read_register(&x86Reg::RDX)? & 0xFFFFFFFF;
let base = ((rdx as u64) << 32) | rax as u64;
self.apic_base = base;
self.vcpu.set_apic_addr(base & !0xFFF)?;
}
IA32_X2APIC_TPR => {}
IA32_X2APIC_SIVR => {}
IA32_X2APIC_LVT_TIMER => {}
IA32_X2APIC_LVT_THERMAL => {}
IA32_X2APIC_LVT_PMI => {}
IA32_X2APIC_LVT_LINT0 => {}
IA32_X2APIC_LVT_LINT1 => {}
IA32_X2APIC_LVT_ERROR => {}
IA32_X2APIC_EOI => {}
IA32_X2APIC_ICR => {}
_ => {
error!("Unable to write msr 0x{:x}!", rcx);
return Err(Error::InternalError);
}
}
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
Ok(())
}
fn emulate_xsetbv(&mut self, rip: u64) -> Result<()> {
let len = self.vcpu.read_vmcs(VMCS_RO_VMEXIT_INSTR_LEN)?;
let eax = self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF;
let edx = self.vcpu.read_register(&x86Reg::RDX)? & 0xFFFFFFFF;
let xcr0: u64 = ((edx as u64) << 32) | eax as u64;
self.vcpu.write_register(&x86Reg::XCR0, xcr0)?;
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
Ok(())
}
fn emulate_ioapic(&mut self, rip: u64, address: u64) -> Result<()> {
let len = self.vcpu.read_vmcs(VMCS_RO_VMEXIT_INSTR_LEN)?;
let qualification = self.vcpu.read_vmcs(VMCS_RO_EXIT_QUALIFIC)?;
let read = (qualification & (1 << 0)) != 0;
let write = (qualification & (1 << 1)) != 0;
let code =
unsafe { std::slice::from_raw_parts(self.host_address(rip as usize) as *const u8, 8) };
if let Ok(instr) = disassemble_64(code, rip as usize, code.len()) {
match instr.operation {
InstructionOperation::MOV => {
if write {
let val = match instr.operands[1].operand {
OperandType::IMM => instr.operands[1].immediate as u64,
OperandType::REG_EDI => {
self.vcpu.read_register(&x86Reg::RDI)? & 0xFFFFFFFF
}
OperandType::REG_ESI => {
self.vcpu.read_register(&x86Reg::RSI)? & 0xFFFFFFFF
}
OperandType::REG_EBP => {
self.vcpu.read_register(&x86Reg::RBP)? & 0xFFFFFFFF
}
OperandType::REG_EAX => {
self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF
}
OperandType::REG_EBX => {
self.vcpu.read_register(&x86Reg::RBX)? & 0xFFFFFFFF
}
OperandType::REG_ECX => {
self.vcpu.read_register(&x86Reg::RCX)? & 0xFFFFFFFF
}
OperandType::REG_EDX => {
self.vcpu.read_register(&x86Reg::RDX)? & 0xFFFFFFFF
}
_ => {
error!("IO-APIC write failed: {:?}", instr.operands);
return Err(Error::InternalError);
}
};
self.ioapic
.lock()
.unwrap()
.write(address - IOAPIC_BASE, val)?;
}
if read {
let value = self.ioapic.lock().unwrap().read(address - IOAPIC_BASE)?;
match instr.operands[0].operand {
OperandType::REG_EDI => {
self.vcpu.write_register(&x86Reg::RDI, value)?;
}
OperandType::REG_ESI => {
self.vcpu.write_register(&x86Reg::RSI, value)?;
}
OperandType::REG_EBP => {
self.vcpu.write_register(&x86Reg::RBP, value)?;
}
OperandType::REG_EAX => {
self.vcpu.write_register(&x86Reg::RAX, value)?;
}
OperandType::REG_EBX => {
self.vcpu.write_register(&x86Reg::RBX, value)?;
}
OperandType::REG_ECX => {
self.vcpu.write_register(&x86Reg::RCX, value)?;
}
OperandType::REG_EDX => {
self.vcpu.write_register(&x86Reg::RDX, value)?;
}
_ => {
error!("IO-APIC read failed: {:?}", instr.operands);
return Err(Error::InternalError);
}
}
}
}
_ => {
error!("IO-APIC Emulation failed");
return Err(Error::InternalError);
}
}
};
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
Ok(())
}
pub fn get_vcpu(&self) -> &vCPU {
&self.vcpu
}
}
impl VirtualCPU for UhyveCPU {
fn init(&mut self, entry_point: u64) -> Result<()> {
self.setup_capabilities()?;
self.setup_msr()?;
self.vcpu
.write_vmcs(VMCS_CTRL_EXC_BITMAP, (1 << 3) | (1 << 1))?;
self.vcpu.write_vmcs(VMCS_CTRL_TPR_THRESHOLD, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_SYSENTER_EIP, 0)?;
self.vcpu.write_vmcs(VMCS_GUEST_SYSENTER_ESP, 0)?;
debug!("Setup general purpose registers");
self.vcpu.write_register(&x86Reg::RIP, entry_point)?;
self.vcpu.write_register(&x86Reg::RFLAGS, 0x2)?;
// create temporary stack to boot the kernel
self.vcpu.write_register(&x86Reg::RSP, 0x200000 - 0x1000)?;
self.vcpu.write_register(&x86Reg::RBP, 0)?;
self.vcpu.write_register(&x86Reg::RAX, 0)?;
self.vcpu.write_register(&x86Reg::RBX, 0)?;
self.vcpu.write_register(&x86Reg::RCX, 0)?;
self.vcpu.write_register(&x86Reg::RDX, 0)?;
self.vcpu.write_register(&x86Reg::RSI, 0)?;
self.vcpu.write_register(&x86Reg::RDI, BOOT_INFO_ADDR)?;
self.vcpu.write_register(&x86Reg::R8, 0)?;
self.vcpu.write_register(&x86Reg::R9, 0)?;
self.vcpu.write_register(&x86Reg::R10, 0)?;
self.vcpu.write_register(&x86Reg::R11, 0)?;
self.vcpu.write_register(&x86Reg::R12, 0)?;
self.vcpu.write_register(&x86Reg::R13, 0)?;
self.vcpu.write_register(&x86Reg::R14, 0)?;
self.vcpu.write_register(&x86Reg::R15, 0)?;
self.setup_system_gdt()?;
self.setup_system_64bit()?;
Ok(())
}
fn kernel_path(&self) -> String {
self.kernel_path.clone()
}
fn host_address(&self, addr: usize) -> usize {
addr + self.vm_start
}
fn virt_to_phys(&self, addr: usize) -> usize {
let executable_disable_mask: usize = !PageTableEntryFlags::EXECUTE_DISABLE.bits();
let mut page_table = self.host_address(BOOT_PML4 as usize) as *const usize;
let mut page_bits = 39;
let mut entry: usize = 0;
for _i in 0..4 {
let index = (addr >> page_bits) & ((1 << PAGE_MAP_BITS) - 1);
entry = unsafe { *page_table.add(index) & executable_disable_mask };
// bit 7 is set if this entry references a 1 GiB (PDPT) or 2 MiB (PDT) page.
if entry & PageTableEntryFlags::HUGE_PAGE.bits() != 0 {
return (entry & ((!0usize) << page_bits)) | (addr & !((!0usize) << page_bits));
} else {
page_table = self.host_address(entry & !((1 << PAGE_BITS) - 1)) as *const usize;
page_bits -= PAGE_MAP_BITS;
}
}
(entry & ((!0usize) << PAGE_BITS)) | (addr & !((!0usize) << PAGE_BITS))
}
fn run(&mut self) -> Result<Option<i32>> {
//self.print_registers();
// Pause first CPU before first execution, so we have time to attach debugger
if self.id == 0 {
self.gdb_handle_exception(false);
}
debug!("Run vCPU {}", self.id);
loop {
/*if self.extint_pending == true {
let irq_info = self.vcpu.read_vmcs(VMCS_CTRL_VMENTRY_IRQ_INFO)?;
let flags = self.vcpu.read_register(&x86Reg::RFLAGS)?;
let ignore_irq = self.vcpu.read_vmcs(VMCS_GUEST_IGNORE_IRQ)?;
if ignore_irq & 1 != 1
&& irq_info & (1 << 31) != (1 << 31)
&& flags & (1 << 9) == (1 << 9)
{
// deliver timer interrupt, we don't support other kind of interrupts
// => see table 24-15 of the Intel Manual
let info = 0x20 | (0 << 8) | (1 << 31);
self.vcpu.write_vmcs(VMCS_CTRL_VMENTRY_IRQ_INFO, info)?;
self.extint_pending = false;
}
}*/
self.vcpu.run()?;
let reason = self.vcpu.read_vmcs(VMCS_RO_EXIT_REASON)? & 0xffff;
let rip = self.vcpu.read_register(&x86Reg::RIP)?;
match reason {
vmx_exit::VMX_REASON_EXC_NMI => {
let irq_info = self.vcpu.read_vmcs(VMCS_RO_VMEXIT_IRQ_INFO)?;
let irq_vec = irq_info & 0xFF;
//let irq_type = (irq_info >> 8) & 0xFF;
let valid = (irq_info & (1 << 31)) != 0;
let trap_or_breakpoint = (irq_vec == 3) || (irq_vec == 1);
if valid && trap_or_breakpoint {
debug!("Handle breakpoint exception");
self.gdb_handle_exception(true);
} else {
debug!("Receive exception or non-maskable interrupt {}!", irq_vec);
//self.print_registers();
return Err(Error::InternalError);
}
}
vmx_exit::VMX_REASON_TRIPLE_FAULT => {
error!("Triple fault! System crashed!");
self.print_registers();
return Err(Error::UnhandledExitReason);
}
vmx_exit::VMX_REASON_CPUID => {
self.emulate_cpuid(rip)?;
}
vmx_exit::VMX_REASON_RDMSR => {
self.emulate_rdmsr(rip)?;
}
vmx_exit::VMX_REASON_WRMSR => {
self.emulate_wrmsr(rip)?;
}
vmx_exit::VMX_REASON_XSETBV => {
self.emulate_xsetbv(rip)?;
}
vmx_exit::VMX_REASON_IRQ => {
trace!("Exit reason {} - External interrupt", reason);
}
vmx_exit::VMX_REASON_VMENTRY_GUEST => {
error!(
"Exit reason {} - VM-entry failure due to invalid guest state",
reason
);
//self.print_registers();
return Err(Error::InternalError);
}
vmx_exit::VMX_REASON_EPT_VIOLATION => {
let gpa = self.vcpu.read_vmcs(VMCS_GUEST_PHYSICAL_ADDRESS)?;
trace!("Exit reason {} - EPT violation at 0x{:x}", reason, gpa);
if (IOAPIC_BASE..IOAPIC_BASE + IOAPIC_SIZE).contains(&gpa) {
self.emulate_ioapic(rip, gpa)?;
}
}
vmx_exit::VMX_REASON_RDRAND => {
debug!("Exit reason {} - VMX_REASON_RDRAND", reason);
}
vmx_exit::VMX_REASON_IO => {
let qualification = self.vcpu.read_vmcs(VMCS_RO_EXIT_QUALIFIC)?;
let input = (qualification & 8) != 0;
let len = self.vcpu.read_vmcs(VMCS_RO_VMEXIT_INSTR_LEN)?;
let port: u16 = ((qualification >> 16) & 0xFFFF) as u16;
if input {
error!("Invalid I/O operation");
return Err(Error::InternalError);
}
match port {
SHUTDOWN_PORT => {
return Ok(None);
}
UHYVE_UART_PORT => {
let al = (self.vcpu.read_register(&x86Reg::RAX)? & 0xFF) as u8;
self.uart(&[al]).unwrap();
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
}
UHYVE_PORT_CMDSIZE => {
let data_addr: u64 =
self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF;
self.cmdsize(self.host_address(data_addr as usize))?;
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
}
UHYVE_PORT_CMDVAL => {
let data_addr: u64 =
self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF;
self.cmdval(self.host_address(data_addr as usize))?;
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
}
UHYVE_PORT_EXIT => {
let data_addr: u64 =
self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF;
return Ok(Some(self.exit(self.host_address(data_addr as usize))));
}
UHYVE_PORT_OPEN => {
let data_addr: u64 =
self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF;
self.open(self.host_address(data_addr as usize))?;
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
}
UHYVE_PORT_WRITE => {
let data_addr: u64 =
self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF;
self.write(self.host_address(data_addr as usize))?;
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
}
UHYVE_PORT_READ => {
let data_addr: u64 =
self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF;
self.read(self.host_address(data_addr as usize))?;
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
}
UHYVE_PORT_UNLINK => {
let data_addr: u64 =
self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF;
self.unlink(self.host_address(data_addr as usize))?;
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
}
UHYVE_PORT_LSEEK => {
let data_addr: u64 =
self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF;
self.lseek(self.host_address(data_addr as usize))?;
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
}
UHYVE_PORT_CLOSE => {
let data_addr: u64 =
self.vcpu.read_register(&x86Reg::RAX)? & 0xFFFFFFFF;
self.close(self.host_address(data_addr as usize))?;
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
}
_ => {
trace!("Receive unhandled output command at port 0x{:x}", port);
self.vcpu.write_register(&x86Reg::RIP, rip + len)?;
}
}
}
_ => {
error!("Unhandled exit: {}", reason);
self.print_registers();
return Err(Error::UnhandledExitReason);
}
}
}
}
fn print_registers(&self) {
println!("\nDump state of CPU {}", self.id);
println!("VMCS:");
println!("-----");
println!(
"CR0: mask {:016x} shadow {:016x}",
self.vcpu.read_vmcs(VMCS_CTRL_CR0_MASK).unwrap(),
self.vcpu.read_vmcs(VMCS_CTRL_CR0_SHADOW).unwrap()
);
println!(
"CR4: mask {:016x} shadow {:016x}",
self.vcpu.read_vmcs(VMCS_CTRL_CR4_MASK).unwrap(),
self.vcpu.read_vmcs(VMCS_CTRL_CR4_SHADOW).unwrap()
);
println!(
"Pinbased: {:016x}\n1st: {:016x}\n2nd: {:016x}",
self.vcpu.read_vmcs(VMCS_CTRL_PIN_BASED).unwrap(),
self.vcpu.read_vmcs(VMCS_CTRL_CPU_BASED).unwrap(),
self.vcpu.read_vmcs(VMCS_CTRL_CPU_BASED2).unwrap()
);
println!(
"Entry: {:016x}\nExit: {:016x}",
self.vcpu.read_vmcs(VMCS_CTRL_VMENTRY_CONTROLS).unwrap(),
self.vcpu.read_vmcs(VMCS_CTRL_VMEXIT_CONTROLS).unwrap()
);
println!("\nRegisters:");
println!("----------");
let rip = self.vcpu.read_register(&x86Reg::RIP).unwrap();
let rflags = self.vcpu.read_register(&x86Reg::RFLAGS).unwrap();
let rsp = self.vcpu.read_register(&x86Reg::RSP).unwrap();
let rbp = self.vcpu.read_register(&x86Reg::RBP).unwrap();
let rax = self.vcpu.read_register(&x86Reg::RAX).unwrap();
let rbx = self.vcpu.read_register(&x86Reg::RBX).unwrap();
let rcx = self.vcpu.read_register(&x86Reg::RCX).unwrap();
let rdx = self.vcpu.read_register(&x86Reg::RDX).unwrap();
let rsi = self.vcpu.read_register(&x86Reg::RSI).unwrap();
let rdi = self.vcpu.read_register(&x86Reg::RDI).unwrap();
let r8 = self.vcpu.read_register(&x86Reg::R8).unwrap();
let r9 = self.vcpu.read_register(&x86Reg::R9).unwrap();
let r10 = self.vcpu.read_register(&x86Reg::R10).unwrap();
let r11 = self.vcpu.read_register(&x86Reg::R11).unwrap();
let r12 = self.vcpu.read_register(&x86Reg::R12).unwrap();
let r13 = self.vcpu.read_register(&x86Reg::R13).unwrap();
let r14 = self.vcpu.read_register(&x86Reg::R14).unwrap();
let r15 = self.vcpu.read_register(&x86Reg::R15).unwrap();
print!(
"rip: {:016x} rsp: {:016x} flags: {:016x}\n\
rax: {:016x} rbx: {:016x} rcx: {:016x}\n\
rdx: {:016x} rsi: {:016x} rdi: {:016x}\n\
rbp: {:016x} r8: {:016x} r9: {:016x}\n\
r10: {:016x} r11: {:016x} r12: {:016x}\n\
r13: {:016x} r14: {:016x} r15: {:016x}\n",
rip,
rsp,
rflags,
rax,
rbx,
rcx,
rdx,
rsi,
rdi,
rbp,
r8,
r9,
r10,
r11,
r12,
r13,
r14,
r15
);
let cr0 = self.vcpu.read_register(&x86Reg::CR0).unwrap();
let cr2 = self.vcpu.read_register(&x86Reg::CR2).unwrap();
let cr3 = self.vcpu.read_register(&x86Reg::CR3).unwrap();
let cr4 = self.vcpu.read_register(&x86Reg::CR4).unwrap();
let efer = self.vcpu.read_vmcs(VMCS_GUEST_IA32_EFER).unwrap();
println!(
"cr0: {:016x} cr2: {:016x} cr3: {:016x}\ncr4: {:016x} efer: {:016x}",
cr0, cr2, cr3, cr4, efer
);
println!("\nSegment registers:");
println!("------------------");
println!("register selector base limit type p dpl db s l g avl");
let cs = self.vcpu.read_register(&x86Reg::CS).unwrap();
let ds = self.vcpu.read_register(&x86Reg::DS).unwrap();
let es = self.vcpu.read_register(&x86Reg::ES).unwrap();
let ss = self.vcpu.read_register(&x86Reg::SS).unwrap();
let fs = self.vcpu.read_register(&x86Reg::FS).unwrap();
let gs = self.vcpu.read_register(&x86Reg::GS).unwrap();
let tr = self.vcpu.read_register(&x86Reg::TR).unwrap();
let ldtr = self.vcpu.read_register(&x86Reg::LDTR).unwrap();
let cs_limit = self.vcpu.read_vmcs(VMCS_GUEST_CS_LIMIT).unwrap();
let cs_base = self.vcpu.read_vmcs(VMCS_GUEST_CS_BASE).unwrap();
let cs_ar = self.vcpu.read_vmcs(VMCS_GUEST_CS_AR).unwrap();
let ss_limit = self.vcpu.read_vmcs(VMCS_GUEST_SS_LIMIT).unwrap();
let ss_base = self.vcpu.read_vmcs(VMCS_GUEST_SS_BASE).unwrap();
let ss_ar = self.vcpu.read_vmcs(VMCS_GUEST_SS_AR).unwrap();
let ds_limit = self.vcpu.read_vmcs(VMCS_GUEST_DS_LIMIT).unwrap();
let ds_base = self.vcpu.read_vmcs(VMCS_GUEST_DS_BASE).unwrap();
let ds_ar = self.vcpu.read_vmcs(VMCS_GUEST_DS_AR).unwrap();
let es_limit = self.vcpu.read_vmcs(VMCS_GUEST_ES_LIMIT).unwrap();
let es_base = self.vcpu.read_vmcs(VMCS_GUEST_ES_BASE).unwrap();
let es_ar = self.vcpu.read_vmcs(VMCS_GUEST_ES_AR).unwrap();
let fs_limit = self.vcpu.read_vmcs(VMCS_GUEST_FS_LIMIT).unwrap();
let fs_base = self.vcpu.read_vmcs(VMCS_GUEST_FS_BASE).unwrap();
let fs_ar = self.vcpu.read_vmcs(VMCS_GUEST_FS_AR).unwrap();
let gs_limit = self.vcpu.read_vmcs(VMCS_GUEST_GS_LIMIT).unwrap();
let gs_base = self.vcpu.read_vmcs(VMCS_GUEST_GS_BASE).unwrap();
let gs_ar = self.vcpu.read_vmcs(VMCS_GUEST_GS_AR).unwrap();
let tr_limit = self.vcpu.read_vmcs(VMCS_GUEST_TR_LIMIT).unwrap();
let tr_base = self.vcpu.read_vmcs(VMCS_GUEST_TR_BASE).unwrap();
let tr_ar = self.vcpu.read_vmcs(VMCS_GUEST_TR_AR).unwrap();
let ldtr_limit = self.vcpu.read_vmcs(VMCS_GUEST_LDTR_LIMIT).unwrap();
let ldtr_base = self.vcpu.read_vmcs(VMCS_GUEST_LDTR_BASE).unwrap();
let ldtr_ar = self.vcpu.read_vmcs(VMCS_GUEST_LDTR_AR).unwrap();
/*
* Format of Access Rights
* -----------------------
* 3-0 : Segment type
* 4 : S — Descriptor type (0 = system; 1 = code or data)
* 6-5 : DPL — Descriptor privilege level
* 7 : P — Segment present
* 11-8: Reserved
* 12 : AVL — Available for use by system software
* 13 : L — 64-bit mode active (for CS only)
* 14 : D/B — Default operation size (0 = 16-bit segment; 1 = 32-bit segment)
* 15 : G — Granularity
* 16 : Segment unusable (0 = usable; 1 = unusable)
*
* Output sequence: type p dpl db s l g avl
*/
println!("cs {:04x} {:016x} {:08x} {:02x} {:x} {:x} {:x} {:x} {:x} {:x} {:x}",
cs, cs_base, cs_limit, (cs_ar) & 0xf, (cs_ar >> 7) & 0x1, (cs_ar >> 5) & 0x3, (cs_ar >> 14) & 0x1,
(cs_ar >> 4) & 0x1, (cs_ar >> 13) & 0x1, (cs_ar >> 15) & 0x1, (cs_ar >> 12) & 1);
println!("ss {:04x} {:016x} {:08x} {:02x} {:x} {:x} {:x} {:x} {:x} {:x} {:x}",
ss, ss_base, ss_limit, (ss_ar) & 0xf, (ss_ar >> 7) & 0x1, (ss_ar >> 5) & 0x3, (ss_ar >> 14) & 0x1,
(ss_ar >> 4) & 0x1, (ss_ar >> 13) & 0x1, (ss_ar >> 15) & 0x1, (ss_ar >> 12) & 1);
println!("ds {:04x} {:016x} {:08x} {:02x} {:x} {:x} {:x} {:x} {:x} {:x} {:x}",
ds, ds_base, ds_limit, (ds_ar) & 0xf, (ds_ar >> 7) & 0x1, (ds_ar >> 5) & 0x3, (ds_ar >> 14) & 0x1,
(ds_ar >> 4) & 0x1, (ds_ar >> 13) & 0x1, (ds_ar >> 15) & 0x1, (ds_ar >> 12) & 1);
println!("es {:04x} {:016x} {:08x} {:02x} {:x} {:x} {:x} {:x} {:x} {:x} {:x}",
es, es_base, es_limit, (es_ar) & 0xf, (es_ar >> 7) & 0x1, (es_ar >> 5) & 0x3, (es_ar >> 14) & 0x1,
(es_ar >> 4) & 0x1, (es_ar >> 13) & 0x1, (es_ar >> 15) & 0x1, (es_ar >> 12) & 1);
println!("fs {:04x} {:016x} {:08x} {:02x} {:x} {:x} {:x} {:x} {:x} {:x} {:x}",
fs, fs_base, fs_limit, (fs_ar) & 0xf, (fs_ar >> 7) & 0x1, (fs_ar >> 5) & 0x3, (fs_ar >> 14) & 0x1,
(fs_ar >> 4) & 0x1, (fs_ar >> 13) & 0x1, (fs_ar >> 15) & 0x1, (fs_ar >> 12) & 1);
println!("gs {:04x} {:016x} {:08x} {:02x} {:x} {:x} {:x} {:x} {:x} {:x} {:x}",
gs, gs_base, gs_limit, (gs_ar) & 0xf, (gs_ar >> 7) & 0x1, (gs_ar >> 5) & 0x3, (gs_ar >> 14) & 0x1,
(gs_ar >> 4) & 0x1, (gs_ar >> 13) & 0x1, (gs_ar >> 15) & 0x1, (gs_ar >> 12) & 1);
println!("tr {:04x} {:016x} {:08x} {:02x} {:x} {:x} {:x} {:x} {:x} {:x} {:x}",
tr, tr_base, tr_limit, (tr_ar) & 0xf, (tr_ar >> 7) & 0x1, (tr_ar >> 5) & 0x3, (tr_ar >> 14) & 0x1,
(tr_ar >> 4) & 0x1, (tr_ar >> 13) & 0x1, (tr_ar >> 15) & 0x1, (tr_ar >> 12) & 1);
println!("ldt {:04x} {:016x} {:08x} {:02x} {:x} {:x} {:x} {:x} {:x} {:x} {:x}",
ldtr, ldtr_base, ldtr_limit, (ldtr_ar) & 0xf, (ldtr_ar >> 7) & 0x1, (ldtr_ar >> 5) & 0x3, (ldtr_ar >> 14) & 0x1,
(ldtr_ar >> 4) & 0x1, (ldtr_ar >> 13) & 0x1, (ldtr_ar >> 15) & 0x1, (ldtr_ar >> 12) & 1);
let gdt_base = self.vcpu.read_vmcs(VMCS_GUEST_GDTR_BASE).unwrap();
let gdt_limit = self.vcpu.read_vmcs(VMCS_GUEST_GDTR_LIMIT).unwrap();
println!("gdt {:016x} {:08x}", gdt_base, gdt_limit);
let idt_base = self.vcpu.read_vmcs(VMCS_GUEST_IDTR_BASE).unwrap();
let idt_limit = self.vcpu.read_vmcs(VMCS_GUEST_IDTR_LIMIT).unwrap();
println!("idt {:016x} {:08x}", idt_base, idt_limit);
println!(
"VMCS link pointer {:016x}",
self.vcpu.read_vmcs(VMCS_GUEST_LINK_POINTER).unwrap()
);
}
}
impl Drop for UhyveCPU {
fn drop(&mut self) {
debug!("Drop virtual CPU {}", self.id);
let _ = self.vcpu.destroy();
}
}
| 34.371036 | 115 | 0.636937 |
bf80d74a778aeaa3ed46454f09f8a6b6b4f1196a
| 7,169 |
mod lookup_ref_delta_objects {
use git_hash::ObjectId;
use git_pack::data::{entry::Header, input, input::LookupRefDeltaObjectsIter};
use crate::pack::hex_to_id;
const D_A: &[u8] = b"a";
const D_B: &[u8] = b"bb";
const D_C: &[u8] = b"ccc";
const D_D: &[u8] = b"dddd";
fn base() -> Header {
Header::Blob
}
fn delta_ofs(offset: u64) -> Header {
Header::OfsDelta { base_distance: offset }
}
fn delta_ref(id: ObjectId) -> Header {
Header::RefDelta { base_id: id }
}
fn extract_delta_offset(header: Header) -> u64 {
match header {
Header::OfsDelta { base_distance } => base_distance,
_ => unreachable!("this is supposed to be an offset header, was {:?}", header),
}
}
fn entry(header: Header, data: &'static [u8]) -> input::Entry {
let obj = git_object::Data {
kind: header.as_kind().unwrap_or(git_object::Kind::Blob),
data,
};
let mut entry = input::Entry::from_data_obj(&obj, 0).expect("valid object");
entry.header = header;
entry.header_size = header.size(data.len() as u64) as u16;
entry
}
fn compute_offsets(mut entries: Vec<input::Entry>) -> Vec<input::Entry> {
let mut offset = 0;
for entry in &mut entries {
entry.pack_offset = offset;
offset += entry.bytes_in_pack();
}
entries
}
fn validate_pack_offsets(entries: &[input::Entry]) {
let mut offset = 0;
for (eid, entry) in entries.iter().enumerate() {
assert_eq!(entry.pack_offset, offset, "invalid pack offset for entry {}", eid);
offset += entry.bytes_in_pack();
}
}
fn into_results_iter(
entries: Vec<input::Entry>,
) -> impl ExactSizeIterator<Item = Result<input::Entry, input::Error>> {
entries.into_iter().map(Ok)
}
#[test]
fn only_ref_deltas_are_handled() -> crate::Result {
let input = compute_offsets(vec![entry(base(), D_A), entry(delta_ofs(100), D_B)]);
let expected = input.clone();
let actual =
LookupRefDeltaObjectsIter::new(into_results_iter(input), |_, _| unreachable!("not going to be called"))
.collect::<Result<Vec<_>, _>>()?;
assert_eq!(actual, expected, "it won't change the input at all");
validate_pack_offsets(&actual);
Ok(())
}
#[test]
fn ref_deltas_have_their_base_injected_if_not_done_before_and_all_future_entries_are_offset() {
let first_id = hex_to_id("0000000000000000000000000000000000000001");
let second_id = hex_to_id("0000000000000000000000000000000000000002");
let first = entry(delta_ref(first_id), D_A);
let inserted_data = D_D;
let mut inserted = entry(base(), inserted_data);
let second = entry(delta_ref(second_id), D_B);
let third_entry = entry(delta_ofs(second.bytes_in_pack()), D_C);
let fourth_entry = entry(delta_ofs(third_entry.bytes_in_pack()), D_D);
let fifth = entry(delta_ref(second_id), D_A);
let input = compute_offsets(vec![first.clone(), second, third_entry, fourth_entry, fifth]);
let mut calls = 0;
let input_entries = into_results_iter(input);
let actual_size = input_entries.size_hint();
let iter = LookupRefDeltaObjectsIter::new(input_entries, |_oid, buf| {
calls += 1;
buf.resize(inserted_data.len(), 0);
buf.copy_from_slice(inserted_data);
Some(git_object::Data {
kind: git_object::Kind::Blob,
data: buf.as_slice(),
})
});
assert_eq!(iter.size_hint(), (actual_size.0, actual_size.1.map(|s| s * 2)),
"size hints are estimated and the upper bound reflects the worst-case scenario for the amount of possible objects");
let actual = iter.collect::<Result<Vec<_>, _>>().unwrap();
assert_eq!(calls, 2, "there is only two objects to insert");
assert_eq!(actual.len(), 7, "two object was inserted");
assert_eq!(&actual[0], &inserted, "first object is inserted one");
let altered = &actual[1];
assert_eq!(
extract_delta_offset(altered.header),
inserted.bytes_in_pack(),
"former first entry is now an offset delta pointing at the item before"
);
inserted.pack_offset = inserted.bytes_in_pack() + altered.bytes_in_pack();
assert_eq!(&actual[2], &inserted, "third object is a newly inserted one, too");
let altered = &actual[3];
assert_eq!(
extract_delta_offset(altered.header),
inserted.bytes_in_pack(),
"former second entry is now an offset delta pointing at the inserted item before"
);
let third = &actual[4];
assert_eq!(
extract_delta_offset(third.header),
altered.bytes_in_pack(),
"delta offset was adjusted to deal with change in size of predecessor(s)"
);
let fourth = &actual[5];
assert_eq!(
extract_delta_offset(fourth.header),
third.bytes_in_pack(),
"the fourth header base distance was adjusted accordingly"
);
let fifth = &actual[6];
assert_eq!(
fifth.pack_offset - extract_delta_offset(fifth.header),
actual[2].pack_offset,
"the fifth entry points exactly to the second inserted object, as objects are inserted only once"
);
validate_pack_offsets(&actual);
}
#[test]
fn lookup_errors_trigger_a_fuse_and_stop_iteration() {
let input = vec![entry(delta_ref(git_hash::Kind::Sha1.null()), D_A), entry(base(), D_B)];
let mut calls = 0;
let mut result = LookupRefDeltaObjectsIter::new(into_results_iter(input), |_, _| {
calls += 1;
None
})
.collect::<Vec<_>>();
assert_eq!(calls, 1, "it tries to lookup the object");
assert_eq!(result.len(), 1, "the error stops iteration");
assert!(matches!(
result.pop().expect("one"),
Err(input::Error::NotFound {
object_id
}) if object_id == git_hash::Kind::Sha1.null()
))
}
#[test]
fn inner_errors_are_passed_on() {
let input = vec![
Ok(entry(base(), D_A)),
Err(input::Error::NotFound {
object_id: git_hash::Kind::Sha1.null(),
}),
Ok(entry(base(), D_B)),
];
let expected = vec![
Ok(entry(base(), D_A)),
Err(input::Error::NotFound {
object_id: git_hash::Kind::Sha1.null(),
}),
Ok(entry(base(), D_B)),
];
let actual = LookupRefDeltaObjectsIter::new(input.into_iter(), |_, _| unreachable!("wont be called"))
.collect::<Vec<_>>();
for (actual, expected) in actual.into_iter().zip(expected.into_iter()) {
assert_eq!(format!("{:?}", actual), format!("{:?}", expected));
}
}
}
| 37.338542 | 134 | 0.579439 |
d7a1d7d2364b82c39617b145a39f656c3fb6682b
| 7,528 |
use std::collections::HashMap;
use tracing_subscriber;
use tracing::info;
use chrono::{DateTime, Utc};
use hyper::service::{make_service_fn, service_fn};
use hyper::{header, Body, Method, Request, Response, Server, StatusCode};
use muduo_rust::{Error, Result};
static MOVED_PERMANENTLY: &[u8] = b"Moved Permanently";
static NOT_FOUND: &[u8] = b"Not Found";
const FAVICON: &'static [u8] = &[
b'\x89', b'P', b'N', b'G', b'\x0D', b'\x0A', b'\x1A', b'\x0A',
b'\x00', b'\x00', b'\x00', b'\x0D', b'I', b'H', b'D', b'R',
b'\x00', b'\x00', b'\x00', b'\x10', b'\x00', b'\x00', b'\x00', b'\x10',
b'\x08', b'\x06', b'\x00', b'\x00', b'\x00', b'\x1F', b'\xF3', b'\xFF',
b'a', b'\x00', b'\x00', b'\x00', b'\x19', b't', b'E', b'X',
b't', b'S', b'o', b'f', b't', b'w', b'a', b'r',
b'e', b'\x00', b'A', b'd', b'o', b'b', b'e', b'\x20',
b'I', b'm', b'a', b'g', b'e', b'R', b'e', b'a',
b'd', b'y', b'q', b'\xC9', b'e', b'\x3C', b'\x00', b'\x00',
b'\x01', b'\xCD', b'I', b'D', b'A', b'T', b'x', b'\xDA',
b'\x94', b'\x93', b'9', b'H', b'\x03', b'A', b'\x14', b'\x86',
b'\xFF', b'\x5D', b'b', b'\xA7', b'\x04', b'R', b'\xC4', b'm',
b'\x22', b'\x1E', b'\xA0', b'F', b'\x24', b'\x08', b'\x16', b'\x16',
b'v', b'\x0A', b'6', b'\xBA', b'J', b'\x9A', b'\x80', b'\x08',
b'A', b'\xB4', b'q', b'\x85', b'X', b'\x89', b'G', b'\xB0',
b'I', b'\xA9', b'Q', b'\x24', b'\xCD', b'\xA6', b'\x08', b'\xA4',
b'H', b'c', b'\x91', b'B', b'\x0B', b'\xAF', b'V', b'\xC1',
b'F', b'\xB4', b'\x15', b'\xCF', b'\x22', b'X', b'\x98', b'\x0B',
b'T', b'H', b'\x8A', b'd', b'\x93', b'\x8D', b'\xFB', b'F',
b'g', b'\xC9', b'\x1A', b'\x14', b'\x7D', b'\xF0', b'f', b'v',
b'f', b'\xDF', b'\x7C', b'\xEF', b'\xE7', b'g', b'F', b'\xA8',
b'\xD5', b'j', b'H', b'\x24', b'\x12', b'\x2A', b'\x00', b'\x05',
b'\xBF', b'G', b'\xD4', b'\xEF', b'\xF7', b'\x2F', b'6', b'\xEC',
b'\x12', b'\x20', b'\x1E', b'\x8F', b'\xD7', b'\xAA', b'\xD5', b'\xEA',
b'\xAF', b'I', b'5', b'F', b'\xAA', b'T', b'\x5F', b'\x9F',
b'\x22', b'A', b'\x2A', b'\x95', b'\x0A', b'\x83', b'\xE5', b'r',
b'9', b'd', b'\xB3', b'Y', b'\x96', b'\x99', b'L', b'\x06',
b'\xE9', b't', b'\x9A', b'\x25', b'\x85', b'\x2C', b'\xCB', b'T',
b'\xA7', b'\xC4', b'b', b'1', b'\xB5', b'\x5E', b'\x00', b'\x03',
b'h', b'\x9A', b'\xC6', b'\x16', b'\x82', b'\x20', b'X', b'R',
b'\x14', b'E', b'6', b'S', b'\x94', b'\xCB', b'e', b'x',
b'\xBD', b'\x5E', b'\xAA', b'U', b'T', b'\x23', b'L', b'\xC0',
b'\xE0', b'\xE2', b'\xC1', b'\x8F', b'\x00', b'\x9E', b'\xBC', b'\x09',
b'A', b'\x7C', b'\x3E', b'\x1F', b'\x83', b'D', b'\x22', b'\x11',
b'\xD5', b'T', b'\x40', b'\x3F', b'8', b'\x80', b'w', b'\xE5',
b'3', b'\x07', b'\xB8', b'\x5C', b'\x2E', b'H', b'\x92', b'\x04',
b'\x87', b'\xC3', b'\x81', b'\x40', b'\x20', b'\x40', b'g', b'\x98',
b'\xE9', b'6', b'\x1A', b'\xA6', b'g', b'\x15', b'\x04', b'\xE3',
b'\xD7', b'\xC8', b'\xBD', b'\x15', b'\xE1', b'i', b'\xB7', b'C',
b'\xAB', b'\xEA', b'x', b'\x2F', b'j', b'X', b'\x92', b'\xBB',
b'\x18', b'\x20', b'\x9F', b'\xCF', b'3', b'\xC3', b'\xB8', b'\xE9',
b'N', b'\xA7', b'\xD3', b'l', b'J', b'\x00', b'i', b'6',
b'\x7C', b'\x8E', b'\xE1', b'\xFE', b'V', b'\x84', b'\xE7', b'\x3C',
b'\x9F', b'r', b'\x2B', b'\x3A', b'B', b'\x7B', b'7', b'f',
b'w', b'\xAE', b'\x8E', b'\x0E', b'\xF3', b'\xBD', b'R', b'\xA9',
b'd', b'\x02', b'B', b'\xAF', b'\x85', b'2', b'f', b'F',
b'\xBA', b'\x0C', b'\xD9', b'\x9F', b'\x1D', b'\x9A', b'l', b'\x22',
b'\xE6', b'\xC7', b'\x3A', b'\x2C', b'\x80', b'\xEF', b'\xC1', b'\x15',
b'\x90', b'\x07', b'\x93', b'\xA2', b'\x28', b'\xA0', b'S', b'j',
b'\xB1', b'\xB8', b'\xDF', b'\x29', b'5', b'C', b'\x0E', b'\x3F',
b'X', b'\xFC', b'\x98', b'\xDA', b'y', b'j', b'P', b'\x40',
b'\x00', b'\x87', b'\xAE', b'\x1B', b'\x17', b'B', b'\xB4', b'\x3A',
b'\x3F', b'\xBE', b'y', b'\xC7', b'\x0A', b'\x26', b'\xB6', b'\xEE',
b'\xD9', b'\x9A', b'\x60', b'\x14', b'\x93', b'\xDB', b'\x8F', b'\x0D',
b'\x0A', b'\x2E', b'\xE9', b'\x23', b'\x95', b'\x29', b'X', b'\x00',
b'\x27', b'\xEB', b'n', b'V', b'p', b'\xBC', b'\xD6', b'\xCB',
b'\xD6', b'G', b'\xAB', b'\x3D', b'l', b'\x7D', b'\xB8', b'\xD2',
b'\xDD', b'\xA0', b'\x60', b'\x83', b'\xBA', b'\xEF', b'\x5F', b'\xA4',
b'\xEA', b'\xCC', b'\x02', b'N', b'\xAE', b'\x5E', b'p', b'\x1A',
b'\xEC', b'\xB3', b'\x40', b'9', b'\xAC', b'\xFE', b'\xF2', b'\x91',
b'\x89', b'g', b'\x91', b'\x85', b'\x21', b'\xA8', b'\x87', b'\xB7',
b'X', b'\x7E', b'\x7E', b'\x85', b'\xBB', b'\xCD', b'N', b'N',
b'b', b't', b'\x40', b'\xFA', b'\x93', b'\x89', b'\xEC', b'\x1E',
b'\xEC', b'\x86', b'\x02', b'H', b'\x26', b'\x93', b'\xD0', b'u',
b'\x1D', b'\x7F', b'\x09', b'2', b'\x95', b'\xBF', b'\x1F', b'\xDB',
b'\xD7', b'c', b'\x8A', b'\x1A', b'\xF7', b'\x5C', b'\xC1', b'\xFF',
b'\x22', b'J', b'\xC3', b'\x87', b'\x00', b'\x03', b'\x00', b'K',
b'\xBB', b'\xF8', b'\xD6', b'\x2A', b'v', b'\x98', b'I', b'\x00',
b'\x00', b'\x00', b'\x00', b'I', b'E', b'N', b'D', b'\xAE',
b'B', b'\x60', b'\x82'
];
async fn on_request(
req: Request<Body>,
redirections: HashMap<String, String>,
) -> Result<Response<Body>> {
info!("method:{} path:{}", req.method(), req.uri().path());
match (req.method(), req.uri().path()) {
(&Method::GET, "/1") | (&Method::GET, "/2") => {
let response = Response::builder()
.status(StatusCode::MOVED_PERMANENTLY)
.header("Location", redirections.get(req.uri().path()).unwrap())
.body(MOVED_PERMANENTLY.into())?;
Ok(response)
},
(&Method::GET, "/") => {
let mut resp = String::new();
resp.push_str("<html><head><title>My tiny short url service</title></head>");
resp.push_str("<body><h1>Known redirections</h1>");
for (path, url) in redirections {
resp.push_str(&format!("<ul>{} => {}</ul>", path, url));
}
let now: DateTime<Utc> = Utc::now();
resp.push_str(&format!("Now is {}</body></html>", now.to_rfc2822()));
let response = Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "text/html")
.body(resp.into())?;
Ok(response)
},
(&Method::GET, "/favicon.ico") => {
let response = Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "image/png")
.body(FAVICON.into())?;
Ok(response)
},
_ => {
// Return 404 not found response.
let response = Response::builder()
.status(StatusCode::NOT_FOUND)
.body(NOT_FOUND.into())?;
Ok(response)
}
}
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let addr = "127.0.0.1:3000".parse().unwrap();
let mut redirections = HashMap::new();
redirections.insert("/1".to_string(), "http://chenshuo.com".to_string());
redirections.insert("/2".to_string(), "http://blog.csdn.net/Solstice".to_string());
let new_service = make_service_fn(move |_| {
let redirections = redirections.clone();
async {
Ok::<_, Error>(service_fn(move |req| {
on_request(req, redirections.to_owned())
}))
}
});
let server = Server::bind(&addr).serve(new_service);
println!("Listening on http://{}", addr);
server.await?;
Ok(())
}
| 47.05 | 89 | 0.457226 |
f472cefd33a81b5139fe516fa4196039ab8e93e8
| 5,342 |
// --- Day 9: Encoding Error ---
// With your neighbor happily enjoying their video game, you turn your attention to an open data
// port on the little screen in the seat in front of you.
// Though the port is non-standard, you manage to connect it to your computer through the clever
// use of several paperclips. Upon connection, the port outputs a series of numbers (your puzzle
// input).
// The data appears to be encrypted with the eXchange-Masking Addition System (XMAS) which,
// conveniently for you, is an old cypher with an important weakness.
// XMAS starts by transmitting a preamble of 25 numbers. After that, each number you receive should
// be the sum of any two of the 25 immediately previous numbers. The two numbers will have
// different values, and there might be more than one such pair.
// For example, suppose your preamble consists of the numbers 1 through 25 in a random order. To be
// valid, the next number must be the sum of two of those numbers:
// 26 would be a valid next number, as it could be 1 plus 25 (or many other pairs, like 2 and 24).
// 49 would be a valid next number, as it is the sum of 24 and 25.
// 100 would not be valid; no two of the previous 25 numbers sum to 100.
// 50 would also not be valid; although 25 appears in the previous 25 numbers, the two numbers
// in the pair must be different.
// Suppose the 26th number is 45, and the first number (no longer an option, as it is more than 25
// numbers ago) was 20. Now, for the next number to be valid, there needs to be some pair of
// numbers among 1-19, 21-25, or 45 that add up to it:
// 26 would still be a valid next number, as 1 and 25 are still within the previous 25 numbers.
// 65 would not be valid, as no two of the available numbers sum to it.
// 64 and 66 would both be valid, as they are the result of 19+45 and 21+45 respectively.
// Here is a larger example which only considers the previous 5 numbers (and has a preamble of
// length 5):
// 35
// 20
// 15
// 25
// 47
// 40
// 62
// 55
// 65
// 95
// 102
// 117
// 150
// 182
// 127
// 219
// 299
// 277
// 309
// 576
// In this example, after the 5-number preamble, almost every number is the sum of two of the
// previous 5 numbers; the only number that does not follow this rule is 127.
// The first step of attacking the weakness in the XMAS data is to find the first number in the
// list (after the preamble) which is not the sum of two of the 25 numbers before it. What is the
// first number that does not have this property?
//
// --- Part Two ---
// The final step in breaking the XMAS encryption relies on the invalid number you just found: you must find a contiguous set of at least two numbers in your list which sum to the invalid number from step 1.
// Again consider the above example:
// 35
// 20
// 15
// 25
// 47
// 40
// 62
// 55
// 65
// 95
// 102
// 117
// 150
// 182
// 127
// 219
// 299
// 277
// 309
// 576
// In this list, adding up all of the numbers from 15 through 40 produces the invalid number from step 1, 127. (Of course, the contiguous set of numbers in your actual list might be much longer.)
// To find the encryption weakness, add together the smallest and largest number in this contiguous range; in this example, these are 15 and 47, producing 62.
// What is the encryption weakness in your XMAS-encrypted list of numbers?
use std::collections::HashSet;
use std::io;
use std::io::prelude::*;
const PREAMBLE: usize = 25;
fn part1(input: &[i64], queue: &mut Vec<i64>, set: &mut HashSet<i64>) -> Option<(usize, i64)> {
for (i, &num) in input.iter().skip(PREAMBLE).enumerate() {
let mut not_satisfied = true;
for v in queue.clone() {
if v < num && set.contains(&(num - v)) && num - v != v {
set.remove(&queue.remove(0));
queue.push(num);
set.insert(num);
not_satisfied = false;
break;
}
}
if not_satisfied {
return Some((i, num));
}
}
None
}
fn part2(input: &[i64], invalid_num: i64) -> Option<i64> {
for i in 0..input.len() {
for set_length in 2..input.len() - i {
let possible_val: i64 = input.iter().skip(i).take(set_length).sum();
match possible_val.cmp(&invalid_num) {
std::cmp::Ordering::Greater => break,
std::cmp::Ordering::Equal => {
let mut v: Vec<i64> = input[i..i + set_length].iter().copied().collect();
v.sort_unstable();
return Some(v.get(0).unwrap() + v.iter().last().unwrap());
}
_ => continue,
}
}
}
None
}
fn main() {
let stdin = io::stdin();
let input: Vec<i64> = stdin
.lock()
.lines()
.filter_map(|x| x.ok())
.filter_map(|x| x.parse::<i64>().ok())
.collect();
let mut queue: Vec<i64> = input.iter().take(PREAMBLE).copied().collect();
let mut set: HashSet<i64> = input.iter().take(PREAMBLE).copied().collect();
if let Some(ans) = part1(&input, &mut queue, &mut set) {
println!("answer part1: {}", ans.1);
if let Some(ans2) = part2(&input[..ans.0], ans.1) {
println!("answer part2: {}", ans2);
}
}
}
| 33.597484 | 207 | 0.627668 |
ebcf4d5158c643f94101849d65baa153bc858587
| 245 |
impl Solution {
pub fn max_count(m: i32, n: i32, ops: Vec<Vec<i32>>) -> i32 {
let mut r = m;
let mut c = n;
for op in &ops {
r = r.min(op[0]);
c = c.min(op[1]);
}
r * c
}
}
| 20.416667 | 65 | 0.379592 |
fc217f460c4eaa68d695f5c609c8d87cca96d09b
| 9,330 |
//! The circle primitive
use super::super::drawable::{Drawable, Pixel};
use super::super::transform::Transform;
use crate::geometry::{Dimensions, Point, Size};
use crate::pixelcolor::PixelColor;
use crate::primitives::Primitive;
use crate::style::Style;
use crate::style::WithStyle;
/// Circle primitive
///
/// # Examples
///
/// The [macro examples](../../macro.egcircle.html) make for more concise code.
///
/// ## Create some circles with different styles
///
/// ```rust
/// use embedded_graphics::prelude::*;
/// use embedded_graphics::primitives::Circle;
/// use embedded_graphics::pixelcolor::Rgb565;
/// # use embedded_graphics::mock_display::MockDisplay;
/// # let mut display = MockDisplay::default();
///
/// // Default circle with only a stroke centered around (10, 20) with a radius of 30
/// let c1 = Circle::new(Point::new(10, 20), 30);
///
/// // Circle with styled stroke and fill centered around (50, 20) with a radius of 30
/// let c2 = Circle::new(Point::new(50, 20), 30)
/// .stroke_color(Some(Rgb565::RED))
/// .stroke_width(3)
/// .fill_color(Some(Rgb565::GREEN));
///
/// // Circle with no stroke and a translation applied
/// let c3 = Circle::new(Point::new(10, 20), 30)
/// .stroke_color(None)
/// .fill_color(Some(Rgb565::BLUE))
/// .translate(Point::new(65, 35));
///
/// display.draw(c1);
/// display.draw(c2);
/// display.draw(c3);
/// ```
#[derive(Debug, Copy, Clone)]
pub struct Circle<C: PixelColor> {
/// Center point of circle
pub center: Point,
/// Radius of the circle
pub radius: u32,
/// Style of the circle
pub style: Style<C>,
}
impl<C> Circle<C>
where
C: PixelColor,
{
/// Create a new circle centered around a given point with a specific radius
pub fn new(center: Point, radius: u32) -> Self {
Circle {
center,
radius,
style: Style::default(),
}
}
}
impl<C> Primitive for Circle<C> where C: PixelColor {}
impl<C> Dimensions for Circle<C>
where
C: PixelColor,
{
fn top_left(&self) -> Point {
let radius_coord = Point::new(self.radius as i32, self.radius as i32);
self.center - radius_coord
}
fn bottom_right(&self) -> Point {
self.top_left() + self.size()
}
fn size(&self) -> Size {
Size::new(self.radius * 2, self.radius * 2)
}
}
impl<C> WithStyle<C> for Circle<C>
where
C: PixelColor,
{
fn style(mut self, style: Style<C>) -> Self {
self.style = style;
self
}
fn stroke_color(mut self, color: Option<C>) -> Self {
self.style.stroke_color = color;
self
}
fn stroke_width(mut self, width: u8) -> Self {
self.style.stroke_width = width;
self
}
fn fill_color(mut self, color: Option<C>) -> Self {
self.style.fill_color = color;
self
}
}
impl<C> IntoIterator for Circle<C>
where
C: PixelColor,
{
type Item = Pixel<C>;
type IntoIter = CircleIterator<C>;
fn into_iter(self) -> Self::IntoIter {
(&self).into_iter()
}
}
impl<'a, C> IntoIterator for &'a Circle<C>
where
C: PixelColor,
{
type Item = Pixel<C>;
type IntoIter = CircleIterator<C>;
fn into_iter(self) -> Self::IntoIter {
CircleIterator {
center: self.center,
radius: self.radius,
style: self.style,
p: Point::new(-(self.radius as i32), -(self.radius as i32)),
}
}
}
/// Pixel iterator for each pixel in the circle border
#[derive(Debug, Copy, Clone)]
pub struct CircleIterator<C: PixelColor> {
center: Point,
radius: u32,
style: Style<C>,
p: Point,
}
impl<C> Iterator for CircleIterator<C>
where
C: PixelColor,
{
type Item = Pixel<C>;
// https://stackoverflow.com/questions/1201200/fast-algorithm-for-drawing-filled-circles
fn next(&mut self) -> Option<Self::Item> {
// If border or stroke colour is `None`, treat entire object as transparent and exit early
if self.style.stroke_color.is_none() && self.style.fill_color.is_none() {
return None;
}
let radius = self.radius as i32 - i32::from(self.style.stroke_width) + 1;
let outer_radius = self.radius as i32;
let radius_sq = radius * radius;
let outer_radius_sq = outer_radius * outer_radius;
loop {
let t = self.p;
let len = t.x * t.x + t.y * t.y;
let is_border = len > radius_sq - radius && len < outer_radius_sq + radius;
let is_fill = len <= outer_radius_sq + 1;
let item = if is_border && self.style.stroke_color.is_some() {
Some(Pixel(
self.center + t,
self.style.stroke_color.expect("Border color not defined"),
))
} else if is_fill && self.style.fill_color.is_some() {
Some(Pixel(
self.center + t,
self.style.fill_color.expect("Fill color not defined"),
))
} else {
None
};
self.p.x += 1;
if self.p.x > self.radius as i32 {
self.p.x = -(self.radius as i32);
self.p.y += 1;
}
if self.p.y > self.radius as i32 {
break None;
}
if item.is_some() {
break item;
}
}
}
}
impl<C> Drawable for Circle<C> where C: PixelColor {}
impl<C> Transform for Circle<C>
where
C: PixelColor,
{
/// Translate the circle center from its current position to a new position by (x, y) pixels,
/// returning a new `Circle`. For a mutating transform, see `translate_mut`.
///
/// ```
/// # use embedded_graphics::primitives::Circle;
/// # use embedded_graphics::prelude::*;
/// # use embedded_graphics::pixelcolor::Rgb565;
/// #
/// # let style = Style::stroke_color(Rgb565::RED);
/// #
/// let circle = Circle::new(Point::new(5, 10), 10)
/// # .style(style);
/// let moved = circle.translate(Point::new(10, 10));
///
/// assert_eq!(moved.center, Point::new(15, 20));
/// ```
fn translate(&self, by: Point) -> Self {
Self {
center: self.center + by,
..*self
}
}
/// Translate the circle center from its current position to a new position by (x, y) pixels.
///
/// ```
/// # use embedded_graphics::primitives::Circle;
/// # use embedded_graphics::prelude::*;
/// # use embedded_graphics::pixelcolor::Rgb565;
/// #
/// # let style = Style::stroke_color(Rgb565::RED);
/// #
/// let mut circle = Circle::new(Point::new(5, 10), 10)
/// # .style(style);
/// circle.translate_mut(Point::new(10, 10));
///
/// assert_eq!(circle.center, Point::new(15, 20));
/// ```
fn translate_mut(&mut self, by: Point) -> &mut Self {
self.center += by;
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pixelcolor::BinaryColor;
/// Test for issue #143
#[test]
fn issue_143_stroke_and_fill() {
let circle_no_stroke: Circle<BinaryColor> =
Circle::new(Point::new(10, 16), 3).fill_color(Some(BinaryColor::On));
let circle_stroke: Circle<BinaryColor> = Circle::new(Point::new(10, 16), 3)
.fill_color(Some(BinaryColor::On))
.stroke_color(Some(BinaryColor::On));
assert_eq!(circle_stroke.size(), circle_no_stroke.size());
assert!(circle_no_stroke.into_iter().eq(circle_stroke.into_iter()));
}
#[test]
fn negative_dimensions() {
let circ: Circle<BinaryColor> = Circle::new(Point::new(-10, -10), 5);
assert_eq!(circ.top_left(), Point::new(-15, -15));
assert_eq!(circ.bottom_right(), Point::new(-5, -5));
assert_eq!(circ.size(), Size::new(10, 10));
}
#[test]
fn dimensions() {
let circ: Circle<BinaryColor> = Circle::new(Point::new(10, 20), 5);
assert_eq!(circ.top_left(), Point::new(5, 15));
assert_eq!(circ.bottom_right(), Point::new(15, 25));
assert_eq!(circ.size(), Size::new(10, 10));
}
#[test]
fn large_radius() {
let circ: Circle<BinaryColor> = Circle::new(Point::new(5, 5), 10);
assert_eq!(circ.top_left(), Point::new(-5, -5));
assert_eq!(circ.bottom_right(), Point::new(15, 15));
assert_eq!(circ.size(), Size::new(20, 20));
}
#[test]
fn transparent_border() {
let circ: Circle<BinaryColor> = Circle::new(Point::new(5, 5), 10)
.stroke_color(None)
.fill_color(Some(BinaryColor::On));
assert!(circ.into_iter().count() > 0);
}
#[test]
fn it_handles_negative_coordinates() {
let positive: CircleIterator<BinaryColor> = Circle::new(Point::new(10, 10), 5)
.style(Style::stroke_color(BinaryColor::On))
.into_iter();
let negative: CircleIterator<BinaryColor> = Circle::new(Point::new(-10, -10), 5)
.style(Style::stroke_color(BinaryColor::On))
.into_iter();
assert!(negative.into_iter().eq(positive
.into_iter()
.map(|Pixel(p, c)| Pixel(p - Point::new(20, 20), c))));
}
}
| 27.60355 | 98 | 0.56806 |
d903360690b3c9b8a43170f5cab65089e0c7c5eb
| 560 |
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use deno_crypto::op_crypto_get_random_values;
use deno_crypto::rand::rngs::StdRng;
use deno_crypto::rand::SeedableRng;
pub fn init(rt: &mut deno_core::JsRuntime, maybe_seed: Option<u64>) {
if let Some(seed) = maybe_seed {
let rng = StdRng::seed_from_u64(seed);
let op_state = rt.op_state();
let mut state = op_state.borrow_mut();
state.put::<StdRng>(rng);
}
super::reg_json_sync(
rt,
"op_crypto_get_random_values",
op_crypto_get_random_values,
);
}
| 31.111111 | 74 | 0.714286 |
8abaf575de5da96bb8d00b2ac02a4bd4dac00149
| 11,684 |
// Copyright (c) 2019-2020, The rav1e contributors. All rights reserved
//
// This source code is subject to the terms of the BSD 2 Clause License and
// the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
// was not distributed with this source code in the LICENSE file, you can
// obtain it at www.aomedia.org/license/software. If the Alliance for Open
// Media Patent License 1.0 was not distributed with this source code in the
// PATENTS file, you can obtain it at www.aomedia.org/license/patent.
cfg_if::cfg_if! {
if #[cfg(nasm_x86_64)] {
pub use crate::asm::x86::dist::*;
} else if #[cfg(asm_neon)] {
pub use crate::asm::aarch64::dist::*;
pub use self::rust::get_satd;
pub use self::rust::get_weighted_sse;
} else {
pub use self::rust::*;
}
}
pub(crate) mod rust {
use crate::cpu_features::CpuFeatureLevel;
use crate::partition::BlockSize;
use crate::tiling::*;
use crate::util::*;
use crate::encoder::IMPORTANCE_BLOCK_SIZE;
use crate::rdo::{DistortionScale, RawDistortion};
use simd_helpers::cold_for_target_arch;
#[cold_for_target_arch("x86_64")]
pub fn get_sad<T: Pixel>(
plane_org: &PlaneRegion<'_, T>, plane_ref: &PlaneRegion<'_, T>,
bsize: BlockSize, _bit_depth: usize, _cpu: CpuFeatureLevel,
) -> u32 {
let blk_w = bsize.width();
let blk_h = bsize.height();
let mut sum: u32 = 0;
for (slice_org, slice_ref) in
plane_org.rows_iter().take(blk_h).zip(plane_ref.rows_iter())
{
sum += slice_org
.iter()
.take(blk_w)
.zip(slice_ref)
.map(|(&a, &b)| (i32::cast_from(a) - i32::cast_from(b)).abs() as u32)
.sum::<u32>();
}
sum
}
#[inline(always)]
const fn butterfly(a: i32, b: i32) -> (i32, i32) {
((a + b), (a - b))
}
#[inline(always)]
#[allow(clippy::identity_op, clippy::erasing_op)]
fn hadamard4_1d(data: &mut [i32], n: usize, stride0: usize, stride1: usize) {
for i in 0..n {
let sub: &mut [i32] = &mut data[i * stride0..];
let (a0, a1) = butterfly(sub[0 * stride1], sub[1 * stride1]);
let (a2, a3) = butterfly(sub[2 * stride1], sub[3 * stride1]);
let (b0, b2) = butterfly(a0, a2);
let (b1, b3) = butterfly(a1, a3);
sub[0 * stride1] = b0;
sub[1 * stride1] = b1;
sub[2 * stride1] = b2;
sub[3 * stride1] = b3;
}
}
#[inline(always)]
#[allow(clippy::identity_op, clippy::erasing_op)]
fn hadamard8_1d(data: &mut [i32], n: usize, stride0: usize, stride1: usize) {
for i in 0..n {
let sub: &mut [i32] = &mut data[i * stride0..];
let (a0, a1) = butterfly(sub[0 * stride1], sub[1 * stride1]);
let (a2, a3) = butterfly(sub[2 * stride1], sub[3 * stride1]);
let (a4, a5) = butterfly(sub[4 * stride1], sub[5 * stride1]);
let (a6, a7) = butterfly(sub[6 * stride1], sub[7 * stride1]);
let (b0, b2) = butterfly(a0, a2);
let (b1, b3) = butterfly(a1, a3);
let (b4, b6) = butterfly(a4, a6);
let (b5, b7) = butterfly(a5, a7);
let (c0, c4) = butterfly(b0, b4);
let (c1, c5) = butterfly(b1, b5);
let (c2, c6) = butterfly(b2, b6);
let (c3, c7) = butterfly(b3, b7);
sub[0 * stride1] = c0;
sub[1 * stride1] = c1;
sub[2 * stride1] = c2;
sub[3 * stride1] = c3;
sub[4 * stride1] = c4;
sub[5 * stride1] = c5;
sub[6 * stride1] = c6;
sub[7 * stride1] = c7;
}
}
#[inline(always)]
fn hadamard2d(data: &mut [i32], (w, h): (usize, usize)) {
/*Vertical transform.*/
let vert_func = if h == 4 { hadamard4_1d } else { hadamard8_1d };
vert_func(data, w, 1, h);
/*Horizontal transform.*/
let horz_func = if w == 4 { hadamard4_1d } else { hadamard8_1d };
horz_func(data, h, w, 1);
}
fn hadamard4x4(data: &mut [i32]) {
hadamard2d(data, (4, 4));
}
fn hadamard8x8(data: &mut [i32]) {
hadamard2d(data, (8, 8));
}
/// Sum of absolute transformed differences
/// Use the sum of 4x4 and 8x8 hadamard transforms for the transform. 4x* and
/// *x4 blocks use 4x4 and all others use 8x8.
#[cold_for_target_arch("x86_64")]
pub fn get_satd<T: Pixel>(
plane_org: &PlaneRegion<'_, T>, plane_ref: &PlaneRegion<'_, T>,
bsize: BlockSize, _bit_depth: usize, _cpu: CpuFeatureLevel,
) -> u32 {
let blk_w = bsize.width();
let blk_h = bsize.height();
// Size of hadamard transform should be 4x4 or 8x8
// 4x* and *x4 use 4x4 and all other use 8x8
let size: usize = blk_w.min(blk_h).min(8);
let tx2d = if size == 4 { hadamard4x4 } else { hadamard8x8 };
let mut sum: u64 = 0;
// Loop over chunks the size of the chosen transform
for chunk_y in (0..blk_h).step_by(size) {
for chunk_x in (0..blk_w).step_by(size) {
let chunk_area: Area = Area::Rect {
x: chunk_x as isize,
y: chunk_y as isize,
width: size,
height: size,
};
let chunk_org = plane_org.subregion(chunk_area);
let chunk_ref = plane_ref.subregion(chunk_area);
let buf: &mut [i32] = &mut [0; 8 * 8][..size * size];
// Move the difference of the transforms to a buffer
for (row_diff, (row_org, row_ref)) in buf
.chunks_mut(size)
.zip(chunk_org.rows_iter().zip(chunk_ref.rows_iter()))
{
for (diff, (a, b)) in
row_diff.iter_mut().zip(row_org.iter().zip(row_ref.iter()))
{
*diff = i32::cast_from(*a) - i32::cast_from(*b);
}
}
// Perform the hadamard transform on the differences
tx2d(buf);
// Sum the absolute values of the transformed differences
sum += buf.iter().map(|a| a.abs() as u64).sum::<u64>();
}
}
// Normalize the results
let ln = msb(size as i32) as u64;
((sum + (1 << ln >> 1)) >> ln) as u32
}
/// Computes weighted sum of squared error.
///
/// Each scale is applied to a 4x4 region in the provided inputs. Each scale
/// value is a fixed point number, currently ['DistortionScale'].
///
/// Implementations can require alignment (bw (block width) for ['src1'] and
/// ['src2'] and bw/4 for scale).
#[inline(never)]
pub fn get_weighted_sse<T: Pixel>(
src1: &PlaneRegion<'_, T>, src2: &PlaneRegion<'_, T>, scale: &[u32],
scale_stride: usize, w: usize, h: usize, _bit_depth: usize,
_cpu: CpuFeatureLevel,
) -> u64 {
// Always chunk and apply scaling on the sse of squares the size of
// decimated/sub-sampled importance block sizes.
// Warning: Changing this will require changing/disabling assembly.
let chunk_size = IMPORTANCE_BLOCK_SIZE >> 1;
let mut sse: u64 = 0;
for block_y in 0..(h + chunk_size - 1) / chunk_size {
for block_x in 0..(w + chunk_size - 1) / chunk_size {
let mut block_sse: u32 = 0;
for j in 0..chunk_size {
let s1 = &src1[block_y * chunk_size + j]
[block_x * chunk_size..((block_x + 1) * chunk_size).min(w)];
let s2 = &src2[block_y * chunk_size + j]
[block_x * chunk_size..((block_x + 1) * chunk_size).min(w)];
block_sse += s1
.iter()
.zip(s2)
.map(|(&a, &b)| {
let c = (i16::cast_from(a) - i16::cast_from(b)) as i32;
(c * c) as u32
})
.sum::<u32>();
}
sse += (RawDistortion::new(block_sse as u64)
* DistortionScale(scale[block_y * scale_stride + block_x]))
.0;
}
}
sse
}
}
#[cfg(test)]
pub mod test {
use super::*;
use crate::cpu_features::CpuFeatureLevel;
use crate::frame::*;
use crate::partition::BlockSize;
use crate::partition::BlockSize::*;
use crate::tiling::Area;
use crate::util::Pixel;
// Generate plane data for get_sad_same()
fn setup_planes<T: Pixel>() -> (Plane<T>, Plane<T>) {
// Two planes with different strides
let mut input_plane = Plane::new(640, 480, 0, 0, 128 + 8, 128 + 8);
let mut rec_plane = Plane::new(640, 480, 0, 0, 2 * 128 + 8, 2 * 128 + 8);
// Make the test pattern robust to data alignment
let xpad_off =
(input_plane.cfg.xorigin - input_plane.cfg.xpad) as i32 - 8i32;
for (i, row) in
input_plane.data.chunks_mut(input_plane.cfg.stride).enumerate()
{
for (j, pixel) in row.iter_mut().enumerate() {
let val = ((j + i) as i32 - xpad_off) & 255i32;
assert!(
val >= u8::min_value().into() && val <= u8::max_value().into()
);
*pixel = T::cast_from(val);
}
}
for (i, row) in rec_plane.data.chunks_mut(rec_plane.cfg.stride).enumerate()
{
for (j, pixel) in row.iter_mut().enumerate() {
let val = (j as i32 - i as i32 - xpad_off) & 255i32;
assert!(
val >= u8::min_value().into() && val <= u8::max_value().into()
);
*pixel = T::cast_from(val);
}
}
(input_plane, rec_plane)
}
// Regression and validation test for SAD computation
fn get_sad_same_inner<T: Pixel>() {
// dynamic allocation: test
let blocks: Vec<(BlockSize, u32)> = vec![
(BLOCK_4X4, 1912),
(BLOCK_4X8, 4296),
(BLOCK_8X4, 3496),
(BLOCK_8X8, 7824),
(BLOCK_8X16, 16592),
(BLOCK_16X8, 14416),
(BLOCK_16X16, 31136),
(BLOCK_16X32, 60064),
(BLOCK_32X16, 59552),
(BLOCK_32X32, 120128),
(BLOCK_32X64, 186688),
(BLOCK_64X32, 250176),
(BLOCK_64X64, 438912),
(BLOCK_64X128, 654272),
(BLOCK_128X64, 1016768),
(BLOCK_128X128, 1689792),
(BLOCK_4X16, 8680),
(BLOCK_16X4, 6664),
(BLOCK_8X32, 31056),
(BLOCK_32X8, 27600),
(BLOCK_16X64, 93344),
(BLOCK_64X16, 116384),
];
let bit_depth: usize = 8;
let (input_plane, rec_plane) = setup_planes::<T>();
for block in blocks {
let area = Area::StartingAt { x: 32, y: 40 };
let input_region = input_plane.region(area);
let rec_region = rec_plane.region(area);
assert_eq!(
block.1,
get_sad(
&input_region,
&rec_region,
block.0,
bit_depth,
CpuFeatureLevel::default()
)
);
}
}
#[test]
fn get_sad_same_u8() {
get_sad_same_inner::<u8>();
}
#[test]
fn get_sad_same_u16() {
get_sad_same_inner::<u16>();
}
fn get_satd_same_inner<T: Pixel>() {
let blocks: Vec<(BlockSize, u32)> = vec![
(BLOCK_4X4, 1408),
(BLOCK_4X8, 2016),
(BLOCK_8X4, 1816),
(BLOCK_8X8, 3984),
(BLOCK_8X16, 5136),
(BLOCK_16X8, 4864),
(BLOCK_16X16, 9984),
(BLOCK_16X32, 13824),
(BLOCK_32X16, 13760),
(BLOCK_32X32, 27952),
(BLOCK_32X64, 37168),
(BLOCK_64X32, 45104),
(BLOCK_64X64, 84176),
(BLOCK_64X128, 127920),
(BLOCK_128X64, 173680),
(BLOCK_128X128, 321456),
(BLOCK_4X16, 3136),
(BLOCK_16X4, 2632),
(BLOCK_8X32, 7056),
(BLOCK_32X8, 6624),
(BLOCK_16X64, 18432),
(BLOCK_64X16, 21312),
];
let bit_depth: usize = 8;
let (input_plane, rec_plane) = setup_planes::<T>();
for block in blocks {
let area = Area::StartingAt { x: 32, y: 40 };
let input_region = input_plane.region(area);
let rec_region = rec_plane.region(area);
assert_eq!(
block.1,
get_satd(
&input_region,
&rec_region,
block.0,
bit_depth,
CpuFeatureLevel::default()
)
);
}
}
#[test]
fn get_satd_same_u8() {
get_satd_same_inner::<u8>();
}
#[test]
fn get_satd_same_u16() {
get_satd_same_inner::<u16>();
}
}
| 29.43073 | 79 | 0.574461 |
22caa97266bb8c7b248a41c627da051f9fa84f2b
| 16,587 |
#![allow(dead_code)]
use std::mem;
use lazy_static::lazy_static;
#[cfg(h5_have_direct)]
use hdf5_sys::h5fd::H5FD_direct_init;
#[cfg(h5_have_parallel)]
use hdf5_sys::h5fd::H5FD_mpio_init;
use hdf5_sys::h5fd::{
H5FD_core_init, H5FD_family_init, H5FD_log_init, H5FD_multi_init, H5FD_sec2_init,
H5FD_stdio_init,
};
use hdf5_sys::{h5e, h5p, h5t};
use crate::internal_prelude::*;
lazy_static! {
static ref LIBRARY_INIT: () = {
h5lock!({
// Ensure hdf5 does not invalidate handles which might
// still be live on other threads on program exit
::hdf5_sys::h5::H5dont_atexit();
::hdf5_sys::h5::H5open();
crate::error::silence_errors(true);
});
let _e = crate::hl::filters::register_filters();
};
}
#[cfg(h5_dll_indirection)]
pub struct H5GlobalConstant(&'static usize);
#[cfg(not(h5_dll_indirection))]
pub struct H5GlobalConstant(&'static hdf5_sys::h5i::hid_t);
impl std::ops::Deref for H5GlobalConstant {
type Target = hdf5_sys::h5i::hid_t;
fn deref(&self) -> &Self::Target {
lazy_static::initialize(&LIBRARY_INIT);
cfg_if::cfg_if! {
if #[cfg(h5_dll_indirection)] {
let dll_ptr = self.0 as *const usize;
let ptr: *const *const hdf5_sys::h5i::hid_t = dll_ptr.cast();
unsafe {
&**ptr
}
} else {
self.0
}
}
}
}
macro_rules! link_hid {
($rust_name:ident, $c_name:path) => {
pub static $rust_name: H5GlobalConstant = H5GlobalConstant($c_name);
};
}
// Datatypes
link_hid!(H5T_IEEE_F32BE, h5t::H5T_IEEE_F32BE);
link_hid!(H5T_IEEE_F32LE, h5t::H5T_IEEE_F32LE);
link_hid!(H5T_IEEE_F64BE, h5t::H5T_IEEE_F64BE);
link_hid!(H5T_IEEE_F64LE, h5t::H5T_IEEE_F64LE);
link_hid!(H5T_STD_I8BE, h5t::H5T_STD_I8BE);
link_hid!(H5T_STD_I8LE, h5t::H5T_STD_I8LE);
link_hid!(H5T_STD_I16BE, h5t::H5T_STD_I16BE);
link_hid!(H5T_STD_I16LE, h5t::H5T_STD_I16LE);
link_hid!(H5T_STD_I32BE, h5t::H5T_STD_I32BE);
link_hid!(H5T_STD_I32LE, h5t::H5T_STD_I32LE);
link_hid!(H5T_STD_I64BE, h5t::H5T_STD_I64BE);
link_hid!(H5T_STD_I64LE, h5t::H5T_STD_I64LE);
link_hid!(H5T_STD_U8BE, h5t::H5T_STD_U8BE);
link_hid!(H5T_STD_U8LE, h5t::H5T_STD_U8LE);
link_hid!(H5T_STD_U16BE, h5t::H5T_STD_U16BE);
link_hid!(H5T_STD_U16LE, h5t::H5T_STD_U16LE);
link_hid!(H5T_STD_U32BE, h5t::H5T_STD_U32BE);
link_hid!(H5T_STD_U32LE, h5t::H5T_STD_U32LE);
link_hid!(H5T_STD_U64BE, h5t::H5T_STD_U64BE);
link_hid!(H5T_STD_U64LE, h5t::H5T_STD_U64LE);
link_hid!(H5T_STD_B8BE, h5t::H5T_STD_B8BE);
link_hid!(H5T_STD_B8LE, h5t::H5T_STD_B8LE);
link_hid!(H5T_STD_B16BE, h5t::H5T_STD_B16BE);
link_hid!(H5T_STD_B16LE, h5t::H5T_STD_B16LE);
link_hid!(H5T_STD_B32BE, h5t::H5T_STD_B32BE);
link_hid!(H5T_STD_B32LE, h5t::H5T_STD_B32LE);
link_hid!(H5T_STD_B64BE, h5t::H5T_STD_B64BE);
link_hid!(H5T_STD_B64LE, h5t::H5T_STD_B64LE);
link_hid!(H5T_STD_REF_OBJ, h5t::H5T_STD_REF_OBJ);
link_hid!(H5T_STD_REF_DSETREG, h5t::H5T_STD_REF_DSETREG);
link_hid!(H5T_UNIX_D32BE, h5t::H5T_UNIX_D32BE);
link_hid!(H5T_UNIX_D32LE, h5t::H5T_UNIX_D32LE);
link_hid!(H5T_UNIX_D64BE, h5t::H5T_UNIX_D64BE);
link_hid!(H5T_UNIX_D64LE, h5t::H5T_UNIX_D64LE);
link_hid!(H5T_C_S1, h5t::H5T_C_S1);
link_hid!(H5T_FORTRAN_S1, h5t::H5T_FORTRAN_S1);
link_hid!(H5T_VAX_F32, h5t::H5T_VAX_F32);
link_hid!(H5T_VAX_F64, h5t::H5T_VAX_F64);
link_hid!(H5T_NATIVE_SCHAR, h5t::H5T_NATIVE_SCHAR);
link_hid!(H5T_NATIVE_UCHAR, h5t::H5T_NATIVE_UCHAR);
link_hid!(H5T_NATIVE_SHORT, h5t::H5T_NATIVE_SHORT);
link_hid!(H5T_NATIVE_USHORT, h5t::H5T_NATIVE_USHORT);
link_hid!(H5T_NATIVE_INT, h5t::H5T_NATIVE_INT);
link_hid!(H5T_NATIVE_UINT, h5t::H5T_NATIVE_UINT);
link_hid!(H5T_NATIVE_LONG, h5t::H5T_NATIVE_LONG);
link_hid!(H5T_NATIVE_ULONG, h5t::H5T_NATIVE_ULONG);
link_hid!(H5T_NATIVE_LLONG, h5t::H5T_NATIVE_LLONG);
link_hid!(H5T_NATIVE_ULLONG, h5t::H5T_NATIVE_ULLONG);
link_hid!(H5T_NATIVE_FLOAT, h5t::H5T_NATIVE_FLOAT);
link_hid!(H5T_NATIVE_DOUBLE, h5t::H5T_NATIVE_DOUBLE);
link_hid!(H5T_NATIVE_LDOUBLE, h5t::H5T_NATIVE_LDOUBLE);
link_hid!(H5T_NATIVE_B8, h5t::H5T_NATIVE_B8);
link_hid!(H5T_NATIVE_B16, h5t::H5T_NATIVE_B16);
link_hid!(H5T_NATIVE_B32, h5t::H5T_NATIVE_B32);
link_hid!(H5T_NATIVE_B64, h5t::H5T_NATIVE_B64);
link_hid!(H5T_NATIVE_OPAQUE, h5t::H5T_NATIVE_OPAQUE);
link_hid!(H5T_NATIVE_HADDR, h5t::H5T_NATIVE_HADDR);
link_hid!(H5T_NATIVE_HSIZE, h5t::H5T_NATIVE_HSIZE);
link_hid!(H5T_NATIVE_HSSIZE, h5t::H5T_NATIVE_HSSIZE);
link_hid!(H5T_NATIVE_HERR, h5t::H5T_NATIVE_HERR);
link_hid!(H5T_NATIVE_HBOOL, h5t::H5T_NATIVE_HBOOL);
link_hid!(H5T_NATIVE_INT8, h5t::H5T_NATIVE_INT8);
link_hid!(H5T_NATIVE_UINT8, h5t::H5T_NATIVE_UINT8);
link_hid!(H5T_NATIVE_INT_LEAST8, h5t::H5T_NATIVE_INT_LEAST8);
link_hid!(H5T_NATIVE_UINT_LEAST8, h5t::H5T_NATIVE_UINT_LEAST8);
link_hid!(H5T_NATIVE_INT_FAST8, h5t::H5T_NATIVE_INT_FAST8);
link_hid!(H5T_NATIVE_UINT_FAST8, h5t::H5T_NATIVE_UINT_FAST8);
link_hid!(H5T_NATIVE_INT16, h5t::H5T_NATIVE_INT16);
link_hid!(H5T_NATIVE_UINT16, h5t::H5T_NATIVE_UINT16);
link_hid!(H5T_NATIVE_INT_LEAST16, h5t::H5T_NATIVE_INT_LEAST16);
link_hid!(H5T_NATIVE_UINT_LEAST16, h5t::H5T_NATIVE_UINT_LEAST16);
link_hid!(H5T_NATIVE_INT_FAST16, h5t::H5T_NATIVE_INT_FAST16);
link_hid!(H5T_NATIVE_UINT_FAST16, h5t::H5T_NATIVE_UINT_FAST16);
link_hid!(H5T_NATIVE_INT32, h5t::H5T_NATIVE_INT32);
link_hid!(H5T_NATIVE_UINT32, h5t::H5T_NATIVE_UINT32);
link_hid!(H5T_NATIVE_INT_LEAST32, h5t::H5T_NATIVE_INT_LEAST32);
link_hid!(H5T_NATIVE_UINT_LEAST32, h5t::H5T_NATIVE_UINT_LEAST32);
link_hid!(H5T_NATIVE_INT_FAST32, h5t::H5T_NATIVE_INT_FAST32);
link_hid!(H5T_NATIVE_UINT_FAST32, h5t::H5T_NATIVE_UINT_FAST32);
link_hid!(H5T_NATIVE_INT64, h5t::H5T_NATIVE_INT64);
link_hid!(H5T_NATIVE_UINT64, h5t::H5T_NATIVE_UINT64);
link_hid!(H5T_NATIVE_INT_LEAST64, h5t::H5T_NATIVE_INT_LEAST64);
link_hid!(H5T_NATIVE_UINT_LEAST64, h5t::H5T_NATIVE_UINT_LEAST64);
link_hid!(H5T_NATIVE_INT_FAST64, h5t::H5T_NATIVE_INT_FAST64);
link_hid!(H5T_NATIVE_UINT_FAST64, h5t::H5T_NATIVE_UINT_FAST64);
// Property list classes
link_hid!(H5P_ROOT, h5p::H5P_CLS_ROOT);
link_hid!(H5P_OBJECT_CREATE, h5p::H5P_CLS_OBJECT_CREATE);
link_hid!(H5P_FILE_CREATE, h5p::H5P_CLS_FILE_CREATE);
link_hid!(H5P_FILE_ACCESS, h5p::H5P_CLS_FILE_ACCESS);
link_hid!(H5P_DATASET_CREATE, h5p::H5P_CLS_DATASET_CREATE);
link_hid!(H5P_DATASET_ACCESS, h5p::H5P_CLS_DATASET_ACCESS);
link_hid!(H5P_DATASET_XFER, h5p::H5P_CLS_DATASET_XFER);
link_hid!(H5P_FILE_MOUNT, h5p::H5P_CLS_FILE_MOUNT);
link_hid!(H5P_GROUP_CREATE, h5p::H5P_CLS_GROUP_CREATE);
link_hid!(H5P_GROUP_ACCESS, h5p::H5P_CLS_GROUP_ACCESS);
link_hid!(H5P_DATATYPE_CREATE, h5p::H5P_CLS_DATATYPE_CREATE);
link_hid!(H5P_DATATYPE_ACCESS, h5p::H5P_CLS_DATATYPE_ACCESS);
link_hid!(H5P_STRING_CREATE, h5p::H5P_CLS_STRING_CREATE);
link_hid!(H5P_ATTRIBUTE_CREATE, h5p::H5P_CLS_ATTRIBUTE_CREATE);
link_hid!(H5P_OBJECT_COPY, h5p::H5P_CLS_OBJECT_COPY);
link_hid!(H5P_LINK_CREATE, h5p::H5P_CLS_LINK_CREATE);
link_hid!(H5P_LINK_ACCESS, h5p::H5P_CLS_LINK_ACCESS);
// Default property lists
link_hid!(H5P_LST_FILE_CREATE_ID, h5p::H5P_LST_FILE_CREATE);
link_hid!(H5P_LST_FILE_ACCESS_ID, h5p::H5P_LST_FILE_ACCESS);
link_hid!(H5P_LST_DATASET_CREATE_ID, h5p::H5P_LST_DATASET_CREATE);
link_hid!(H5P_LST_DATASET_ACCESS_ID, h5p::H5P_LST_DATASET_ACCESS);
link_hid!(H5P_LST_DATASET_XFER_ID, h5p::H5P_LST_DATASET_XFER);
link_hid!(H5P_LST_FILE_MOUNT_ID, h5p::H5P_LST_FILE_MOUNT);
link_hid!(H5P_LST_GROUP_CREATE_ID, h5p::H5P_LST_GROUP_CREATE);
link_hid!(H5P_LST_GROUP_ACCESS_ID, h5p::H5P_LST_GROUP_ACCESS);
link_hid!(H5P_LST_DATATYPE_CREATE_ID, h5p::H5P_LST_DATATYPE_CREATE);
link_hid!(H5P_LST_DATATYPE_ACCESS_ID, h5p::H5P_LST_DATATYPE_ACCESS);
link_hid!(H5P_LST_ATTRIBUTE_CREATE_ID, h5p::H5P_LST_ATTRIBUTE_CREATE);
link_hid!(H5P_LST_OBJECT_COPY_ID, h5p::H5P_LST_OBJECT_COPY);
link_hid!(H5P_LST_LINK_CREATE_ID, h5p::H5P_LST_LINK_CREATE);
link_hid!(H5P_LST_LINK_ACCESS_ID, h5p::H5P_LST_LINK_ACCESS);
// Error class
link_hid!(H5E_ERR_CLS, h5e::H5E_ERR_CLS);
// Errors
link_hid!(H5E_DATASET, h5e::H5E_DATASET);
link_hid!(H5E_FUNC, h5e::H5E_FUNC);
link_hid!(H5E_STORAGE, h5e::H5E_STORAGE);
link_hid!(H5E_FILE, h5e::H5E_FILE);
link_hid!(H5E_SOHM, h5e::H5E_SOHM);
link_hid!(H5E_SYM, h5e::H5E_SYM);
link_hid!(H5E_PLUGIN, h5e::H5E_PLUGIN);
link_hid!(H5E_VFL, h5e::H5E_VFL);
link_hid!(H5E_INTERNAL, h5e::H5E_INTERNAL);
link_hid!(H5E_BTREE, h5e::H5E_BTREE);
link_hid!(H5E_REFERENCE, h5e::H5E_REFERENCE);
link_hid!(H5E_DATASPACE, h5e::H5E_DATASPACE);
link_hid!(H5E_RESOURCE, h5e::H5E_RESOURCE);
link_hid!(H5E_PLIST, h5e::H5E_PLIST);
link_hid!(H5E_LINK, h5e::H5E_LINK);
link_hid!(H5E_DATATYPE, h5e::H5E_DATATYPE);
link_hid!(H5E_RS, h5e::H5E_RS);
link_hid!(H5E_HEAP, h5e::H5E_HEAP);
link_hid!(H5E_OHDR, h5e::H5E_OHDR);
link_hid!(H5E_ATOM, h5e::H5E_ATOM);
link_hid!(H5E_ATTR, h5e::H5E_ATTR);
link_hid!(H5E_NONE_MAJOR, h5e::H5E_NONE_MAJOR);
link_hid!(H5E_IO, h5e::H5E_IO);
link_hid!(H5E_SLIST, h5e::H5E_SLIST);
link_hid!(H5E_EFL, h5e::H5E_EFL);
link_hid!(H5E_TST, h5e::H5E_TST);
link_hid!(H5E_ARGS, h5e::H5E_ARGS);
link_hid!(H5E_ERROR, h5e::H5E_ERROR);
link_hid!(H5E_PLINE, h5e::H5E_PLINE);
link_hid!(H5E_FSPACE, h5e::H5E_FSPACE);
link_hid!(H5E_CACHE, h5e::H5E_CACHE);
link_hid!(H5E_SEEKERROR, h5e::H5E_SEEKERROR);
link_hid!(H5E_READERROR, h5e::H5E_READERROR);
link_hid!(H5E_WRITEERROR, h5e::H5E_WRITEERROR);
link_hid!(H5E_CLOSEERROR, h5e::H5E_CLOSEERROR);
link_hid!(H5E_OVERFLOW, h5e::H5E_OVERFLOW);
link_hid!(H5E_FCNTL, h5e::H5E_FCNTL);
link_hid!(H5E_NOSPACE, h5e::H5E_NOSPACE);
link_hid!(H5E_CANTALLOC, h5e::H5E_CANTALLOC);
link_hid!(H5E_CANTCOPY, h5e::H5E_CANTCOPY);
link_hid!(H5E_CANTFREE, h5e::H5E_CANTFREE);
link_hid!(H5E_ALREADYEXISTS, h5e::H5E_ALREADYEXISTS);
link_hid!(H5E_CANTLOCK, h5e::H5E_CANTLOCK);
link_hid!(H5E_CANTUNLOCK, h5e::H5E_CANTUNLOCK);
link_hid!(H5E_CANTGC, h5e::H5E_CANTGC);
link_hid!(H5E_CANTGETSIZE, h5e::H5E_CANTGETSIZE);
link_hid!(H5E_OBJOPEN, h5e::H5E_OBJOPEN);
link_hid!(H5E_CANTRESTORE, h5e::H5E_CANTRESTORE);
link_hid!(H5E_CANTCOMPUTE, h5e::H5E_CANTCOMPUTE);
link_hid!(H5E_CANTEXTEND, h5e::H5E_CANTEXTEND);
link_hid!(H5E_CANTATTACH, h5e::H5E_CANTATTACH);
link_hid!(H5E_CANTUPDATE, h5e::H5E_CANTUPDATE);
link_hid!(H5E_CANTOPERATE, h5e::H5E_CANTOPERATE);
link_hid!(H5E_CANTINIT, h5e::H5E_CANTINIT);
link_hid!(H5E_ALREADYINIT, h5e::H5E_ALREADYINIT);
link_hid!(H5E_CANTRELEASE, h5e::H5E_CANTRELEASE);
link_hid!(H5E_CANTGET, h5e::H5E_CANTGET);
link_hid!(H5E_CANTSET, h5e::H5E_CANTSET);
link_hid!(H5E_DUPCLASS, h5e::H5E_DUPCLASS);
link_hid!(H5E_SETDISALLOWED, h5e::H5E_SETDISALLOWED);
link_hid!(H5E_CANTMERGE, h5e::H5E_CANTMERGE);
link_hid!(H5E_CANTREVIVE, h5e::H5E_CANTREVIVE);
link_hid!(H5E_CANTSHRINK, h5e::H5E_CANTSHRINK);
link_hid!(H5E_LINKCOUNT, h5e::H5E_LINKCOUNT);
link_hid!(H5E_VERSION, h5e::H5E_VERSION);
link_hid!(H5E_ALIGNMENT, h5e::H5E_ALIGNMENT);
link_hid!(H5E_BADMESG, h5e::H5E_BADMESG);
link_hid!(H5E_CANTDELETE, h5e::H5E_CANTDELETE);
link_hid!(H5E_BADITER, h5e::H5E_BADITER);
link_hid!(H5E_CANTPACK, h5e::H5E_CANTPACK);
link_hid!(H5E_CANTRESET, h5e::H5E_CANTRESET);
link_hid!(H5E_CANTRENAME, h5e::H5E_CANTRENAME);
link_hid!(H5E_SYSERRSTR, h5e::H5E_SYSERRSTR);
link_hid!(H5E_NOFILTER, h5e::H5E_NOFILTER);
link_hid!(H5E_CALLBACK, h5e::H5E_CALLBACK);
link_hid!(H5E_CANAPPLY, h5e::H5E_CANAPPLY);
link_hid!(H5E_SETLOCAL, h5e::H5E_SETLOCAL);
link_hid!(H5E_NOENCODER, h5e::H5E_NOENCODER);
link_hid!(H5E_CANTFILTER, h5e::H5E_CANTFILTER);
link_hid!(H5E_CANTOPENOBJ, h5e::H5E_CANTOPENOBJ);
link_hid!(H5E_CANTCLOSEOBJ, h5e::H5E_CANTCLOSEOBJ);
link_hid!(H5E_COMPLEN, h5e::H5E_COMPLEN);
link_hid!(H5E_PATH, h5e::H5E_PATH);
link_hid!(H5E_NONE_MINOR, h5e::H5E_NONE_MINOR);
link_hid!(H5E_OPENERROR, h5e::H5E_OPENERROR);
link_hid!(H5E_FILEEXISTS, h5e::H5E_FILEEXISTS);
link_hid!(H5E_FILEOPEN, h5e::H5E_FILEOPEN);
link_hid!(H5E_CANTCREATE, h5e::H5E_CANTCREATE);
link_hid!(H5E_CANTOPENFILE, h5e::H5E_CANTOPENFILE);
link_hid!(H5E_CANTCLOSEFILE, h5e::H5E_CANTCLOSEFILE);
link_hid!(H5E_NOTHDF5, h5e::H5E_NOTHDF5);
link_hid!(H5E_BADFILE, h5e::H5E_BADFILE);
link_hid!(H5E_TRUNCATED, h5e::H5E_TRUNCATED);
link_hid!(H5E_MOUNT, h5e::H5E_MOUNT);
link_hid!(H5E_BADATOM, h5e::H5E_BADATOM);
link_hid!(H5E_BADGROUP, h5e::H5E_BADGROUP);
link_hid!(H5E_CANTREGISTER, h5e::H5E_CANTREGISTER);
link_hid!(H5E_CANTINC, h5e::H5E_CANTINC);
link_hid!(H5E_CANTDEC, h5e::H5E_CANTDEC);
link_hid!(H5E_NOIDS, h5e::H5E_NOIDS);
link_hid!(H5E_CANTFLUSH, h5e::H5E_CANTFLUSH);
link_hid!(H5E_CANTSERIALIZE, h5e::H5E_CANTSERIALIZE);
link_hid!(H5E_CANTLOAD, h5e::H5E_CANTLOAD);
link_hid!(H5E_PROTECT, h5e::H5E_PROTECT);
link_hid!(H5E_NOTCACHED, h5e::H5E_NOTCACHED);
link_hid!(H5E_SYSTEM, h5e::H5E_SYSTEM);
link_hid!(H5E_CANTINS, h5e::H5E_CANTINS);
link_hid!(H5E_CANTPROTECT, h5e::H5E_CANTPROTECT);
link_hid!(H5E_CANTUNPROTECT, h5e::H5E_CANTUNPROTECT);
link_hid!(H5E_CANTPIN, h5e::H5E_CANTPIN);
link_hid!(H5E_CANTUNPIN, h5e::H5E_CANTUNPIN);
link_hid!(H5E_CANTMARKDIRTY, h5e::H5E_CANTMARKDIRTY);
link_hid!(H5E_CANTDIRTY, h5e::H5E_CANTDIRTY);
link_hid!(H5E_CANTEXPUNGE, h5e::H5E_CANTEXPUNGE);
link_hid!(H5E_CANTRESIZE, h5e::H5E_CANTRESIZE);
link_hid!(H5E_TRAVERSE, h5e::H5E_TRAVERSE);
link_hid!(H5E_NLINKS, h5e::H5E_NLINKS);
link_hid!(H5E_NOTREGISTERED, h5e::H5E_NOTREGISTERED);
link_hid!(H5E_CANTMOVE, h5e::H5E_CANTMOVE);
link_hid!(H5E_CANTSORT, h5e::H5E_CANTSORT);
link_hid!(H5E_MPI, h5e::H5E_MPI);
link_hid!(H5E_MPIERRSTR, h5e::H5E_MPIERRSTR);
link_hid!(H5E_CANTRECV, h5e::H5E_CANTRECV);
link_hid!(H5E_CANTCLIP, h5e::H5E_CANTCLIP);
link_hid!(H5E_CANTCOUNT, h5e::H5E_CANTCOUNT);
link_hid!(H5E_CANTSELECT, h5e::H5E_CANTSELECT);
link_hid!(H5E_CANTNEXT, h5e::H5E_CANTNEXT);
link_hid!(H5E_BADSELECT, h5e::H5E_BADSELECT);
link_hid!(H5E_CANTCOMPARE, h5e::H5E_CANTCOMPARE);
link_hid!(H5E_UNINITIALIZED, h5e::H5E_UNINITIALIZED);
link_hid!(H5E_UNSUPPORTED, h5e::H5E_UNSUPPORTED);
link_hid!(H5E_BADTYPE, h5e::H5E_BADTYPE);
link_hid!(H5E_BADRANGE, h5e::H5E_BADRANGE);
link_hid!(H5E_BADVALUE, h5e::H5E_BADVALUE);
link_hid!(H5E_NOTFOUND, h5e::H5E_NOTFOUND);
link_hid!(H5E_EXISTS, h5e::H5E_EXISTS);
link_hid!(H5E_CANTENCODE, h5e::H5E_CANTENCODE);
link_hid!(H5E_CANTDECODE, h5e::H5E_CANTDECODE);
link_hid!(H5E_CANTSPLIT, h5e::H5E_CANTSPLIT);
link_hid!(H5E_CANTREDISTRIBUTE, h5e::H5E_CANTREDISTRIBUTE);
link_hid!(H5E_CANTSWAP, h5e::H5E_CANTSWAP);
link_hid!(H5E_CANTINSERT, h5e::H5E_CANTINSERT);
link_hid!(H5E_CANTLIST, h5e::H5E_CANTLIST);
link_hid!(H5E_CANTMODIFY, h5e::H5E_CANTMODIFY);
link_hid!(H5E_CANTREMOVE, h5e::H5E_CANTREMOVE);
link_hid!(H5E_CANTCONVERT, h5e::H5E_CANTCONVERT);
link_hid!(H5E_BADSIZE, h5e::H5E_BADSIZE);
// H5R constants
lazy_static! {
pub static ref H5R_OBJ_REF_BUF_SIZE: usize = mem::size_of::<haddr_t>();
pub static ref H5R_DSET_REG_REF_BUF_SIZE: usize = mem::size_of::<haddr_t>() + 4;
}
// File drivers
lazy_static! {
pub static ref H5FD_CORE: hid_t = unsafe { h5lock!(H5FD_core_init()) };
pub static ref H5FD_SEC2: hid_t = unsafe { h5lock!(H5FD_sec2_init()) };
pub static ref H5FD_STDIO: hid_t = unsafe { h5lock!(H5FD_stdio_init()) };
pub static ref H5FD_FAMILY: hid_t = unsafe { h5lock!(H5FD_family_init()) };
pub static ref H5FD_LOG: hid_t = unsafe { h5lock!(H5FD_log_init()) };
pub static ref H5FD_MULTI: hid_t = unsafe { h5lock!(H5FD_multi_init()) };
}
// MPI-IO file driver
#[cfg(h5_have_parallel)]
lazy_static! {
pub static ref H5FD_MPIO: hid_t = unsafe { h5lock!(H5FD_mpio_init()) };
}
#[cfg(not(h5_have_parallel))]
lazy_static! {
pub static ref H5FD_MPIO: hid_t = H5I_INVALID_HID;
}
// Direct VFD
#[cfg(h5_have_direct)]
lazy_static! {
pub static ref H5FD_DIRECT: hid_t = unsafe { h5lock!(H5FD_direct_init()) };
}
#[cfg(not(h5_have_direct))]
lazy_static! {
pub static ref H5FD_DIRECT: hid_t = H5I_INVALID_HID;
}
#[cfg(target_os = "windows")]
lazy_static! {
pub static ref H5FD_WINDOWS: hid_t = *H5FD_SEC2;
}
#[cfg(test)]
mod tests {
use std::mem;
use hdf5_sys::{h5::haddr_t, h5i::H5I_INVALID_HID};
use super::{
H5E_DATASET, H5E_ERR_CLS, H5P_LST_LINK_ACCESS_ID, H5P_ROOT, H5R_DSET_REG_REF_BUF_SIZE,
H5R_OBJ_REF_BUF_SIZE, H5T_IEEE_F32BE, H5T_NATIVE_INT,
};
#[test]
pub fn test_lazy_globals() {
assert_ne!(*H5T_IEEE_F32BE, H5I_INVALID_HID);
assert_ne!(*H5T_NATIVE_INT, H5I_INVALID_HID);
assert_ne!(*H5P_ROOT, H5I_INVALID_HID);
assert_ne!(*H5P_LST_LINK_ACCESS_ID, H5I_INVALID_HID);
assert_ne!(*H5E_ERR_CLS, H5I_INVALID_HID);
assert_ne!(*H5E_DATASET, H5I_INVALID_HID);
assert_eq!(*H5R_OBJ_REF_BUF_SIZE, mem::size_of::<haddr_t>());
assert_eq!(*H5R_DSET_REG_REF_BUF_SIZE, mem::size_of::<haddr_t>() + 4);
}
}
| 41.261194 | 94 | 0.775909 |
01a28aeeb414aa7f46b2da3a8992bcc73c6ebdde
| 13,512 |
//! This module implements import-resolution/macro expansion algorithm.
//!
//! The result of this module is `CrateDefMap`: a data structure which contains:
//!
//! * a tree of modules for the crate
//! * for each module, a set of items visible in the module (directly declared
//! or imported)
//!
//! Note that `CrateDefMap` contains fully macro expanded code.
//!
//! Computing `CrateDefMap` can be partitioned into several logically
//! independent "phases". The phases are mutually recursive though, there's no
//! strict ordering.
//!
//! ## Collecting RawItems
//!
//! This happens in the `raw` module, which parses a single source file into a
//! set of top-level items. Nested imports are desugared to flat imports in this
//! phase. Macro calls are represented as a triple of (Path, Option<Name>,
//! TokenTree).
//!
//! ## Collecting Modules
//!
//! This happens in the `collector` module. In this phase, we recursively walk
//! tree of modules, collect raw items from submodules, populate module scopes
//! with defined items (so, we assign item ids in this phase) and record the set
//! of unresolved imports and macros.
//!
//! While we walk tree of modules, we also record macro_rules definitions and
//! expand calls to macro_rules defined macros.
//!
//! ## Resolving Imports
//!
//! We maintain a list of currently unresolved imports. On every iteration, we
//! try to resolve some imports from this list. If the import is resolved, we
//! record it, by adding an item to current module scope and, if necessary, by
//! recursively populating glob imports.
//!
//! ## Resolving Macros
//!
//! macro_rules from the same crate use a global mutable namespace. We expand
//! them immediately, when we collect modules.
//!
//! Macros from other crates (including proc-macros) can be used with
//! `foo::bar!` syntax. We handle them similarly to imports. There's a list of
//! unexpanded macros. On every iteration, we try to resolve each macro call
//! path and, upon success, we run macro expansion and "collect module" phase on
//! the result
mod collector;
mod mod_resolution;
mod path_resolution;
#[cfg(test)]
mod tests;
use std::sync::Arc;
use arena::Arena;
use base_db::{CrateId, Edition, FileId};
use hir_expand::{diagnostics::DiagnosticSink, name::Name, InFile};
use rustc_hash::FxHashMap;
use stdx::format_to;
use syntax::ast;
use crate::{
db::DefDatabase,
item_scope::{BuiltinShadowMode, ItemScope},
nameres::{diagnostics::DefDiagnostic, path_resolution::ResolveMode},
path::ModPath,
per_ns::PerNs,
AstId, LocalModuleId, ModuleDefId, ModuleId,
};
/// Contains all top-level defs from a macro-expanded crate
#[derive(Debug, PartialEq, Eq)]
pub struct CrateDefMap {
pub root: LocalModuleId,
pub modules: Arena<ModuleData>,
pub(crate) krate: CrateId,
/// The prelude module for this crate. This either comes from an import
/// marked with the `prelude_import` attribute, or (in the normal case) from
/// a dependency (`std` or `core`).
pub(crate) prelude: Option<ModuleId>,
pub(crate) extern_prelude: FxHashMap<Name, ModuleDefId>,
edition: Edition,
diagnostics: Vec<DefDiagnostic>,
}
impl std::ops::Index<LocalModuleId> for CrateDefMap {
type Output = ModuleData;
fn index(&self, id: LocalModuleId) -> &ModuleData {
&self.modules[id]
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub enum ModuleOrigin {
CrateRoot {
definition: FileId,
},
/// Note that non-inline modules, by definition, live inside non-macro file.
File {
is_mod_rs: bool,
declaration: AstId<ast::Module>,
definition: FileId,
},
Inline {
definition: AstId<ast::Module>,
},
}
impl Default for ModuleOrigin {
fn default() -> Self {
ModuleOrigin::CrateRoot { definition: FileId(0) }
}
}
impl ModuleOrigin {
fn declaration(&self) -> Option<AstId<ast::Module>> {
match self {
ModuleOrigin::File { declaration: module, .. }
| ModuleOrigin::Inline { definition: module, .. } => Some(*module),
ModuleOrigin::CrateRoot { .. } => None,
}
}
pub fn file_id(&self) -> Option<FileId> {
match self {
ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
Some(*definition)
}
_ => None,
}
}
pub fn is_inline(&self) -> bool {
match self {
ModuleOrigin::Inline { .. } => true,
ModuleOrigin::CrateRoot { .. } | ModuleOrigin::File { .. } => false,
}
}
/// Returns a node which defines this module.
/// That is, a file or a `mod foo {}` with items.
fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
match self {
ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
let file_id = *definition;
let sf = db.parse(file_id).tree();
InFile::new(file_id.into(), ModuleSource::SourceFile(sf))
}
ModuleOrigin::Inline { definition } => InFile::new(
definition.file_id,
ModuleSource::Module(definition.to_node(db.upcast())),
),
}
}
}
#[derive(Default, Debug, PartialEq, Eq)]
pub struct ModuleData {
pub parent: Option<LocalModuleId>,
pub children: FxHashMap<Name, LocalModuleId>,
pub scope: ItemScope,
/// Where does this module come from?
pub origin: ModuleOrigin,
}
impl CrateDefMap {
pub(crate) fn crate_def_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<CrateDefMap> {
let _p = profile::span("crate_def_map_query").detail(|| {
db.crate_graph()[krate].display_name.as_deref().unwrap_or_default().to_string()
});
let def_map = {
let edition = db.crate_graph()[krate].edition;
let mut modules: Arena<ModuleData> = Arena::default();
let root = modules.alloc(ModuleData::default());
CrateDefMap {
krate,
edition,
extern_prelude: FxHashMap::default(),
prelude: None,
root,
modules,
diagnostics: Vec::new(),
}
};
let def_map = collector::collect_defs(db, def_map);
Arc::new(def_map)
}
pub fn add_diagnostics(
&self,
db: &dyn DefDatabase,
module: LocalModuleId,
sink: &mut DiagnosticSink,
) {
self.diagnostics.iter().for_each(|it| it.add_to(db, module, sink))
}
pub fn modules_for_file(&self, file_id: FileId) -> impl Iterator<Item = LocalModuleId> + '_ {
self.modules
.iter()
.filter(move |(_id, data)| data.origin.file_id() == Some(file_id))
.map(|(id, _data)| id)
}
pub(crate) fn resolve_path(
&self,
db: &dyn DefDatabase,
original_module: LocalModuleId,
path: &ModPath,
shadow: BuiltinShadowMode,
) -> (PerNs, Option<usize>) {
let res =
self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path, shadow);
(res.resolved_def, res.segment_index)
}
// FIXME: this can use some more human-readable format (ideally, an IR
// even), as this should be a great debugging aid.
pub fn dump(&self) -> String {
let mut buf = String::new();
go(&mut buf, self, "crate", self.root);
return buf;
fn go(buf: &mut String, map: &CrateDefMap, path: &str, module: LocalModuleId) {
format_to!(buf, "{}\n", path);
let mut entries: Vec<_> = map.modules[module].scope.resolutions().collect();
entries.sort_by_key(|(name, _)| name.clone());
for (name, def) in entries {
format_to!(buf, "{}:", name.map_or("_".to_string(), |name| name.to_string()));
if def.types.is_some() {
buf.push_str(" t");
}
if def.values.is_some() {
buf.push_str(" v");
}
if def.macros.is_some() {
buf.push_str(" m");
}
if def.is_none() {
buf.push_str(" _");
}
buf.push_str("\n");
}
for (name, child) in map.modules[module].children.iter() {
let path = format!("{}::{}", path, name);
buf.push('\n');
go(buf, map, &path, *child);
}
}
}
}
impl ModuleData {
/// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
pub fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
self.origin.definition_source(db)
}
/// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
/// `None` for the crate root or block.
pub fn declaration_source(&self, db: &dyn DefDatabase) -> Option<InFile<ast::Module>> {
let decl = self.origin.declaration()?;
let value = decl.to_node(db.upcast());
Some(InFile { file_id: decl.file_id, value })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModuleSource {
SourceFile(ast::SourceFile),
Module(ast::Module),
}
mod diagnostics {
use hir_expand::diagnostics::DiagnosticSink;
use hir_expand::hygiene::Hygiene;
use hir_expand::InFile;
use syntax::{ast, AstPtr, SyntaxNodePtr};
use crate::path::ModPath;
use crate::{db::DefDatabase, diagnostics::*, nameres::LocalModuleId, AstId};
#[derive(Debug, PartialEq, Eq)]
enum DiagnosticKind {
UnresolvedModule { declaration: AstId<ast::Module>, candidate: String },
UnresolvedExternCrate { ast: AstId<ast::ExternCrate> },
UnresolvedImport { ast: AstId<ast::Use>, index: usize },
UnconfiguredCode { ast: InFile<SyntaxNodePtr> },
}
#[derive(Debug, PartialEq, Eq)]
pub(super) struct DefDiagnostic {
in_module: LocalModuleId,
kind: DiagnosticKind,
}
impl DefDiagnostic {
pub(super) fn unresolved_module(
container: LocalModuleId,
declaration: AstId<ast::Module>,
candidate: String,
) -> Self {
Self {
in_module: container,
kind: DiagnosticKind::UnresolvedModule { declaration, candidate },
}
}
pub(super) fn unresolved_extern_crate(
container: LocalModuleId,
declaration: AstId<ast::ExternCrate>,
) -> Self {
Self {
in_module: container,
kind: DiagnosticKind::UnresolvedExternCrate { ast: declaration },
}
}
pub(super) fn unresolved_import(
container: LocalModuleId,
ast: AstId<ast::Use>,
index: usize,
) -> Self {
Self { in_module: container, kind: DiagnosticKind::UnresolvedImport { ast, index } }
}
pub(super) fn unconfigured_code(
container: LocalModuleId,
ast: InFile<SyntaxNodePtr>,
) -> Self {
Self { in_module: container, kind: DiagnosticKind::UnconfiguredCode { ast } }
}
pub(super) fn add_to(
&self,
db: &dyn DefDatabase,
target_module: LocalModuleId,
sink: &mut DiagnosticSink,
) {
if self.in_module != target_module {
return;
}
match &self.kind {
DiagnosticKind::UnresolvedModule { declaration, candidate } => {
let decl = declaration.to_node(db.upcast());
sink.push(UnresolvedModule {
file: declaration.file_id,
decl: AstPtr::new(&decl),
candidate: candidate.clone(),
})
}
DiagnosticKind::UnresolvedExternCrate { ast } => {
let item = ast.to_node(db.upcast());
sink.push(UnresolvedExternCrate {
file: ast.file_id,
item: AstPtr::new(&item),
});
}
DiagnosticKind::UnresolvedImport { ast, index } => {
let use_item = ast.to_node(db.upcast());
let hygiene = Hygiene::new(db.upcast(), ast.file_id);
let mut cur = 0;
let mut tree = None;
ModPath::expand_use_item(
InFile::new(ast.file_id, use_item),
&hygiene,
|_mod_path, use_tree, _is_glob, _alias| {
if cur == *index {
tree = Some(use_tree.clone());
}
cur += 1;
},
);
if let Some(tree) = tree {
sink.push(UnresolvedImport { file: ast.file_id, node: AstPtr::new(&tree) });
}
}
DiagnosticKind::UnconfiguredCode { ast } => {
sink.push(InactiveCode { file: ast.file_id, node: ast.value.clone() });
}
}
}
}
}
| 33.362963 | 100 | 0.564165 |
e8b06b05c1a022a4c86b9ded7549aefd7471f206
| 17,193 |
#[cfg(not(feature = "binary"))]
fn main() {}
#[cfg(feature = "binary")]
fn main() {
binary::main();
}
#[cfg(feature = "binary")]
mod binary {
use quote::quote;
use std::convert::TryInto;
pub fn main() {
use llvm_tools_build as llvm_tools;
use std::{
env,
fs::{self, File},
io::Write,
path::{Path, PathBuf},
process::{self, Command},
};
use toml::Value;
let target = env::var("TARGET").expect("TARGET not set");
let (firmware, expected_target) = if cfg!(feature = "uefi_bin") {
("UEFI", "x86_64-unknown-uefi")
} else if cfg!(feature = "bios_bin") {
("BIOS", "x86_64-bootloader")
} else {
panic!(
"Either the `uefi_bin` or `bios_bin` feature must be enabled when \
the `binary` feature is enabled"
);
};
if Path::new(&target)
.file_stem()
.expect("target has no file stem")
!= expected_target
{
panic!(
"The {} bootloader must be compiled for the `{}` target.",
firmware, expected_target,
);
}
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set"));
let kernel = PathBuf::from(match env::var("KERNEL") {
Ok(kernel) => kernel,
Err(_) => {
eprintln!(
"The KERNEL environment variable must be set for building the bootloader.\n\n\
Please use the `cargo builder` command for building."
);
process::exit(1);
}
});
let kernel_file_name = kernel
.file_name()
.expect("KERNEL has no valid file name")
.to_str()
.expect("kernel file name not valid utf8");
// check that the kernel file exists
assert!(
kernel.exists(),
"KERNEL does not exist: {}",
kernel.display()
);
// get access to llvm tools shipped in the llvm-tools-preview rustup component
let llvm_tools = match llvm_tools::LlvmTools::new() {
Ok(tools) => tools,
Err(llvm_tools::Error::NotFound) => {
eprintln!("Error: llvm-tools not found");
eprintln!("Maybe the rustup component `llvm-tools-preview` is missing?");
eprintln!(" Install it through: `rustup component add llvm-tools-preview`");
process::exit(1);
}
Err(err) => {
eprintln!("Failed to retrieve llvm-tools component: {:?}", err);
process::exit(1);
}
};
// check that kernel executable has code in it
let llvm_size = llvm_tools
.tool(&llvm_tools::exe("llvm-size"))
.expect("llvm-size not found in llvm-tools");
let mut cmd = Command::new(llvm_size);
cmd.arg(&kernel);
let output = cmd.output().expect("failed to run llvm-size");
let output_str = String::from_utf8_lossy(&output.stdout);
let second_line_opt = output_str.lines().skip(1).next();
let second_line = second_line_opt.expect("unexpected llvm-size line output");
let text_size_opt = second_line.split_ascii_whitespace().next();
let text_size = text_size_opt.expect("unexpected llvm-size output");
if text_size == "0" {
panic!("Kernel executable has an empty text section. Perhaps the entry point was set incorrectly?\n\n\
Kernel executable at `{}`\n", kernel.display());
}
// strip debug symbols from kernel for faster loading
let stripped_kernel_file_name = format!("kernel_stripped-{}", kernel_file_name);
let stripped_kernel = out_dir.join(&stripped_kernel_file_name);
let objcopy = llvm_tools
.tool(&llvm_tools::exe("llvm-objcopy"))
.expect("llvm-objcopy not found in llvm-tools");
let mut cmd = Command::new(&objcopy);
cmd.arg("--strip-debug");
cmd.arg(&kernel);
cmd.arg(&stripped_kernel);
let exit_status = cmd
.status()
.expect("failed to run objcopy to strip debug symbols");
if !exit_status.success() {
eprintln!("Error: Stripping debug symbols failed");
process::exit(1);
}
if cfg!(feature = "uefi_bin") {
// write file for including kernel in binary
let file_path = out_dir.join("kernel_info.rs");
let mut file = File::create(file_path).expect("failed to create kernel_info.rs");
let kernel_size = fs::metadata(&stripped_kernel)
.expect("Failed to read file metadata of stripped kernel")
.len();
file.write_all(
format!(
"const KERNEL_SIZE: usize = {}; const KERNEL_BYTES: [u8; KERNEL_SIZE] = *include_bytes!(r\"{}\");",
kernel_size,
stripped_kernel.display(),
)
.as_bytes(),
)
.expect("write to kernel_info.rs failed");
}
if cfg!(feature = "bios_bin") {
// wrap the kernel executable as binary in a new ELF file
let stripped_kernel_file_name_replaced = stripped_kernel_file_name
.replace('-', "_")
.replace('.', "_");
let kernel_bin = out_dir.join(format!("kernel_bin-{}.o", kernel_file_name));
let kernel_archive = out_dir.join(format!("libkernel_bin-{}.a", kernel_file_name));
let mut cmd = Command::new(&objcopy);
cmd.arg("-I").arg("binary");
cmd.arg("-O").arg("elf64-x86-64");
cmd.arg("--binary-architecture=i386:x86-64");
cmd.arg("--rename-section").arg(".data=.kernel");
cmd.arg("--redefine-sym").arg(format!(
"_binary_{}_start=_kernel_start_addr",
stripped_kernel_file_name_replaced
));
cmd.arg("--redefine-sym").arg(format!(
"_binary_{}_end=_kernel_end_addr",
stripped_kernel_file_name_replaced
));
cmd.arg("--redefine-sym").arg(format!(
"_binary_{}_size=_kernel_size",
stripped_kernel_file_name_replaced
));
cmd.current_dir(&out_dir);
cmd.arg(&stripped_kernel_file_name);
cmd.arg(&kernel_bin);
let exit_status = cmd.status().expect("failed to run objcopy");
if !exit_status.success() {
eprintln!("Error: Running objcopy failed");
process::exit(1);
}
// create an archive for linking
let ar = llvm_tools
.tool(&llvm_tools::exe("llvm-ar"))
.unwrap_or_else(|| {
eprintln!("Failed to retrieve llvm-ar component");
eprint!("This component is available since nightly-2019-03-29,");
eprintln!("so try updating your toolchain if you're using an older nightly");
process::exit(1);
});
let mut cmd = Command::new(ar);
cmd.arg("crs");
cmd.arg(&kernel_archive);
cmd.arg(&kernel_bin);
let exit_status = cmd.status().expect("failed to run ar");
if !exit_status.success() {
eprintln!("Error: Running ar failed");
process::exit(1);
}
// pass link arguments to rustc
println!("cargo:rustc-link-search=native={}", out_dir.display());
println!(
"cargo:rustc-link-lib=static=kernel_bin-{}",
kernel_file_name
);
}
// Parse configuration from the kernel's Cargo.toml
let config = match env::var("KERNEL_MANIFEST") {
Err(env::VarError::NotPresent) => {
panic!("The KERNEL_MANIFEST environment variable must be set for building the bootloader.\n\n\
Please use `cargo builder` for building.");
}
Err(env::VarError::NotUnicode(_)) => {
panic!("The KERNEL_MANIFEST environment variable contains invalid unicode")
}
Ok(path)
if Path::new(&path).file_name().and_then(|s| s.to_str()) != Some("Cargo.toml") =>
{
let err = format!(
"The given `--kernel-manifest` path `{}` does not \
point to a `Cargo.toml`",
path,
);
quote! { compile_error!(#err) }
}
Ok(path) if !Path::new(&path).exists() => {
let err = format!(
"The given `--kernel-manifest` path `{}` does not exist.",
path
);
quote! {
compile_error!(#err)
}
}
Ok(path) => {
println!("cargo:rerun-if-changed={}", path);
let contents = fs::read_to_string(&path).expect(&format!(
"failed to read kernel manifest file (path: {})",
path
));
let manifest = contents
.parse::<Value>()
.expect("failed to parse kernel's Cargo.toml");
if manifest
.get("dependencies")
.and_then(|d| d.get("bootloader"))
.is_some()
{
// it seems to be the correct Cargo.toml
let config_table = manifest
.get("package")
.and_then(|table| table.get("metadata"))
.and_then(|table| table.get("bootloader"))
.cloned()
.unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
config_table
.try_into::<ParsedConfig>()
.map(|c| quote! { #c })
.unwrap_or_else(|err| {
let err = format!(
"failed to parse bootloader config in {}:\n\n{}",
path,
err.to_string()
);
quote! {
compile_error!(#err)
}
})
} else {
let err = format!(
"no bootloader dependency in {}\n\n The \
`--kernel-manifest` path should point to the `Cargo.toml` \
of the kernel.",
path
);
quote! {
compile_error!(#err)
}
}
}
};
// Write config to file
let file_path = out_dir.join("bootloader_config.rs");
let mut file = File::create(file_path).expect("failed to create bootloader_config.rs");
file.write_all(
quote::quote! {
mod parsed_config {
use crate::config::Config;
pub const CONFIG: Config = #config;
}
}
.to_string()
.as_bytes(),
)
.expect("write to bootloader_config.rs failed");
println!("cargo:rerun-if-env-changed=KERNEL");
println!("cargo:rerun-if-env-changed=KERNEL_MANIFEST");
println!("cargo:rerun-if-changed={}", kernel.display());
println!("cargo:rerun-if-changed=build.rs");
}
fn val_true() -> bool {
true
}
/// Must be always identical with the struct in `src/config.rs`
///
/// This copy is needed because we can't derive Deserialize in the `src/config.rs`
/// module itself, since cargo currently unifies dependencies (the `toml` crate enables
/// serde's standard feature). Also, it allows to separate the parsing special cases
/// such as `AlignedAddress` more cleanly.
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct ParsedConfig {
#[serde(default)]
pub map_physical_memory: bool,
#[serde(default)]
pub map_page_table_recursively: bool,
#[serde(default = "val_true")]
pub map_framebuffer: bool,
pub kernel_stack_size: Option<AlignedAddress>,
pub physical_memory_offset: Option<AlignedAddress>,
pub recursive_index: Option<u16>,
pub kernel_stack_address: Option<AlignedAddress>,
pub boot_info_address: Option<AlignedAddress>,
pub framebuffer_address: Option<AlignedAddress>,
}
/// Convert to tokens suitable for initializing the `Config` struct.
impl quote::ToTokens for ParsedConfig {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
fn optional(value: Option<impl quote::ToTokens>) -> proc_macro2::TokenStream {
value.map(|v| quote!(Some(#v))).unwrap_or(quote!(None))
}
let map_physical_memory = self.map_physical_memory;
let map_page_table_recursively = self.map_page_table_recursively;
let map_framebuffer = self.map_framebuffer;
let kernel_stack_size = optional(self.kernel_stack_size);
let physical_memory_offset = optional(self.physical_memory_offset);
let recursive_index = optional(self.recursive_index);
let kernel_stack_address = optional(self.kernel_stack_address);
let boot_info_address = optional(self.boot_info_address);
let framebuffer_address = optional(self.framebuffer_address);
tokens.extend(quote! { Config {
map_physical_memory: #map_physical_memory,
map_page_table_recursively: #map_page_table_recursively,
map_framebuffer: #map_framebuffer,
kernel_stack_size: #kernel_stack_size,
physical_memory_offset: #physical_memory_offset,
recursive_index: #recursive_index,
kernel_stack_address: #kernel_stack_address,
boot_info_address: #boot_info_address,
framebuffer_address: #framebuffer_address,
}});
}
}
#[derive(Debug, Clone, Copy)]
struct AlignedAddress(u64);
impl quote::ToTokens for AlignedAddress {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
self.0.to_tokens(tokens);
}
}
impl<'de> serde::Deserialize<'de> for AlignedAddress {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_str(AlignedAddressVisitor)
}
}
/// Helper struct for implementing the `optional_version_deserialize` function.
struct AlignedAddressVisitor;
impl serde::de::Visitor<'_> for AlignedAddressVisitor {
type Value = AlignedAddress;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
formatter,
"a page-aligned memory address, either as integer or as decimal or hexadecimal \
string (e.g. \"0xffff0000\"); large addresses must be given as string because \
TOML does not support unsigned 64-bit integers"
)
}
fn visit_u64<E>(self, num: u64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
if num % 0x1000 == 0 {
Ok(AlignedAddress(num))
} else {
Err(serde::de::Error::custom(format!(
"address {:#x} is not page aligned",
num
)))
}
}
fn visit_i64<E>(self, num: i64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
let unsigned: u64 = num
.try_into()
.map_err(|_| serde::de::Error::custom(format!("address {} is negative", num)))?;
self.visit_u64(unsigned)
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
// ignore any `_` (used for digit grouping)
let value = &value.replace('_', "");
let num = if value.starts_with("0x") {
u64::from_str_radix(&value[2..], 16)
} else {
u64::from_str_radix(&value, 10)
}
.map_err(|_err| {
serde::de::Error::custom(format!(
"string \"{}\" is not a valid memory address",
value
))
})?;
self.visit_u64(num)
}
}
}
| 39.253425 | 119 | 0.514628 |
d77f41113da9a2441dac49617b6f19133977ecb6
| 2,806 |
use linfa_logistic::LogisticRegression;
use ndarray::{prelude::*, OwnedRepr};
use linfa::DatasetBase;
use linfa::metrics::ConfusionMatrix;
use linfa::prelude::{Fit, Predict, ToConfusionMatrix};
pub fn train_with_hyperparameter_tuning_and_test_classifier(train: &DatasetBase<
ArrayBase<OwnedRepr<f64>, Dim<[usize; 2]>>,
ArrayBase<OwnedRepr<&'static str>, Dim<[usize; 2]>>,
>,
test: &DatasetBase<
ArrayBase<OwnedRepr<f64>, Dim<[usize; 2]>>,
ArrayBase<OwnedRepr<&'static str>, Dim<[usize; 2]>>,
>,){
println!("training and testing model...");
// TODO: split into train, dev and test set, as hyperparameter tuning may overfit the test set
let mut max_f1score_confusion_matrix = iterate_with_values(&train, &test, 0.01, 100);
let mut best_threshold = 0.0;
let mut best_max_iterations = 0;
let mut threshold = 0.02;
// very crude and basic hyperparameter tuning
// TODO: create a function that optimises based on a user defined grid, as for sklearn
for max_iterations in (1000..5000).step_by(500) {
while threshold < 1.0 {
let confusion_matrix = iterate_with_values(&train, &test, threshold, max_iterations);
if confusion_matrix.f1_score() > max_f1score_confusion_matrix.f1_score() {
max_f1score_confusion_matrix = confusion_matrix;
best_threshold = threshold;
best_max_iterations = max_iterations;
}
threshold += 0.01;
}
threshold = 0.02;
}
println!(
"most accurate confusion matrix: {:?}",
max_f1score_confusion_matrix
);
println!(
"with max_iterations: {}, threshold: {}",
best_max_iterations, best_threshold
);
println!("accuracy {}", max_f1score_confusion_matrix.accuracy(),);
println!("f1 score {}", max_f1score_confusion_matrix.f1_score(),);
println!("precision {}", max_f1score_confusion_matrix.precision(),);
println!("recall {}", max_f1score_confusion_matrix.recall(),);
}
fn iterate_with_values(
train: &DatasetBase<
ArrayBase<OwnedRepr<f64>, Dim<[usize; 2]>>,
ArrayBase<OwnedRepr<&'static str>, Dim<[usize; 2]>>,
>,
test: &DatasetBase<
ArrayBase<OwnedRepr<f64>, Dim<[usize; 2]>>,
ArrayBase<OwnedRepr<&'static str>, Dim<[usize; 2]>>,
>,
threshold: f64,
max_iterations: u64,
) -> ConfusionMatrix<&'static str> {
let model = LogisticRegression::default()
.max_iterations(max_iterations)
.gradient_tolerance(0.0001)
.fit(train)
.expect("can train model");
let validation = model.set_threshold(threshold).predict(test);
let confusion_matrix = validation
.confusion_matrix(test)
.expect("can create confusion matrix");
confusion_matrix
}
| 35.974359 | 98 | 0.657876 |
16ef81c9ea31ff16ccbc02936810a7af01068f64
| 3,467 |
use crate::datatypes::{parse_param_type, tokenize};
use ethabi::param_type::ParamType;
#[derive(Serialize, Debug, PartialEq)]
pub struct AbiInput {
#[serde(skip_serializing_if = "Option::is_none")]
name: Option<String>,
#[serde(rename = "type")]
data_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
components: Option<Vec<AbiInput>>,
#[serde(skip_serializing_if = "Option::is_none")]
indexed: Option<bool>,
}
#[derive(Serialize, Debug, PartialEq)]
pub struct AbiItem {
name: String,
inputs: Vec<AbiInput>,
}
fn param_to_abi_input(param: &ParamType, indexed: Option<bool>) -> AbiInput {
match param {
ParamType::Tuple(inner) => AbiInput {
name: None,
data_type: String::from("tuple"),
components: Some(
inner
.iter()
.map(|p| param_to_abi_input(p, None))
.collect::<Vec<AbiInput>>(),
),
indexed: indexed,
},
_ => AbiInput {
name: None,
data_type: format!("{}", param),
components: None,
indexed: indexed,
},
}
}
fn parse_fn_args(args_str: &String, allow_indexed_flag: bool) -> Result<Vec<AbiInput>, String> {
if args_str.chars().next() != Some('(') || args_str.chars().last() != Some(')') {
return Err(String::from(
"Unable to parse signature: Invalid argument list",
));
}
let tokens = match tokenize(&args_str[1..(args_str.len() - 1)]) {
Ok(t) => t,
Err(e) => return Err(format!("{}", e)),
};
let mut inputs = Vec::new();
for token in tokens {
let mut indexed = None;
let mut cur = token;
if allow_indexed_flag {
if cur.ends_with(" indexed") {
cur = &cur[0..(cur.len() - 8)];
indexed = Some(true);
} else {
indexed = Some(false);
}
}
match parse_param_type(&String::from(cur)) {
Ok(p) => {
inputs.push(param_to_abi_input(&p, indexed));
}
Err(e) => {
return Err(format!("Unable to parse signature: {}", e));
}
}
}
return Ok(inputs);
}
fn is_valid_function_name(name: &str) -> bool {
name.chars().all(|ch| ch == '_' || ch.is_alphanumeric())
}
pub fn parse_signature(sig: &String, allow_indexed_flag: bool) -> Result<AbiItem, String> {
match sig.chars().position(|c| c == '(') {
Some(pos) => {
let name = &sig[..pos];
if name.len() == 0 {
return Err(String::from(
"Unable to parse signature: Empty function name",
));
}
if !is_valid_function_name(name) {
return Err(format!(
"Unable to parse signature: Invalid function name: {:?}",
name
));
}
let args = &sig[pos..];
match parse_fn_args(&String::from(args), allow_indexed_flag) {
Ok(args) => Ok(AbiItem {
name: String::from(name),
inputs: args,
}),
Err(msg) => Err(format!("{}", msg)),
}
}
None => Err(String::from(
"Unable to parse signature: no open parenthesis found",
)),
}
}
| 31.234234 | 96 | 0.494664 |
f8bb9935d04d72f7bc73367578d318a1a53da8be
| 430 |
//! Access to various system and model specific registers.
pub mod control;
pub mod model_specific;
pub mod rflags;
/// Gets the current instruction pointer. Note that this is only approximate as it requires a few
/// instructions to execute.
#[inline(always)]
pub fn read_rip() -> u64 {
let rip: u64;
unsafe {
asm!(
"lea (%rip), $0"
: "=r"(rip) ::: "volatile"
);
}
rip
}
| 21.5 | 97 | 0.597674 |
d6e909b8b5103290f19e0f7df1d1e0061df1a995
| 37,469 |
// Copyright 2018 Parity Technologies (UK) Ltd.
// Copyright 2020 Netwarps Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// This module contains the `Connection` type and associated helpers.
// A `Connection` wraps an underlying (async) I/O resource and multiplexes
// `Stream`s over it.
//
// The overall idea is as follows: The `Connection` makes progress via calls
// to its `next_stream` method which polls several futures, one that decodes
// `Frame`s from the I/O resource, one that consumes `ControlCommand`s
// from an MPSC channel and another one that consumes `StreamCommand`s from
// yet another MPSC channel. The latter channel is shared with every `Stream`
// created and whenever a `Stream` wishes to send a `Frame` to the remote end,
// it enqueues it into this channel (waiting if the channel is full). The
// former is shared with every `Control` clone and used to open new outbound
// streams or to trigger a connection close.
//
// The `Connection` updates the `Stream` state based on incoming frames, e.g.
// it pushes incoming data to the `Stream` via channel or increases the sending
// credit if the remote has sent us a corresponding `Frame::<WindowUpdate>`.
//
// Closing a `Connection`
// ----------------------
//
// Every `Control` may send a `ControlCommand::Close` at any time and then
// waits on a `oneshot::Receiver` for confirmation that the connection is
// closed. The closing proceeds as follows:
//
// 1. As soon as we receive the close command we close the MPSC receiver
// of `StreamCommand`s. We want to process any stream commands which are
// already enqueued at this point but no more.
// 2. We change the internal shutdown state to `Shutdown::InProgress` which
// contains the `oneshot::Sender` of the `Control` which triggered the
// closure and which we need to notify eventually.
// 3. Crucially -- while closing -- we no longer process further control
// commands, because opening new streams should no longer be allowed
// and further close commands would mean we need to save those
// `oneshot::Sender`s for later. On the other hand we also do not simply
// close the control channel as this would signal to `Control`s that
// try to send close commands, that the connection is already closed,
// which it is not. So we just pause processing control commands which
// means such `Control`s will wait.
// 4. We keep processing I/O and stream commands until the remaining stream
// commands have all been consumed, at which point we transition the
// shutdown state to `Shutdown::Complete`, which entails sending the
// final termination frame to the remote, informing the `Control` and
// now also closing the control channel.
// 5. Now that we are closed we go through all pending control commands
// and tell the `Control`s that we are closed and we are finally done.
//
// While all of this may look complicated, it ensures that `Control`s are
// only informed about a closed connection when it really is closed.
//
// specific
// ----------------------
// - All stream's state is managed by connection, stream state get from channel
// Shared lock is not efficient.
// - Connection pushes incoming data to the `Stream` via channel, not buffer
// - Stream must be closed explicitly Since garbage collect is not implemented.
// Drop it directly do nothing
//
// Potential improvements
// ----------------------
//
// There is always more work that can be done to make this a better crate,
// for example:
// - Loop in handle_coming() is performance bottleneck. More seriously, it will be block
// when two peers echo with mass of data with lot of stream Since they block
// on write data and none of them can read data.
// One solution is spawn runtime for reader and writer But depend on async runtime
// is not attractive. See detail from concurrent in tests
pub mod control;
pub mod stream;
use futures::{
channel::{mpsc, oneshot},
prelude::*,
select,
stream::FusedStream,
};
use crate::connection::stream::Flag;
use crate::{
error::ConnectionError,
frame::header::{self, Data, GoAway, Header, Ping, StreamId, Tag, WindowUpdate, CONNECTION_ID},
frame::{io, Frame, FrameDecodeError},
pause::Pausable,
Config, WindowUpdateMode, DEFAULT_CREDIT,
};
use control::Control;
use libp2prs_traits::{SplitEx, SplittableReadWrite};
use nohash_hasher::IntMap;
use std::collections::VecDeque;
use std::fmt;
use std::pin::Pin;
use std::sync::Arc;
use stream::{State, Stream, StreamStat};
/// `Control` to `Connection` commands.
#[derive(Debug)]
pub enum ControlCommand {
/// Open a new stream to the remote end.
OpenStream(oneshot::Sender<Result<Stream>>),
/// Accept a new stream from the remote end.
AcceptStream(oneshot::Sender<Result<Stream>>),
/// Close the whole connection.
CloseConnection(oneshot::Sender<()>),
}
/// `Stream` to `Connection` commands.
#[derive(Debug)]
pub(crate) enum StreamCommand {
/// A new frame should be sent to the remote.
SendFrame(Frame<Data>, oneshot::Sender<usize>),
/// Close a stream.
CloseStream(StreamId, oneshot::Sender<()>),
/// Reset a stream.
ResetStream(StreamId, oneshot::Sender<()>),
}
/// Possible actions as a result of incoming frame handling.
#[derive(Debug)]
enum Action {
/// Nothing to be done.
None,
/// A new stream has been opened by the remote.
New(Stream, Option<Frame<WindowUpdate>>),
/// A window update should be sent to the remote.
Update(Frame<WindowUpdate>),
/// A ping should be answered.
Ping(Frame<Ping>),
/// A stream should be reset.
Reset(StreamId),
/// The connection should be terminated.
Terminate(Frame<GoAway>),
}
/// How the connection is used.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum Mode {
/// Client to server connection.
Client,
/// Server to client connection.
Server,
}
/// The connection identifier.
///
/// Randomly generated, this is mainly intended to improve log output.
#[derive(Clone, Copy)]
pub struct Id(u32, Mode);
impl Id {
/// Create a random connection ID.
pub(crate) fn random(mode: Mode) -> Self {
Id(rand::random(), mode)
}
}
impl fmt::Debug for Id {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}({:08x})", self.1, self.0)
}
}
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}({:08x})", self.1, self.0)
}
}
/// This enum captures the various stages of shutting down the connection.
#[derive(Debug)]
enum Shutdown {
/// We are open for business.
NotStarted,
/// We have received a `ControlCommand::Close` and are shutting
/// down operations. The `Sender` will be informed once we are done.
InProgress(oneshot::Sender<()>),
/// The shutdown is complete and we are closed for good.
Complete,
}
impl Shutdown {
fn has_not_started(&self) -> bool {
matches!(self, Shutdown::NotStarted)
}
fn is_in_progress(&self) -> bool {
matches!(self, Shutdown::InProgress(_))
}
fn is_complete(&self) -> bool {
matches!(self, Shutdown::Complete)
}
}
type Result<T> = std::result::Result<T, ConnectionError>;
pub struct Connection<T: SplitEx> {
id: Id,
mode: Mode,
config: Arc<Config>,
reader: Pin<Box<dyn FusedStream<Item = std::result::Result<Frame<()>, FrameDecodeError>> + Send>>,
// writer: io::Io<WriteHalf<T>>,
writer: io::Io<T::Writer>,
is_closed: bool,
shutdown: Shutdown,
next_stream_id: u32,
streams: IntMap<StreamId, mpsc::UnboundedSender<Vec<u8>>>,
streams_stat: IntMap<StreamId, StreamStat>,
stream_sender: mpsc::UnboundedSender<StreamCommand>,
stream_receiver: mpsc::UnboundedReceiver<StreamCommand>,
control_sender: mpsc::UnboundedSender<ControlCommand>,
control_receiver: Pausable<mpsc::UnboundedReceiver<ControlCommand>>,
waiting_stream_sender: Option<oneshot::Sender<Result<Stream>>>,
pending_streams: VecDeque<Stream>,
pending_frames: IntMap<StreamId, (Frame<Data>, oneshot::Sender<usize>)>,
}
impl<T: SplittableReadWrite> Connection<T> {
/// Create a new `Connection` from the given I/O resource.
pub fn new(socket: T, cfg: Config, mode: Mode) -> Self {
let id = Id::random(mode);
log::debug!("new connection: {}", id);
let (reader, writer) = socket.split();
// let (reader, writer) = socket.split2();
let reader = io::Io::new(id, reader, cfg.max_buffer_size);
let reader = futures::stream::unfold(reader, |mut io| async { Some((io.recv_frame().await, io)) });
let reader = Box::pin(reader);
let writer = io::Io::new(id, writer, cfg.max_buffer_size);
let (stream_sender, stream_receiver) = mpsc::unbounded();
let (control_sender, control_receiver) = mpsc::unbounded();
Connection {
id,
mode,
config: Arc::new(cfg),
reader,
writer,
is_closed: false,
next_stream_id: match mode {
Mode::Client => 1,
Mode::Server => 2,
},
shutdown: Shutdown::NotStarted,
streams: IntMap::default(),
streams_stat: IntMap::default(),
stream_sender,
stream_receiver,
control_sender,
control_receiver: Pausable::new(control_receiver),
waiting_stream_sender: None,
pending_streams: VecDeque::default(),
pending_frames: IntMap::default(),
}
}
/// Returns the id of the connection
pub fn id(&self) -> Id {
self.id
}
/// Get a controller for this connection.
pub fn control(&self) -> Control {
Control::new(self.control_sender.clone())
}
/// Get the next incoming stream, opened by the remote.
///
/// This must be called repeatedly in order to make progress.
/// Once `Ok(()))` or `Err(_)` is returned the connection is
/// considered closed and no further invocation of this method
/// must be attempted.
pub async fn next_stream(&mut self) -> Result<()> {
if self.is_closed {
log::debug!("{}: connection is closed", self.id);
return Ok(());
}
let result = self.handle_coming().await;
log::debug!("{}: error exit, {:?}", self.id, result);
self.is_closed = true;
if let Some(sender) = self.waiting_stream_sender.take() {
sender.send(Err(ConnectionError::Closed)).expect("send err");
}
self.drop_pending_frame();
// Close and drain the control command receiver.
if !self.control_receiver.stream().is_terminated() {
self.control_receiver.stream().close();
self.control_receiver.unpause();
while let Some(cmd) = self.control_receiver.next().await {
match cmd {
ControlCommand::OpenStream(reply) => {
let _ = reply.send(Err(ConnectionError::Closed));
}
ControlCommand::AcceptStream(reply) => {
let _ = reply.send(Err(ConnectionError::Closed));
}
ControlCommand::CloseConnection(reply) => {
let _ = reply.send(());
}
}
}
}
self.drop_all_streams().await;
// Close and drain the stream command receiver.
if !self.stream_receiver.is_terminated() {
self.stream_receiver.close();
while let Some(cmd) = self.stream_receiver.next().await {
match cmd {
StreamCommand::SendFrame(_, reply) => {
let _ = reply.send(0);
}
StreamCommand::CloseStream(_, reply) => {
let _ = reply.send(());
}
StreamCommand::ResetStream(_, reply) => {
let _ = reply.send(());
}
}
// drop it
log::trace!("drop stream receiver frame");
}
}
result
}
/// This is called from `Connection::next_stream` instead of being a
/// public method itself in order to guarantee proper closing in
/// case of an error or at EOF.
async fn handle_coming(&mut self) -> Result<()> {
loop {
select! {
// handle incoming
frame = self.reader.next() => {
if let Some(f) = frame {
let frame = f?;
self.on_frame(frame).await?;
}
}
// handle outcoming
scmd = self.stream_receiver.next() => {
self.on_stream_command(scmd).await?;
}
ccmd = self.control_receiver.next() => {
self.on_control_command(ccmd).await?;
}
}
self.writer.flush().await.or(Err(ConnectionError::Closed))?
}
}
/// Process the result of reading from the socket.
///
/// Unless `frame` is `Ok(()))` we will assume the connection got closed
/// and return a corresponding error, which terminates the connection.
/// Otherwise we process the frame
async fn on_frame(&mut self, frame: Frame<()>) -> Result<()> {
log::debug!("{}: received: {}", self.id, frame.header());
let action = match frame.header().tag() {
Tag::Data => self.on_data(frame.into_data()).await,
Tag::WindowUpdate => self.on_window_update(&frame.into_window_update()).await,
Tag::Ping => self.on_ping(&frame.into_ping()),
Tag::GoAway => return Err(ConnectionError::Closed),
};
match action {
Action::None => {}
Action::New(stream, update) => {
log::trace!("{}: new inbound {} of {}", self.id, stream, self);
if let Some(sender) = self.waiting_stream_sender.take() {
sender.send(Ok(stream)).expect("send err");
} else {
self.pending_streams.push_back(stream);
}
if let Some(f) = update {
log::trace!("{}/{}: sending update", self.id, f.header().stream_id());
self.writer.send_frame(&f).await.or(Err(ConnectionError::Closed))?
}
}
Action::Update(f) => {
log::debug!("{}/{}: sending update", self.id, f.header().stream_id());
self.writer.send_frame(&f).await.or(Err(ConnectionError::Closed))?
}
Action::Ping(f) => {
log::trace!("{}/{}: pong", self.id, f.header().stream_id());
self.writer.send_frame(&f).await.or(Err(ConnectionError::Closed))?
}
Action::Reset(stream_id) => {
log::trace!("{}/{}: sending reset", self.id, stream_id);
self.send_reset_stream(stream_id).await.or(Err(ConnectionError::Closed))?
}
Action::Terminate(f) => {
log::trace!("{}: sending term", self.id);
// yamux crate just send GoAway, while go-yamux session will exitErr at this time.
// I think connecttion is useless now, so exit
self.writer.send_frame(&f).await.or(Err(ConnectionError::Closed))?;
return Err(ConnectionError::Closed);
}
}
Ok(())
}
/// Process new inbound stream when recv Data frame
async fn new_stream_data(&mut self, stream_id: StreamId, is_finish: bool, frame_body: Vec<u8>) -> Action {
let frame_len = frame_body.len();
if !self.is_valid_remote_id(stream_id, Tag::Data) {
// log::error!("{}: invalid stream id {}", self.id, stream_id);
return Action::Terminate(Frame::protocol_error());
}
if frame_len > DEFAULT_CREDIT as usize {
log::error!("{}/{}: 1st body of stream exceeds default credit", self.id, stream_id);
return Action::Terminate(Frame::protocol_error());
}
if self.streams.contains_key(&stream_id) {
log::error!("{}/{}: stream already exists", self.id, stream_id);
return Action::Terminate(Frame::protocol_error());
}
if self.streams.len() == self.config.max_num_streams {
log::error!("{}: maximum number of streams reached", self.id);
return Action::Terminate(Frame::internal_error());
}
if self.streams_stat.contains_key(&stream_id) {
log::error!("received NewStream message for existing stream: {}", stream_id);
return Action::Terminate(Frame::protocol_error());
}
let (mut stream_sender, stream_receiver) = mpsc::unbounded();
let stream = Stream::new(stream_id, self.id, self.config.clone(), self.stream_sender.clone(), stream_receiver);
let mut stream_stat = StreamStat::new(DEFAULT_CREDIT, DEFAULT_CREDIT as usize);
// support lazy_open, peer can send data with SYN flag
let window_update;
{
if is_finish {
stream_stat.update_state(self.id, stream_id, State::RecvClosed);
self.streams.remove(&stream_id);
}
stream_stat.window = stream_stat.window.saturating_sub(frame_len as u32);
let _ = stream_sender.send(frame_body).await;
if !is_finish && stream_stat.window == 0 && self.config.window_update_mode == WindowUpdateMode::OnReceive {
stream_stat.window = self.config.receive_window;
let mut frame = Frame::window_update(stream_id, self.config.receive_window);
frame.header_mut().ack();
window_update = Some(frame)
} else {
window_update = None
}
}
if window_update.is_none() {
stream_stat.set_flag(stream::Flag::Ack)
}
self.streams.insert(stream_id, stream_sender);
self.streams_stat.insert(stream_id, stream_stat);
Action::New(stream, window_update)
}
/// Process received Data frame
async fn on_data(&mut self, frame: Frame<Data>) -> Action {
let stream_id = frame.header().stream_id();
let flags = frame.header().flags();
let frame_len = frame.body_len();
log::trace!("{}/{}: received {:?}", self.id, stream_id, frame.header());
// stream reset
if flags.contains(header::RST) {
self.streams.remove(&stream_id);
self.streams_stat.remove(&stream_id);
return Action::None;
}
let is_finish = frame.header().flags().contains(header::FIN); // half-close
// new stream
if flags.contains(header::SYN) {
return self.new_stream_data(stream_id, is_finish, frame.into_body()).await;
}
// flag to remove stat from streams_stat
let mut rm = false;
if let Some(stat) = self.streams_stat.get_mut(&stream_id) {
if frame_len > stat.window {
log::error!("{}/{}: frame body larger than window of stream", self.id, stream_id);
return Action::Terminate(Frame::protocol_error());
}
stat.window = stat.window.saturating_sub(frame_len);
if frame_len > 0 && (self.config.read_after_close || stat.state().can_read()) {
if let Some(sender) = self.streams.get_mut(&stream_id) {
let _ = sender.send(frame.into_body()).await;
}
}
if is_finish {
self.streams.remove(&stream_id);
let prev = stat.update_state(self.id, stream_id, State::RecvClosed);
if prev == State::SendClosed {
rm = true;
}
}
if !is_finish && stat.window == 0 && self.config.window_update_mode == WindowUpdateMode::OnReceive {
stat.window = self.config.receive_window;
let frame = Frame::window_update(stream_id, self.config.receive_window);
return Action::Update(frame);
}
} else if !is_finish {
log::debug!("{}/{}: data for unknown stream", self.id, stream_id);
return Action::Reset(stream_id);
}
// If stream is completely closed, remove it
if rm {
self.streams_stat.remove(&stream_id);
self.pending_frames.remove(&stream_id);
}
Action::None
}
/// Process new inbound stream when recv window update frame
fn new_stream_window_update(&mut self, stream_id: StreamId, is_finish: bool) -> Action {
if !self.is_valid_remote_id(stream_id, Tag::WindowUpdate) {
// log::error!("{}: invalid stream id {}", self.id, stream_id);
return Action::Terminate(Frame::protocol_error());
}
if self.streams.contains_key(&stream_id) {
log::error!("{}/{}: stream already exists", self.id, stream_id);
return Action::Terminate(Frame::protocol_error());
}
if self.streams.len() == self.config.max_num_streams {
// log::error!("{}: maximum number of streams reached", self.id);
return Action::Terminate(Frame::internal_error());
}
if self.streams_stat.contains_key(&stream_id) {
log::error!("received NewStream message for existing stream: {}", stream_id);
return Action::Terminate(Frame::protocol_error());
}
let (stream_sender, stream_receiver) = mpsc::unbounded();
self.streams.insert(stream_id, stream_sender);
let stream = Stream::new(stream_id, self.id, self.config.clone(), self.stream_sender.clone(), stream_receiver);
// in order to communicate with go-yamux, ignore len of windows update frame, credit is always DEFAULT_CREDIT
let mut stream_stat = StreamStat::new(DEFAULT_CREDIT, DEFAULT_CREDIT as usize);
stream_stat.set_flag(Flag::Ack);
if is_finish {
stream_stat.update_state(self.id, stream_id, State::RecvClosed);
self.streams.remove(&stream_id);
}
self.streams_stat.insert(stream_id, stream_stat);
Action::New(stream, None)
}
/// Process received window update frame
async fn on_window_update(&mut self, frame: &Frame<WindowUpdate>) -> Action {
let mut updated = false;
let stream_id = frame.header().stream_id();
let flags = frame.header().flags();
if flags.contains(header::RST) {
// stream reset
self.streams.remove(&stream_id);
self.streams_stat.remove(&stream_id);
return Action::None;
}
let is_finish = frame.header().flags().contains(header::FIN); // half-close
// new stream
if flags.contains(header::SYN) {
return self.new_stream_window_update(stream_id, is_finish);
}
// flag to remove stat from streams_stat
let mut rm = false;
if let Some(stat) = self.streams_stat.get_mut(&stream_id) {
stat.credit += frame.header().credit();
updated = true;
if is_finish {
self.streams.remove(&stream_id);
let prev = stat.update_state(self.id, stream_id, State::RecvClosed);
if prev == State::SendClosed {
rm = true;
}
}
} else if !is_finish {
log::debug!("{}/{}: window update for unknown stream", self.id, stream_id);
return Action::Reset(stream_id);
}
// If stream is completely closed, remove it
if rm {
self.streams_stat.remove(&stream_id);
self.pending_frames.remove(&stream_id);
} else if updated {
// If window size is updated, send pending frames
if let Some((frame, reply)) = self.pending_frames.remove(&stream_id) {
let _ = self.send_frame(frame, reply).await;
}
}
Action::None
}
/// Process received Ping frame
fn on_ping(&mut self, frame: &Frame<Ping>) -> Action {
let stream_id = frame.header().stream_id();
if frame.header().flags().contains(header::ACK) {
// pong
return Action::None;
}
if stream_id == CONNECTION_ID || self.streams.contains_key(&stream_id) {
let mut hdr = Header::ping(frame.header().nonce());
hdr.ack();
return Action::Ping(Frame::new(hdr));
}
log::debug!("{}/{}: ping for unknown stream", self.id, stream_id);
Action::Reset(stream_id)
}
/// reset stream
async fn send_reset_stream(&mut self, stream_id: StreamId) -> Result<()> {
// step1: send close frame
let mut header = Header::data(stream_id, 0);
header.rst();
let frame = Frame::new(header);
self.writer.send_frame(&frame).await.or(Err(ConnectionError::Closed))?;
// step2: remove stream
self.streams_stat.remove(&stream_id);
self.streams.remove(&stream_id);
Ok(())
}
/// send frame
async fn send_frame(&mut self, mut frame: Frame<Data>, reply: oneshot::Sender<usize>) -> Result<()> {
let stream_id = frame.header().stream_id();
if let Some(stat) = self.streams_stat.get_mut(&stream_id) {
if stat.state().can_write() {
if stat.credit == 0 {
if self.pending_frames.contains_key(&stream_id) {
let _ = reply.send(0);
return Ok(());
}
self.pending_frames.insert(stream_id, (frame, reply));
return Ok(());
}
let len = frame.body().len();
let n = std::cmp::min(stat.credit, len);
if n < len {
frame.truncate(n);
}
stat.credit -= n;
send_flag(stat, &mut frame);
self.writer.send_frame(&frame).await.or(Err(ConnectionError::Closed))?;
log::debug!("{}: sending: {}", self.id, frame.header());
let _ = reply.send(n);
} else {
log::debug!("{}: stream {} have been removed", self.id, stream_id);
drop(reply);
}
} else {
drop(reply);
}
Ok(())
}
/// Process a command from one of our `Stream`s.
async fn on_stream_command(&mut self, cmd: Option<StreamCommand>) -> Result<()> {
match cmd {
Some(StreamCommand::SendFrame(frame, reply)) => {
self.send_frame(frame, reply).await?;
}
Some(StreamCommand::CloseStream(stream_id, reply)) => {
log::debug!("{}: closing stream {} of {}", self.id, stream_id, self);
// flag to remove stat from streams_stat
let mut rm = false;
if let Some(stat) = self.streams_stat.get_mut(&stream_id) {
if stat.state().can_write() {
// step1: send close frame
let mut header = Header::data(stream_id, 0);
header.fin();
if stat.get_flag() == Flag::Ack {
header.ack();
stat.set_flag(Flag::None);
}
let frame = Frame::new(header);
self.writer.send_frame(&frame).await.or(Err(ConnectionError::Closed))?;
// step2: update state
let prev = stat.update_state(self.id, stream_id, State::SendClosed);
if prev == State::RecvClosed {
rm = true;
}
}
}
// If stream is completely closed, remove it
if rm {
self.streams_stat.remove(&stream_id);
self.pending_frames.remove(&stream_id);
}
let _ = reply.send(());
}
Some(StreamCommand::ResetStream(stream_id, reply)) => {
log::debug!("{}: reset stream {} of {}", self.id, stream_id, self);
if self.streams_stat.contains_key(&stream_id) {
self.send_reset_stream(stream_id).await?;
}
let _ = reply.send(());
}
None => {
// We only get to this point when `self.stream_receiver`
// was closed which only happens in response to a close control
// command. Now that we are at the end of the stream command queue,
// we send the final term frame to the remote and complete the
// closure.
debug_assert!(self.control_receiver.is_paused());
let frame = Frame::term();
self.writer.send_frame(&frame).await.or(Err(ConnectionError::Closed))?;
self.control_receiver.unpause();
self.control_receiver.stream().close();
}
}
Ok(())
}
/// Process a command from a `Control`.
///
/// We only process control commands if we are not in the process of closing
/// the connection. Only once we finished closing will we drain the remaining
/// commands and reply back that we are closed.
async fn on_control_command(&mut self, cmd: Option<ControlCommand>) -> Result<()> {
match cmd {
Some(ControlCommand::OpenStream(reply)) => {
if self.shutdown.is_complete() {
// We are already closed so just inform the control.
let _ = reply.send(Err(ConnectionError::Closed));
return Ok(());
}
if self.streams.len() >= self.config.max_num_streams {
// log::error!("{}: maximum number of streams reached", self.id);
let _ = reply.send(Err(ConnectionError::TooManyStreams));
return Ok(());
}
log::trace!("{}: creating new outbound stream", self.id);
let stream_id = self.next_stream_id()?;
let window = self.config.receive_window;
let mut stream_stat = StreamStat::new(window, DEFAULT_CREDIT as usize);
if !self.config.lazy_open {
let mut frame = Frame::window_update(stream_id, self.config.receive_window);
frame.header_mut().syn();
log::trace!("{}: sending initial {}", self.id, frame.header());
self.writer.send_frame(&frame).await.or(Err(ConnectionError::Closed))?
} else {
stream_stat.set_flag(Flag::Syn);
}
let (stream_sender, stream_receiver) = mpsc::unbounded();
let stream = Stream::new(stream_id, self.id, self.config.clone(), self.stream_sender.clone(), stream_receiver);
if reply.send(Ok(stream)).is_ok() {
log::debug!("{}: new outbound {}", self.id, stream_id);
self.streams.insert(stream_id, stream_sender);
self.streams_stat.insert(stream_id, stream_stat);
} else {
log::debug!("{}: open stream {} has been cancelled", self.id, stream_id);
if !self.config.lazy_open {
self.send_reset_stream(stream_id).await?;
}
}
}
Some(ControlCommand::AcceptStream(reply)) => {
if self.waiting_stream_sender.is_some() {
reply.send(Err(ConnectionError::Closed)).expect("send err");
return Ok(());
}
if let Some(stream) = self.pending_streams.pop_front() {
reply.send(Ok(stream)).expect("send err");
} else {
self.waiting_stream_sender = Some(reply);
}
}
Some(ControlCommand::CloseConnection(reply)) => {
if !self.shutdown.has_not_started() {
log::debug!("shutdown had started, ingore this request");
let _ = reply.send(());
return Ok(());
}
self.shutdown = Shutdown::InProgress(reply);
log::debug!("closing connection {}", self);
self.stream_receiver.close();
self.control_receiver.pause();
}
None => {
// We only get here after the whole connection shutdown is complete.
// No further processing of commands of any kind or incoming frames
// will happen.
debug_assert!(self.shutdown.is_in_progress());
log::debug!("{}: closing {}", self.id, self);
let shutdown = std::mem::replace(&mut self.shutdown, Shutdown::Complete);
if let Shutdown::InProgress(tx) = shutdown {
// Inform the `Control` that initiated the shutdown.
let _ = tx.send(());
}
self.writer.close().await.or(Err(ConnectionError::Closed))?;
return Err(ConnectionError::Closed);
}
}
Ok(())
}
}
fn send_flag(stat: &mut StreamStat, frame: &mut Frame<Data>) {
// send ack/syn along with frame
match stat.get_flag() {
Flag::None => (),
Flag::Syn => {
frame.header_mut().syn();
stat.set_flag(Flag::None);
}
Flag::Ack => {
frame.header_mut().ack();
stat.set_flag(Flag::None);
}
}
}
impl<T: SplitEx> fmt::Display for Connection<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(Connection {} (streams {}))", self.id, self.streams.len())
}
}
impl<T: SplitEx> Connection<T> {
// next_stream_id is only used to get stream id when open stream
fn next_stream_id(&mut self) -> Result<StreamId> {
let proposed = StreamId::new(self.next_stream_id);
self.next_stream_id = self.next_stream_id.checked_add(2).ok_or(ConnectionError::NoMoreStreamIds)?;
match self.mode {
Mode::Client => assert!(proposed.is_client()),
Mode::Server => assert!(proposed.is_server()),
}
Ok(proposed)
}
// Check if the given stream ID is valid w.r.t. the provided tag and our connection mode.
fn is_valid_remote_id(&self, id: StreamId, tag: Tag) -> bool {
if tag == Tag::Ping || tag == Tag::GoAway {
return id.is_session();
}
match self.mode {
Mode::Client => id.is_server(),
Mode::Server => id.is_client(),
}
}
pub fn streams_length(&self) -> usize {
self.streams_stat.len()
}
/// Close and drop all `Stream`s sender and stat.
async fn drop_all_streams(&mut self) {
log::trace!("{}: Drop all Streams sender count={}", self.id, self.streams.len());
for (id, _sender) in self.streams.drain().take(1) {
// drop it
log::trace!("{}: drop stream sender {:?}", self.id, id);
}
log::trace!("{}: Drop all Streams stat count={}", self.id, self.streams.len());
for (id, _stat) in self.streams_stat.drain().take(1) {
// drop it
log::trace!("{}: drop stream stat {:?}", self.id, id);
}
}
fn drop_pending_frame(&mut self) {
log::trace!("{}: Drop all pengding frame count={}", self.id, self.pending_frames.len());
for (stream_id, (_, reply)) in self.pending_frames.drain().take(1) {
log::trace!("{} drop pengding frame of stream {:?}", self.id, stream_id);
let _ = reply.send(0);
}
}
}
| 40.332616 | 127 | 0.570392 |
bf3686780b5b76a0365ccb4dcc9d1c62afe30651
| 35,893 |
// Copyright 2020 - present Alex Dukhno
//
// 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::{
CatalogDefinition, DataCatalog, DataTable, Database, InMemoryCatalogHandle, SchemaHandle, SqlSchema, SqlTable,
COLUMNS_TABLE, DEFINITION_SCHEMA, SCHEMATA_TABLE, TABLES_TABLE,
};
use binary::Binary;
use definition::{ColumnDef, FullTableName, TableDef};
use definition_operations::{
ExecutionError, ExecutionOutcome, Kind, ObjectState, Record, Step, SystemObject, SystemOperation,
};
use repr::Datum;
use std::sync::Arc;
use types::SqlType;
const CATALOG: Datum = Datum::from_str("IN_MEMORY");
fn create_public_schema() -> SystemOperation {
SystemOperation {
kind: Kind::Create(SystemObject::Schema),
skip_steps_if: None,
steps: vec![vec![
Step::CheckExistence {
system_object: SystemObject::Schema,
object_name: vec!["public".to_owned()],
},
Step::CreateFolder {
name: "public".to_owned(),
},
Step::CreateRecord {
system_schema: DEFINITION_SCHEMA.to_owned(),
system_table: SCHEMATA_TABLE.to_owned(),
record: Record::Schema {
catalog_name: "".to_owned(),
schema_name: "public".to_owned(),
},
},
]],
}
}
pub struct InMemoryDatabase {
catalog: InMemoryCatalogHandle,
}
impl InMemoryDatabase {
pub fn new() -> Arc<InMemoryDatabase> {
Arc::new(InMemoryDatabase::create().bootstrap())
}
fn create() -> InMemoryDatabase {
InMemoryDatabase {
catalog: InMemoryCatalogHandle::default(),
}
}
fn bootstrap(self) -> InMemoryDatabase {
self.catalog.create_schema(DEFINITION_SCHEMA);
self.catalog.work_with(DEFINITION_SCHEMA, |schema| {
schema.create_table(SCHEMATA_TABLE);
schema.create_table(TABLES_TABLE);
schema.create_table(COLUMNS_TABLE);
});
let public_schema = self.execute(create_public_schema());
debug_assert!(
matches!(public_schema, Ok(_)),
"Default `public` schema has to be created, but failed due to {:?}",
public_schema
);
self
}
fn schema_exists(&self, schema_name: &str) -> bool {
let full_schema_name = Binary::pack(&[CATALOG, Datum::from_str(schema_name)]);
let schema = self.catalog.work_with(DEFINITION_SCHEMA, |schema| {
schema.work_with(SCHEMATA_TABLE, |table| {
table.select().any(|(_key, value)| value == full_schema_name)
})
});
schema == Some(Some(true))
}
fn table_exists(&self, full_table_name: &FullTableName) -> bool {
let full_table_name = Binary::pack(&full_table_name.raw(CATALOG));
let table = self.catalog.work_with(DEFINITION_SCHEMA, |schema| {
schema.work_with(TABLES_TABLE, |table| {
table.select().any(|(_key, value)| value == full_table_name)
})
});
table == Some(Some(true))
}
fn table_columns(&self, full_table_name: &FullTableName) -> Vec<ColumnDef> {
let full_table_name = Binary::pack(&full_table_name.raw(CATALOG));
self.catalog
.work_with(DEFINITION_SCHEMA, |schema| {
schema.work_with(COLUMNS_TABLE, |table| {
table
.select()
.filter(|(_key, value)| value.start_with(&full_table_name))
.map(|(_key, value)| {
let row = value.unpack();
let name = row[3].as_str().to_owned();
let sql_type = SqlType::from_type_id(row[4].as_u64(), row[5].as_u64());
let ord_num = row[6].as_u64() as usize;
ColumnDef::new(name, sql_type, ord_num)
})
.collect()
})
})
.unwrap()
.unwrap()
}
}
impl CatalogDefinition for InMemoryDatabase {
fn table_definition(&self, full_table_name: &FullTableName) -> Option<Option<TableDef>> {
if !(self.schema_exists(full_table_name.schema())) {
return None;
}
if !(self.table_exists(full_table_name)) {
return Some(None);
}
let column_info = self.table_columns(full_table_name);
Some(Some(TableDef::new(full_table_name, column_info)))
}
}
impl Database for InMemoryDatabase {
type Schema = InMemorySchema;
type Table = InMemoryTable;
fn execute(&self, operation: SystemOperation) -> Result<ExecutionOutcome, ExecutionError> {
let SystemOperation {
kind,
skip_steps_if,
steps,
} = operation;
let end = steps.len();
let mut index = 0;
while index < end {
let operations = &steps[index];
index += 1;
for operation in operations {
println!("{:?}", operation);
match operation {
Step::CheckExistence {
system_object,
object_name,
} => match system_object {
SystemObject::Schema => {
let result = self.catalog.work_with(DEFINITION_SCHEMA, |schema| {
schema.work_with(SCHEMATA_TABLE, |table| {
table.select().any(|(_key, value)| {
value == Binary::pack(&[CATALOG, Datum::from_str(&object_name[0])])
})
})
});
match skip_steps_if {
None => {
if let (&Kind::Create(SystemObject::Schema), Some(Some(true))) = (&kind, result) {
return Err(ExecutionError::SchemaAlreadyExists(object_name[0].to_owned()));
}
if let (&Kind::Drop(SystemObject::Schema), Some(Some(false))) = (&kind, result) {
return Err(ExecutionError::SchemaDoesNotExist(object_name[0].to_owned()));
}
if let (&Kind::Create(SystemObject::Table), Some(Some(false))) = (&kind, result) {
return Err(ExecutionError::SchemaDoesNotExist(object_name[0].to_owned()));
}
if let (&Kind::Drop(SystemObject::Table), Some(Some(false))) = (&kind, result) {
return Err(ExecutionError::SchemaDoesNotExist(object_name[0].to_owned()));
}
}
Some(ObjectState::NotExists) => break,
Some(ObjectState::Exists) => {}
}
}
SystemObject::Table => {
let result = self.catalog.work_with(DEFINITION_SCHEMA, |schema| {
schema.work_with(TABLES_TABLE, |table| {
table.select().any(|(_key, value)| {
value
== Binary::pack(&[
CATALOG,
Datum::from_str(&object_name[0]),
Datum::from_str(&object_name[1]),
])
})
})
});
match skip_steps_if {
None => {
if let (&Kind::Create(SystemObject::Table), Some(Some(true))) = (&kind, result) {
return Err(ExecutionError::TableAlreadyExists(
object_name[0].to_owned(),
object_name[1].to_owned(),
));
}
if let (&Kind::Drop(SystemObject::Table), Some(Some(false))) = (&kind, result) {
return Err(ExecutionError::TableDoesNotExist(
object_name[0].to_owned(),
object_name[1].to_owned(),
));
}
}
Some(ObjectState::NotExists) => unimplemented!(),
Some(ObjectState::Exists) => break,
}
}
},
Step::CheckDependants {
system_object,
object_name,
} => match system_object {
SystemObject::Schema => {
let result = self.catalog.work_with(DEFINITION_SCHEMA, |schema| {
let schema_id = Binary::pack(&[CATALOG, Datum::from_str(&object_name[0])]);
schema.work_with(TABLES_TABLE, |table| {
table.select().any(|(_key, value)| value.start_with(&schema_id))
})
});
if let Some(Some(true)) = result {
return Err(ExecutionError::SchemaHasDependentObjects(object_name[0].to_owned()));
}
}
SystemObject::Table => {}
},
Step::RemoveDependants { .. } => {}
Step::RemoveColumns { .. } => {}
Step::CreateFolder { name } => {
self.catalog.create_schema(&name);
}
Step::RemoveFolder { name } => {
self.catalog.drop_schema(&name);
return Ok(ExecutionOutcome::SchemaDropped);
}
Step::CreateFile { folder_name, name } => {
self.catalog.work_with(folder_name, |schema| schema.create_table(name));
}
Step::RemoveFile { .. } => {}
Step::RemoveRecord {
system_schema: _system_schema,
system_table: _system_table,
record,
} => match record {
Record::Schema {
catalog_name: _catalog_name,
schema_name,
} => {
let full_schema_name = Binary::pack(&[CATALOG, Datum::from_str(&schema_name)]);
self.catalog.work_with(DEFINITION_SCHEMA, |schema| {
schema.work_with(SCHEMATA_TABLE, |table| {
let schema_id = table
.select()
.find(|(_key, value)| value == &full_schema_name)
.map(|(key, _value)| key);
debug_assert!(
matches!(schema_id, Some(_)),
"record for {:?} schema had to be found in {:?} system table",
schema_name,
SCHEMATA_TABLE
);
let schema_id = schema_id.unwrap();
table.delete(vec![schema_id]);
});
});
}
Record::Table {
catalog_name: _catalog_name,
schema_name,
table_name,
} => {
let full_table_name =
Binary::pack(&[CATALOG, Datum::from_str(schema_name), Datum::from_str(table_name)]);
self.catalog.work_with(DEFINITION_SCHEMA, |schema| {
schema.work_with(TABLES_TABLE, |table| {
let table_id = table
.select()
.find(|(_key, value)| value == &full_table_name)
.map(|(key, _value)| key);
debug_assert!(
matches!(table_id, Some(_)),
"record for {:?}.{:?} table had to be found in {:?} system table",
schema_name,
table_name,
TABLES_TABLE
);
println!("FOUND TABLE ID - {:?}", table_id);
let table_id = table_id.unwrap();
table.delete(vec![table_id]);
let table_id = table
.select()
.find(|(_key, value)| value == &full_table_name)
.map(|(key, _value)| key);
println!("TABLE ID AFTER DROP - {:?}", table_id);
});
});
}
Record::Column { .. } => unimplemented!(),
},
Step::CreateRecord {
system_schema: _system_schema,
system_table: _system_table,
record,
} => match record {
Record::Schema {
catalog_name: _catalog_name,
schema_name,
} => {
self.catalog.work_with(DEFINITION_SCHEMA, |schema| {
schema.work_with(SCHEMATA_TABLE, |table| {
table.insert(vec![Binary::pack(&[CATALOG, Datum::from_str(&schema_name)])])
})
});
return Ok(ExecutionOutcome::SchemaCreated);
}
Record::Table {
catalog_name: _catalog_name,
schema_name,
table_name,
} => {
let full_table_name =
Binary::pack(&[CATALOG, Datum::from_str(&schema_name), Datum::from_str(&table_name)]);
self.catalog.work_with(DEFINITION_SCHEMA, |schema| {
schema.work_with(TABLES_TABLE, |table| {
table.insert(vec![Binary::pack(&[
CATALOG,
Datum::from_str(&schema_name),
Datum::from_str(&table_name),
])]);
let table_id = table
.select()
.find(|(_key, value)| value == &full_table_name)
.map(|(key, _value)| key);
println!("GENERATED TABLE ID - {:?}", table_id);
})
});
}
Record::Column {
catalog_name: _catalog_name,
schema_name,
table_name,
column_name,
sql_type,
} => {
let ord_num = self.catalog.work_with(schema_name, |schema| {
schema.work_with(table_name, |table| table.next_column_ord())
});
debug_assert!(
matches!(ord_num, Some(Some(_))),
"column ord num has to be generated for {:?}.{:?} but value was {:?}",
schema_name,
table_name,
ord_num
);
let ord_num = ord_num.unwrap().unwrap();
let row = Binary::pack(&[
CATALOG,
Datum::from_str(&schema_name),
Datum::from_str(&table_name),
Datum::from_str(&column_name),
Datum::from_u64(sql_type.type_id()),
Datum::from_optional_u64(sql_type.chars_len()),
Datum::from_u64(ord_num),
]);
self.catalog.work_with(DEFINITION_SCHEMA, |schema| {
schema.work_with(COLUMNS_TABLE, |table| table.insert(vec![row.clone()]))
});
}
},
}
}
}
match kind {
Kind::Create(SystemObject::Schema) => Ok(ExecutionOutcome::SchemaCreated),
Kind::Drop(SystemObject::Schema) => Ok(ExecutionOutcome::SchemaDropped),
Kind::Create(SystemObject::Table) => Ok(ExecutionOutcome::TableCreated),
Kind::Drop(SystemObject::Table) => Ok(ExecutionOutcome::TableDropped),
}
}
}
pub struct InMemorySchema;
impl SqlSchema for InMemorySchema {}
pub struct InMemoryTable;
impl SqlTable for InMemoryTable {}
#[cfg(test)]
mod test {
use super::*;
use types::SqlType;
const DEFAULT_CATALOG: &str = "public";
const SCHEMA: &str = "schema_name";
const OTHER_SCHEMA: &str = "other_schema_name";
const TABLE: &str = "table_name";
const OTHER_TABLE: &str = "other_table_name";
fn executor() -> Arc<InMemoryDatabase> {
InMemoryDatabase::new()
}
fn create_schema_ops(schema_name: &str) -> SystemOperation {
create_schema_inner(schema_name, false)
}
fn create_schema_if_not_exists_ops(schema_name: &str) -> SystemOperation {
create_schema_inner(schema_name, true)
}
fn create_schema_inner(schema_name: &str, if_not_exists: bool) -> SystemOperation {
SystemOperation {
kind: Kind::Create(SystemObject::Schema),
skip_steps_if: if if_not_exists { Some(ObjectState::Exists) } else { None },
steps: vec![vec![
Step::CheckExistence {
system_object: SystemObject::Schema,
object_name: vec![schema_name.to_owned()],
},
Step::CreateFolder {
name: schema_name.to_owned(),
},
Step::CreateRecord {
system_schema: DEFINITION_SCHEMA.to_owned(),
system_table: SCHEMATA_TABLE.to_owned(),
record: Record::Schema {
catalog_name: DEFAULT_CATALOG.to_owned(),
schema_name: schema_name.to_owned(),
},
},
]],
}
}
fn drop_schemas_ops(schema_names: Vec<&str>) -> SystemOperation {
drop_schemas_inner(schema_names, false)
}
fn drop_schemas_if_exists_ops(schema_names: Vec<&str>) -> SystemOperation {
drop_schemas_inner(schema_names, true)
}
fn drop_schemas_inner(schema_names: Vec<&str>, if_exists: bool) -> SystemOperation {
let steps = schema_names.into_iter().map(drop_schema_op).collect::<Vec<Vec<Step>>>();
SystemOperation {
kind: Kind::Drop(SystemObject::Schema),
skip_steps_if: if if_exists { Some(ObjectState::NotExists) } else { None },
steps,
}
}
fn drop_schema_op(schema_name: &str) -> Vec<Step> {
vec![
Step::CheckExistence {
system_object: SystemObject::Schema,
object_name: vec![schema_name.to_owned()],
},
Step::CheckDependants {
system_object: SystemObject::Schema,
object_name: vec![schema_name.to_owned()],
},
Step::RemoveRecord {
system_schema: DEFINITION_SCHEMA.to_owned(),
system_table: SCHEMATA_TABLE.to_owned(),
record: Record::Schema {
catalog_name: DEFAULT_CATALOG.to_owned(),
schema_name: schema_name.to_owned(),
},
},
Step::RemoveFolder {
name: schema_name.to_owned(),
},
]
}
fn create_table_ops(schema_name: &str, table_name: &str) -> SystemOperation {
create_table_inner(schema_name, table_name, false)
}
fn create_table_if_not_exists_ops(schema_name: &str, table_name: &str) -> SystemOperation {
create_table_inner(schema_name, table_name, true)
}
fn create_table_inner(schema_name: &str, table_name: &str, if_not_exists: bool) -> SystemOperation {
SystemOperation {
kind: Kind::Create(SystemObject::Table),
skip_steps_if: if if_not_exists { Some(ObjectState::Exists) } else { None },
steps: vec![vec![
Step::CheckExistence {
system_object: SystemObject::Schema,
object_name: vec![schema_name.to_owned()],
},
Step::CheckExistence {
system_object: SystemObject::Table,
object_name: vec![schema_name.to_owned(), table_name.to_owned()],
},
Step::CreateFile {
folder_name: schema_name.to_owned(),
name: table_name.to_owned(),
},
Step::CreateRecord {
system_schema: DEFINITION_SCHEMA.to_owned(),
system_table: TABLES_TABLE.to_owned(),
record: Record::Table {
catalog_name: DEFAULT_CATALOG.to_owned(),
schema_name: schema_name.to_owned(),
table_name: table_name.to_owned(),
},
},
Step::CreateRecord {
system_schema: DEFINITION_SCHEMA.to_owned(),
system_table: COLUMNS_TABLE.to_owned(),
record: Record::Column {
catalog_name: DEFAULT_CATALOG.to_owned(),
schema_name: schema_name.to_owned(),
table_name: table_name.to_owned(),
column_name: "col_1".to_owned(),
sql_type: SqlType::SmallInt,
},
},
Step::CreateRecord {
system_schema: DEFINITION_SCHEMA.to_owned(),
system_table: COLUMNS_TABLE.to_owned(),
record: Record::Column {
catalog_name: DEFAULT_CATALOG.to_owned(),
schema_name: schema_name.to_owned(),
table_name: table_name.to_owned(),
column_name: "col_2".to_owned(),
sql_type: SqlType::BigInt,
},
},
]],
}
}
fn drop_tables_ops(schema_name: &str, table_names: Vec<&str>) -> SystemOperation {
let steps = table_names
.into_iter()
.map(|table_name| drop_table_inner(schema_name, table_name))
.collect::<Vec<Vec<Step>>>();
SystemOperation {
kind: Kind::Drop(SystemObject::Table),
skip_steps_if: None,
steps,
}
}
fn drop_tables_if_exists_ops(schema_name: &str, table_names: Vec<&str>) -> SystemOperation {
let steps = table_names
.into_iter()
.map(|table_name| drop_table_inner(schema_name, table_name))
.collect::<Vec<Vec<Step>>>();
SystemOperation {
kind: Kind::Drop(SystemObject::Table),
skip_steps_if: Some(ObjectState::NotExists),
steps,
}
}
fn drop_table_inner(schema_name: &str, table_name: &str) -> Vec<Step> {
vec![
Step::CheckExistence {
system_object: SystemObject::Schema,
object_name: vec![schema_name.to_owned()],
},
Step::CheckExistence {
system_object: SystemObject::Table,
object_name: vec![schema_name.to_owned(), table_name.to_owned()],
},
Step::RemoveColumns {
schema_name: schema_name.to_owned(),
table_name: table_name.to_owned(),
},
Step::RemoveRecord {
system_schema: DEFINITION_SCHEMA.to_owned(),
system_table: TABLES_TABLE.to_owned(),
record: Record::Table {
catalog_name: DEFAULT_CATALOG.to_owned(),
schema_name: schema_name.to_owned(),
table_name: table_name.to_owned(),
},
},
Step::RemoveFile {
folder_name: schema_name.to_owned(),
name: table_name.to_owned(),
},
]
}
#[cfg(test)]
mod schema {
use super::*;
#[test]
fn create_schema() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
}
#[test]
fn create_if_not_exists() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_if_not_exists_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(create_schema_if_not_exists_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
}
#[test]
fn create_schema_with_the_same_name() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Err(ExecutionError::SchemaAlreadyExists(SCHEMA.to_owned()))
);
}
#[test]
fn drop_nonexistent_schema() {
let executor = executor();
assert_eq!(
executor.execute(drop_schemas_ops(vec![SCHEMA])),
Err(ExecutionError::SchemaDoesNotExist(SCHEMA.to_owned()))
);
}
#[test]
fn drop_single_schema() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(drop_schemas_ops(vec![SCHEMA])),
Ok(ExecutionOutcome::SchemaDropped)
);
}
#[test]
fn drop_many_schemas() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(create_schema_ops(OTHER_SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(drop_schemas_ops(vec![SCHEMA, OTHER_SCHEMA])),
Ok(ExecutionOutcome::SchemaDropped)
);
}
#[test]
fn drop_schema_with_table() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(create_table_ops(SCHEMA, TABLE)),
Ok(ExecutionOutcome::TableCreated)
);
assert_eq!(
executor.execute(drop_schemas_ops(vec![SCHEMA])),
Err(ExecutionError::SchemaHasDependentObjects(SCHEMA.to_owned()))
);
}
#[test]
fn drop_many_cascade() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(create_schema_ops(OTHER_SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(drop_schemas_ops(vec![SCHEMA, OTHER_SCHEMA])),
Ok(ExecutionOutcome::SchemaDropped)
);
}
#[test]
fn drop_many_if_exists_first() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(drop_schemas_if_exists_ops(vec![SCHEMA, OTHER_SCHEMA])),
Ok(ExecutionOutcome::SchemaDropped)
);
}
#[test]
fn drop_many_if_exists_last() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(OTHER_SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(drop_schemas_if_exists_ops(vec![SCHEMA, OTHER_SCHEMA])),
Ok(ExecutionOutcome::SchemaDropped)
);
}
}
#[cfg(test)]
mod table {
use super::*;
#[test]
fn create_table_where_schema_not_found() {
let executor = executor();
assert_eq!(
executor.execute(create_table_ops(SCHEMA, TABLE)),
Err(ExecutionError::SchemaDoesNotExist(SCHEMA.to_owned()))
);
}
#[test]
fn create_table_with_the_same_name() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(create_table_ops(SCHEMA, TABLE)),
Ok(ExecutionOutcome::TableCreated)
);
assert_eq!(
executor.execute(create_table_ops(SCHEMA, TABLE)),
Err(ExecutionError::TableAlreadyExists(SCHEMA.to_owned(), TABLE.to_owned()))
);
}
#[test]
fn create_if_not_exists() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(create_table_ops(SCHEMA, TABLE)),
Ok(ExecutionOutcome::TableCreated)
);
assert_eq!(
executor.execute(create_table_if_not_exists_ops(SCHEMA, TABLE)),
Ok(ExecutionOutcome::TableCreated)
);
}
#[test]
fn drop_table_where_schema_not_found() {
let executor = executor();
assert_eq!(
executor.execute(drop_tables_ops(SCHEMA, vec![TABLE])),
Err(ExecutionError::SchemaDoesNotExist(SCHEMA.to_owned()))
);
}
#[test]
fn drop_nonexistent_table() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(drop_tables_ops(SCHEMA, vec![TABLE])),
Err(ExecutionError::TableDoesNotExist(SCHEMA.to_owned(), TABLE.to_owned()))
);
}
#[test]
fn drop_many() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(create_table_ops(SCHEMA, TABLE)),
Ok(ExecutionOutcome::TableCreated)
);
assert_eq!(
executor.execute(create_table_ops(SCHEMA, OTHER_TABLE)),
Ok(ExecutionOutcome::TableCreated)
);
assert_eq!(
executor.execute(drop_tables_ops(SCHEMA, vec![TABLE, OTHER_TABLE])),
Ok(ExecutionOutcome::TableDropped)
);
}
#[test]
fn drop_if_exists_first() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(create_table_ops(SCHEMA, TABLE)),
Ok(ExecutionOutcome::TableCreated)
);
assert_eq!(
executor.execute(drop_tables_if_exists_ops(SCHEMA, vec![TABLE, OTHER_TABLE])),
Ok(ExecutionOutcome::TableDropped)
);
}
#[test]
fn drop_if_exists_last() {
let executor = executor();
assert_eq!(
executor.execute(create_schema_ops(SCHEMA)),
Ok(ExecutionOutcome::SchemaCreated)
);
assert_eq!(
executor.execute(create_table_ops(SCHEMA, OTHER_TABLE)),
Ok(ExecutionOutcome::TableCreated)
);
assert_eq!(
executor.execute(drop_tables_if_exists_ops(SCHEMA, vec![TABLE, OTHER_TABLE])),
Ok(ExecutionOutcome::TableDropped)
);
}
}
}
| 39.529736 | 118 | 0.462931 |
48a33cde117b054255c3bcda80eb18b94d32e73d
| 9,514 |
use std::fmt;
use std::str::FromStr;
use bwasm::ValueType;
use crate::vm::{Trap, VMResult};
use crate::{F32, F64};
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Value {
I32(i32),
I64(i64),
F32(F32),
F64(F64),
}
impl Value {
pub fn default(value_type: ValueType) -> Self {
match value_type {
ValueType::I32 => Value::I32(0),
ValueType::I64 => Value::I64(0),
ValueType::F32 => Value::F32(F32::default()),
ValueType::F64 => Value::F64(F64::default()),
}
}
pub fn value_type(&self) -> ValueType {
match self {
Value::I32(_) => ValueType::I32,
Value::I64(_) => ValueType::I64,
Value::F32(_) => ValueType::F32,
Value::F64(_) => ValueType::F64,
}
}
pub fn to<T: Number>(&self) -> Option<T> {
T::from_value(*self)
}
pub fn from_str(s: &str, value_type: ValueType) -> Option<Self> {
Some(match value_type {
ValueType::I32 => Value::I32(i64::from_str(s).ok()? as i32),
ValueType::I64 => Value::I64(i128::from_str(s).ok()? as i64),
ValueType::F32 => Value::from(f32::from_str(s).ok()?),
ValueType::F64 => Value::from(f64::from_str(s).ok()?),
})
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Value::I32(val) => {
if (val as i32) < 0 {
write!(f, "i32 : 0x{0:08x} = {0} = {1}", val, val as i32)
} else {
write!(f, "i32 : 0x{0:08x} = {0}", val)
}
}
Value::I64(val) => {
if (val as i64) < 0 {
write!(f, "i64 : 0x{0:016x} = {0} = {1}", val, val as i64)
} else {
write!(f, "i64 : 0x{0:016x} = {0}", val)
}
}
Value::F32(val) => write!(f, "f32 : 0x{:08x} ~ {:.8}", val.to_bits(), val.to_float()),
Value::F64(val) => write!(f, "f64 : 0x{:016x} ~ {:.16}", val.to_bits(), val.to_float()),
}
}
}
impl From<i32> for Value {
fn from(val: i32) -> Self {
Value::I32(val)
}
}
impl From<u32> for Value {
fn from(val: u32) -> Self {
Value::I32(val as i32)
}
}
impl From<i64> for Value {
fn from(val: i64) -> Self {
Value::I64(val)
}
}
impl From<u64> for Value {
fn from(val: u64) -> Self {
Value::I64(val as i64)
}
}
impl From<f32> for Value {
fn from(val: f32) -> Self {
Value::F32(F32::from(val))
}
}
impl From<f64> for Value {
fn from(val: f64) -> Self {
Value::F64(F64::from(val))
}
}
impl From<F32> for Value {
fn from(val: F32) -> Self {
Value::F32(val)
}
}
impl From<F64> for Value {
fn from(val: F64) -> Self {
Value::F64(val)
}
}
pub trait Number: Into<Value> + Copy + fmt::Display {
fn value_type() -> ValueType;
fn from_value(val: Value) -> Option<Self>;
}
macro_rules! impl_number {
(float $num_t:ident, $value_t:ident) => {
impl Number for $num_t {
fn value_type() -> ValueType {
ValueType::$value_t
}
fn from_value(val: Value) -> Option<Self> {
if let Value::$value_t(val) = val {
return Some(val.into());
}
None
}
}
};
(int $num_t:ident, $value_t:ident) => {
impl Number for $num_t {
fn value_type() -> ValueType {
ValueType::$value_t
}
fn from_value(val: Value) -> Option<Self> {
if let Value::$value_t(val) = val {
return Some(val as $num_t);
}
None
}
}
};
}
impl_number!(int u32, I32);
impl_number!(int i32, I32);
impl_number!(int u64, I64);
impl_number!(int i64, I64);
impl_number!(float f32, F32);
impl_number!(float f64, F64);
impl_number!(float F32, F32);
impl_number!(float F64, F64);
pub trait Integer: Sized {
fn leading_zeros(self) -> Self;
fn trailing_zeros(self) -> Self;
fn count_ones(self) -> Self;
fn rotl(self, other: Self) -> Self;
fn rotr(self, other: Self) -> Self;
fn rem(self, other: Self) -> VMResult<Self>;
fn div(self, other: Self) -> VMResult<Self>;
fn from_str_with_radix(s: &str) -> Result<Self, std::num::ParseIntError>;
}
macro_rules! impl_integer {
($type:ident) => {
#[allow(clippy::cast_lossless)]
impl Integer for $type {
fn leading_zeros(self) -> Self {
self.leading_zeros() as $type
}
fn trailing_zeros(self) -> Self {
self.trailing_zeros() as $type
}
fn count_ones(self) -> Self {
self.count_ones() as $type
}
fn rotl(self, other: Self) -> Self {
self.rotate_left(other as u32)
}
fn rotr(self, other: Self) -> Self {
self.rotate_right(other as u32)
}
fn rem(self, other: Self) -> VMResult<Self> {
if other == 0 {
Err(Trap::DivisionByZero)
} else {
Ok(self.wrapping_rem(other))
}
}
fn div(self, other: Self) -> VMResult<Self> {
if other == 0 {
return Err(Trap::DivisionByZero);
}
let (result, is_overflow) = self.overflowing_div(other);
if is_overflow {
Err(Trap::SignedIntegerOverflow)
} else {
Ok(result)
}
}
fn from_str_with_radix(s: &str) -> Result<Self, std::num::ParseIntError> {
let radix = if s.len() > 2 {
match s[0..2].to_lowercase().as_str() {
"0x" => Some(16),
"0o" => Some(8),
"0b" => Some(2),
_ => None,
}
} else {
None
};
if let Some(radix) = radix {
$type::from_str_radix(&s[2..], radix)
} else {
$type::from_str_radix(s, 10)
}
}
}
};
}
impl_integer!(i16);
impl_integer!(i32);
impl_integer!(u32);
impl_integer!(i64);
impl_integer!(u64);
impl_integer!(i128);
pub trait LittleEndianConvert: Sized {
fn from_little_endian(buffer: &[u8]) -> Self;
fn to_little_endian(self, buffer: &mut [u8]);
}
impl LittleEndianConvert for i8 {
fn from_little_endian(buffer: &[u8]) -> Self {
buffer[0] as i8
}
fn to_little_endian(self, buffer: &mut [u8]) {
buffer[0] = self as u8;
}
}
impl LittleEndianConvert for u8 {
fn from_little_endian(buffer: &[u8]) -> Self {
buffer[0]
}
fn to_little_endian(self, buffer: &mut [u8]) {
buffer[0] = self;
}
}
macro_rules! impl_little_endian_convert_int {
($t:ident) => {
impl LittleEndianConvert for $t {
fn from_little_endian(buffer: &[u8]) -> Self {
const SIZE: usize = core::mem::size_of::<$t>();
let mut buf = [0u8; SIZE];
buf.copy_from_slice(&buffer[0..SIZE]);
Self::from_le_bytes(buf)
}
fn to_little_endian(self, buffer: &mut [u8]) {
buffer.copy_from_slice(&self.to_le_bytes());
}
}
};
}
macro_rules! impl_little_endian_convert_float {
($t:ident, $repr:ident) => {
impl LittleEndianConvert for $t {
fn from_little_endian(buffer: &[u8]) -> Self {
Self::from_bits($repr::from_little_endian(buffer))
}
fn to_little_endian(self, buffer: &mut [u8]) {
self.to_bits().to_little_endian(buffer);
}
}
};
}
impl_little_endian_convert_int!(i16);
impl_little_endian_convert_int!(u16);
impl_little_endian_convert_int!(i32);
impl_little_endian_convert_int!(u32);
impl_little_endian_convert_int!(i64);
impl_little_endian_convert_int!(u64);
impl_little_endian_convert_float!(f32, u32);
impl_little_endian_convert_float!(f64, u64);
impl_little_endian_convert_float!(F32, u32);
impl_little_endian_convert_float!(F64, u64);
pub trait ExtendTo<T> {
fn extend_to(self) -> T;
}
macro_rules! impl_extend_to {
($from:ident, $to:ident) => {
#[allow(clippy::cast_lossless)]
impl ExtendTo<$to> for $from {
fn extend_to(self) -> $to {
self as $to
}
}
};
}
impl_extend_to!(i8, u32);
impl_extend_to!(u8, u32);
impl_extend_to!(u16, u32);
impl_extend_to!(i16, u32);
impl_extend_to!(i8, u64);
impl_extend_to!(u8, u64);
impl_extend_to!(i16, u64);
impl_extend_to!(u16, u64);
impl_extend_to!(i32, u64);
impl_extend_to!(u32, u64);
pub trait WrapTo<T> {
fn wrap_to(self) -> T;
}
macro_rules! impl_wrap_to {
($from:ident, $to:ident) => {
impl WrapTo<$to> for $from {
fn wrap_to(self) -> $to {
self as $to
}
}
};
}
impl_wrap_to!(u8, u8);
impl_wrap_to!(u16, u8);
impl_wrap_to!(u32, u8);
impl_wrap_to!(u32, u16);
impl_wrap_to!(u64, u8);
impl_wrap_to!(u64, u16);
impl_wrap_to!(u64, u32);
| 27.260745 | 100 | 0.504835 |
acc0a9de6695a44ab83eb1a59fba678861b1f22f
| 120,587 |
pub const MINNEN_JOHNSTON_NUM_CHANNELS: usize = 160;
pub const MINNEN_JOHNSTON_SUPPORT_RANGE: usize = 61;
pub const MINNEN_JOHNSTON_SUPPORT: (i32, i32) = (-30, 31);
// The table is flattened of the form [[f32; MINNEN_JOHNSTON_NUM_CHANNELS]; MINNEN_JOHNSTON_SUPPORT_RANGE]].
pub const MINNEN_JOHNSTON_HYPERPRIOR: [f32; MINNEN_JOHNSTON_NUM_CHANNELS
* MINNEN_JOHNSTON_SUPPORT_RANGE] = [
0.00024822, 0.00000042, 0., 0.00000024, 0., 0.0000118, 0., 0.0000006, 0., 0.00000042,
0.00000012, 0.00000054, 0.00000003, 0.00000021, 0.00000182, 0.00000134, 0.00000006, 0.00000009,
0.00000024, 0.00000024, 0.00000235, 0.00000104, 0.00000054, 0.00000003, 0.00000015, 0.,
0.00001356, 0.00000012, 0.00000066, 0.00005609, 0.00000024, 0.00000012, 0.00000045, 0.00000003,
0.00000599, 0.00000033, 0.00000024, 0.00000015, 0.00000024, 0.00000095, 0.00000018, 0.00000131,
0.00000331, 0.00000012, 0.00000009, 0.00000113, 0.00000006, 0.00000083, 0., 0.00000009,
0.00000054, 0.00000003, 0.00000405, 0.00000015, 0.0000003, 0.00000098, 0.00000358, 0.00001207,
0.00000173, 0.00000015, 0.00000003, 0.00000027, 0.00000003, 0.00000015, 0.00000018, 0.00000027,
0.00000083, 0., 0.00000015, 0.00000033, 0.00000051, 0.00003073, 0.00000036, 0.00000146,
0.00000006, 0.00000006, 0., 0.0000065, 0.00000995, 0.00000024, 0.00000012, 0.00000009,
0.00000063, 0.00000003, 0.00000033, 0.00000021, 0.00000137, 0.00000048, 0.00000012, 0.00000021,
0.00000012, 0.00000015, 0.0000062, 0.0000006, 0.00000012, 0.00000012, 0., 0.00000215, 0.,
0.00000003, 0.00021857, 0.00000587, 0.00000012, 0.00007096, 0.00000027, 0.00000015, 0.00000021,
0.00000671, 0.00000018, 0., 0.00000548, 0.00000012, 0.00002974, 0.00000167, 0.00000003,
0.00000048, 0.00000158, 0.00019842, 0.00000092, 0.00000435, 0.00001264, 0.0637795, 0.00000003,
0.00000003, 0.0000217, 0.00000009, 0.00000021, 0.00000015, 0.00000048, 0.00000012, 0.00000003,
0.00000003, 0.00000313, 0.00000009, 0.00000012, 0.00000253, 0.00000098, 0.00000042, 0.00000167,
0.00000009, 0.00000003, 0.00024745, 0.00002602, 0.00013119, 0.00000006, 0.00000033, 0.00000003,
0.00000155, 0.00000021, 0.00000027, 0., 0.00000021, 0.00000003, 0.00000069, 0.00000054,
0.00000015, 0.00000012, 0.00000098, 0.00000006, 0.00000021, 0.00024822, 0.00000143, 0.,
0.00000024, 0.00000006, 0.0000118, 0.00000018, 0.00000265, 0.00000012, 0.00000042, 0.0000003,
0.00000054, 0.00000003, 0.00000021, 0.00000182, 0.00000134, 0.00000006, 0.00000009, 0.00000057,
0.00000092, 0.00000235, 0.00000322, 0.00000054, 0.00000003, 0.00000015, 0., 0.00001356,
0.00000012, 0.00000209, 0.00005609, 0.00000024, 0.00000012, 0.00000045, 0.00000003, 0.00001565,
0.00000033, 0.00000024, 0.00000015, 0.00000024, 0.00000307, 0.00000018, 0.00000131, 0.00000331,
0.0000008, 0.00000009, 0.00000113, 0.00000006, 0.00000083, 0., 0.00000057, 0.00000224,
0.00000003, 0.00000405, 0.00000015, 0.0000003, 0.00000098, 0.00000358, 0.00001207, 0.00000173,
0.00000015, 0.00000006, 0.00000027, 0.00000003, 0.00000015, 0.00000018, 0.00000027, 0.00000083,
0.00000015, 0.00000015, 0.00000033, 0.00000051, 0.00003073, 0.00000092, 0.00000146, 0.00000003,
0.00000021, 0., 0.0000065, 0.00000995, 0.00000024, 0.00000012, 0.00000054, 0.00000063,
0.00000021, 0.0000011, 0.00000021, 0.00000441, 0.00000048, 0.00000012, 0.00000021, 0.00000012,
0.00000015, 0.0000062, 0.0000006, 0., 0.00000012, 0., 0.00000215, 0., 0.00000003, 0.00021857,
0.00000587, 0.00000006, 0.00007096, 0.00000027, 0.00000012, 0.00000095, 0.00000671, 0.00000018,
0., 0.00000548, 0.00000012, 0.00002974, 0.00000167, 0.00000003, 0.00000048, 0.00000158,
0.00019842, 0.00000274, 0.00000435, 0.00001264, 0.0637795, 0.00000003, 0.00000003, 0.00005141,
0.00000012, 0.00000069, 0.00000015, 0.00000048, 0.00000003, 0.00000018, 0.00000012, 0.00000313,
0.00000009, 0.00000012, 0.00000253, 0.00000098, 0.00000134, 0.00000167, 0.00000015, 0.00000003,
0.00053084, 0.00002602, 0.00013119, 0.00000006, 0.00000033, 0.00000003, 0.00000155, 0.00000021,
0.00000027, 0.00000012, 0.00000089, 0.00000009, 0.00000238, 0.00000054, 0.00000063, 0.00000027,
0.00000098, 0.00000024, 0.00000021, 0.00024822, 0.00000143, 0., 0.00000116, 0.00000006,
0.0000118, 0.00000018, 0.00000265, 0.00000012, 0.00000128, 0.0000003, 0.00000206, 0.00000003,
0.00000098, 0.00000182, 0.00000134, 0.00000006, 0.00000009, 0.00000057, 0.00000092, 0.00000235,
0.00000322, 0.00000054, 0.00000021, 0.00000048, 0.00000018, 0.00001356, 0.00000012, 0.00000209,
0.00013819, 0.00000101, 0.00000012, 0.00000045, 0.00000003, 0.00001565, 0.00000033, 0.00000024,
0.00000021, 0.00000024, 0.00000307, 0.00000018, 0.00000504, 0.00000331, 0.0000008, 0.00000003,
0.00000113, 0.00000006, 0.00000083, 0., 0.00000057, 0.00000224, 0.00000003, 0.000011,
0.00000015, 0.0000003, 0.00000098, 0.00000358, 0.00001207, 0.00000581, 0.00000045, 0.00000006,
0.00000086, 0.00000003, 0.00000015, 0.0000006, 0.00000027, 0.00000083, 0.00000015, 0.00000015,
0.00000033, 0.00000221, 0.00003073, 0.00000092, 0.00000146, 0.00000003, 0.00000021, 0.,
0.0000065, 0.00000995, 0.00000089, 0.00000024, 0.00000054, 0.00000063, 0.00000021, 0.0000011,
0.00000021, 0.00000441, 0.00000048, 0.00000012, 0.00000021, 0.00000012, 0.00000075, 0.0000062,
0.0000006, 0., 0.00000012, 0., 0.00000215, 0., 0.00000003, 0.00021857, 0.00000587, 0.00000006,
0.00013742, 0.00000027, 0.00000012, 0.00000095, 0.00000671, 0.00000018, 0., 0.00000548,
0.00000072, 0.00002974, 0.00000539, 0.00000012, 0.00000048, 0.00000158, 0.00019842, 0.00000274,
0.00001359, 0.00001264, 0.0637795, 0.00000021, 0.00000012, 0.00005141, 0.00000012, 0.00000069,
0.00000015, 0.00000048, 0.00000003, 0.00000018, 0.00000012, 0.00000313, 0.00000009, 0.00000012,
0.00000253, 0.00000098, 0.00000134, 0.00000533, 0.00000015, 0.00000003, 0.00053084, 0.00002602,
0.00013119, 0.00000018, 0.00000033, 0.00000003, 0.00000155, 0.00000021, 0.00000027, 0.00000012,
0.00000089, 0.00000009, 0.00000238, 0.00000054, 0.00000063, 0.00000027, 0.00000098, 0.00000024,
0.00000021, 0.00024822, 0.00000143, 0.00000012, 0.00000116, 0.00000006, 0.0000118, 0.00000018,
0.00000265, 0.00000012, 0.00000128, 0.0000003, 0.00000206, 0.00000027, 0.00000098, 0.00000611,
0.00000134, 0.00000054, 0.00000021, 0.00000057, 0.00000092, 0.00000679, 0.00000322, 0.00000054,
0.00000021, 0.00000048, 0.00000018, 0.00003326, 0.00000051, 0.00000209, 0.00013819, 0.00000101,
0.0000006, 0.00000045, 0.00000003, 0.00001565, 0.00000033, 0.00000024, 0.00000021, 0.00000125,
0.00000307, 0.00000033, 0.00000504, 0.00000331, 0.0000008, 0.00000003, 0.00000113, 0.00000006,
0.00000083, 0., 0.00000057, 0.00000224, 0.00000018, 0.000011, 0.00000015, 0.00000101,
0.0000034, 0.00000358, 0.00001207, 0.00000581, 0.00000045, 0.00000006, 0.00000086, 0.0000006,
0.0000008, 0.0000006, 0.00000027, 0.00000298, 0.00000015, 0.00000015, 0.00000033, 0.00000221,
0.00008041, 0.00000092, 0.00000146, 0.00000003, 0.00000021, 0., 0.0000065, 0.00000995,
0.00000089, 0.00000024, 0.00000054, 0.00000226, 0.00000021, 0.0000011, 0.00000021, 0.00000441,
0.00000146, 0.00000012, 0.00000021, 0.00000018, 0.00000075, 0.0000062, 0.0000006, 0.,
0.00000012, 0.00000075, 0.00000215, 0.00000015, 0.00000012, 0.00054771, 0.00000587, 0.00000006,
0.00013742, 0.00000027, 0.00000012, 0.00000095, 0.00002021, 0.00000072, 0., 0.00001696,
0.00000072, 0.00006732, 0.00000539, 0.00000012, 0.00000048, 0.00000158, 0.00035813, 0.00000274,
0.00001359, 0.00001264, 0.0637795, 0.00000021, 0.00000012, 0.00005141, 0.00000012, 0.00000069,
0.00000015, 0.00000048, 0.00000003, 0.00000018, 0.00000012, 0.00001037, 0.00000009, 0.00000012,
0.00000253, 0.00000098, 0.00000134, 0.00000533, 0.00000015, 0.00000003, 0.00053084, 0.00002602,
0.00013119, 0.00000018, 0.00000033, 0.00000036, 0.0000053, 0.00000089, 0.00000119, 0.00000012,
0.00000089, 0.00000009, 0.00000238, 0.00000054, 0.00000063, 0.00000027, 0.00000098, 0.00000024,
0.00000077, 0.00061658, 0.00000143, 0.00000012, 0.00000116, 0.00000006, 0.00003329, 0.00000018,
0.00000265, 0.00000012, 0.00000128, 0.0000003, 0.00000206, 0.00000027, 0.00000098, 0.00000611,
0.0000048, 0.00000054, 0.00000021, 0.00000057, 0.00000092, 0.00000679, 0.00000322, 0.00000212,
0.00000021, 0.00000048, 0.00000018, 0.00003326, 0.00000051, 0.00000209, 0.00013819, 0.00000101,
0.0000006, 0.00000173, 0.00000075, 0.00001565, 0.00000119, 0.00000137, 0.00000021, 0.00000125,
0.00000307, 0.00000033, 0.00000504, 0.00001022, 0.0000008, 0.00000003, 0.00000387, 0.00000069,
0.00000301, 0., 0.00000057, 0.00000224, 0.00000018, 0.000011, 0.00000045, 0.00000101,
0.0000034, 0.00001112, 0.00003368, 0.00000581, 0.00000045, 0.00000006, 0.00000086, 0.0000006,
0.0000008, 0.0000006, 0.00000122, 0.00000298, 0.00000015, 0.00000069, 0.00000131, 0.00000221,
0.00008041, 0.00000092, 0.00000525, 0.00000003, 0.00000021, 0.00000021, 0.00001952, 0.00002488,
0.00000089, 0.00000024, 0.00000054, 0.00000226, 0.00000021, 0.0000011, 0.00000089, 0.00000441,
0.00000146, 0.00000012, 0.00000122, 0.00000018, 0.00000075, 0.00001809, 0.00000253, 0.,
0.00000063, 0.00000075, 0.00000703, 0.00000015, 0.00000012, 0.00054771, 0.00001758, 0.00000006,
0.00013742, 0.00000149, 0.00000012, 0.00000095, 0.00002021, 0.00000072, 0.00000033, 0.00001696,
0.00000072, 0.00006732, 0.00000539, 0.00000012, 0.00000203, 0.00000507, 0.00035813, 0.00000274,
0.00001359, 0.00003552, 0.10005975, 0.00000021, 0.00000012, 0.00005141, 0.00000012, 0.00000069,
0.00000039, 0.00000158, 0.00000003, 0.00000018, 0.00000012, 0.00001037, 0.00000012, 0.00000018,
0.00000805, 0.00000367, 0.00000134, 0.00000533, 0.00000015, 0.00000003, 0.00053084, 0.00006771,
0.00029746, 0.00000018, 0.00000152, 0.00000036, 0.0000053, 0.00000089, 0.00000119, 0.00000012,
0.00000089, 0.00000009, 0.00000238, 0.00000224, 0.00000063, 0.00000027, 0.00000334, 0.00000024,
0.00000077, 0.00061658, 0.00000489, 0.00000012, 0.00000116, 0.00000051, 0.00003329, 0.00000086,
0.00001022, 0.00000045, 0.00000128, 0.00000131, 0.00000206, 0.00000027, 0.00000098, 0.00000611,
0.0000048, 0.00000054, 0.00000021, 0.00000259, 0.00000322, 0.00000679, 0.00000998, 0.00000212,
0.00000021, 0.00000048, 0.00000018, 0.00003326, 0.00000051, 0.00000671, 0.00013819, 0.00000101,
0.0000006, 0.00000173, 0.00000075, 0.0000425, 0.00000119, 0.00000137, 0.00000021, 0.00000125,
0.00000995, 0.00000033, 0.00000504, 0.00001022, 0.00000271, 0.00000003, 0.00000387, 0.00000069,
0.00000301, 0.00000018, 0.00000194, 0.00000876, 0.00000018, 0.000011, 0.00000045, 0.00000101,
0.0000034, 0.00001112, 0.00003368, 0.00000581, 0.00000045, 0.00000048, 0.00000086, 0.0000006,
0.0000008, 0.0000006, 0.00000122, 0.00000298, 0.00000089, 0.00000069, 0.00000131, 0.00000221,
0.00008041, 0.00000346, 0.00000525, 0.00000027, 0.00000098, 0.00000021, 0.00001952, 0.00002488,
0.00000089, 0.00000024, 0.00000167, 0.00000226, 0.00000089, 0.00000408, 0.00000089, 0.0000135,
0.00000146, 0.00000012, 0.00000122, 0.00000018, 0.00000075, 0.00001809, 0.00000253, 0.0000006,
0.00000063, 0.00000075, 0.00000703, 0.00000015, 0.00000012, 0.00054771, 0.00001758, 0.00000039,
0.00013742, 0.00000149, 0.00000069, 0.00000334, 0.00002021, 0.00000072, 0.00000033, 0.00001696,
0.00000072, 0.00006732, 0.00000539, 0.00000012, 0.00000203, 0.00000507, 0.00035813, 0.00000909,
0.00001359, 0.00003552, 0.10005975, 0.00000021, 0.00000012, 0.00012583, 0.00000057, 0.00000274,
0.00000039, 0.00000158, 0.00000063, 0.00000083, 0.00000075, 0.00001037, 0.00000012, 0.00000018,
0.00000805, 0.00000367, 0.0000048, 0.00000533, 0.00000069, 0.00000003, 0.0012165, 0.00006771,
0.00029746, 0.00000018, 0.00000152, 0.00000036, 0.0000053, 0.00000089, 0.00000119, 0.00000051,
0.00000283, 0.0000003, 0.00000784, 0.00000224, 0.0000025, 0.0000011, 0.00000334, 0.00000101,
0.00000077, 0.00061658, 0.00000489, 0.00000012, 0.00000477, 0.00000051, 0.00003329, 0.00000086,
0.00001022, 0.00000045, 0.00000459, 0.00000131, 0.00000861, 0.00000027, 0.00000489, 0.00000611,
0.0000048, 0.00000054, 0.00000021, 0.00000259, 0.00000322, 0.00000679, 0.00000998, 0.00000212,
0.00000057, 0.00000176, 0.00000045, 0.00003326, 0.00000051, 0.00000671, 0.00036159, 0.00000465,
0.0000006, 0.00000173, 0.00000075, 0.0000425, 0.00000119, 0.00000137, 0.0000014, 0.00000125,
0.00000995, 0.00000033, 0.0000186, 0.00001022, 0.00000271, 0.00000066, 0.00000387, 0.00000069,
0.00000301, 0.00000018, 0.00000194, 0.00000876, 0.00000018, 0.00003064, 0.00000045, 0.00000101,
0.0000034, 0.00001112, 0.00003368, 0.00002137, 0.00000244, 0.00000048, 0.00000325, 0.0000006,
0.0000008, 0.00000274, 0.00000122, 0.00000298, 0.00000089, 0.00000069, 0.00000131, 0.00000903,
0.00008041, 0.00000346, 0.00000525, 0.00000027, 0.00000098, 0.00000021, 0.00001952, 0.00002488,
0.00000405, 0.00000122, 0.00000167, 0.00000226, 0.00000089, 0.00000408, 0.00000089, 0.0000135,
0.00000146, 0.00000033, 0.00000122, 0.00000018, 0.00000334, 0.00001809, 0.00000253, 0.0000006,
0.00000063, 0.00000075, 0.00000703, 0.00000015, 0.00000012, 0.00054771, 0.00001758, 0.00000039,
0.00027534, 0.00000149, 0.00000069, 0.00000334, 0.00002021, 0.00000072, 0.00000033, 0.00001696,
0.00000229, 0.00006732, 0.00001982, 0.00000048, 0.00000203, 0.00000507, 0.00035813, 0.00000909,
0.00004503, 0.00003552, 0.10005975, 0.00000057, 0.00000027, 0.00012583, 0.00000057, 0.00000274,
0.00000039, 0.00000158, 0.00000063, 0.00000083, 0.00000075, 0.00001037, 0.00000012, 0.00000018,
0.00000805, 0.00000367, 0.0000048, 0.00001991, 0.00000069, 0.00000045, 0.0012165, 0.00006771,
0.00029746, 0.00000101, 0.00000152, 0.00000036, 0.0000053, 0.00000089, 0.00000119, 0.00000051,
0.00000283, 0.0000003, 0.00000784, 0.00000224, 0.0000025, 0.0000011, 0.00000334, 0.00000101,
0.00000077, 0.00061658, 0.00000489, 0.0000003, 0.00000477, 0.00000051, 0.00003329, 0.00000086,
0.00001022, 0.00000045, 0.00000459, 0.00000131, 0.00000861, 0.00000131, 0.00000489, 0.00002179,
0.0000048, 0.00000185, 0.00000134, 0.00000259, 0.00000322, 0.00002003, 0.00000998, 0.00000212,
0.00000057, 0.00000176, 0.00000045, 0.00008446, 0.00000274, 0.00000671, 0.00036159, 0.00000465,
0.00000226, 0.00000173, 0.00000075, 0.0000425, 0.00000119, 0.00000137, 0.0000014, 0.00000548,
0.00000995, 0.00000197, 0.0000186, 0.00001022, 0.00000271, 0.00000066, 0.00000387, 0.00000069,
0.00000301, 0.00000018, 0.00000194, 0.00000876, 0.00000063, 0.00003064, 0.00000045, 0.00000444,
0.00001299, 0.00001112, 0.00003368, 0.00002137, 0.00000244, 0.00000048, 0.00000325, 0.00000286,
0.00000355, 0.00000274, 0.00000122, 0.00001121, 0.00000089, 0.00000069, 0.00000131, 0.00000903,
0.00022322, 0.00000346, 0.00000525, 0.00000027, 0.00000098, 0.00000021, 0.00001952, 0.00002488,
0.00000405, 0.00000122, 0.00000167, 0.00000948, 0.00000089, 0.00000408, 0.00000089, 0.0000135,
0.00000492, 0.00000033, 0.00000122, 0.00000158, 0.00000334, 0.00001809, 0.00000253, 0.0000006,
0.00000063, 0.00000337, 0.00000703, 0.00000095, 0.00000012, 0.00154367, 0.00001758, 0.00000039,
0.00027534, 0.00000149, 0.00000069, 0.00000334, 0.00006461, 0.00000337, 0.00000033, 0.00005561,
0.00000229, 0.00015956, 0.00001982, 0.00000048, 0.00000203, 0.00000507, 0.00066876, 0.00000909,
0.00004503, 0.00003552, 0.10005975, 0.00000057, 0.00000027, 0.00012583, 0.00000057, 0.00000274,
0.00000039, 0.00000158, 0.00000063, 0.00000083, 0.00000075, 0.00003576, 0.00000012, 0.00000018,
0.00000805, 0.00000367, 0.0000048, 0.00001991, 0.00000069, 0.00000045, 0.0012165, 0.00006771,
0.00029746, 0.00000101, 0.00000152, 0.0000017, 0.0000194, 0.0000039, 0.00000519, 0.00000051,
0.00000283, 0.0000003, 0.00000784, 0.00000224, 0.0000025, 0.0000011, 0.00000334, 0.00000101,
0.00000307, 0.00171137, 0.00000489, 0.0000003, 0.00000477, 0.00000051, 0.00010058, 0.00000086,
0.00001022, 0.00000045, 0.00000459, 0.00000131, 0.00000861, 0.00000131, 0.00000489, 0.00002179,
0.0000183, 0.00000185, 0.00000134, 0.00000259, 0.00000322, 0.00002003, 0.00000998, 0.00000843,
0.00000057, 0.00000176, 0.00000045, 0.00008446, 0.00000274, 0.00000671, 0.00036159, 0.00000465,
0.00000226, 0.00000721, 0.00000319, 0.0000425, 0.00000539, 0.00000587, 0.0000014, 0.00000548,
0.00000995, 0.00000197, 0.0000186, 0.00003529, 0.00000271, 0.00000066, 0.00001478, 0.00000298,
0.00001189, 0.00000018, 0.00000194, 0.00000876, 0.00000063, 0.00003064, 0.0000025, 0.00000444,
0.00001299, 0.00003839, 0.00010073, 0.00002137, 0.00000244, 0.00000048, 0.00000325, 0.00000286,
0.00000355, 0.00000274, 0.00000542, 0.00001121, 0.00000089, 0.0000034, 0.00000551, 0.00000903,
0.00022322, 0.00000346, 0.00001955, 0.00000027, 0.00000098, 0.00000095, 0.00006279, 0.00006473,
0.00000405, 0.00000122, 0.00000167, 0.00000948, 0.00000089, 0.00000408, 0.00000402, 0.0000135,
0.00000492, 0.00000033, 0.00000545, 0.00000158, 0.00000334, 0.0000574, 0.0000098, 0.0000006,
0.00000289, 0.00000337, 0.00002453, 0.00000095, 0.00000012, 0.00154367, 0.0000563, 0.00000039,
0.00027534, 0.00000647, 0.00000069, 0.00000334, 0.00006461, 0.00000337, 0.00000137, 0.00005561,
0.00000229, 0.00015956, 0.00001982, 0.00000048, 0.00000793, 0.00001869, 0.00066876, 0.00000909,
0.00004503, 0.00010604, 0.14302838, 0.00000057, 0.00000027, 0.00012583, 0.00000057, 0.00000274,
0.00000238, 0.00000671, 0.00000063, 0.00000083, 0.00000075, 0.00003576, 0.00000137, 0.00000152,
0.00002822, 0.00001365, 0.0000048, 0.00001991, 0.00000069, 0.00000045, 0.0012165, 0.00018811,
0.00071973, 0.00000101, 0.00000679, 0.0000017, 0.0000194, 0.0000039, 0.00000519, 0.00000051,
0.00000283, 0.0000003, 0.00000784, 0.00000888, 0.0000025, 0.0000011, 0.00001296, 0.00000101,
0.00000307, 0.00171137, 0.00001785, 0.0000003, 0.00000477, 0.00000226, 0.00010058, 0.00000367,
0.00004613, 0.00000226, 0.00000459, 0.00000548, 0.00000861, 0.00000131, 0.00000489, 0.00002179,
0.0000183, 0.00000185, 0.00000134, 0.0000098, 0.00001279, 0.00002003, 0.00003392, 0.00000843,
0.00000057, 0.00000176, 0.00000045, 0.00008446, 0.00000274, 0.00002345, 0.00036159, 0.00000465,
0.00000226, 0.00000721, 0.00000319, 0.00012341, 0.00000539, 0.00000587, 0.0000014, 0.00000548,
0.00003344, 0.00000197, 0.0000186, 0.00003529, 0.00001082, 0.00000066, 0.00001478, 0.00000298,
0.00001189, 0.00000048, 0.00000802, 0.00004032, 0.00000063, 0.00003064, 0.0000025, 0.00000444,
0.00001299, 0.00003839, 0.00010073, 0.00002137, 0.00000244, 0.00000244, 0.00000325, 0.00000286,
0.00000355, 0.00000274, 0.00000542, 0.00001121, 0.00000402, 0.0000034, 0.00000551, 0.00000903,
0.00022322, 0.00001347, 0.00001955, 0.00000131, 0.00000447, 0.00000095, 0.00006279, 0.00006473,
0.00000405, 0.00000122, 0.00000688, 0.00000948, 0.00000393, 0.00001529, 0.00000402, 0.00004473,
0.00000492, 0.00000033, 0.00000545, 0.00000158, 0.00000334, 0.0000574, 0.0000098, 0.00000292,
0.00000289, 0.00000337, 0.00002453, 0.00000095, 0.00000012, 0.00154367, 0.0000563, 0.00000232,
0.00027534, 0.00000647, 0.00000355, 0.00001281, 0.00006461, 0.00000337, 0.00000137, 0.00005561,
0.00000229, 0.00015956, 0.00001982, 0.00000048, 0.00000793, 0.00001869, 0.00066876, 0.00003138,
0.00004503, 0.00010604, 0.14302838, 0.00000057, 0.00000027, 0.00033188, 0.00000307, 0.00001088,
0.00000238, 0.00000671, 0.00000298, 0.00000381, 0.00000367, 0.00003576, 0.00000137, 0.00000152,
0.00002822, 0.00001365, 0.00001803, 0.00001991, 0.00000325, 0.00000045, 0.00312266, 0.00018811,
0.00071973, 0.00000101, 0.00000679, 0.0000017, 0.0000194, 0.0000039, 0.00000519, 0.00000221,
0.00001135, 0.00000179, 0.00002748, 0.00000888, 0.0000096, 0.00000513, 0.00001296, 0.00000447,
0.00000307, 0.00171137, 0.00001785, 0.0000003, 0.00002408, 0.00000226, 0.00010058, 0.00000367,
0.00004613, 0.00000226, 0.00001675, 0.00000548, 0.00003943, 0.00000131, 0.00002378, 0.00002179,
0.0000183, 0.00000185, 0.00000134, 0.0000098, 0.00001279, 0.00002003, 0.00003392, 0.00000843,
0.00000301, 0.00000745, 0.00000241, 0.00008446, 0.00000274, 0.00002345, 0.00105959, 0.00002247,
0.00000226, 0.00000721, 0.00000319, 0.00012341, 0.00000539, 0.00000587, 0.00000843, 0.00000548,
0.00003344, 0.00000197, 0.00007889, 0.00003529, 0.00001082, 0.0000028, 0.00001478, 0.00000298,
0.00001189, 0.00000048, 0.00000802, 0.00004032, 0.00000063, 0.00009137, 0.0000025, 0.00000444,
0.00001299, 0.00003839, 0.00010073, 0.00008878, 0.00001353, 0.00000244, 0.00001213, 0.00000286,
0.00000355, 0.00001523, 0.00000542, 0.00001121, 0.00000402, 0.0000034, 0.00000551, 0.00004098,
0.00022322, 0.00001347, 0.00001955, 0.00000131, 0.00000447, 0.00000095, 0.00006279, 0.00006473,
0.00002074, 0.00000498, 0.00000688, 0.00000948, 0.00000393, 0.00001529, 0.00000402, 0.00004473,
0.00000492, 0.00000137, 0.00000545, 0.00000158, 0.00001732, 0.0000574, 0.0000098, 0.00000292,
0.00000289, 0.00000337, 0.00002453, 0.00000095, 0.00000012, 0.00154367, 0.0000563, 0.00000232,
0.00058341, 0.00000647, 0.00000355, 0.00001281, 0.00006461, 0.00000337, 0.00000137, 0.00005561,
0.00000942, 0.00015956, 0.00008056, 0.00000241, 0.00000793, 0.00001869, 0.00066876, 0.00003138,
0.00016779, 0.00010604, 0.14302838, 0.00000322, 0.00000158, 0.00033188, 0.00000307, 0.00001088,
0.00000238, 0.00000671, 0.00000298, 0.00000381, 0.00000367, 0.00003576, 0.00000137, 0.00000152,
0.00002822, 0.00001365, 0.00001803, 0.00008106, 0.00000325, 0.00000229, 0.00312266, 0.00018811,
0.00071973, 0.00000453, 0.00000679, 0.0000017, 0.0000194, 0.0000039, 0.00000519, 0.00000221,
0.00001135, 0.00000179, 0.00002748, 0.00000888, 0.0000096, 0.00000513, 0.00001296, 0.00000447,
0.00000307, 0.00171137, 0.00001785, 0.00000179, 0.00002408, 0.00000226, 0.00010058, 0.00000367,
0.00004613, 0.00000226, 0.00001675, 0.00000548, 0.00003943, 0.00000563, 0.00002378, 0.00008821,
0.0000183, 0.00000724, 0.00000733, 0.0000098, 0.00001279, 0.00006396, 0.00003392, 0.00000843,
0.00000301, 0.00000745, 0.00000241, 0.000231, 0.00001428, 0.00002345, 0.00105959, 0.00002247,
0.00000918, 0.00000721, 0.00000319, 0.00012341, 0.00000539, 0.00000587, 0.00000843, 0.00002667,
0.00003344, 0.00001043, 0.00007889, 0.00003529, 0.00001082, 0.0000028, 0.00001478, 0.00000298,
0.00001189, 0.00000048, 0.00000802, 0.00004032, 0.0000028, 0.00009137, 0.0000025, 0.00002241,
0.00005701, 0.00003839, 0.00010073, 0.00008878, 0.00001353, 0.00000244, 0.00001213, 0.00001451,
0.00001803, 0.00001523, 0.00000542, 0.00004923, 0.00000402, 0.0000034, 0.00000551, 0.00004098,
0.00069749, 0.00001347, 0.00001955, 0.00000131, 0.00000447, 0.00000095, 0.00006279, 0.00006473,
0.00002074, 0.00000498, 0.00000688, 0.00004339, 0.00000393, 0.00001529, 0.00000402, 0.00004473,
0.00001767, 0.00000137, 0.00000545, 0.00000891, 0.00001732, 0.0000574, 0.0000098, 0.00000292,
0.00000289, 0.00001702, 0.00002453, 0.00000399, 0.00000134, 0.00535333, 0.0000563, 0.00000232,
0.00058341, 0.00000647, 0.00000355, 0.00001281, 0.00023177, 0.00001737, 0.00000137, 0.00020361,
0.00000942, 0.00040707, 0.00008056, 0.00000241, 0.00000793, 0.00001869, 0.0013206, 0.00003138,
0.00016779, 0.00010604, 0.14302838, 0.00000322, 0.00000158, 0.00033188, 0.00000307, 0.00001088,
0.00000238, 0.00000671, 0.00000298, 0.00000381, 0.00000367, 0.00013864, 0.00000137, 0.00000152,
0.00002822, 0.00001365, 0.00001803, 0.00008106, 0.00000325, 0.00000229, 0.00312266, 0.00018811,
0.00071973, 0.00000453, 0.00000679, 0.0000096, 0.00007984, 0.00002044, 0.00002527, 0.00000221,
0.00001135, 0.00000179, 0.00002748, 0.00000888, 0.0000096, 0.00000513, 0.00001296, 0.00000447,
0.00001135, 0.00579044, 0.00001785, 0.00000179, 0.00002408, 0.00000226, 0.00034335, 0.00000367,
0.00004613, 0.00000226, 0.00001675, 0.00000548, 0.00003943, 0.00000563, 0.00002378, 0.00008821,
0.00007772, 0.00000724, 0.00000733, 0.0000098, 0.00001279, 0.00006396, 0.00003392, 0.00003827,
0.00000301, 0.00000745, 0.00000241, 0.000231, 0.00001428, 0.00002345, 0.00105959, 0.00002247,
0.00000918, 0.00003377, 0.00001684, 0.00012341, 0.00002617, 0.00002778, 0.00000843, 0.00002667,
0.00003344, 0.00001043, 0.00007889, 0.00013596, 0.00001082, 0.0000028, 0.00006321, 0.00001532,
0.00005251, 0.00000048, 0.00000802, 0.00004032, 0.0000028, 0.00009137, 0.00001296, 0.00002241,
0.00005701, 0.00014779, 0.00033894, 0.00008878, 0.00001353, 0.00000244, 0.00001213, 0.00001451,
0.00001803, 0.00001523, 0.00002682, 0.00004923, 0.00000402, 0.00001717, 0.00002643, 0.00004098,
0.00069749, 0.00001347, 0.00008252, 0.00000131, 0.00000447, 0.00000569, 0.00022632, 0.00018221,
0.00002074, 0.00000498, 0.00000688, 0.00004339, 0.00000393, 0.00001529, 0.00002092, 0.00004473,
0.00001767, 0.00000137, 0.00002632, 0.00000891, 0.00001732, 0.00020674, 0.00004426, 0.00000292,
0.00001526, 0.00001702, 0.00009704, 0.00000399, 0.00000134, 0.00535333, 0.0002034, 0.00000232,
0.00058341, 0.00003034, 0.00000355, 0.00001281, 0.00023177, 0.00001737, 0.00000802, 0.00020361,
0.00000942, 0.00040707, 0.00008056, 0.00000241, 0.00003716, 0.00007778, 0.0013206, 0.00003138,
0.00016779, 0.00035551, 0.17063886, 0.00000322, 0.00000158, 0.00033188, 0.00000307, 0.00001088,
0.00001246, 0.00003192, 0.00000298, 0.00000381, 0.00000367, 0.00013864, 0.00000757, 0.0000084,
0.00011063, 0.00005823, 0.00001803, 0.00008106, 0.00000325, 0.00000229, 0.00312266, 0.00058872,
0.00195289, 0.00000453, 0.00003189, 0.0000096, 0.00007984, 0.00002044, 0.00002527, 0.00000221,
0.00001135, 0.00000179, 0.00002748, 0.00004056, 0.0000096, 0.00000513, 0.00005597, 0.00000447,
0.00001135, 0.00579044, 0.00007522, 0.00000179, 0.00002408, 0.00001243, 0.00034335, 0.00001901,
0.00026697, 0.00001252, 0.00001675, 0.00002599, 0.00003943, 0.00000563, 0.00002378, 0.00008821,
0.00007772, 0.00000724, 0.00000733, 0.00004438, 0.00005487, 0.00006396, 0.00012863, 0.00003827,
0.00000301, 0.00000745, 0.00000241, 0.000231, 0.00001428, 0.00009373, 0.00105959, 0.00002247,
0.00000918, 0.00003377, 0.00001684, 0.00040486, 0.00002617, 0.00002778, 0.00000843, 0.00002667,
0.00012848, 0.00001043, 0.00007889, 0.00013596, 0.00004795, 0.0000028, 0.00006321, 0.00001532,
0.00005251, 0.00000378, 0.00003672, 0.00023419, 0.0000028, 0.00009137, 0.00001296, 0.00002241,
0.00005701, 0.00014779, 0.00033894, 0.00008878, 0.00001353, 0.00001299, 0.00001213, 0.00001451,
0.00001803, 0.00001523, 0.00002682, 0.00004923, 0.00002077, 0.00001717, 0.00002643, 0.00004098,
0.00069749, 0.000058, 0.00008252, 0.00000781, 0.00002247, 0.00000569, 0.00022632, 0.00018221,
0.00002074, 0.00000498, 0.00003171, 0.00004339, 0.00001931, 0.00006542, 0.00002092, 0.00016698,
0.00001767, 0.00000137, 0.00002632, 0.00000891, 0.00001732, 0.00020674, 0.00004426, 0.00001475,
0.00001526, 0.00001702, 0.00009704, 0.00000399, 0.00000134, 0.00535333, 0.0002034, 0.00001225,
0.00058341, 0.00003034, 0.00001773, 0.00005588, 0.00023177, 0.00001737, 0.00000802, 0.00020361,
0.00000942, 0.00040707, 0.00008056, 0.00000241, 0.00003716, 0.00007778, 0.0013206, 0.00012237,
0.00016779, 0.00035551, 0.17063886, 0.00000322, 0.00000158, 0.00099707, 0.00001603, 0.00004685,
0.00001246, 0.00003192, 0.00001547, 0.00001928, 0.00001824, 0.00013864, 0.00000757, 0.0000084,
0.00011063, 0.00005823, 0.00007561, 0.00008106, 0.00001681, 0.00000229, 0.00969782, 0.00058872,
0.00195289, 0.00000453, 0.00003189, 0.0000096, 0.00007984, 0.00002044, 0.00002527, 0.00001228,
0.0000504, 0.00001007, 0.00010911, 0.00004056, 0.00004369, 0.00002521, 0.00005597, 0.00002268,
0.00001135, 0.00579044, 0.00007522, 0.00000179, 0.00015348, 0.00001243, 0.00034335, 0.00001901,
0.00026697, 0.00001252, 0.00007015, 0.00002599, 0.00022855, 0.00000563, 0.00015065, 0.00008821,
0.00007772, 0.00000724, 0.00000733, 0.00004438, 0.00005487, 0.00006396, 0.00012863, 0.00003827,
0.0000152, 0.00003472, 0.00001332, 0.000231, 0.00001428, 0.00009373, 0.00382492, 0.00014099,
0.00000918, 0.00003377, 0.00001684, 0.00040486, 0.00002617, 0.00002778, 0.00006196, 0.00002667,
0.00012848, 0.00001043, 0.00042096, 0.00013596, 0.00004795, 0.00001472, 0.00006321, 0.00001532,
0.00005251, 0.00000378, 0.00003672, 0.00023419, 0.0000028, 0.00031063, 0.00001296, 0.00002241,
0.00005701, 0.00014779, 0.00033894, 0.00046507, 0.00009385, 0.00001299, 0.00005254, 0.00001451,
0.00001803, 0.00010169, 0.00002682, 0.00004923, 0.00002077, 0.00001717, 0.00002643, 0.00023708,
0.00069749, 0.000058, 0.00008252, 0.00000781, 0.00002247, 0.00000569, 0.00022632, 0.00018221,
0.0001339, 0.00002468, 0.00003171, 0.00004339, 0.00001931, 0.00006542, 0.00002092, 0.00016698,
0.00001767, 0.00000799, 0.00002632, 0.00000891, 0.00011444, 0.00020674, 0.00004426, 0.00001475,
0.00001526, 0.00001702, 0.00009704, 0.00000399, 0.00000134, 0.00535333, 0.0002034, 0.00001225,
0.00135314, 0.00003034, 0.00001773, 0.00005588, 0.00023177, 0.00001737, 0.00000802, 0.00020361,
0.00004205, 0.00040707, 0.0004175, 0.00001308, 0.00003716, 0.00007778, 0.0013206, 0.00012237,
0.00079021, 0.00035551, 0.17063886, 0.00001666, 0.00000897, 0.00099707, 0.00001603, 0.00004685,
0.00001246, 0.00003192, 0.00001547, 0.00001928, 0.00001824, 0.00013864, 0.00000757, 0.0000084,
0.00011063, 0.00005823, 0.00007561, 0.00041738, 0.00001681, 0.00001186, 0.00969782, 0.00058872,
0.00195289, 0.00002316, 0.00003189, 0.0000096, 0.00007984, 0.00002044, 0.00002527, 0.00001228,
0.0000504, 0.00001007, 0.00010911, 0.00004056, 0.00004369, 0.00002521, 0.00005597, 0.00002268,
0.00001135, 0.00579044, 0.00007522, 0.00000954, 0.00015348, 0.00001243, 0.00034335, 0.00001901,
0.00026697, 0.00001252, 0.00007015, 0.00002599, 0.00022855, 0.00002703, 0.00015065, 0.00045449,
0.00007772, 0.00003302, 0.00005624, 0.00004438, 0.00005487, 0.00023264, 0.00012863, 0.00003827,
0.0000152, 0.00003472, 0.00001332, 0.00071943, 0.00009793, 0.00009373, 0.00382492, 0.00014099,
0.00004148, 0.00003377, 0.00001684, 0.00040486, 0.00002617, 0.00002778, 0.00006196, 0.00016272,
0.00012848, 0.00007284, 0.00042096, 0.00013596, 0.00004795, 0.00001472, 0.00006321, 0.00001532,
0.00005251, 0.00000378, 0.00003672, 0.00023419, 0.0000149, 0.00031063, 0.00001296, 0.00013995,
0.00032106, 0.00014779, 0.00033894, 0.00046507, 0.00009385, 0.00001299, 0.00005254, 0.00009957,
0.00011829, 0.00010169, 0.00002682, 0.0002766, 0.00002077, 0.00001717, 0.00002643, 0.00023708,
0.00271443, 0.000058, 0.00008252, 0.00000781, 0.00002247, 0.00000569, 0.00022632, 0.00018221,
0.0001339, 0.00002468, 0.00003171, 0.00025222, 0.00001931, 0.00006542, 0.00002092, 0.00016698,
0.00007403, 0.00000799, 0.00002632, 0.00006452, 0.00011444, 0.00020674, 0.00004426, 0.00001475,
0.00001526, 0.00011152, 0.00009704, 0.00001985, 0.00000772, 0.02632967, 0.0002034, 0.00001225,
0.00135314, 0.00003034, 0.00001773, 0.00005588, 0.00103998, 0.00011703, 0.00000802, 0.00093484,
0.00004205, 0.00118688, 0.0004175, 0.00001308, 0.00003716, 0.00007778, 0.00284371, 0.00012237,
0.00079021, 0.00035551, 0.17063886, 0.00001666, 0.00000897, 0.00099707, 0.00001603, 0.00004685,
0.00001246, 0.00003192, 0.00001547, 0.00001928, 0.00001824, 0.00067893, 0.00000757, 0.0000084,
0.00011063, 0.00005823, 0.00007561, 0.00041738, 0.00001681, 0.00001186, 0.00969782, 0.00058872,
0.00195289, 0.00002316, 0.00003189, 0.00006875, 0.0004164, 0.00013107, 0.00015888, 0.00001228,
0.0000504, 0.00001007, 0.00010911, 0.00004056, 0.00004369, 0.00002521, 0.00005597, 0.00002268,
0.00004938, 0.02746293, 0.00007522, 0.00000954, 0.00015348, 0.00001243, 0.00147748, 0.00001901,
0.00026697, 0.00001252, 0.00007015, 0.00002599, 0.00022855, 0.00002703, 0.00015065, 0.00045449,
0.0004136, 0.00003302, 0.00005624, 0.00004438, 0.00005487, 0.00023264, 0.00012863, 0.00021854,
0.0000152, 0.00003472, 0.00001332, 0.00071943, 0.00009793, 0.00009373, 0.00382492, 0.00014099,
0.00004148, 0.00020024, 0.00011283, 0.00040486, 0.00016358, 0.00017232, 0.00006196, 0.00016272,
0.00012848, 0.00007284, 0.00042096, 0.00066525, 0.00004795, 0.00001472, 0.00034156, 0.00010335,
0.00029758, 0.00000378, 0.00003672, 0.00023419, 0.0000149, 0.00031063, 0.00008845, 0.00013995,
0.00032106, 0.0007149, 0.00143564, 0.00046507, 0.00009385, 0.00001299, 0.00005254, 0.00009957,
0.00011829, 0.00010169, 0.00016689, 0.0002766, 0.00002077, 0.00011474, 0.00016543, 0.00023708,
0.00271443, 0.000058, 0.00043786, 0.00000781, 0.00002247, 0.00004423, 0.0010201, 0.00059006,
0.0001339, 0.00002468, 0.00003171, 0.00025222, 0.00001931, 0.00006542, 0.0001356, 0.00016698,
0.00007403, 0.00000799, 0.00016603, 0.00006452, 0.00011444, 0.00096002, 0.00025371, 0.00001475,
0.00010258, 0.00011152, 0.00048798, 0.00001985, 0.00000772, 0.02632967, 0.00092679, 0.00001225,
0.00135314, 0.00018749, 0.00001773, 0.00005588, 0.00103998, 0.00011703, 0.0000591, 0.00093484,
0.00004205, 0.00118688, 0.0004175, 0.00001308, 0.00022027, 0.00041664, 0.00284371, 0.00012237,
0.00079021, 0.00149798, 0.15748763, 0.00001666, 0.00000897, 0.00099707, 0.00001603, 0.00004685,
0.00008619, 0.00019324, 0.00001547, 0.00001928, 0.00001824, 0.00067893, 0.00005627, 0.00006336,
0.00055432, 0.00031504, 0.00007561, 0.00041738, 0.00001681, 0.00001186, 0.00969782, 0.00231227,
0.00647306, 0.00002316, 0.00019282, 0.00006875, 0.0004164, 0.00013107, 0.00015888, 0.00001228,
0.0000504, 0.00001007, 0.00010911, 0.00023758, 0.00004369, 0.00002521, 0.00030649, 0.00002268,
0.00004938, 0.02746293, 0.00040781, 0.00000954, 0.00015348, 0.00008774, 0.00147748, 0.00012296,
0.00258854, 0.00008866, 0.00007015, 0.0001592, 0.00022855, 0.00002703, 0.00015065, 0.00045449,
0.0004136, 0.00003302, 0.00005624, 0.00025418, 0.00030681, 0.00023264, 0.00062472, 0.00021854,
0.0000152, 0.00003472, 0.00001332, 0.00071943, 0.00009793, 0.00048637, 0.00382492, 0.00014099,
0.00004148, 0.00020024, 0.00011283, 0.00167862, 0.00016358, 0.00017232, 0.00006196, 0.00016272,
0.00062397, 0.00007284, 0.00042096, 0.00066525, 0.00027147, 0.00001472, 0.00034156, 0.00010335,
0.00029758, 0.00003108, 0.0002214, 0.00226411, 0.0000149, 0.00031063, 0.00008845, 0.00013995,
0.00032106, 0.0007149, 0.00143564, 0.00046507, 0.00009385, 0.0000892, 0.00005254, 0.00009957,
0.00011829, 0.00010169, 0.00016689, 0.0002766, 0.00013676, 0.00011474, 0.00016543, 0.00023708,
0.00271443, 0.00031978, 0.00043786, 0.00005865, 0.00014353, 0.00004423, 0.0010201, 0.00059006,
0.0001339, 0.00002468, 0.00019106, 0.00025222, 0.00012469, 0.00035664, 0.0001356, 0.00078461,
0.00007403, 0.00000799, 0.00016603, 0.00006452, 0.00011444, 0.00096002, 0.00025371, 0.00009757,
0.00010258, 0.00011152, 0.00048798, 0.00001985, 0.00000772, 0.02632967, 0.00092679, 0.00008446,
0.00135314, 0.00018749, 0.00011685, 0.00031176, 0.00103998, 0.00011703, 0.0000591, 0.00093484,
0.00004205, 0.00118688, 0.0004175, 0.00001308, 0.00022027, 0.00041664, 0.00284371, 0.0006018,
0.00079021, 0.00149798, 0.15748763, 0.00001666, 0.00000897, 0.0037542, 0.0001078, 0.00026274,
0.00008619, 0.00019324, 0.00010502, 0.00012287, 0.00011879, 0.00067893, 0.00005627, 0.00006336,
0.00055432, 0.00031504, 0.00040603, 0.00041738, 0.00011158, 0.00001186, 0.04019886, 0.00231227,
0.00647306, 0.00002316, 0.00019282, 0.00006875, 0.0004164, 0.00013107, 0.00015888, 0.00008512,
0.00028718, 0.00007373, 0.00054997, 0.00023758, 0.00025681, 0.00015733, 0.00030649, 0.00014579,
0.00004938, 0.02746293, 0.00040781, 0.00000954, 0.00167143, 0.00008774, 0.00147748, 0.00012296,
0.00258854, 0.00008866, 0.00037476, 0.0001592, 0.00220951, 0.00002703, 0.00160763, 0.00045449,
0.0004136, 0.00003302, 0.00005624, 0.00025418, 0.00030681, 0.00023264, 0.00062472, 0.00021854,
0.00010192, 0.00020868, 0.00009504, 0.00071943, 0.00009793, 0.00048637, 0.02013129, 0.00151616,
0.00004148, 0.00020024, 0.00011283, 0.00167862, 0.00016358, 0.00017232, 0.0008083, 0.00016272,
0.00062397, 0.00007284, 0.00365263, 0.00066525, 0.00027147, 0.00010151, 0.00034156, 0.00010335,
0.00029758, 0.00003108, 0.0002214, 0.00226411, 0.0000149, 0.00135109, 0.00008845, 0.00013995,
0.00032106, 0.0007149, 0.00143564, 0.00394565, 0.00111622, 0.0000892, 0.00029367, 0.00009957,
0.00011829, 0.00116101, 0.00016689, 0.0002766, 0.00013676, 0.00011474, 0.00016543, 0.00226173,
0.00271443, 0.00031978, 0.00043786, 0.00005865, 0.00014353, 0.00004423, 0.0010201, 0.00059006,
0.00146374, 0.00015694, 0.00019106, 0.00025222, 0.00012469, 0.00035664, 0.0001356, 0.00078461,
0.00007403, 0.00006241, 0.00016603, 0.00006452, 0.00128904, 0.00096002, 0.00025371, 0.00009757,
0.00010258, 0.00011152, 0.00048798, 0.00001985, 0.00000772, 0.02632967, 0.00092679, 0.00008446,
0.00361291, 0.00018749, 0.00011685, 0.00031176, 0.00103998, 0.00011703, 0.0000591, 0.00093484,
0.00024533, 0.00118688, 0.0036149, 0.00009009, 0.00022027, 0.00041664, 0.00284371, 0.0006018,
0.00602058, 0.00149798, 0.15748763, 0.00011435, 0.00006682, 0.0037542, 0.0001078, 0.00026274,
0.00008619, 0.00019324, 0.00010502, 0.00012287, 0.00011879, 0.00067893, 0.00005627, 0.00006336,
0.00055432, 0.00031504, 0.00040603, 0.00355545, 0.00011158, 0.00008282, 0.04019886, 0.00231227,
0.00647306, 0.00014657, 0.00019282, 0.00006875, 0.0004164, 0.00013107, 0.00015888, 0.00008512,
0.00028718, 0.00007373, 0.00054997, 0.00023758, 0.00025681, 0.00015733, 0.00030649, 0.00014579,
0.00004938, 0.02746293, 0.00040781, 0.00006825, 0.00167143, 0.00008774, 0.00147748, 0.00012296,
0.00258854, 0.00008866, 0.00037476, 0.0001592, 0.00220951, 0.00016987, 0.00160763, 0.00389916,
0.0004136, 0.00019956, 0.00073993, 0.00025418, 0.00030681, 0.00108504, 0.00062472, 0.00021854,
0.00010192, 0.00020868, 0.00009504, 0.00282833, 0.00116584, 0.00048637, 0.02013129, 0.00151616,
0.00024262, 0.00020024, 0.00011283, 0.00167862, 0.00016358, 0.00017232, 0.0008083, 0.00169295,
0.00062397, 0.0008986, 0.00365263, 0.00066525, 0.00027147, 0.00010151, 0.00034156, 0.00010335,
0.00029758, 0.00003108, 0.0002214, 0.00226411, 0.00010073, 0.00135109, 0.00008845, 0.00150138,
0.00302497, 0.0007149, 0.00143564, 0.00394565, 0.00111622, 0.0000892, 0.00029367, 0.00117171,
0.00132829, 0.00116101, 0.00016689, 0.00264472, 0.00013676, 0.00011474, 0.00016543, 0.00226173,
0.01580209, 0.00031978, 0.00043786, 0.00005865, 0.00014353, 0.00004423, 0.0010201, 0.00059006,
0.00146374, 0.00015694, 0.00019106, 0.00243986, 0.00012469, 0.00035664, 0.0001356, 0.00078461,
0.00041437, 0.00006241, 0.00016603, 0.00083962, 0.00128904, 0.00096002, 0.00025371, 0.00009757,
0.00010258, 0.00126997, 0.00048798, 0.00012892, 0.00005963, 0.18725133, 0.00092679, 0.00008446,
0.00361291, 0.00018749, 0.00011685, 0.00031176, 0.0073486, 0.00134701, 0.0000591, 0.00678647,
0.00024533, 0.00436392, 0.0036149, 0.00009009, 0.00022027, 0.00041664, 0.00696138, 0.0006018,
0.00602058, 0.00149798, 0.15748763, 0.00011435, 0.00006682, 0.0037542, 0.0001078, 0.00026274,
0.00008619, 0.00019324, 0.00010502, 0.00012287, 0.00011879, 0.00534058, 0.00005627, 0.00006336,
0.00055432, 0.00031504, 0.00040603, 0.00355545, 0.00011158, 0.00008282, 0.04019886, 0.00231227,
0.00647306, 0.00014657, 0.00019282, 0.00085577, 0.00357217, 0.00144175, 0.00172868, 0.00008512,
0.00028718, 0.00007373, 0.00054997, 0.00023758, 0.00025681, 0.00015733, 0.00030649, 0.00014579,
0.00027412, 0.1876458, 0.00040781, 0.00006825, 0.00167143, 0.00008774, 0.0099248, 0.00012296,
0.00258854, 0.00008866, 0.00037476, 0.0001592, 0.00220951, 0.00016987, 0.00160763, 0.00389916,
0.00356123, 0.00019956, 0.00073993, 0.00025418, 0.00030681, 0.00108504, 0.00062472, 0.0020974,
0.00010192, 0.00020868, 0.00009504, 0.00282833, 0.00116584, 0.00048637, 0.02013129, 0.00151616,
0.00024262, 0.0020034, 0.00127488, 0.00167862, 0.0017437, 0.00180757, 0.0008083, 0.00169295,
0.00062397, 0.0008986, 0.00365263, 0.00525022, 0.00027147, 0.00010151, 0.00306025, 0.00118163,
0.00280404, 0.00003108, 0.0002214, 0.00226411, 0.00010073, 0.00135109, 0.00104561, 0.00150138,
0.00302497, 0.00551659, 0.0095883, 0.00394565, 0.00111622, 0.0000892, 0.00029367, 0.00117171,
0.00132829, 0.00116101, 0.00176251, 0.00264472, 0.00013676, 0.00134033, 0.00181386, 0.00226173,
0.01580209, 0.00031978, 0.0037424, 0.00005865, 0.00014353, 0.0006175, 0.00721383, 0.00244284,
0.00146374, 0.00015694, 0.00019106, 0.00243986, 0.00012469, 0.00035664, 0.00148663, 0.00078461,
0.00041437, 0.00006241, 0.00179961, 0.00083962, 0.00128904, 0.00734261, 0.00245211, 0.00009757,
0.00119099, 0.00126997, 0.00409123, 0.00012892, 0.00005963, 0.18725133, 0.00681201, 0.00008446,
0.00361291, 0.00196847, 0.00011685, 0.00031176, 0.0073486, 0.00134701, 0.00076371, 0.00678647,
0.00024533, 0.00436392, 0.0036149, 0.00009009, 0.00219995, 0.00372243, 0.00696138, 0.0006018,
0.00602058, 0.00988311, 0.11151674, 0.00011435, 0.00006682, 0.0037542, 0.0001078, 0.00026274,
0.00103179, 0.00199121, 0.00010502, 0.00012287, 0.00011879, 0.00534058, 0.00075153, 0.00083855,
0.00456104, 0.00283989, 0.00040603, 0.00355545, 0.00011158, 0.00008282, 0.04019886, 0.0139271,
0.02983135, 0.00014657, 0.00197542, 0.00085577, 0.00357217, 0.00144175, 0.00172868, 0.00008512,
0.00028718, 0.00007373, 0.00054997, 0.00234124, 0.00025681, 0.00015733, 0.00280336, 0.00014579,
0.00027412, 0.1876458, 0.00368428, 0.00006825, 0.00167143, 0.00107422, 0.0099248, 0.00136444,
0.07786965, 0.0010944, 0.00037476, 0.00166506, 0.00220951, 0.00016987, 0.00160763, 0.00389916,
0.00356123, 0.00019956, 0.00073993, 0.00245732, 0.00288641, 0.00108504, 0.00504148, 0.0020974,
0.00010192, 0.00020868, 0.00009504, 0.00282833, 0.00116584, 0.00428116, 0.02013129, 0.00151616,
0.00024262, 0.0020034, 0.00127488, 0.01091868, 0.0017437, 0.00180757, 0.0008083, 0.00169295,
0.00496677, 0.0008986, 0.00365263, 0.00525022, 0.00255278, 0.00010151, 0.00306025, 0.00118163,
0.00280404, 0.0004915, 0.00234768, 0.07169721, 0.00010073, 0.00135109, 0.00104561, 0.00150138,
0.00302497, 0.00551659, 0.0095883, 0.00394565, 0.00111622, 0.00106469, 0.00029367, 0.00117171,
0.00132829, 0.00116101, 0.00176251, 0.00264472, 0.00153154, 0.00134033, 0.00181386, 0.00226173,
0.01580209, 0.00293866, 0.0037424, 0.00078797, 0.00156081, 0.0006175, 0.00721383, 0.00244284,
0.00146374, 0.00015694, 0.00197247, 0.00243986, 0.00140753, 0.00324783, 0.00148663, 0.00593737,
0.00041437, 0.00006241, 0.00179961, 0.00083962, 0.00128904, 0.00734261, 0.00245211, 0.00111559,
0.00119099, 0.00126997, 0.00409123, 0.00012892, 0.00005963, 0.18725133, 0.00681201, 0.00101241,
0.00361291, 0.00196847, 0.00132379, 0.00291747, 0.0073486, 0.00134701, 0.00076371, 0.00678647,
0.00024533, 0.00436392, 0.0036149, 0.00009009, 0.00219995, 0.00372243, 0.00696138, 0.00484881,
0.00602058, 0.00988311, 0.11151674, 0.00011435, 0.00006682, 0.02072832, 0.00123781, 0.00249714,
0.00103179, 0.00199121, 0.00122812, 0.00133866, 0.00135082, 0.00534058, 0.00075153, 0.00083855,
0.00456104, 0.00283989, 0.00357729, 0.00355545, 0.00129434, 0.00008282, 0.20509902, 0.0139271,
0.02983135, 0.00014657, 0.00197542, 0.00085577, 0.00357217, 0.00144175, 0.00172868, 0.00102264,
0.00275928, 0.00095099, 0.00453496, 0.00234124, 0.00256181, 0.00167844, 0.00280336, 0.00163364,
0.00027412, 0.1876458, 0.00368428, 0.00006825, 0.06283662, 0.00107422, 0.0099248, 0.00136444,
0.07786965, 0.0010944, 0.00334731, 0.00166506, 0.07118574, 0.00016987, 0.06109977, 0.00389916,
0.00356123, 0.00019956, 0.00073993, 0.00245732, 0.00288641, 0.00108504, 0.00504148, 0.0020974,
0.00120625, 0.00213173, 0.00118345, 0.00282833, 0.00116584, 0.00428116, 0.1723538, 0.06069371,
0.00024262, 0.0020034, 0.00127488, 0.01091868, 0.0017437, 0.00180757, 0.04408795, 0.00169295,
0.00496677, 0.0008986, 0.08899134, 0.00525022, 0.00255278, 0.00121656, 0.00306025, 0.00118163,
0.00280404, 0.0004915, 0.00234768, 0.07169721, 0.00010073, 0.00946453, 0.00104561, 0.00150138,
0.00302497, 0.00551659, 0.0095883, 0.09221488, 0.0504449, 0.00106469, 0.00278428, 0.00117171,
0.00132829, 0.05134639, 0.00176251, 0.00264472, 0.00153154, 0.00134033, 0.00181386, 0.07077682,
0.01580209, 0.00293866, 0.0037424, 0.00078797, 0.00156081, 0.0006175, 0.00721383, 0.00244284,
0.0579361, 0.0017038, 0.00197247, 0.00243986, 0.00140753, 0.00324783, 0.00148663, 0.00593737,
0.00041437, 0.00091988, 0.00179961, 0.00083962, 0.05586374, 0.00734261, 0.00245211, 0.00111559,
0.00119099, 0.00126997, 0.00409123, 0.00012892, 0.00005963, 0.18725133, 0.00681201, 0.00101241,
0.01185927, 0.00196847, 0.00132379, 0.00291747, 0.0073486, 0.00134701, 0.00076371, 0.00678647,
0.0024395, 0.00436392, 0.09182414, 0.00108629, 0.00219995, 0.00372243, 0.00696138, 0.00484881,
0.11306641, 0.00988311, 0.11151674, 0.00134221, 0.00089082, 0.02072832, 0.00123781, 0.00249714,
0.00103179, 0.00199121, 0.00122812, 0.00133866, 0.00135082, 0.00534058, 0.00075153, 0.00083855,
0.00456104, 0.00283989, 0.00357729, 0.08941841, 0.00129434, 0.00101602, 0.20509902, 0.0139271,
0.02983135, 0.00155309, 0.00197542, 0.00085577, 0.00357217, 0.00144175, 0.00172868, 0.00102264,
0.00275928, 0.00095099, 0.00453496, 0.00234124, 0.00256181, 0.00167844, 0.00280336, 0.00163364,
0.00027412, 0.1876458, 0.00368428, 0.00085694, 0.06283662, 0.00107422, 0.0099248, 0.00136444,
0.07786965, 0.0010944, 0.00334731, 0.00166506, 0.07118574, 0.00184241, 0.06109977, 0.09547165,
0.00356123, 0.00215003, 0.04141349, 0.00245732, 0.00288641, 0.00807175, 0.00504148, 0.0020974,
0.00120625, 0.00213173, 0.00118345, 0.01678693, 0.05250749, 0.00428116, 0.1723538, 0.06069371,
0.00238824, 0.0020034, 0.00127488, 0.01091868, 0.0017437, 0.00180757, 0.04408795, 0.06401992,
0.00496677, 0.04745361, 0.08899134, 0.00525022, 0.00255278, 0.00121656, 0.00306025, 0.00118163,
0.00280404, 0.0004915, 0.00234768, 0.07169721, 0.00117919, 0.00946453, 0.00104561, 0.05963156,
0.08467317, 0.00551659, 0.0095883, 0.09221488, 0.0504449, 0.00106469, 0.00278428, 0.05256888,
0.0556742, 0.05134639, 0.00176251, 0.08098838, 0.00153154, 0.00134033, 0.00181386, 0.07077682,
0.16114199, 0.00293866, 0.0037424, 0.00078797, 0.00156081, 0.0006175, 0.00721383, 0.00244284,
0.0579361, 0.0017038, 0.00197247, 0.07445812, 0.00140753, 0.00324783, 0.00148663, 0.00593737,
0.00403398, 0.00091988, 0.00179961, 0.04596084, 0.05586374, 0.00734261, 0.00245211, 0.00111559,
0.00119099, 0.05606791, 0.00409123, 0.00142655, 0.00082061, 0.5607718, 0.00681201, 0.00101241,
0.01185927, 0.00196847, 0.00132379, 0.00291747, 0.1201914, 0.05680764, 0.00076371, 0.11630166,
0.0024395, 0.02359119, 0.09182414, 0.00108629, 0.00219995, 0.00372243, 0.02024356, 0.00484881,
0.11306641, 0.00988311, 0.11151674, 0.00134221, 0.00089082, 0.02072832, 0.00123781, 0.00249714,
0.00103179, 0.00199121, 0.00122812, 0.00133866, 0.00135082, 0.10662499, 0.00075153, 0.00083855,
0.00456104, 0.00283989, 0.00357729, 0.08941841, 0.00129434, 0.00101602, 0.20509902, 0.0139271,
0.02983135, 0.00155309, 0.00197542, 0.04456154, 0.08931115, 0.05876806, 0.06591743, 0.00102264,
0.00275928, 0.00095099, 0.00453496, 0.00234124, 0.00256181, 0.00167844, 0.00280336, 0.00163364,
0.00259417, 0.55904055, 0.00368428, 0.00085694, 0.06283662, 0.00107422, 0.13763326, 0.00136444,
0.07786965, 0.0010944, 0.00334731, 0.00166506, 0.07118574, 0.00184241, 0.06109977, 0.09547165,
0.08777454, 0.00215003, 0.04141349, 0.00245732, 0.00288641, 0.00807175, 0.00504148, 0.0694761,
0.00120625, 0.00213173, 0.00118345, 0.01678693, 0.05250749, 0.00428116, 0.1723538, 0.06069371,
0.00238824, 0.0684669, 0.05362549, 0.01091868, 0.06445098, 0.06545544, 0.04408795, 0.06401992,
0.00496677, 0.04745361, 0.08899134, 0.10613319, 0.00255278, 0.00121656, 0.0836997, 0.05249813,
0.08057874, 0.0004915, 0.00234768, 0.07169721, 0.00117919, 0.00946453, 0.05012465, 0.05963156,
0.08467317, 0.10664308, 0.1364629, 0.09221488, 0.0504449, 0.00106469, 0.00278428, 0.05256888,
0.0556742, 0.05134639, 0.06397066, 0.08098838, 0.00153154, 0.05767852, 0.06829494, 0.07077682,
0.16114199, 0.00293866, 0.08930382, 0.00078797, 0.00156081, 0.03878433, 0.11871937, 0.01549688,
0.0579361, 0.0017038, 0.00197247, 0.07445812, 0.00140753, 0.00324783, 0.05798522, 0.00593737,
0.00403398, 0.00091988, 0.06694564, 0.04596084, 0.05586374, 0.1284537, 0.07561344, 0.00111559,
0.05335674, 0.05606791, 0.09769404, 0.00142655, 0.00082061, 0.5607718, 0.12018207, 0.00101241,
0.01185927, 0.06859747, 0.00132379, 0.00291747, 0.1201914, 0.05680764, 0.04211965, 0.11630166,
0.0024395, 0.02359119, 0.09182414, 0.00108629, 0.07154921, 0.09385532, 0.02024356, 0.00484881,
0.11306641, 0.13692307, 0.06509548, 0.00134221, 0.00089082, 0.02072832, 0.00123781, 0.00249714,
0.04984915, 0.06897187, 0.00122812, 0.00133866, 0.00135082, 0.10662499, 0.04467908, 0.04521033,
0.10090852, 0.08095402, 0.00357729, 0.08941841, 0.00129434, 0.00101602, 0.20509902, 0.15650138,
0.1917508, 0.00155309, 0.06792396, 0.04456154, 0.08931115, 0.05876806, 0.06591743, 0.00102264,
0.00275928, 0.00095099, 0.00453496, 0.07487273, 0.00256181, 0.00167844, 0.08059016, 0.00163364,
0.00259417, 0.55904055, 0.09325081, 0.00085694, 0.06283662, 0.05065069, 0.13763326, 0.05743286,
0.8414644, 0.05094713, 0.00334731, 0.06372774, 0.07118574, 0.00184241, 0.06109977, 0.09547165,
0.08777454, 0.00215003, 0.04141349, 0.07630339, 0.08359447, 0.00807175, 0.10810232, 0.0694761,
0.00120625, 0.00213173, 0.00118345, 0.01678693, 0.05250749, 0.1029087, 0.1723538, 0.06069371,
0.00238824, 0.0684669, 0.05362549, 0.1439383, 0.06445098, 0.06545544, 0.04408795, 0.06401992,
0.10541373, 0.04745361, 0.08899134, 0.10613319, 0.07658425, 0.00121656, 0.0836997, 0.05249813,
0.08057874, 0.03694367, 0.07949173, 0.8544947, 0.00117919, 0.00946453, 0.05012465, 0.05963156,
0.08467317, 0.10664308, 0.1364629, 0.09221488, 0.0504449, 0.05025387, 0.00278428, 0.05256888,
0.0556742, 0.05134639, 0.06397066, 0.08098838, 0.05996007, 0.05767852, 0.06829494, 0.07077682,
0.16114199, 0.08350655, 0.08930382, 0.04489601, 0.06073031, 0.03878433, 0.11871937, 0.01549688,
0.0579361, 0.0017038, 0.07059672, 0.07445812, 0.06029746, 0.08666882, 0.05798522, 0.11222455,
0.00403398, 0.00091988, 0.06694564, 0.04596084, 0.05586374, 0.1284537, 0.07561344, 0.05159721,
0.05335674, 0.05606791, 0.09769404, 0.00142655, 0.00082061, 0.5607718, 0.12018207, 0.04932827,
0.01185927, 0.06859747, 0.05731028, 0.08264509, 0.1201914, 0.05680764, 0.04211965, 0.11630166,
0.0024395, 0.02359119, 0.09182414, 0.00108629, 0.07154921, 0.09385532, 0.02024356, 0.10391364,
0.11306641, 0.13692307, 0.06509548, 0.00134221, 0.00089082, 0.17759195, 0.05397317, 0.07817352,
0.04984915, 0.06897187, 0.05357096, 0.05645683, 0.0575192, 0.10662499, 0.04467908, 0.04521033,
0.10090852, 0.08095402, 0.09019101, 0.08941841, 0.05697304, 0.00101602, 0.48060423, 0.15650138,
0.1917508, 0.00155309, 0.06792396, 0.04456154, 0.08931115, 0.05876806, 0.06591743, 0.04945666,
0.08148026, 0.04801679, 0.09971181, 0.07487273, 0.0791733, 0.0632391, 0.08059016, 0.0642955,
0.00259417, 0.55904055, 0.09325081, 0.00085694, 0.8726438, 0.05065069, 0.13763326, 0.05743286,
0.8414644, 0.05094713, 0.08865264, 0.06372774, 0.85657144, 0.00184241, 0.87605, 0.09547165,
0.08777454, 0.00215003, 0.04141349, 0.07630339, 0.08359447, 0.00807175, 0.10810232, 0.0694761,
0.05555928, 0.07140756, 0.054342, 0.01678693, 0.05250749, 0.1029087, 0.6082734, 0.8749311,
0.00238824, 0.0684669, 0.05362549, 0.1439383, 0.06445098, 0.06545544, 0.91050136, 0.06401992,
0.10541373, 0.04745361, 0.81968355, 0.10613319, 0.07658425, 0.05501693, 0.0836997, 0.05249813,
0.08057874, 0.03694367, 0.07949173, 0.8544947, 0.00117919, 0.13987815, 0.05012465, 0.05963156,
0.08467317, 0.10664308, 0.1364629, 0.8129145, 0.901198, 0.05025387, 0.08217692, 0.05256888,
0.0556742, 0.89633656, 0.06397066, 0.08098838, 0.05996007, 0.05767852, 0.06829494, 0.8570231,
0.16114199, 0.08350655, 0.08930382, 0.04489601, 0.06073031, 0.03878433, 0.11871937, 0.01549688,
0.88383365, 0.0643093, 0.07059672, 0.07445812, 0.06029746, 0.08666882, 0.05798522, 0.11222455,
0.00403398, 0.05371317, 0.06694564, 0.04596084, 0.883718, 0.1284537, 0.07561344, 0.05159721,
0.05335674, 0.05606791, 0.09769404, 0.00142655, 0.00082061, 0.5607718, 0.12018207, 0.04932827,
0.05006891, 0.06859747, 0.05731028, 0.08264509, 0.1201914, 0.05680764, 0.04211965, 0.11630166,
0.07859802, 0.02359119, 0.8057381, 0.05181158, 0.07154921, 0.09385532, 0.02024356, 0.10391364,
0.76164925, 0.13692307, 0.06509548, 0.05664554, 0.04917243, 0.17759195, 0.05397317, 0.07817352,
0.04984915, 0.06897187, 0.05357096, 0.05645683, 0.0575192, 0.10662499, 0.04467908, 0.04521033,
0.10090852, 0.08095402, 0.09019101, 0.8163814, 0.05697304, 0.05106667, 0.48060423, 0.15650138,
0.1917508, 0.0586223, 0.06792396, 0.04456154, 0.08931115, 0.05876806, 0.06591743, 0.04945666,
0.08148026, 0.04801679, 0.09971181, 0.07487273, 0.0791733, 0.0632391, 0.08059016, 0.0642955,
0.00259417, 0.55904055, 0.09325081, 0.0460805, 0.8726438, 0.05065069, 0.13763326, 0.05743286,
0.8414644, 0.05094713, 0.08865264, 0.06372774, 0.85657144, 0.06823337, 0.87605, 0.7969105,
0.08777454, 0.07725197, 0.91682243, 0.07630339, 0.08359447, 0.12941176, 0.10810232, 0.0694761,
0.05555928, 0.07140756, 0.054342, 0.16767746, 0.895396, 0.1029087, 0.6082734, 0.8749311,
0.07669553, 0.0684669, 0.05362549, 0.1439383, 0.06445098, 0.06545544, 0.91050136, 0.8685583,
0.10541373, 0.89928746, 0.81968355, 0.10613319, 0.07658425, 0.05501693, 0.0836997, 0.05249813,
0.08057874, 0.03694367, 0.07949173, 0.8544947, 0.0542697, 0.13987815, 0.05012465, 0.8777895,
0.8243624, 0.10664308, 0.1364629, 0.8129145, 0.901198, 0.05025387, 0.08217692, 0.8936882,
0.8877065, 0.89633656, 0.06397066, 0.82829916, 0.05996007, 0.05767852, 0.06829494, 0.8570231,
0.6433294, 0.08350655, 0.08930382, 0.04489601, 0.06073031, 0.03878433, 0.11871937, 0.01549688,
0.88383365, 0.0643093, 0.07059672, 0.8494234, 0.06029746, 0.08666882, 0.05798522, 0.11222455,
0.10434505, 0.05371317, 0.06694564, 0.90392756, 0.883718, 0.1284537, 0.07561344, 0.05159721,
0.05335674, 0.88208985, 0.09769404, 0.05902085, 0.04716936, 0.18726319, 0.12018207, 0.04932827,
0.05006891, 0.06859747, 0.05731028, 0.08264509, 0.74668074, 0.8849905, 0.04211965, 0.75614476,
0.07859802, 0.18736437, 0.8057381, 0.05181158, 0.07154921, 0.09385532, 0.06958741, 0.10391364,
0.76164925, 0.13692307, 0.06509548, 0.05664554, 0.04917243, 0.17759195, 0.05397317, 0.07817352,
0.04984915, 0.06897187, 0.05357096, 0.05645683, 0.0575192, 0.77812827, 0.04467908, 0.04521033,
0.10090852, 0.08095402, 0.09019101, 0.8163814, 0.05697304, 0.05106667, 0.48060423, 0.15650138,
0.1917508, 0.0586223, 0.06792396, 0.9099586, 0.8144233, 0.8782998, 0.8627554, 0.04945666,
0.08148026, 0.04801679, 0.09971181, 0.07487273, 0.0791733, 0.0632391, 0.08059016, 0.0642955,
0.08050439, 0.18770587, 0.09325081, 0.0460805, 0.8726438, 0.05065069, 0.7036953, 0.05743286,
0.8414644, 0.05094713, 0.08865264, 0.06372774, 0.85657144, 0.06823337, 0.87605, 0.7969105,
0.8241409, 0.07725197, 0.91682243, 0.07630339, 0.08359447, 0.12941176, 0.10810232, 0.85597414,
0.05555928, 0.07140756, 0.054342, 0.16767746, 0.895396, 0.1029087, 0.6082734, 0.8749311,
0.07669553, 0.8589487, 0.89613384, 0.1439383, 0.8677505, 0.86478317, 0.91050136, 0.8685583,
0.10541373, 0.89928746, 0.81968355, 0.7764456, 0.07658425, 0.05501693, 0.8257015, 0.89306235,
0.834512, 0.03694367, 0.07949173, 0.8544947, 0.0542697, 0.13987815, 0.89570355, 0.8777895,
0.8243624, 0.7804407, 0.7036059, 0.8129145, 0.901198, 0.05025387, 0.08217692, 0.8936882,
0.8877065, 0.89633656, 0.8706768, 0.82829916, 0.05996007, 0.88194877, 0.85756874, 0.8570231,
0.6433294, 0.08350655, 0.82120705, 0.04489601, 0.06073031, 0.9202901, 0.75231653, 0.1658409,
0.88383365, 0.0643093, 0.07059672, 0.8494234, 0.06029746, 0.08666882, 0.8846772, 0.11222455,
0.10434505, 0.05371317, 0.8620441, 0.90392756, 0.883718, 0.71831596, 0.84481394, 0.05159721,
0.8905785, 0.88208985, 0.7911752, 0.05902085, 0.04716936, 0.18726319, 0.7425746, 0.04932827,
0.05006891, 0.85987055, 0.05731028, 0.08264509, 0.74668074, 0.8849905, 0.914279, 0.75614476,
0.07859802, 0.18736437, 0.8057381, 0.05181158, 0.8538587, 0.8024919, 0.06958741, 0.10391364,
0.76164925, 0.7051737, 0.03472066, 0.05664554, 0.04917243, 0.17759195, 0.05397317, 0.07817352,
0.897732, 0.85832596, 0.05357096, 0.05645683, 0.0575192, 0.77812827, 0.9036199, 0.90888894,
0.7871765, 0.8311273, 0.09019101, 0.8163814, 0.05697304, 0.05106667, 0.48060423, 0.6506678,
0.54044604, 0.0586223, 0.86272025, 0.9099586, 0.8144233, 0.8782998, 0.8627554, 0.04945666,
0.08148026, 0.04801679, 0.09971181, 0.8461373, 0.0791733, 0.0632391, 0.83341396, 0.0642955,
0.08050439, 0.18770587, 0.80429196, 0.0460805, 0.8726438, 0.8983611, 0.7036953, 0.88040733,
0.07527992, 0.8993358, 0.08865264, 0.8654097, 0.85657144, 0.06823337, 0.87605, 0.7969105,
0.8241409, 0.07725197, 0.91682243, 0.8427737, 0.82374185, 0.12941176, 0.7682617, 0.85597414,
0.05555928, 0.07140756, 0.054342, 0.16767746, 0.895396, 0.7774577, 0.6082734, 0.8749311,
0.07669553, 0.8589487, 0.89613384, 0.6838312, 0.8677505, 0.86478317, 0.91050136, 0.8685583,
0.77612627, 0.89928746, 0.81968355, 0.7764456, 0.84303474, 0.05501693, 0.8257015, 0.89306235,
0.834512, 0.91994524, 0.8303048, 0.06916997, 0.0542697, 0.13987815, 0.89570355, 0.8777895,
0.8243624, 0.7804407, 0.7036059, 0.8129145, 0.901198, 0.8971911, 0.08217692, 0.8936882,
0.8877065, 0.89633656, 0.8706768, 0.82829916, 0.8802587, 0.88194877, 0.85756874, 0.8570231,
0.6433294, 0.8246695, 0.82120705, 0.9066945, 0.87579954, 0.9202901, 0.75231653, 0.1658409,
0.88383365, 0.0643093, 0.8492942, 0.8494234, 0.87110424, 0.8209583, 0.8846772, 0.7618023,
0.10434505, 0.05371317, 0.8620441, 0.90392756, 0.883718, 0.71831596, 0.84481394, 0.8926691,
0.8905785, 0.88208985, 0.7911752, 0.05902085, 0.04716936, 0.18726319, 0.7425746, 0.89788043,
0.05006891, 0.85987055, 0.88027894, 0.8294249, 0.74668074, 0.8849905, 0.914279, 0.75614476,
0.07859802, 0.18736437, 0.8057381, 0.05181158, 0.8538587, 0.8024919, 0.06958741, 0.7825513,
0.76164925, 0.7051737, 0.03472066, 0.05664554, 0.04917243, 0.5921409, 0.891099, 0.8356217,
0.897732, 0.85832596, 0.8925878, 0.8828648, 0.881287, 0.77812827, 0.9036199, 0.90888894,
0.7871765, 0.8311273, 0.81167185, 0.8163814, 0.882864, 0.05106667, 0.20638701, 0.6506678,
0.54044604, 0.0586223, 0.86272025, 0.9099586, 0.8144233, 0.8782998, 0.8627554, 0.8975127,
0.8299825, 0.90282845, 0.79186463, 0.8461373, 0.83594143, 0.8727574, 0.83341396, 0.8658649,
0.08050439, 0.18770587, 0.80429196, 0.0460805, 0.06099761, 0.8983611, 0.7036953, 0.88040733,
0.07527992, 0.8993358, 0.8133875, 0.8654097, 0.06794932, 0.06823337, 0.05955291, 0.7969105,
0.8241409, 0.07725197, 0.91682243, 0.8427737, 0.82374185, 0.12941176, 0.7682617, 0.85597414,
0.88248694, 0.85288113, 0.8906687, 0.16767746, 0.895396, 0.7774577, 0.1718246, 0.061077,
0.07669553, 0.8589487, 0.89613384, 0.6838312, 0.8677505, 0.86478317, 0.04365623, 0.8685583,
0.77612627, 0.89928746, 0.08402699, 0.7764456, 0.84303474, 0.8869784, 0.8257015, 0.89306235,
0.834512, 0.91994524, 0.8303048, 0.06916997, 0.0542697, 0.6918363, 0.89570355, 0.8777895,
0.8243624, 0.7804407, 0.7036059, 0.08698645, 0.04627696, 0.8971911, 0.82726204, 0.8936882,
0.8877065, 0.04999214, 0.8706768, 0.82829916, 0.8802587, 0.88194877, 0.85756874, 0.06771582,
0.6433294, 0.8246695, 0.82120705, 0.9066945, 0.87579954, 0.9202901, 0.75231653, 0.1658409,
0.05530539, 0.86786497, 0.8492942, 0.8494234, 0.87110424, 0.8209583, 0.8846772, 0.7618023,
0.10434505, 0.8831587, 0.8620441, 0.90392756, 0.05750066, 0.71831596, 0.84481394, 0.8926691,
0.8905785, 0.88208985, 0.7911752, 0.05902085, 0.04716936, 0.18726319, 0.7425746, 0.89788043,
0.21912381, 0.85987055, 0.88027894, 0.8294249, 0.74668074, 0.8849905, 0.914279, 0.75614476,
0.8323419, 0.18736437, 0.09383032, 0.89232653, 0.8538587, 0.8024919, 0.06958741, 0.7825513,
0.11186543, 0.7051737, 0.03472066, 0.88630444, 0.89457256, 0.5921409, 0.891099, 0.8356217,
0.897732, 0.85832596, 0.8925878, 0.8828648, 0.881287, 0.77812827, 0.9036199, 0.90888894,
0.7871765, 0.8311273, 0.81167185, 0.0867404, 0.882864, 0.8919127, 0.20638701, 0.6506678,
0.54044604, 0.8847536, 0.86272025, 0.9099586, 0.8144233, 0.8782998, 0.8627554, 0.8975127,
0.8299825, 0.90282845, 0.79186463, 0.8461373, 0.83594143, 0.8727574, 0.83341396, 0.8658649,
0.08050439, 0.18770587, 0.80429196, 0.9031364, 0.06099761, 0.8983611, 0.7036953, 0.88040733,
0.07527992, 0.8993358, 0.8133875, 0.8654097, 0.06794932, 0.85722053, 0.05955291, 0.09812751,
0.8241409, 0.8334694, 0.04023388, 0.8427737, 0.82374185, 0.723374, 0.7682617, 0.85597414,
0.88248694, 0.85288113, 0.8906687, 0.6210257, 0.04972553, 0.7774577, 0.1718246, 0.061077,
0.83924717, 0.8589487, 0.89613384, 0.6838312, 0.8677505, 0.86478317, 0.04365623, 0.06382826,
0.77612627, 0.0510813, 0.08402699, 0.7764456, 0.84303474, 0.8869784, 0.8257015, 0.89306235,
0.834512, 0.91994524, 0.8303048, 0.06916997, 0.8853345, 0.6918363, 0.89570355, 0.05935162,
0.08419314, 0.7804407, 0.7036059, 0.08698645, 0.04627696, 0.8971911, 0.82726204, 0.05122954,
0.05385739, 0.04999214, 0.8706768, 0.08416823, 0.8802587, 0.88194877, 0.85756874, 0.06771582,
0.15922159, 0.8246695, 0.82120705, 0.9066945, 0.87579954, 0.9202901, 0.75231653, 0.1658409,
0.05530539, 0.86786497, 0.8492942, 0.07109526, 0.87110424, 0.8209583, 0.8846772, 0.7618023,
0.77270293, 0.8831587, 0.8620441, 0.048112, 0.05750066, 0.71831596, 0.84481394, 0.8926691,
0.8905785, 0.05884066, 0.7911752, 0.8772712, 0.90008557, 0.02411205, 0.7425746, 0.89788043,
0.21912381, 0.85987055, 0.88027894, 0.8294249, 0.11723101, 0.05533674, 0.914279, 0.11309293,
0.8323419, 0.5601175, 0.09383032, 0.89232653, 0.8538587, 0.8024919, 0.22067052, 0.7825513,
0.11186543, 0.7051737, 0.03472066, 0.88630444, 0.89457256, 0.5921409, 0.891099, 0.8356217,
0.897732, 0.85832596, 0.8925878, 0.8828648, 0.881287, 0.10379472, 0.9036199, 0.90888894,
0.7871765, 0.8311273, 0.81167185, 0.0867404, 0.882864, 0.8919127, 0.20638701, 0.6506678,
0.54044604, 0.8847536, 0.86272025, 0.04371148, 0.08835551, 0.05968317, 0.06722918, 0.8975127,
0.8299825, 0.90282845, 0.79186463, 0.8461373, 0.83594143, 0.8727574, 0.83341396, 0.8658649,
0.8286029, 0.02354819, 0.80429196, 0.9031364, 0.06099761, 0.8983611, 0.13584837, 0.88040733,
0.07527992, 0.8993358, 0.8133875, 0.8654097, 0.06794932, 0.85722053, 0.05955291, 0.09812751,
0.08132082, 0.8334694, 0.04023388, 0.8427737, 0.82374185, 0.723374, 0.7682617, 0.06990317,
0.88248694, 0.85288113, 0.8906687, 0.6210257, 0.04972553, 0.7774577, 0.1718246, 0.061077,
0.83924717, 0.06819576, 0.04795229, 0.6838312, 0.06396237, 0.06573203, 0.04365623, 0.06382826,
0.77612627, 0.0510813, 0.08402699, 0.1054965, 0.84303474, 0.8869784, 0.08372089, 0.05194348,
0.07883495, 0.91994524, 0.8303048, 0.06916997, 0.8853345, 0.6918363, 0.0517723, 0.05935162,
0.08419314, 0.10159352, 0.1368002, 0.08698645, 0.04627696, 0.8971911, 0.82726204, 0.05122954,
0.05385739, 0.04999214, 0.06167814, 0.08416823, 0.8802587, 0.05736792, 0.0697847, 0.06771582,
0.15922159, 0.8246695, 0.08239546, 0.9066945, 0.87579954, 0.03954163, 0.11373714, 0.62817,
0.05530539, 0.86786497, 0.8492942, 0.07109526, 0.87110424, 0.8209583, 0.05442351, 0.7618023,
0.77270293, 0.8831587, 0.06692463, 0.048112, 0.05750066, 0.13326734, 0.07421702, 0.8926691,
0.05345723, 0.05884066, 0.10094288, 0.8772712, 0.90008557, 0.02411205, 0.12095198, 0.89788043,
0.21912381, 0.06721494, 0.88027894, 0.8294249, 0.11723101, 0.05533674, 0.042016, 0.11309293,
0.8323419, 0.5601175, 0.09383032, 0.89232653, 0.06987256, 0.09487528, 0.22067052, 0.7825513,
0.11186543, 0.13534436, 0.01836181, 0.88630444, 0.89457256, 0.5921409, 0.891099, 0.8356217,
0.05011776, 0.0683077, 0.8925878, 0.8828648, 0.881287, 0.10379472, 0.04967177, 0.04411417,
0.10122958, 0.08153421, 0.81167185, 0.0867404, 0.882864, 0.8919127, 0.20638701, 0.15747982,
0.19234109, 0.8847536, 0.06526124, 0.04371148, 0.08835551, 0.05968317, 0.06722918, 0.8975127,
0.8299825, 0.90282845, 0.79186463, 0.07392329, 0.83594143, 0.8727574, 0.07987085, 0.8658649,
0.8286029, 0.02354819, 0.09368655, 0.9031364, 0.06099761, 0.04876363, 0.13584837, 0.05902252,
0.00220585, 0.04752943, 0.8133875, 0.06682745, 0.06794932, 0.85722053, 0.05955291, 0.09812751,
0.08132082, 0.8334694, 0.04023388, 0.07545695, 0.08570319, 0.723374, 0.11103037, 0.06990317,
0.88248694, 0.85288113, 0.8906687, 0.6210257, 0.04972553, 0.10812089, 0.1718246, 0.061077,
0.83924717, 0.06819576, 0.04795229, 0.14481401, 0.06396237, 0.06573203, 0.04365623, 0.06382826,
0.10666651, 0.0510813, 0.08402699, 0.1054965, 0.0749554, 0.8869784, 0.08372089, 0.05194348,
0.07883495, 0.04171562, 0.0840168, 0.0018771, 0.8853345, 0.6918363, 0.0517723, 0.05935162,
0.08419314, 0.10159352, 0.1368002, 0.08698645, 0.04627696, 0.05024266, 0.82726204, 0.05122954,
0.05385739, 0.04999214, 0.06167814, 0.08416823, 0.05668899, 0.05736792, 0.0697847, 0.06771582,
0.15922159, 0.08511311, 0.08239546, 0.04653519, 0.06011224, 0.03954163, 0.11373714, 0.62817,
0.05530539, 0.86786497, 0.07507476, 0.07109526, 0.06496084, 0.08522177, 0.05442351, 0.1122131,
0.77270293, 0.8831587, 0.06692463, 0.048112, 0.05750066, 0.13326734, 0.07421702, 0.05319288,
0.05345723, 0.05884066, 0.10094288, 0.8772712, 0.90008557, 0.02411205, 0.12095198, 0.05051127,
0.21912381, 0.06721494, 0.05931064, 0.08143798, 0.11723101, 0.05533674, 0.042016, 0.11309293,
0.8323419, 0.5601175, 0.09383032, 0.89232653, 0.06987256, 0.09487528, 0.22067052, 0.10290858,
0.11186543, 0.13534436, 0.01836181, 0.88630444, 0.89457256, 0.177407, 0.05233279, 0.08020887,
0.05011776, 0.0683077, 0.05131751, 0.05770358, 0.05811858, 0.10379472, 0.04967177, 0.04411417,
0.10122958, 0.08153421, 0.09008676, 0.0867404, 0.05715263, 0.8919127, 0.03897297, 0.15747982,
0.19234109, 0.8847536, 0.06526124, 0.04371148, 0.08835551, 0.05968317, 0.06722918, 0.05071405,
0.0821006, 0.04709196, 0.09838042, 0.07392329, 0.07904652, 0.06049165, 0.07987085, 0.06593019,
0.8286029, 0.02354819, 0.09368655, 0.9031364, 0.00150132, 0.04876363, 0.13584837, 0.05902252,
0.00220585, 0.04752943, 0.09000364, 0.06682745, 0.00164565, 0.85722053, 0.00137171, 0.09812751,
0.08132082, 0.8334694, 0.04023388, 0.07545695, 0.08570319, 0.723374, 0.11103037, 0.06990317,
0.05889845, 0.07095593, 0.05249947, 0.6210257, 0.04972553, 0.10812089, 0.01772964, 0.00146189,
0.83924717, 0.06819576, 0.04795229, 0.14481401, 0.06396237, 0.06573203, 0.00080231, 0.06382826,
0.10666651, 0.0510813, 0.00276518, 0.1054965, 0.0749554, 0.05525097, 0.08372089, 0.05194348,
0.07883495, 0.04171562, 0.0840168, 0.0018771, 0.8853345, 0.14300928, 0.0517723, 0.05935162,
0.08419314, 0.10159352, 0.1368002, 0.00297078, 0.0007866, 0.05024266, 0.08387303, 0.05122954,
0.05385739, 0.000958, 0.06167814, 0.08416823, 0.05668899, 0.05736792, 0.0697847, 0.00174549,
0.15922159, 0.08511311, 0.08239546, 0.04653519, 0.06011224, 0.03954163, 0.11373714, 0.62817,
0.0011858, 0.06400746, 0.07507476, 0.07109526, 0.06496084, 0.08522177, 0.05442351, 0.1122131,
0.77270293, 0.06030846, 0.06692463, 0.048112, 0.00135455, 0.13326734, 0.07421702, 0.05319288,
0.05345723, 0.05884066, 0.10094288, 0.8772712, 0.90008557, 0.02411205, 0.12095198, 0.05051127,
0.41833147, 0.06721494, 0.05931064, 0.08143798, 0.11723101, 0.05533674, 0.042016, 0.11309293,
0.08273876, 0.5601175, 0.00390905, 0.05333331, 0.06987256, 0.09487528, 0.22067052, 0.10290858,
0.00552109, 0.13534436, 0.01836181, 0.05424494, 0.05386925, 0.177407, 0.05233279, 0.08020887,
0.05011776, 0.0683077, 0.05131751, 0.05770358, 0.05811858, 0.10379472, 0.04967177, 0.04411417,
0.10122958, 0.08153421, 0.09008676, 0.00300497, 0.05715263, 0.05447432, 0.03897297, 0.15747982,
0.19234109, 0.05374959, 0.06526124, 0.04371148, 0.08835551, 0.05968317, 0.06722918, 0.05071405,
0.0821006, 0.04709196, 0.09838042, 0.07392329, 0.07904652, 0.06049165, 0.07987085, 0.06593019,
0.8286029, 0.02354819, 0.09368655, 0.04874086, 0.00150132, 0.04876363, 0.13584837, 0.05902252,
0.00220585, 0.04752943, 0.09000364, 0.06682745, 0.00164565, 0.07004488, 0.00137171, 0.00436196,
0.08132082, 0.08324245, 0.00066909, 0.07545695, 0.08570319, 0.1283072, 0.11103037, 0.06990317,
0.05889845, 0.07095593, 0.05249947, 0.16853261, 0.00099424, 0.10812089, 0.01772964, 0.00146189,
0.07849872, 0.06819576, 0.04795229, 0.14481401, 0.06396237, 0.06573203, 0.00080231, 0.0015493,
0.10666651, 0.00109288, 0.00276518, 0.1054965, 0.0749554, 0.05525097, 0.08372089, 0.05194348,
0.07883495, 0.04171562, 0.0840168, 0.0018771, 0.05755261, 0.14300928, 0.0517723, 0.00141537,
0.00295693, 0.10159352, 0.1368002, 0.00297078, 0.0007866, 0.05024266, 0.08387303, 0.00110948,
0.00117564, 0.000958, 0.06167814, 0.00313523, 0.05668899, 0.05736792, 0.0697847, 0.00174549,
0.01377538, 0.08511311, 0.08239546, 0.04653519, 0.06011224, 0.03954163, 0.11373714, 0.62817,
0.0011858, 0.06400746, 0.07507476, 0.00203273, 0.06496084, 0.08522177, 0.05442351, 0.1122131,
0.11111701, 0.06030846, 0.06692463, 0.00099021, 0.00135455, 0.13326734, 0.07421702, 0.05319288,
0.05345723, 0.00144777, 0.10094288, 0.06043282, 0.05066103, 0.00450966, 0.12095198, 0.05051127,
0.41833147, 0.06721494, 0.05931064, 0.08143798, 0.00616276, 0.00124928, 0.042016, 0.00556803,
0.08273876, 0.18670154, 0.00390905, 0.05333331, 0.06987256, 0.09487528, 0.34697795, 0.10290858,
0.00552109, 0.13534436, 0.01836181, 0.05424494, 0.05386925, 0.177407, 0.05233279, 0.08020887,
0.05011776, 0.0683077, 0.05131751, 0.05770358, 0.05811858, 0.00456572, 0.04967177, 0.04411417,
0.10122958, 0.08153421, 0.09008676, 0.00300497, 0.05715263, 0.05447432, 0.03897297, 0.15747982,
0.19234109, 0.05374959, 0.06526124, 0.00076771, 0.00334865, 0.00149041, 0.0019449, 0.05071405,
0.0821006, 0.04709196, 0.09838042, 0.07392329, 0.07904652, 0.06049165, 0.07987085, 0.06593019,
0.08447334, 0.00426695, 0.09368655, 0.04874086, 0.00150132, 0.04876363, 0.00916007, 0.05902252,
0.00220585, 0.04752943, 0.09000364, 0.06682745, 0.00164565, 0.07004488, 0.00137171, 0.00436196,
0.00240439, 0.08324245, 0.00066909, 0.07545695, 0.08570319, 0.1283072, 0.11103037, 0.00204363,
0.05889845, 0.07095593, 0.05249947, 0.16853261, 0.00099424, 0.10812089, 0.01772964, 0.00146189,
0.07849872, 0.00192052, 0.00080982, 0.14481401, 0.00170103, 0.00180528, 0.00080231, 0.0015493,
0.10666651, 0.00109288, 0.00276518, 0.0050185, 0.0749554, 0.05525097, 0.00299227, 0.00108755,
0.0025714, 0.04171562, 0.0840168, 0.0018771, 0.05755261, 0.14300928, 0.0011363, 0.00141537,
0.00295693, 0.00426137, 0.0097059, 0.00297078, 0.0007866, 0.05024266, 0.08387303, 0.00110948,
0.00117564, 0.000958, 0.00154158, 0.00313523, 0.05668899, 0.00138041, 0.00208497, 0.00174549,
0.01377538, 0.08511311, 0.00250322, 0.04653519, 0.06011224, 0.00066057, 0.00573212, 0.16622683,
0.0011858, 0.06400746, 0.07507476, 0.00203273, 0.06496084, 0.08522177, 0.00115094, 0.1122131,
0.11111701, 0.06030846, 0.00186771, 0.00099021, 0.00135455, 0.00948012, 0.00230578, 0.05319288,
0.0011774, 0.00144777, 0.0047451, 0.06043282, 0.05066103, 0.00450966, 0.00703669, 0.05051127,
0.41833147, 0.00189266, 0.05931064, 0.08143798, 0.00616276, 0.00124928, 0.00069508, 0.00556803,
0.08273876, 0.18670154, 0.00390905, 0.05333331, 0.00201023, 0.00395641, 0.34697795, 0.10290858,
0.00552109, 0.00896361, 0.01006562, 0.05424494, 0.05386925, 0.177407, 0.05233279, 0.08020887,
0.00106284, 0.00193959, 0.05131751, 0.05770358, 0.05811858, 0.00456572, 0.00110403, 0.00080186,
0.00468078, 0.00279421, 0.09008676, 0.00300497, 0.05715263, 0.05447432, 0.03897297, 0.01476368,
0.02759668, 0.05374959, 0.0016945, 0.00076771, 0.00334865, 0.00149041, 0.0019449, 0.05071405,
0.0821006, 0.04709196, 0.09838042, 0.00217947, 0.07904652, 0.06049165, 0.00261715, 0.06593019,
0.08447334, 0.00426695, 0.00397119, 0.04874086, 0.00150132, 0.00095612, 0.00916007, 0.00146988,
0.00021699, 0.00090268, 0.09000364, 0.00194764, 0.00164565, 0.07004488, 0.00137171, 0.00436196,
0.00240439, 0.08324245, 0.00066909, 0.00239515, 0.00324497, 0.1283072, 0.00581071, 0.00204363,
0.05889845, 0.07095593, 0.05249947, 0.16853261, 0.00099424, 0.00567359, 0.01772964, 0.00146189,
0.07849872, 0.00192052, 0.00080982, 0.0116744, 0.00170103, 0.00180528, 0.00080231, 0.0015493,
0.00520414, 0.00109288, 0.00276518, 0.0050185, 0.00226209, 0.05525097, 0.00299227, 0.00108755,
0.0025714, 0.00079694, 0.00314316, 0.00017464, 0.05755261, 0.14300928, 0.0011363, 0.00141537,
0.00295693, 0.00426137, 0.0097059, 0.00297078, 0.0007866, 0.00104305, 0.08387303, 0.00110948,
0.00117564, 0.000958, 0.00154158, 0.00313523, 0.00126609, 0.00138041, 0.00208497, 0.00174549,
0.01377538, 0.00299564, 0.00250322, 0.00092891, 0.00146848, 0.00066057, 0.00573212, 0.16622683,
0.0011858, 0.06400746, 0.0025112, 0.00203273, 0.00186384, 0.00304553, 0.00115094, 0.00583997,
0.11111701, 0.06030846, 0.00186771, 0.00099021, 0.00135455, 0.00948012, 0.00230578, 0.001192,
0.0011774, 0.00144777, 0.0047451, 0.06043282, 0.05066103, 0.00450966, 0.00703669, 0.00106576,
0.41833147, 0.00189266, 0.00147915, 0.00280964, 0.00616276, 0.00124928, 0.00069508, 0.00556803,
0.08273876, 0.18670154, 0.00390905, 0.05333331, 0.00201023, 0.00395641, 0.34697795, 0.00439429,
0.00552109, 0.00896361, 0.01006562, 0.05424494, 0.05386925, 0.02108133, 0.0011192, 0.00280526,
0.00106284, 0.00193959, 0.00106567, 0.00135344, 0.0014278, 0.00456572, 0.00110403, 0.00080186,
0.00468078, 0.00279421, 0.00347653, 0.00300497, 0.00142536, 0.05447432, 0.00897217, 0.01476368,
0.02759668, 0.05374959, 0.0016945, 0.00076771, 0.00334865, 0.00149041, 0.0019449, 0.00108728,
0.00292647, 0.00093436, 0.0041897, 0.00217947, 0.00261834, 0.00148314, 0.00261715, 0.00187719,
0.08447334, 0.00426695, 0.00397119, 0.04874086, 0.00013772, 0.00095612, 0.00916007, 0.00146988,
0.00021699, 0.00090268, 0.00361887, 0.00194764, 0.00013459, 0.07004488, 0.00011596, 0.00436196,
0.00240439, 0.08324245, 0.00066909, 0.00239515, 0.00324497, 0.1283072, 0.00581071, 0.00204363,
0.00155187, 0.00211179, 0.0010868, 0.16853261, 0.00099424, 0.00567359, 0.00301817, 0.0001263,
0.07849872, 0.00192052, 0.00080982, 0.0116744, 0.00170103, 0.00180528, 0.00006166, 0.0015493,
0.00520414, 0.00109288, 0.00028738, 0.0050185, 0.00226209, 0.0012818, 0.00299227, 0.00108755,
0.0025714, 0.00079694, 0.00314316, 0.00017464, 0.05755261, 0.01152217, 0.0011363, 0.00141537,
0.00295693, 0.00426137, 0.0097059, 0.00031078, 0.00005767, 0.00104305, 0.00311452, 0.00110948,
0.00117564, 0.00007322, 0.00154158, 0.00313523, 0.00126609, 0.00138041, 0.00208497, 0.00015607,
0.01377538, 0.00299564, 0.00250322, 0.00092891, 0.00146848, 0.00066057, 0.00573212, 0.16622683,
0.0000979, 0.00172633, 0.0025112, 0.00203273, 0.00186384, 0.00304553, 0.00115094, 0.00583997,
0.11111701, 0.00164074, 0.00186771, 0.00099021, 0.00011638, 0.00948012, 0.00230578, 0.001192,
0.0011774, 0.00144777, 0.0047451, 0.06043282, 0.05066103, 0.00450966, 0.00703669, 0.00106576,
0.20962137, 0.00189266, 0.00147915, 0.00280964, 0.00616276, 0.00124928, 0.00069508, 0.00556803,
0.00314122, 0.18670154, 0.00044659, 0.00121224, 0.00201023, 0.00395641, 0.34697795, 0.00439429,
0.00067213, 0.00896361, 0.01006562, 0.00120246, 0.00128275, 0.02108133, 0.0011192, 0.00280526,
0.00106284, 0.00193959, 0.00106567, 0.00135344, 0.0014278, 0.00456572, 0.00110403, 0.00080186,
0.00468078, 0.00279421, 0.00347653, 0.00030485, 0.00142536, 0.00129774, 0.00897217, 0.01476368,
0.02759668, 0.00104848, 0.0016945, 0.00076771, 0.00334865, 0.00149041, 0.0019449, 0.00108728,
0.00292647, 0.00093436, 0.0041897, 0.00217947, 0.00261834, 0.00148314, 0.00261715, 0.00187719,
0.08447334, 0.00426695, 0.00397119, 0.00100979, 0.00013772, 0.00095612, 0.00916007, 0.00146988,
0.00021699, 0.00090268, 0.00361887, 0.00194764, 0.00013459, 0.00217724, 0.00011596, 0.00051957,
0.00240439, 0.00319594, 0.00004858, 0.00239515, 0.00324497, 0.0079512, 0.00581071, 0.00204363,
0.00155187, 0.00211179, 0.0010868, 0.01767138, 0.00008112, 0.00567359, 0.00301817, 0.0001263,
0.00255716, 0.00192052, 0.00080982, 0.0116744, 0.00170103, 0.00180528, 0.00006166, 0.00013068,
0.00520414, 0.00008616, 0.00028738, 0.0050185, 0.00226209, 0.0012818, 0.00299227, 0.00108755,
0.0025714, 0.00079694, 0.00314316, 0.00017464, 0.0013985, 0.01152217, 0.0011363, 0.00012046,
0.00031805, 0.00426137, 0.0097059, 0.00031078, 0.00005767, 0.00104305, 0.00311452, 0.00009653,
0.00009915, 0.00007322, 0.00154158, 0.00034207, 0.00126609, 0.00138041, 0.00208497, 0.00015607,
0.00216827, 0.00299564, 0.00250322, 0.00092891, 0.00146848, 0.00066057, 0.00573212, 0.16622683,
0.0000979, 0.00172633, 0.0025112, 0.00019932, 0.00186384, 0.00304553, 0.00115094, 0.00583997,
0.00619534, 0.00164074, 0.00186771, 0.00008059, 0.00011638, 0.00948012, 0.00230578, 0.001192,
0.0011774, 0.00012714, 0.0047451, 0.00152862, 0.00108847, 0.00122607, 0.00703669, 0.00106576,
0.20962137, 0.00189266, 0.00147915, 0.00280964, 0.00078911, 0.00010929, 0.00069508, 0.00069106,
0.00314122, 0.02736115, 0.00044659, 0.00121224, 0.00201023, 0.00395641, 0.20510197, 0.00439429,
0.00067213, 0.00896361, 0.01006562, 0.00120246, 0.00128275, 0.02108133, 0.0011192, 0.00280526,
0.00106284, 0.00193959, 0.00106567, 0.00135344, 0.0014278, 0.00053516, 0.00110403, 0.00080186,
0.00468078, 0.00279421, 0.00347653, 0.00030485, 0.00142536, 0.00129774, 0.00897217, 0.01476368,
0.02759668, 0.00104848, 0.0016945, 0.00005579, 0.0003733, 0.00013408, 0.00019243, 0.00108728,
0.00292647, 0.00093436, 0.0041897, 0.00217947, 0.00261834, 0.00148314, 0.00261715, 0.00187719,
0.0030849, 0.00113282, 0.00397119, 0.00100979, 0.00013772, 0.00095612, 0.00132567, 0.00146988,
0.00021699, 0.00090268, 0.00361887, 0.00194764, 0.00013459, 0.00217724, 0.00011596, 0.00051957,
0.00023091, 0.00319594, 0.00004858, 0.00239515, 0.00324497, 0.0079512, 0.00581071, 0.0001964,
0.00155187, 0.00211179, 0.0010868, 0.01767138, 0.00008112, 0.00567359, 0.00301817, 0.0001263,
0.00255716, 0.00018314, 0.00005984, 0.0116744, 0.00016132, 0.00017297, 0.00006166, 0.00013068,
0.00520414, 0.00008616, 0.00028738, 0.00062767, 0.00226209, 0.0012818, 0.00032318, 0.00008866,
0.0002701, 0.00079694, 0.00314316, 0.00017464, 0.0013985, 0.01152217, 0.00009578, 0.00012046,
0.00031805, 0.00049612, 0.0014329, 0.00031078, 0.00005767, 0.00104305, 0.00311452, 0.00009653,
0.00009915, 0.00007322, 0.00014147, 0.00034207, 0.00126609, 0.00012416, 0.00020877, 0.00015607,
0.00216827, 0.00299564, 0.00024539, 0.00092891, 0.00146848, 0.00004774, 0.00072908, 0.01687244,
0.0000979, 0.00172633, 0.0025112, 0.00019932, 0.00186384, 0.00304553, 0.00009686, 0.00583997,
0.00619534, 0.00164074, 0.00018084, 0.00008059, 0.00011638, 0.00141925, 0.00023466, 0.001192,
0.00009957, 0.00012714, 0.00057805, 0.00152862, 0.00108847, 0.00122607, 0.00094512, 0.00106576,
0.20962137, 0.00018871, 0.00147915, 0.00280964, 0.00078911, 0.00010929, 0.00005007, 0.00069106,
0.00314122, 0.02736115, 0.00044659, 0.00121224, 0.00019848, 0.00045991, 0.20510197, 0.00439429,
0.00067213, 0.00127801, 0.00580952, 0.00120246, 0.00128275, 0.02108133, 0.0011192, 0.00280526,
0.00008881, 0.00018954, 0.00106567, 0.00135344, 0.0014278, 0.00053516, 0.00009218, 0.00006217,
0.00057954, 0.00029153, 0.00347653, 0.00030485, 0.00142536, 0.00129774, 0.00897217, 0.00249642,
0.00563759, 0.00104848, 0.00015843, 0.00005579, 0.0003733, 0.00013408, 0.00019243, 0.00108728,
0.00292647, 0.00093436, 0.0041897, 0.0002107, 0.00261834, 0.00148314, 0.00026521, 0.00187719,
0.0030849, 0.00113282, 0.00047973, 0.00100979, 0.00013772, 0.00007764, 0.00132567, 0.00013116,
0.00003695, 0.00007352, 0.00361887, 0.00019011, 0.00013459, 0.00217724, 0.00011596, 0.00051957,
0.00023091, 0.00319594, 0.00004858, 0.00024638, 0.00036204, 0.0079512, 0.00074229, 0.0001964,
0.00155187, 0.00211179, 0.0010868, 0.01767138, 0.00008112, 0.0007368, 0.00301817, 0.0001263,
0.00255716, 0.00018314, 0.00005984, 0.00186914, 0.00016132, 0.00017297, 0.00006166, 0.00013068,
0.00064442, 0.00008616, 0.00028738, 0.00062767, 0.00022638, 0.0012818, 0.00032318, 0.00008866,
0.0002701, 0.00006172, 0.00034568, 0.00002825, 0.0013985, 0.01152217, 0.00009578, 0.00012046,
0.00031805, 0.00049612, 0.0014329, 0.00031078, 0.00005767, 0.00008464, 0.00311452, 0.00009653,
0.00009915, 0.00007322, 0.00014147, 0.00034207, 0.00011069, 0.00012416, 0.00020877, 0.00015607,
0.00216827, 0.00030953, 0.00024539, 0.00007612, 0.0001314, 0.00004774, 0.00072908, 0.01687244,
0.0000979, 0.00172633, 0.00026089, 0.00019932, 0.00018007, 0.00033391, 0.00009686, 0.00075036,
0.00619534, 0.00164074, 0.00018084, 0.00008059, 0.00011638, 0.00141925, 0.00023466, 0.00009957,
0.00009957, 0.00012714, 0.00057805, 0.00152862, 0.00108847, 0.00122607, 0.00094512, 0.00008708,
0.20962137, 0.00018871, 0.00013253, 0.00030622, 0.00078911, 0.00010929, 0.00005007, 0.00069106,
0.00314122, 0.02736115, 0.00044659, 0.00121224, 0.00019848, 0.00045991, 0.20510197, 0.00049141,
0.00067213, 0.00127801, 0.00580952, 0.00120246, 0.00128275, 0.0039919, 0.00009355, 0.00029954,
0.00008881, 0.00018954, 0.00008947, 0.00011471, 0.00012976, 0.00053516, 0.00009218, 0.00006217,
0.00057954, 0.00029153, 0.00039154, 0.00030485, 0.00013191, 0.00129774, 0.00278491, 0.00249642,
0.00563759, 0.00104848, 0.00015843, 0.00005579, 0.0003733, 0.00013408, 0.00019243, 0.0000903,
0.00032106, 0.00007764, 0.00049213, 0.0002107, 0.00027946, 0.00013456, 0.00026521, 0.00018519,
0.0030849, 0.00113282, 0.00047973, 0.00100979, 0.00002187, 0.00007764, 0.00132567, 0.00013116,
0.00003695, 0.00007352, 0.00041685, 0.00019011, 0.00001952, 0.00217724, 0.00001708, 0.00051957,
0.00023091, 0.00319594, 0.00004858, 0.00024638, 0.00036204, 0.0079512, 0.00074229, 0.0001964,
0.00014681, 0.00021228, 0.00009134, 0.01767138, 0.00008112, 0.0007368, 0.00077614, 0.00001931,
0.00255716, 0.00018314, 0.00005984, 0.00186914, 0.00016132, 0.00017297, 0.00000834, 0.00013068,
0.00064442, 0.00008616, 0.00005135, 0.00062767, 0.00022638, 0.0001139, 0.00032318, 0.00008866,
0.0002701, 0.00006172, 0.00034568, 0.00002825, 0.0013985, 0.00183535, 0.00009578, 0.00012046,
0.00031805, 0.00049612, 0.0014329, 0.00005567, 0.00000754, 0.00008464, 0.00034413, 0.00009653,
0.00009915, 0.00001001, 0.00014147, 0.00034207, 0.00011069, 0.00012416, 0.00020877, 0.00002438,
0.00216827, 0.00030953, 0.00024539, 0.00007612, 0.0001314, 0.00004774, 0.00072908, 0.01687244,
0.00001419, 0.00016552, 0.00026089, 0.00019932, 0.00018007, 0.00033391, 0.00009686, 0.00075036,
0.00619534, 0.00015622, 0.00018084, 0.00008059, 0.00001723, 0.00141925, 0.00023466, 0.00009957,
0.00009957, 0.00012714, 0.00057805, 0.00152862, 0.00108847, 0.00122607, 0.00094512, 0.00008708,
0.05676088, 0.00018871, 0.00013253, 0.00030622, 0.00078911, 0.00010929, 0.00005007, 0.00069106,
0.00035429, 0.02736115, 0.00008363, 0.00010455, 0.00019848, 0.00045991, 0.20510197, 0.00049141,
0.0001334, 0.00127801, 0.00580952, 0.00010547, 0.00011346, 0.0039919, 0.00009355, 0.00029954,
0.00008881, 0.00018954, 0.00008947, 0.00011471, 0.00012976, 0.00053516, 0.00009218, 0.00006217,
0.00057954, 0.00029153, 0.00039154, 0.00005248, 0.00013191, 0.00011396, 0.00278491, 0.00249642,
0.00563759, 0.00008267, 0.00015843, 0.00005579, 0.0003733, 0.00013408, 0.00019243, 0.0000903,
0.00032106, 0.00007764, 0.00049213, 0.0002107, 0.00027946, 0.00013456, 0.00026521, 0.00018519,
0.0030849, 0.00113282, 0.00047973, 0.00008154, 0.00002187, 0.00007764, 0.00132567, 0.00013116,
0.00003695, 0.00007352, 0.00041685, 0.00019011, 0.00001952, 0.00022662, 0.00001708, 0.00010121,
0.00023091, 0.00036088, 0.00000626, 0.00024638, 0.00036204, 0.00111473, 0.00074229, 0.0001964,
0.00014681, 0.00021228, 0.00009134, 0.00312015, 0.00001162, 0.0007368, 0.00077614, 0.00001931,
0.00025898, 0.00018314, 0.00005984, 0.00186914, 0.00016132, 0.00017297, 0.00000834, 0.00001922,
0.00064442, 0.00001156, 0.00005135, 0.00062767, 0.00022638, 0.0001139, 0.00032318, 0.00008866,
0.0002701, 0.00006172, 0.00034568, 0.00002825, 0.00012299, 0.00183535, 0.00009578, 0.0000177,
0.00005752, 0.00049612, 0.0014329, 0.00005567, 0.00000754, 0.00008464, 0.00034413, 0.00001442,
0.00001445, 0.00001001, 0.00014147, 0.00006175, 0.00011069, 0.00012416, 0.00020877, 0.00002438,
0.00053197, 0.00030953, 0.00024539, 0.00007612, 0.0001314, 0.00004774, 0.00072908, 0.01687244,
0.00001419, 0.00016552, 0.00026089, 0.00003344, 0.00018007, 0.00033391, 0.00009686, 0.00075036,
0.00084329, 0.00015622, 0.00018084, 0.00001132, 0.00001723, 0.00141925, 0.00023466, 0.00009957,
0.00009957, 0.00001919, 0.00057805, 0.00013888, 0.00009021, 0.00041816, 0.00094512, 0.00008708,
0.05676088, 0.00018871, 0.00013253, 0.00030622, 0.0001651, 0.00001669, 0.00005007, 0.00014174,
0.00035429, 0.00581521, 0.00008363, 0.00010455, 0.00019848, 0.00045991, 0.07460758, 0.00049141,
0.0001334, 0.00127801, 0.00580952, 0.00010547, 0.00011346, 0.0039919, 0.00009355, 0.00029954,
0.00008881, 0.00018954, 0.00008947, 0.00011471, 0.00012976, 0.00010484, 0.00009218, 0.00006217,
0.00057954, 0.00029153, 0.00039154, 0.00005248, 0.00013191, 0.00011396, 0.00278491, 0.00249642,
0.00563759, 0.00008267, 0.00015843, 0.00000721, 0.00006971, 0.00002077, 0.00003201, 0.0000903,
0.00032106, 0.00007764, 0.00049213, 0.0002107, 0.00027946, 0.00013456, 0.00026521, 0.00018519,
0.00032601, 0.00038067, 0.00047973, 0.00008154, 0.00002187, 0.00007764, 0.00030494, 0.00013116,
0.00003695, 0.00007352, 0.00041685, 0.00019011, 0.00001952, 0.00022662, 0.00001708, 0.00010121,
0.0000391, 0.00036088, 0.00000626, 0.00024638, 0.00036204, 0.00111473, 0.00074229, 0.00003207,
0.00014681, 0.00021228, 0.00009134, 0.00312015, 0.00001162, 0.0007368, 0.00077614, 0.00001931,
0.00025898, 0.00002986, 0.0000082, 0.00186914, 0.00002626, 0.00002825, 0.00000834, 0.00001922,
0.00064442, 0.00001156, 0.00005135, 0.00012878, 0.00022638, 0.0001139, 0.00005865, 0.00001261,
0.00004813, 0.00006172, 0.00034568, 0.00002825, 0.00012299, 0.00183535, 0.00001392, 0.0000177,
0.00005752, 0.00009692, 0.00033024, 0.00005567, 0.00000754, 0.00008464, 0.00034413, 0.00001442,
0.00001445, 0.00001001, 0.00002235, 0.00006175, 0.00011069, 0.00001901, 0.00003499, 0.00002438,
0.00053197, 0.00030953, 0.00004235, 0.00007612, 0.0001314, 0.0000059, 0.00015306, 0.0029164,
0.00001419, 0.00016552, 0.00026089, 0.00003344, 0.00018007, 0.00033391, 0.00001445, 0.00075036,
0.00084329, 0.00015622, 0.00002986, 0.00001132, 0.00001723, 0.00032812, 0.00004014, 0.00009957,
0.00001451, 0.00001919, 0.00011376, 0.00013888, 0.00009021, 0.00041816, 0.00020322, 0.00008708,
0.05676088, 0.00003189, 0.00013253, 0.00030622, 0.0001651, 0.00001669, 0.00000644, 0.00014174,
0.00035429, 0.00581521, 0.00008363, 0.00010455, 0.00003332, 0.00008836, 0.07460758, 0.00049141,
0.0001334, 0.00029111, 0.00352725, 0.00010547, 0.00011346, 0.0039919, 0.00009355, 0.00029954,
0.00001299, 0.00003144, 0.00008947, 0.00011471, 0.00012976, 0.00010484, 0.00001314, 0.00000849,
0.0001168, 0.00005126, 0.00039154, 0.00005248, 0.00013191, 0.00011396, 0.00278491, 0.00063825,
0.00165501, 0.00008267, 0.0000256, 0.00000721, 0.00006971, 0.00002077, 0.00003201, 0.0000903,
0.00032106, 0.00007764, 0.00049213, 0.00003517, 0.00027946, 0.00013456, 0.00004551, 0.00018519,
0.00032601, 0.00038067, 0.0000948, 0.00008154, 0.00002187, 0.00001097, 0.00030494, 0.00002003,
0.00000805, 0.00001058, 0.00041685, 0.00003129, 0.00001952, 0.00022662, 0.00001708, 0.00010121,
0.0000391, 0.00036088, 0.00000626, 0.00004268, 0.00006676, 0.00111473, 0.00015229, 0.00003207,
0.00014681, 0.00021228, 0.00009134, 0.00312015, 0.00001162, 0.00015202, 0.00077614, 0.00001931,
0.00025898, 0.00002986, 0.0000082, 0.00045985, 0.00002626, 0.00002825, 0.00000834, 0.00001922,
0.00013006, 0.00001156, 0.00005135, 0.00012878, 0.00003868, 0.0001139, 0.00005865, 0.00001261,
0.00004813, 0.00000817, 0.00006226, 0.00000593, 0.00012299, 0.00183535, 0.00001392, 0.0000177,
0.00005752, 0.00009692, 0.00033024, 0.00005567, 0.00000754, 0.00001204, 0.00034413, 0.00001442,
0.00001445, 0.00001001, 0.00002235, 0.00006175, 0.00001699, 0.00001901, 0.00003499, 0.00002438,
0.00053197, 0.00005427, 0.00004235, 0.00001076, 0.00002021, 0.0000059, 0.00015306, 0.0029164,
0.00001419, 0.00016552, 0.00004488, 0.00003344, 0.00002912, 0.00006121, 0.00001445, 0.00015619,
0.00084329, 0.00015622, 0.00002986, 0.00001132, 0.00001723, 0.00032812, 0.00004014, 0.00001433,
0.00001451, 0.00001919, 0.00011376, 0.00013888, 0.00009021, 0.00041816, 0.00020322, 0.00001237,
0.05676088, 0.00003189, 0.00002038, 0.00005594, 0.0001651, 0.00001669, 0.00000644, 0.00014174,
0.00035429, 0.00581521, 0.00008363, 0.00010455, 0.00003332, 0.00008836, 0.07460758, 0.00009191,
0.0001334, 0.00029111, 0.00352725, 0.00010547, 0.00011346, 0.00111419, 0.0000138, 0.00005335,
0.00001299, 0.00003144, 0.00001305, 0.00001681, 0.00002012, 0.00010484, 0.00001314, 0.00000849,
0.0001168, 0.00005126, 0.00007388, 0.00005248, 0.00002077, 0.00011396, 0.00105849, 0.00063825,
0.00165501, 0.00008267, 0.0000256, 0.00000721, 0.00006971, 0.00002077, 0.00003201, 0.00001305,
0.00005856, 0.00001132, 0.00009543, 0.00003517, 0.00005019, 0.00002107, 0.00004551, 0.00003067,
0.00032601, 0.00038067, 0.0000948, 0.00008154, 0.00000444, 0.00001097, 0.00030494, 0.00002003,
0.00000805, 0.00001058, 0.00007892, 0.00003129, 0.00000378, 0.00022662, 0.00000337, 0.00010121,
0.0000391, 0.00036088, 0.00000626, 0.00004268, 0.00006676, 0.00111473, 0.00015229, 0.00003207,
0.00002337, 0.00003603, 0.00001353, 0.00312015, 0.00001162, 0.00015202, 0.00025263, 0.0000039,
0.00025898, 0.00002986, 0.0000082, 0.00045985, 0.00002626, 0.00002825, 0.0000014, 0.00001922,
0.00013006, 0.00001156, 0.00001183, 0.00012878, 0.00003868, 0.00001732, 0.00005865, 0.00001261,
0.00004813, 0.00000817, 0.00006226, 0.00000593, 0.00012299, 0.00044572, 0.00001392, 0.0000177,
0.00005752, 0.00009692, 0.00033024, 0.00001305, 0.0000014, 0.00001204, 0.00006258, 0.00001442,
0.00001445, 0.00000182, 0.00002235, 0.00006175, 0.00001699, 0.00001901, 0.00003499, 0.00000498,
0.00053197, 0.00005427, 0.00004235, 0.00001076, 0.00002021, 0.0000059, 0.00015306, 0.0029164,
0.00000268, 0.00002703, 0.00004488, 0.00003344, 0.00002912, 0.00006121, 0.00001445, 0.00015619,
0.00084329, 0.00002462, 0.00002986, 0.00001132, 0.0000034, 0.00032812, 0.00004014, 0.00001433,
0.00001451, 0.00001919, 0.00011376, 0.00013888, 0.00009021, 0.00041816, 0.00020322, 0.00001237,
0.0168584, 0.00003189, 0.00002038, 0.00005594, 0.0001651, 0.00001669, 0.00000644, 0.00014174,
0.00006551, 0.00581521, 0.00002012, 0.00001553, 0.00003332, 0.00008836, 0.07460758, 0.00009191,
0.000034, 0.00029111, 0.00352725, 0.00001588, 0.0000169, 0.00111419, 0.0000138, 0.00005335,
0.00001299, 0.00003144, 0.00001305, 0.00001681, 0.00002012, 0.00010484, 0.00001314, 0.00000849,
0.0001168, 0.00005126, 0.00007388, 0.00001186, 0.00002077, 0.00001699, 0.00105849, 0.00063825,
0.00165501, 0.00001192, 0.0000256, 0.00000721, 0.00006971, 0.00002077, 0.00003201, 0.00001305,
0.00005856, 0.00001132, 0.00009543, 0.00003517, 0.00005019, 0.00002107, 0.00004551, 0.00003067,
0.00032601, 0.00038067, 0.0000948, 0.00001144, 0.00000444, 0.00001097, 0.00030494, 0.00002003,
0.00000805, 0.00001058, 0.00007892, 0.00003129, 0.00000378, 0.00003931, 0.00000337, 0.00002506,
0.0000391, 0.00006613, 0.00000104, 0.00004268, 0.00006676, 0.0002507, 0.00015229, 0.00003207,
0.00002337, 0.00003603, 0.00001353, 0.00082418, 0.000002, 0.00015202, 0.00025263, 0.0000039,
0.00004461, 0.00002986, 0.0000082, 0.00045985, 0.00002626, 0.00002825, 0.0000014, 0.00000381,
0.00013006, 0.00000212, 0.00001183, 0.00012878, 0.00003868, 0.00001732, 0.00005865, 0.00001261,
0.00004813, 0.00000817, 0.00006226, 0.00000593, 0.00001863, 0.00044572, 0.00001392, 0.00000328,
0.00001326, 0.00009692, 0.00033024, 0.00001305, 0.0000014, 0.00001204, 0.00006258, 0.00000274,
0.0000028, 0.00000182, 0.00002235, 0.00001425, 0.00001699, 0.00001901, 0.00003499, 0.00000498,
0.00016603, 0.00005427, 0.00004235, 0.00001076, 0.00002021, 0.0000059, 0.00015306, 0.0029164,
0.00000268, 0.00002703, 0.00004488, 0.0000073, 0.00002912, 0.00006121, 0.00001445, 0.00015619,
0.00018057, 0.00002462, 0.00002986, 0.00000197, 0.0000034, 0.00032812, 0.00004014, 0.00001433,
0.00001451, 0.00000376, 0.00011376, 0.00002155, 0.00001281, 0.00016275, 0.00020322, 0.00001237,
0.0168584, 0.00003189, 0.00002038, 0.00005594, 0.00004429, 0.00000322, 0.00000644, 0.00003737,
0.00006551, 0.00173068, 0.00002012, 0.00001553, 0.00003332, 0.00008836, 0.02732348, 0.00009191,
0.000034, 0.00029111, 0.00352725, 0.00001588, 0.0000169, 0.00111419, 0.0000138, 0.00005335,
0.00001299, 0.00003144, 0.00001305, 0.00001681, 0.00002012, 0.00002655, 0.00001314, 0.00000849,
0.0001168, 0.00005126, 0.00007388, 0.00001186, 0.00002077, 0.00001699, 0.00105849, 0.00063825,
0.00165501, 0.00001192, 0.0000256, 0.00000119, 0.00001669, 0.00000414, 0.00000677, 0.00001305,
0.00005856, 0.00001132, 0.00009543, 0.00003517, 0.00005019, 0.00002107, 0.00004551, 0.00003067,
0.00005752, 0.00014678, 0.0000948, 0.00001144, 0.00000444, 0.00001097, 0.0000889, 0.00002003,
0.00000805, 0.00001058, 0.00007892, 0.00003129, 0.00000378, 0.00003931, 0.00000337, 0.00002506,
0.00000882, 0.00006613, 0.00000104, 0.00004268, 0.00006676, 0.0002507, 0.00015229, 0.00000685,
0.00002337, 0.00003603, 0.00001353, 0.00082418, 0.000002, 0.00015202, 0.00025263, 0.0000039,
0.00004461, 0.00000626, 0.00000143, 0.00045985, 0.00000548, 0.00000587, 0.0000014, 0.00000381,
0.00013006, 0.00000212, 0.00001183, 0.00003365, 0.00003868, 0.00001732, 0.00001353, 0.00000244,
0.00001082, 0.00000817, 0.00006226, 0.00000593, 0.00001863, 0.00044572, 0.00000265, 0.00000328,
0.00001326, 0.00002435, 0.0000962, 0.00001305, 0.0000014, 0.00001204, 0.00006258, 0.00000274,
0.0000028, 0.00000182, 0.00000447, 0.00001425, 0.00001699, 0.00000378, 0.00000757, 0.00000498,
0.00016603, 0.00005427, 0.00000969, 0.00001076, 0.00002021, 0.00000098, 0.00004122, 0.00075853,
0.00000268, 0.00002703, 0.00004488, 0.0000073, 0.00002912, 0.00006121, 0.00000277, 0.00015619,
0.00018057, 0.00002462, 0.00000632, 0.00000197, 0.0000034, 0.0000945, 0.00000885, 0.00001433,
0.00000283, 0.00000376, 0.00002855, 0.00002155, 0.00001281, 0.00016275, 0.00005558, 0.00001237,
0.0168584, 0.00000682, 0.00002038, 0.00005594, 0.00004429, 0.00000322, 0.0000011, 0.00003737,
0.00006551, 0.00173068, 0.00002012, 0.00001553, 0.00000715, 0.00002161, 0.02732348, 0.00009191,
0.000034, 0.00008443, 0.00223404, 0.00001588, 0.0000169, 0.00111419, 0.0000138, 0.00005335,
0.00000241, 0.00000665, 0.00001305, 0.00001681, 0.00002012, 0.00002655, 0.00000235, 0.00000152,
0.00002986, 0.00001162, 0.00007388, 0.00001186, 0.00002077, 0.00001699, 0.00105849, 0.00020409,
0.00060308, 0.00001192, 0.00000539, 0.00000119, 0.00001669, 0.00000414, 0.00000677, 0.00001305,
0.00005856, 0.00001132, 0.00009543, 0.00000757, 0.00005019, 0.00002107, 0.0000101, 0.00003067,
0.00005752, 0.00014678, 0.00002357, 0.00001144, 0.00000444, 0.00000209, 0.0000889, 0.00000393,
0.00000203, 0.00000194, 0.00007892, 0.00000662, 0.00000378, 0.00003931, 0.00000337, 0.00002506,
0.00000882, 0.00006613, 0.00000104, 0.00000942, 0.00001568, 0.0002507, 0.00003976, 0.00000685,
0.00002337, 0.00003603, 0.00001353, 0.00082418, 0.000002, 0.00003931, 0.00025263, 0.0000039,
0.00004461, 0.00000626, 0.00000143, 0.0001415, 0.00000548, 0.00000587, 0.0000014, 0.00000381,
0.00003344, 0.00000212, 0.00001183, 0.00003365, 0.00000867, 0.00001732, 0.00001353, 0.00000244,
0.00001082, 0.00000134, 0.00001416, 0.00000143, 0.00001863, 0.00044572, 0.00000265, 0.00000328,
0.00001326, 0.00002435, 0.0000962, 0.00001305, 0.0000014, 0.00000212, 0.00006258, 0.00000274,
0.0000028, 0.00000182, 0.00000447, 0.00001425, 0.00000343, 0.00000378, 0.00000757, 0.00000498,
0.00016603, 0.00001228, 0.00000969, 0.00000191, 0.00000405, 0.00000098, 0.00004122, 0.00075853,
0.00000268, 0.00002703, 0.00000975, 0.0000073, 0.00000605, 0.00001433, 0.00000277, 0.0000414,
0.00018057, 0.00002462, 0.00000632, 0.00000197, 0.0000034, 0.0000945, 0.00000885, 0.00000277,
0.00000283, 0.00000376, 0.00002855, 0.00002155, 0.00001281, 0.00016275, 0.00005558, 0.00000221,
0.0168584, 0.00000682, 0.00000402, 0.00001293, 0.00004429, 0.00000322, 0.0000011, 0.00003737,
0.00006551, 0.00173068, 0.00002012, 0.00001553, 0.00000715, 0.00002161, 0.02732348, 0.00002232,
0.000034, 0.00008443, 0.00223404, 0.00001588, 0.0000169, 0.00038582, 0.00000256, 0.0000121,
0.00000241, 0.00000665, 0.00000256, 0.00000316, 0.00000405, 0.00002655, 0.00000235, 0.00000152,
0.00002986, 0.00001162, 0.00001785, 0.00001186, 0.0000042, 0.00001699, 0.00045511, 0.00020409,
0.00060308, 0.00001192, 0.00000539, 0.00000119, 0.00001669, 0.00000414, 0.00000677, 0.0000025,
0.00001359, 0.00000203, 0.00002357, 0.00000757, 0.00001144, 0.00000429, 0.0000101, 0.00000641,
0.00005752, 0.00014678, 0.00002357, 0.00001144, 0.00000098, 0.00000209, 0.0000889, 0.00000393,
0.00000203, 0.00000194, 0.00001892, 0.00000662, 0.00000086, 0.00003931, 0.00000072, 0.00002506,
0.00000882, 0.00006613, 0.00000104, 0.00000942, 0.00001568, 0.0002507, 0.00003976, 0.00000685,
0.00000468, 0.00000775, 0.00000262, 0.00082418, 0.000002, 0.00003931, 0.00009394, 0.00000083,
0.00004461, 0.00000626, 0.00000143, 0.0001415, 0.00000548, 0.00000587, 0.00000018, 0.00000381,
0.00003344, 0.00000212, 0.00000316, 0.00003365, 0.00000867, 0.0000034, 0.00001353, 0.00000244,
0.00001082, 0.00000134, 0.00001416, 0.00000143, 0.00001863, 0.00013486, 0.00000265, 0.00000328,
0.00001326, 0.00002435, 0.0000962, 0.00000343, 0.00000012, 0.00000212, 0.00001451, 0.00000274,
0.0000028, 0.00000033, 0.00000447, 0.00001425, 0.00000343, 0.00000378, 0.00000757, 0.00000113,
0.00016603, 0.00001228, 0.00000969, 0.00000191, 0.00000405, 0.00000098, 0.00004122, 0.00075853,
0.00000057, 0.00000566, 0.00000975, 0.0000073, 0.00000605, 0.00001433, 0.00000277, 0.0000414,
0.00018057, 0.0000048, 0.00000632, 0.00000197, 0.00000075, 0.0000945, 0.00000885, 0.00000277,
0.00000283, 0.00000376, 0.00002855, 0.00002155, 0.00001281, 0.00016275, 0.00005558, 0.00000221,
0.00614968, 0.00000682, 0.00000402, 0.00001293, 0.00004429, 0.00000322, 0.0000011, 0.00003737,
0.00001532, 0.00173068, 0.00000542, 0.00000298, 0.00000715, 0.00002161, 0.02732348, 0.00002232,
0.00001001, 0.00008443, 0.00223404, 0.00000316, 0.00000325, 0.00038582, 0.00000256, 0.0000121,
0.00000241, 0.00000665, 0.00000256, 0.00000316, 0.00000405, 0.00002655, 0.00000235, 0.00000152,
0.00002986, 0.00001162, 0.00001785, 0.0000031, 0.0000042, 0.00000325, 0.00045511, 0.00020409,
0.00060308, 0.00000224, 0.00000539, 0.00000119, 0.00001669, 0.00000414, 0.00000677, 0.0000025,
0.00001359, 0.00000203, 0.00002357, 0.00000757, 0.00001144, 0.00000429, 0.0000101, 0.00000641,
0.00005752, 0.00014678, 0.00002357, 0.00000206, 0.00000098, 0.00000209, 0.0000889, 0.00000393,
0.00000203, 0.00000194, 0.00001892, 0.00000662, 0.00000086, 0.00000855, 0.00000072, 0.000007,
0.00000882, 0.00001532, 0.00000015, 0.00000942, 0.00001568, 0.00007144, 0.00003976, 0.00000685,
0.00000468, 0.00000775, 0.00000262, 0.00027186, 0.00000042, 0.00003931, 0.00009394, 0.00000083,
0.00000986, 0.00000626, 0.00000143, 0.0001415, 0.00000548, 0.00000587, 0.00000018, 0.00000077,
0.00003344, 0.00000033, 0.00000316, 0.00003365, 0.00000867, 0.0000034, 0.00001353, 0.00000244,
0.00001082, 0.00000134, 0.00001416, 0.00000143, 0.00000355, 0.00013486, 0.00000265, 0.0000008,
0.00000352, 0.00002435, 0.0000962, 0.00000343, 0.00000012, 0.00000212, 0.00001451, 0.0000006,
0.00000057, 0.00000033, 0.00000447, 0.0000037, 0.00000343, 0.00000378, 0.00000757, 0.00000113,
0.00005901, 0.00001228, 0.00000969, 0.00000191, 0.00000405, 0.00000098, 0.00004122, 0.00075853,
0.00000057, 0.00000566, 0.00000975, 0.00000176, 0.00000605, 0.00001433, 0.00000277, 0.0000414,
0.00004795, 0.0000048, 0.00000632, 0.00000036, 0.00000075, 0.0000945, 0.00000885, 0.00000277,
0.00000283, 0.00000072, 0.00002855, 0.00000441, 0.00000232, 0.0000684, 0.00005558, 0.00000221,
0.00614968, 0.00000682, 0.00000402, 0.00001293, 0.00001353, 0.00000075, 0.0000011, 0.00001124,
0.00001532, 0.00062722, 0.00000542, 0.00000298, 0.00000715, 0.00002161, 0.01142508, 0.00002232,
0.00001001, 0.00008443, 0.00223404, 0.00000316, 0.00000325, 0.00038582, 0.00000256, 0.0000121,
0.00000241, 0.00000665, 0.00000256, 0.00000316, 0.00000405, 0.00000766, 0.00000235, 0.00000152,
0.00002986, 0.00001162, 0.00001785, 0.0000031, 0.0000042, 0.00000325, 0.00045511, 0.00020409,
0.00060308, 0.00000224, 0.00000539, 0.00000018, 0.00000456, 0.00000092, 0.00000164, 0.0000025,
0.00001359, 0.00000203, 0.00002357, 0.00000757, 0.00001144, 0.00000429, 0.0000101, 0.00000641,
0.00001302, 0.00006133, 0.00002357, 0.00000206, 0.00000098, 0.00000209, 0.00002939, 0.00000393,
0.00000203, 0.00000194, 0.00001892, 0.00000662, 0.00000086, 0.00000855, 0.00000072, 0.000007,
0.00000224, 0.00001532, 0.00000015, 0.00000942, 0.00001568, 0.00007144, 0.00003976, 0.00000164,
0.00000468, 0.00000775, 0.00000262, 0.00027186, 0.00000042, 0.00003931, 0.00009394, 0.00000083,
0.00000986, 0.00000149, 0.00000024, 0.0001415, 0.00000125, 0.00000134, 0.00000018, 0.00000077,
0.00003344, 0.00000033, 0.00000316, 0.00000983, 0.00000867, 0.0000034, 0.00000367, 0.00000042,
0.00000283, 0.00000134, 0.00001416, 0.00000143, 0.00000355, 0.00013486, 0.0000006, 0.0000008,
0.00000352, 0.00000694, 0.00003174, 0.00000343, 0.00000012, 0.00000212, 0.00001451, 0.0000006,
0.00000057, 0.00000033, 0.00000101, 0.0000037, 0.00000343, 0.00000077, 0.00000176, 0.00000113,
0.00005901, 0.00001228, 0.00000247, 0.00000191, 0.00000405, 0.00000018, 0.00001267, 0.00024647,
0.00000057, 0.00000566, 0.00000975, 0.00000176, 0.00000605, 0.00001433, 0.00000057, 0.0000414,
0.00004795, 0.0000048, 0.00000143, 0.00000036, 0.00000075, 0.00003049, 0.00000212, 0.00000277,
0.00000054, 0.00000072, 0.00000799, 0.00000441, 0.00000232, 0.0000684, 0.00001711, 0.00000221,
0.00614968, 0.00000167, 0.00000402, 0.00001293, 0.00001353, 0.00000075, 0.00000021, 0.00001124,
0.00001532, 0.00062722, 0.00000542, 0.00000298, 0.00000173, 0.00000602, 0.01142508, 0.00002232,
0.00001001, 0.00002789, 0.0014613, 0.00000316, 0.00000325, 0.00038582, 0.00000256, 0.0000121,
0.00000051, 0.00000158, 0.00000256, 0.00000316, 0.00000405, 0.00000766, 0.00000051, 0.00000015,
0.00000861, 0.00000292, 0.00001785, 0.0000031, 0.0000042, 0.00000325, 0.00045511, 0.00007367,
0.00024804, 0.00000224, 0.00000116, 0.00000018, 0.00000456, 0.00000092, 0.00000164, 0.0000025,
0.00001359, 0.00000203, 0.00002357, 0.00000188, 0.00001144, 0.00000429, 0.00000259, 0.00000641,
0.00001302, 0.00006133, 0.00000656, 0.00000206, 0.00000098, 0.00000033, 0.00002939, 0.00000077,
0.00000057, 0.00000033, 0.00001892, 0.00000155, 0.00000086, 0.00000855, 0.00000072, 0.000007,
0.00000224, 0.00001532, 0.00000015, 0.00000238, 0.00000408, 0.00007144, 0.00001168, 0.00000164,
0.00000468, 0.00000775, 0.00000262, 0.00027186, 0.00000042, 0.00001141, 0.00009394, 0.00000083,
0.00000986, 0.00000149, 0.00000024, 0.00004891, 0.00000125, 0.00000134, 0.00000018, 0.00000077,
0.00000978, 0.00000033, 0.00000316, 0.00000983, 0.00000224, 0.0000034, 0.00000367, 0.00000042,
0.00000283, 0.00000012, 0.0000037, 0.00000033, 0.00000355, 0.00013486, 0.0000006, 0.0000008,
0.00000352, 0.00000694, 0.00003174, 0.00000343, 0.00000012, 0.00000045, 0.00001451, 0.0000006,
0.00000057, 0.00000033, 0.00000101, 0.0000037, 0.00000066, 0.00000077, 0.00000176, 0.00000113,
0.00005901, 0.00000331, 0.00000247, 0.0000003, 0.00000095, 0.00000018, 0.00001267, 0.00024647,
0.00000057, 0.00000566, 0.00000238, 0.00000176, 0.00000131, 0.00000378, 0.00000057, 0.00001249,
0.00004795, 0.0000048, 0.00000143, 0.00000036, 0.00000075, 0.00003049, 0.00000212, 0.00000054,
0.00000054, 0.00000072, 0.00000799, 0.00000441, 0.00000232, 0.0000684, 0.00001711, 0.00000045,
0.00614968, 0.00000167, 0.00000083, 0.0000034, 0.00001353, 0.00000075, 0.00000021, 0.00001124,
0.00001532, 0.00062722, 0.00000542, 0.00000298, 0.00000173, 0.00000602, 0.01142508, 0.00000632,
0.00001001, 0.00002789, 0.0014613, 0.00000316, 0.00000325, 0.00015011, 0.00000051, 0.00000319,
0.00000051, 0.00000158, 0.00000045, 0.00000072, 0.00000083, 0.00000766, 0.00000051, 0.00000015,
0.00000861, 0.00000292, 0.00000495, 0.0000031, 0.00000089, 0.00000325, 0.00021037, 0.00007367,
0.00024804, 0.00000224, 0.00000116, 0.00000018, 0.00000456, 0.00000092, 0.00000164, 0.00000039,
0.00000352, 0.00000036, 0.00000668, 0.00000188, 0.00000292, 0.00000095, 0.00000259, 0.00000155,
0.00001302, 0.00006133, 0.00000656, 0.00000206, 0.00000021, 0.00000033, 0.00002939, 0.00000077,
0.00000057, 0.00000033, 0.00000522, 0.00000155, 0.00000024, 0.00000855, 0.00000015, 0.000007,
0.00000224, 0.00001532, 0.00000015, 0.00000238, 0.00000408, 0.00007144, 0.00001168, 0.00000164,
0.00000107, 0.00000194, 0.00000054, 0.00027186, 0.00000042, 0.00001141, 0.00003746, 0.00000021,
0.00000986, 0.00000149, 0.00000024, 0.00004891, 0.00000125, 0.00000134, 0.00000012, 0.00000077,
0.00000978, 0.00000033, 0.00000086, 0.00000983, 0.00000224, 0.00000072, 0.00000367, 0.00000042,
0.00000283, 0.00000012, 0.0000037, 0.00000033, 0.00000355, 0.00004584, 0.0000006, 0.0000008,
0.00000352, 0.00000694, 0.00003174, 0.00000098, 0.00000009, 0.00000045, 0.00000373, 0.0000006,
0.00000057, 0.00000012, 0.00000101, 0.0000037, 0.00000066, 0.00000077, 0.00000176, 0.00000027,
0.00005901, 0.00000331, 0.00000247, 0.0000003, 0.00000095, 0.00000018, 0.00001267, 0.00024647,
0.00000006, 0.0000014, 0.00000238, 0.00000176, 0.00000131, 0.00000378, 0.00000057, 0.00001249,
0.00004795, 0.00000107, 0.00000143, 0.00000036, 0.00000015, 0.00003049, 0.00000212, 0.00000054,
0.00000054, 0.00000072, 0.00000799, 0.00000441, 0.00000232, 0.0000684, 0.00001711, 0.00000045,
0.00261366, 0.00000167, 0.00000083, 0.0000034, 0.00001353, 0.00000075, 0.00000021, 0.00001124,
0.00000399, 0.00062722, 0.00000158, 0.00000054, 0.00000173, 0.00000602, 0.01142508, 0.00000632,
0.00000313, 0.00002789, 0.0014613, 0.00000072, 0.00000069, 0.00015011, 0.00000051, 0.00000319,
0.00000051, 0.00000158, 0.00000045, 0.00000072, 0.00000083, 0.00000766, 0.00000051, 0.00000015,
0.00000861, 0.00000292, 0.00000495, 0.0000008, 0.00000089, 0.00000075, 0.00021037, 0.00007367,
0.00024804, 0.00000051, 0.00000116, 0.00000018, 0.00000456, 0.00000092, 0.00000164, 0.00000039,
0.00000352, 0.00000036, 0.00000668, 0.00000188, 0.00000292, 0.00000095, 0.00000259, 0.00000155,
0.00001302, 0.00006133, 0.00000656, 0.00000033, 0.00000021, 0.00000033, 0.00002939, 0.00000077,
0.00000057, 0.00000033, 0.00000522, 0.00000155, 0.00000024, 0.00000212, 0.00000015, 0.00000218,
0.00000224, 0.00000402, 0.00000003, 0.00000238, 0.00000408, 0.00002289, 0.00001168, 0.00000164,
0.00000107, 0.00000194, 0.00000054, 0.00010106, 0.00000012, 0.00001141, 0.00003746, 0.00000021,
0.00000253, 0.00000149, 0.00000024, 0.00004891, 0.00000125, 0.00000134, 0.00000012, 0.00000018,
0.00000978, 0.00000018, 0.00000086, 0.00000983, 0.00000224, 0.00000072, 0.00000367, 0.00000042,
0.00000283, 0.00000012, 0.0000037, 0.00000033, 0.00000077, 0.00004584, 0.0000006, 0.00000012,
0.00000095, 0.00000694, 0.00003174, 0.00000098, 0.00000009, 0.00000045, 0.00000373, 0.00000006,
0.00000012, 0.00000012, 0.00000101, 0.00000107, 0.00000066, 0.00000077, 0.00000176, 0.00000027,
0.00002247, 0.00000331, 0.00000247, 0.0000003, 0.00000095, 0.00000018, 0.00001267, 0.00024647,
0.00000006, 0.0000014, 0.00000238, 0.00000048, 0.00000131, 0.00000378, 0.00000057, 0.00001249,
0.00001425, 0.00000107, 0.00000143, 0.00000015, 0.00000015, 0.00003049, 0.00000212, 0.00000054,
0.00000054, 0.00000018, 0.00000799, 0.00000098, 0.00000039, 0.00003013, 0.00001711, 0.00000045,
0.00261366, 0.00000167, 0.00000083, 0.0000034, 0.00000441, 0.00000015, 0.00000021, 0.00000361,
0.00000399, 0.00025377, 0.00000158, 0.00000054, 0.00000173, 0.00000602, 0.0053651, 0.00000632,
0.00000313, 0.00002789, 0.0014613, 0.00000072, 0.00000069, 0.00015011, 0.00000051, 0.00000319,
0.00000051, 0.00000158, 0.00000045, 0.00000072, 0.00000083, 0.00000229, 0.00000051, 0.00000015,
0.00000861, 0.00000292, 0.00000495, 0.0000008, 0.00000089, 0.00000075, 0.00021037, 0.00007367,
0.00024804, 0.00000051, 0.00000116, 0.00000009, 0.00000125, 0.00000021, 0.00000033, 0.00000039,
0.00000352, 0.00000036, 0.00000668, 0.00000188, 0.00000292, 0.00000095, 0.00000259, 0.00000155,
0.00000346, 0.00002673, 0.00000656, 0.00000033, 0.00000021, 0.00000033, 0.00001022, 0.00000077,
0.00000057, 0.00000033, 0.00000522, 0.00000155, 0.00000024, 0.00000212, 0.00000015, 0.00000218,
0.00000051, 0.00000402, 0.00000003, 0.00000238, 0.00000408, 0.00002289, 0.00001168, 0.00000039,
0.00000107, 0.00000194, 0.00000054, 0.00010106, 0.00000012, 0.00001141, 0.00003746, 0.00000021,
0.00000253, 0.00000039, 0.00000006, 0.00004891, 0.00000021, 0.00000021, 0.00000012, 0.00000018,
0.00000978, 0.00000018, 0.00000086, 0.00000304, 0.00000224, 0.00000072, 0.00000101, 0.00000003,
0.00000072, 0.00000012, 0.0000037, 0.00000033, 0.00000077, 0.00004584, 0., 0.00000012,
0.00000095, 0.00000212, 0.00001121, 0.00000098, 0.00000009, 0.00000045, 0.00000373, 0.00000006,
0.00000012, 0.00000012, 0.00000027, 0.00000107, 0.00000066, 0.00000009, 0.00000045, 0.00000027,
0.00002247, 0.00000331, 0.00000066, 0.0000003, 0.00000095, 0.00000003, 0.00000408, 0.00009039,
0.00000006, 0.0000014, 0.00000238, 0.00000048, 0.00000131, 0.00000378, 0.00000003, 0.00001249,
0.00001425, 0.00000107, 0.0000003, 0.00000015, 0.00000015, 0.00001052, 0.00000066, 0.00000054,
0.00000018, 0.00000018, 0.00000241, 0.00000098, 0.00000039, 0.00003013, 0.00000575, 0.00000045,
0.00261366, 0.00000048, 0.00000083, 0.0000034, 0.00000441, 0.00000015, 0., 0.00000361,
0.00000399, 0.00025377, 0.00000158, 0.00000054, 0.00000048, 0.00000173, 0.0053651, 0.00000632,
0.00000313, 0.0000098, 0.00097838, 0.00000072, 0.00000069, 0.00015011, 0.00000051, 0.00000319,
0.00000003, 0.00000036, 0.00000045, 0.00000072, 0.00000083, 0.00000229, 0.00000006, 0.00000012,
0.00000265, 0.00000086, 0.00000495, 0.0000008, 0.00000089, 0.00000075, 0.00021037, 0.00002834,
0.0001092, 0.00000051, 0.0000003, 0.00000009, 0.00000125, 0.00000021, 0.00000033, 0.00000039,
0.00000352, 0.00000036, 0.00000668, 0.00000048, 0.00000292, 0.00000095, 0.00000066, 0.00000155,
0.00000346, 0.00002673, 0.00000197, 0.00000033, 0.00000021, 0.00000012, 0.00001022, 0.00000018,
0.00000006, 0.00000012, 0.00000522, 0.00000033, 0.00000024, 0.00000212, 0.00000015, 0.00000218,
0.00000051, 0.00000402, 0.00000003, 0.00000072, 0.0000011, 0.00002289, 0.00000378, 0.00000039,
0.00000107, 0.00000194, 0.00000054, 0.00010106, 0.00000012, 0.00000361, 0.00003746, 0.00000021,
0.00000253, 0.00000039, 0.00000006, 0.000018, 0.00000021, 0.00000021, 0.00000012, 0.00000018,
0.00000313, 0.00000018, 0.00000086, 0.00000304, 0.00000048, 0.00000072, 0.00000101, 0.00000003,
0.00000072, 0.00000015, 0.00000095, 0.00000003, 0.00000077, 0.00004584, 0., 0.00000012,
0.00000095, 0.00000212, 0.00001121, 0.00000098, 0.00000009, 0.00000009, 0.00000373, 0.00000006,
0.00000012, 0.00000012, 0.00000027, 0.00000107, 0.00000018, 0.00000009, 0.00000045, 0.00000027,
0.00002247, 0.00000077, 0.00000066, 0.00000015, 0.00000021, 0.00000003, 0.00000408, 0.00009039,
0.00000006, 0.0000014, 0.00000063, 0.00000048, 0.00000027, 0.00000104, 0.00000003, 0.0000039,
0.00001425, 0.00000107, 0.0000003, 0.00000015, 0.00000015, 0.00001052, 0.00000066, 0.00000012,
0.00000018, 0.00000018, 0.00000241, 0.00000098, 0.00000039, 0.00003013, 0.00000575, 0.00000015,
0.00261366, 0.00000048, 0.00000027, 0.00000098, 0.00000441, 0.00000015, 0., 0.00000361,
0.00000399, 0.00025377, 0.00000158, 0.00000054, 0.00000048, 0.00000173, 0.0053651, 0.00000188,
0.00000313, 0.0000098, 0.00097838, 0.00000072, 0.00000069, 0.00006211, 0.00000015, 0.00000077,
0.00000003, 0.00000036, 0.00000009, 0.00000018, 0.00000021, 0.00000229, 0.00000006, 0.00000012,
0.00000265, 0.00000086, 0.00000134, 0.0000008, 0.00000024, 0.00000075, 0.00010139, 0.00002834,
0.0001092, 0.00000051, 0.0000003, 0.00000009, 0.00000125, 0.00000021, 0.00000033, 0.00000015,
0.00000089, 0.00000018, 0.00000188, 0.00000048, 0.00000086, 0.00000024, 0.00000066, 0.00000033,
0.00000346, 0.00002673, 0.00000197, 0.00000033, 0.00000009, 0.00000012, 0.00001022, 0.00000018,
0.00000006, 0.00000012, 0.00000149, 0.00000033, 0.00000006, 0.00000212, 0.00000006, 0.00000218,
0.00000051, 0.00000402, 0.00000003, 0.00000072, 0.0000011, 0.00002289, 0.00000378, 0.00000039,
0.00000027, 0.00000048, 0.00000003, 0.00010106, 0.00000012, 0.00000361, 0.00001562, 0.00000003,
0.00000253, 0.00000039, 0.00000006, 0.000018, 0.00000021, 0.00000021, 0.00000003, 0.00000018,
0.00000313, 0.00000018, 0.0000003, 0.00000304, 0.00000048, 0.00000021, 0.00000101, 0.00000003,
0.00000072, 0.00000015, 0.00000095, 0.00000003, 0.00000077, 0.0000166, 0., 0.00000012,
0.00000095, 0.00000212, 0.00001121, 0.00000018, 0.00000006, 0.00000009, 0.00000104, 0.00000006,
0.00000012, 0., 0.00000027, 0.00000107, 0.00000018, 0.00000009, 0.00000045, 0.00000009,
0.00002247, 0.00000077, 0.00000066, 0.00000015, 0.00000021, 0.00000003, 0.00000408, 0.00009039,
0.00000009, 0.00000027, 0.00000063, 0.00000048, 0.00000027, 0.00000104, 0.00000003, 0.0000039,
0.00001425, 0.00000015, 0.0000003, 0.00000015, 0.00000003, 0.00001052, 0.00000066, 0.00000012,
0.00000018, 0.00000018, 0.00000241, 0.00000098, 0.00000039, 0.00003013, 0.00000575, 0.00000015,
0.00122434, 0.00000048, 0.00000027, 0.00000098, 0.00000441, 0.00000015, 0., 0.00000361,
0.00000107, 0.00025377, 0.00000048, 0.00000012, 0.00000048, 0.00000173, 0.0053651, 0.00000188,
0.00000101, 0.0000098, 0.00097838, 0.00000006, 0.00000009, 0.00006211, 0.00000015, 0.00000077,
0.00000003, 0.00000036, 0.00000009, 0.00000018, 0.00000021, 0.00000229, 0.00000006, 0.00000012,
0.00000265, 0.00000086, 0.00000134, 0.0000003, 0.00000024, 0.00000018, 0.00010139, 0.00002834,
0.0001092, 0.00000003, 0.0000003, 0.00000009, 0.00000125, 0.00000021, 0.00000033, 0.00000015,
0.00000089, 0.00000018, 0.00000188, 0.00000048, 0.00000086, 0.00000024, 0.00000066, 0.00000033,
0.00000346, 0.00002673, 0.00000197, 0.00000018, 0.00000009, 0.00000012, 0.00001022, 0.00000018,
0.00000006, 0.00000012, 0.00000149, 0.00000033, 0.00000006, 0.00000054, 0.00000006, 0.00000063,
0.00000051, 0.00000113, 0., 0.00000072, 0.0000011, 0.00000784, 0.00000378, 0.00000039,
0.00000027, 0.00000048, 0.00000003, 0.00004032, 0.00000006, 0.00000361, 0.00001562, 0.00000003,
0.00000069, 0.00000039, 0.00000006, 0.000018, 0.00000021, 0.00000021, 0.00000003, 0.00000006,
0.00000313, 0., 0.0000003, 0.00000304, 0.00000048, 0.00000021, 0.00000101, 0.00000003,
0.00000072, 0.00000015, 0.00000095, 0.00000003, 0.00000015, 0.0000166, 0., 0.00000006,
0.00000015, 0.00000212, 0.00001121, 0.00000018, 0.00000006, 0.00000009, 0.00000104, 0.00000012,
0.00000003, 0., 0.00000027, 0.00000015, 0.00000018, 0.00000009, 0.00000045, 0.00000009,
0.00000888, 0.00000077, 0.00000066, 0.00000015, 0.00000021, 0.00000003, 0.00000408, 0.00009039,
0.00000009, 0.00000027, 0.00000063, 0.00000012, 0.00000027, 0.00000104, 0.00000003, 0.0000039,
0.00000438, 0.00000015, 0.0000003, 0.00000003, 0.00000003, 0.00001052, 0.00000066, 0.00000012,
0.00000018, 0.00000006, 0.00000241, 0.00000018, 0.00000024, 0.00001341, 0.00000575, 0.00000015,
0.00122434, 0.00000048, 0.00000027, 0.00000098, 0.00000152, 0.00000003, 0., 0.00000128,
0.00000107, 0.00010908, 0.00000048, 0.00000012, 0.00000048, 0.00000173, 0.00272986, 0.00000188,
0.00000101, 0.0000098, 0.00097838, 0.00000006, 0.00000009, 0.00006211, 0.00000015, 0.00000077,
0.00000003, 0.00000036, 0.00000009, 0.00000018, 0.00000021, 0.00000075, 0.00000006, 0.00000012,
0.00000265, 0.00000086, 0.00000134, 0.0000003, 0.00000024, 0.00000018, 0.00010139, 0.00002834,
0.0001092, 0.00000003, 0.0000003, 0., 0.00000039, 0.00000006, 0.00000018, 0.00000015,
0.00000089, 0.00000018, 0.00000188, 0.00000048, 0.00000086, 0.00000024, 0.00000066, 0.00000033,
0.00000089, 0.00001207, 0.00000197, 0.00000018, 0.00000009, 0.00000012, 0.00000381, 0.00000018,
0.00000006, 0.00000012, 0.00000149, 0.00000033, 0.00000006, 0.00000054, 0.00000006, 0.00000063,
0.00000024, 0.00000113, 0., 0.00000072, 0.0000011, 0.00000784, 0.00000378, 0.00000009,
0.00000027, 0.00000048, 0.00000003, 0.00004032, 0.00000006, 0.00000361, 0.00001562, 0.00000003,
0.00000069, 0.00000012, 0.00000003, 0.000018, 0.00000003, 0.00000015, 0.00000003, 0.00000006,
0.00000313, 0., 0.0000003, 0.00000101, 0.00000048, 0.00000021, 0.00000021, 0.00000012,
0.00000024, 0.00000015, 0.00000095, 0.00000003, 0.00000015, 0.0000166, 0.00000012, 0.00000006,
0.00000015, 0.00000077, 0.00000405, 0.00000018, 0.00000006, 0.00000009, 0.00000104, 0.00000012,
0.00000003, 0., 0.00000006, 0.00000015, 0.00000018, 0.00000015, 0.00000015, 0.00000009,
0.00000888, 0.00000077, 0.00000021, 0.00000015, 0.00000021, 0., 0.00000146, 0.00003526,
0.00000009, 0.00000027, 0.00000063, 0.00000012, 0.00000027, 0.00000104, 0.00000012, 0.0000039,
0.00000438, 0.00000015, 0.00000015, 0.00000003, 0.00000003, 0.0000037, 0.00000009, 0.00000012,
0., 0.00000006, 0.0000008, 0.00000018, 0.00000024, 0.00001341, 0.00000188, 0.00000015,
0.00122434, 0.00000012, 0.00000027, 0.00000098, 0.00000152, 0.00000003, 0., 0.00000128,
0.00000107, 0.00010908, 0.00000048, 0.00000012, 0.00000003, 0.00000048, 0.00272986, 0.00000188,
0.00000101, 0.00000361, 0.00066555, 0.00000006, 0.00000009, 0.00006211, 0.00000015, 0.00000077,
0.00000009, 0.00000009, 0.00000009, 0.00000018, 0.00000021, 0.00000075, 0., 0.00000003,
0.00000077, 0.00000015, 0.00000134, 0.0000003, 0.00000024, 0.00000018, 0.00010139, 0.00001135,
0.00004992, 0.00000003, 0.00000012, 0., 0.00000039, 0.00000006, 0.00000018, 0.00000015,
0.00000089, 0.00000018, 0.00000188, 0.00000012, 0.00000086, 0.00000024, 0.00000018, 0.00000033,
0.00000089,
];
| 98.197883 | 108 | 0.716056 |
287f0259047b20bcebf4d06096213d9335c69fa6
| 66 |
// TODO: https://github.com/PeterLuschny/Fast-Factorial-Functions
| 33 | 65 | 0.787879 |
62750f960854efec2762c486a884709eee9fab2c
| 2,531 |
//! logging capability provider
//!
//! ```no_compile
//! use wasmcloud_interface_logging::{log,debug,info};
//! log("info", "log a message at info level");
//! info!("this is also at {} level", "info");
//! ```
mod logging;
pub use logging::*;
#[cfg(target_arch = "wasm32")]
pub use wasm_log::log;
#[cfg(target_arch = "wasm32")]
mod wasm_log {
use std::string::ToString;
use wasmbus_rpc::RpcResult;
/// log a text message at a severity level (debug, info, warn, or error)
/// parameters may be `&str`, `String`, or `&String`.
/// You can also use this crate's macros `debug`,`info`,`warn`, and `error`
pub async fn log<T1: ToString, T2: ToString>(level: T1, text: T2) -> RpcResult<()> {
use crate::logging::{Logging, LoggingSender};
let entry = crate::logging::LogEntry {
level: level.to_string(),
text: text.to_string(),
};
let ctx = wasmbus_rpc::Context::default();
let logger = LoggingSender::new();
logger.write_log(&ctx, &entry).await
}
#[macro_export]
#[doc(hidden)]
/// internal macro to convert format arts into a string
macro_rules! log_fmt {
( $($arg:expr),* $(,)? ) => ({ format!("{}", format_args!($($arg),*) ) });
}
/// Emit log at 'debug' level. The syntax for this macro is the same as `log::debug`.
/// Note that parameters are always evaluated at any logging level
#[macro_export]
macro_rules! debug {
( $($arg:expr),* $(,)? ) => ({ let _ = $crate::log("debug", $crate::log_fmt!($($arg),*) ).await?; });
}
/// Emit log at 'info' level. The syntax for this macro is the same as `log::info`.
/// Note that parameters are always evaluated at any logging level
#[macro_export]
macro_rules! info {
( $($arg:expr),* $(,)? ) => ({ let _ = $crate::log("info", $crate::log_fmt!($($arg),*) ).await?; });
}
/// Emit log at 'warn' level. The syntax for this macro is the same as `log::warn`.
/// Note that parameters are always evaluated at any logging level
#[macro_export]
macro_rules! warn {
( $($arg:expr),* $(,)? ) => ({ let _ = $crate::log("warn", $crate::log_fmt!($($arg),*) ).await?; });
}
/// Emit log at 'error' level. The syntax for this macro is the same as `log::error`.
/// 'error' is the highest priority level.
#[macro_export]
macro_rules! error {
( $($arg:expr),* $(,)? ) => ({ let _ = $crate::log("error", $crate::log_fmt!($($arg),*) ).await?; });
}
}
| 36.681159 | 109 | 0.572896 |
abd1a722e936ed7cca8066e34ddacc634872fc29
| 382 |
// Copyright (c) Microsoft. All rights reserved.
#![deny(rust_2018_idioms, warnings)]
#![deny(clippy::all, clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]
mod error;
mod runtime_util;
mod shell_util;
mod support_bundle;
pub use crate::error::{Error, ErrorKind};
pub use crate::runtime_util::write_logs;
pub use crate::support_bundle::{make_bundle, OutputLocation};
| 25.466667 | 61 | 0.76178 |
18cc528ba57493fc349bba49b2e9cfd6197011e0
| 2,240 |
use crate::{compass::Point, Part};
use aoc_runner_derive::{aoc, aoc_generator};
use std::collections::HashSet;
#[aoc_generator(day18)]
pub fn generator(input: &str) -> Vec<Point> {
let input = input.lines().map(|l| l.trim()).collect::<Vec<_>>();
let mut lights = Vec::new();
for (y, &line) in input.iter().enumerate() {
for (x, c) in line.bytes().enumerate() {
if c == b'#' {
lights.push(Point::new(x as i32, y as i32));
}
}
}
lights
}
#[aoc(day18, part1)]
pub fn part1(input: &[Point]) -> usize {
solve(input, &Part::One)
}
#[aoc(day18, part2)]
pub fn part2(input: &[Point]) -> usize {
solve(input, &Part::Two)
}
fn solve(input: &[Point], part: &Part) -> usize {
let mut current = input.iter().cloned().collect::<HashSet<Point>>();
let mut next = HashSet::new();
for _ in 0..100 {
for x in 0..100 {
for y in 0..100 {
let light = Point::new(x, y);
let lit_neighbours = light
.neighbours()
.iter()
.filter(|&n| n.x >= 0 && n.y >= 0 && n.x < 100 && n.y < 100)
.filter(|&n| current.contains(n))
.count();
if (part == &Part::Two && is_corner(&light))
|| (current.contains(&light) && lit_neighbours >= 2 && lit_neighbours <= 3)
|| (!current.contains(&light) && lit_neighbours == 3)
{
next.insert(light);
}
}
}
// swap next state into current state
current.clear();
for p in next.drain() {
current.insert(p);
}
}
current.len()
}
fn is_corner(point: &Point) -> bool {
let (x, y) = (point.x, point.y);
(y == 99 || y == 0) && (x == 99 || x == 0)
}
#[cfg(test)]
mod tests {
use super::*;
static INPUT: &str = include_str!("../input/2015/day18.txt");
#[test]
fn test_part1() {
let input = generator(INPUT);
assert_eq!(part1(&input), 1061);
}
#[test]
fn test_part2() {
let input = generator(INPUT);
assert_eq!(part2(&input), 1006);
}
}
| 25.168539 | 95 | 0.477232 |
3391dc28ffa8df3de68f79797d364ac1e6bd06bf
| 7,541 |
//! C FFI bindings for *candidateparser* library.
//!
//! The header file is provided by this library, you can find it in the crate source code under
//! [`src/candidateparser.h`](https://github.com/dbrgn/candidateparser/blob/master/candidateparser-ffi/candidateparser.h).
//!
//! You can find an example C program under
//! [`src/example.c`](https://github.com/dbrgn/candidateparser/blob/master/candidateparser-ffi/example.c).
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
extern crate candidateparser;
extern crate libc;
use libc::{c_char, size_t, uint8_t};
use std::boxed::Box;
use std::ffi::{CStr, CString};
use std::ptr;
/// A key value pair.
#[derive(Debug)]
#[repr(C)]
pub struct KeyValuePair {
pub key: *const uint8_t,
pub key_len: size_t,
pub val: *const uint8_t,
pub val_len: size_t,
}
/// A key value map.
///
/// The `len` must be set to the length of the `values` array. Everything else
/// is undefined behavior!
#[derive(Debug)]
#[repr(C)]
pub struct KeyValueMap {
pub values: *const KeyValuePair,
pub len: size_t,
}
/// A wrapper around the `IceCandidate` data that is C compatible.
#[derive(Debug)]
#[repr(C)]
pub struct IceCandidateFFI {
pub foundation: *const c_char,
pub component_id: u32,
pub transport: *const c_char,
pub priority: u64,
pub connection_address: *const c_char,
pub port: u16,
pub candidate_type: *const c_char,
/// The address is optional. If no value is defined, this will contain a
/// null pointer.
pub rel_addr: *const c_char,
/// This port is optional. If no address is defined, this will contain the
/// value `0`.
pub rel_port: u16,
/// The extensions map will always be defined but may be empty.
pub extensions: KeyValueMap,
}
/// Parse an ICE candidate SDP string and return a pointer to an
/// [`IceCandidateFFI`](struct.IceCandidateFFI.html) struct.
///
/// Make sure to always call the [`free_ice_candidate`](fn.free_ice_candidate.html)
/// function after you're done processing the data, to prevent memory leaks!
///
/// This function is marked `unsafe` because it dereferences raw pointers.
#[no_mangle]
pub unsafe extern "C" fn parse_ice_candidate_sdp(sdp: *const c_char) -> *const IceCandidateFFI {
// Convert C string to Rust byte slice
if sdp.is_null() {
return ptr::null();
}
let cstr_sdp = CStr::from_ptr(sdp);
// Parse
let parsed = match candidateparser::parse(cstr_sdp.to_bytes()) {
Some(candidate) => candidate,
None => return ptr::null(),
};
// Convert to FFI representation
let transport_cstring: CString = parsed.transport.into();
let candidate_type_cstring: CString = parsed.candidate_type.into();
let extensions = match parsed.extensions {
Some(e) => {
// Create KeyValuePairs from map entries
let extensions_vec = e.iter().map(|(k, v)| {
let k_vec = k.clone();
let k_len = k_vec.len();
let v_vec = v.clone();
let v_len = v_vec.len();
let pair = KeyValuePair {
key: Box::into_raw(k_vec.into_boxed_slice()) as *const u8,
key_len: k_len,
val: Box::into_raw(v_vec.into_boxed_slice()) as *const u8,
val_len: v_len,
};
pair
}).collect::<Vec<KeyValuePair>>();
let extensions_len = extensions_vec.len();
// Create KeyValueMap
let map = KeyValueMap {
values: Box::into_raw(extensions_vec.into_boxed_slice()) as *const KeyValuePair,
len: extensions_len,
};
map
},
None => KeyValueMap {
values: ptr::null(),
len: 0,
},
};
let boxed = Box::new(IceCandidateFFI {
foundation: CString::new(parsed.foundation).unwrap().into_raw(),
component_id: parsed.component_id,
transport: transport_cstring.into_raw(),
priority: parsed.priority,
connection_address: CString::new(parsed.connection_address.to_string()).unwrap().into_raw(),
port: parsed.port,
candidate_type: candidate_type_cstring.into_raw(),
rel_addr: match parsed.rel_addr {
Some(addr) => CString::new(addr.to_string()).unwrap().into_raw(),
None => ptr::null(),
},
rel_port: parsed.rel_port.unwrap_or(0),
extensions: extensions,
});
Box::into_raw(boxed)
}
/// Free the memory associated with the [`IceCandidateFFI`](struct.IceCandidateFFI.html) struct.
///
/// Make sure to always call this function after you're done processing the
/// data, otherwise you'll end up with memory leaks!
///
/// This function is marked `unsafe` because it dereferences raw pointers.
#[no_mangle]
pub unsafe extern "C" fn free_ice_candidate(ptr: *const IceCandidateFFI) {
if ptr.is_null() { return; }
let ptr = ptr as *mut IceCandidateFFI;
let candidate: Box<IceCandidateFFI> = Box::from_raw(ptr);
CString::from_raw(candidate.foundation as *mut c_char);
CString::from_raw(candidate.transport as *mut c_char);
CString::from_raw(candidate.connection_address as *mut c_char);
CString::from_raw(candidate.candidate_type as *mut c_char);
if !candidate.rel_addr.is_null() {
CString::from_raw(candidate.rel_addr as *mut c_char);
}
let e = candidate.extensions;
let pairs = Vec::from_raw_parts(e.values as *mut KeyValuePair, e.len as usize, e.len as usize);
for p in pairs {
Vec::from_raw_parts(p.key as *mut uint8_t, p.key_len as usize, p.key_len as usize);
Vec::from_raw_parts(p.val as *mut uint8_t, p.val_len as usize, p.val_len as usize);
}
// Resources will be freed here
}
#[cfg(test)]
mod tests {
use std::ffi::CString;
use super::*;
#[test]
fn test_parse_ice_candidate_sdp() {
// Same data as test_parse_full in the `candidateparser` crate.
let sdp = CString::new("candidate:842163049 1 udp 1686052607 1.2.3.4 46154 typ srflx raddr 10.0.0.17 rport 46154 generation 0 ufrag EEtu network-id 3 network-cost 10").unwrap();
// Parse
let parsed: *const IceCandidateFFI = unsafe { parse_ice_candidate_sdp(sdp.into_raw()) };
// Restore
let candidate: Box<IceCandidateFFI> = unsafe { Box::from_raw(parsed as *mut IceCandidateFFI) };
let foundation = unsafe { CString::from_raw(candidate.foundation as *mut c_char) };
let transport = unsafe { CString::from_raw(candidate.transport as *mut c_char) };
let connection_address = unsafe { CString::from_raw(candidate.connection_address as *mut c_char) };
let candidate_type = unsafe { CString::from_raw(candidate.candidate_type as *mut c_char) };
let rel_addr = unsafe { CString::from_raw(candidate.rel_addr as *mut c_char) };
assert_eq!(foundation, CString::new("842163049").unwrap());
assert_eq!(candidate.component_id, 1);
assert_eq!(transport, CString::new("udp").unwrap());
assert_eq!(candidate.priority, 1686052607);
assert_eq!(connection_address, CString::new("1.2.3.4").unwrap());
assert_eq!(candidate.port, 46154);
assert_eq!(candidate_type, CString::new("srflx").unwrap());
assert_eq!(rel_addr, CString::new("10.0.0.17").unwrap());
assert_eq!(candidate.rel_port, 46154);
assert_eq!(candidate.extensions.len, 4);
}
}
| 38.085859 | 185 | 0.648057 |
11e3106e4b5a9213f04523366a18ed87289b7d74
| 13,939 |
// Copyright 2012 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.
//! Types/fns concerning Internet Protocol (IP), versions 4 & 6
#[allow(missing_doc)];
use std::libc;
use std::comm::{stream, SharedChan};
use std::ptr;
use std::result;
use std::str;
use iotask = uv::iotask::IoTask;
use interact = uv::iotask::interact;
use sockaddr_in = uv_ll::sockaddr_in;
use sockaddr_in6 = uv_ll::sockaddr_in6;
use addrinfo = uv_ll::addrinfo;
use uv_getaddrinfo_t = uv_ll::uv_getaddrinfo_t;
use uv_ip4_name = uv_ll::ip4_name;
use uv_ip4_port = uv_ll::ip4_port;
use uv_ip6_name = uv_ll::ip6_name;
use uv_ip6_port = uv_ll::ip6_port;
use uv_getaddrinfo = uv_ll::getaddrinfo;
use uv_freeaddrinfo = uv_ll::freeaddrinfo;
use create_uv_getaddrinfo_t = uv_ll::getaddrinfo_t;
use set_data_for_req = uv_ll::set_data_for_req;
use get_data_for_req = uv_ll::get_data_for_req;
use ll = uv_ll;
/// An IP address
pub enum IpAddr {
/// An IPv4 address
Ipv4(sockaddr_in),
Ipv6(sockaddr_in6)
}
/// Human-friendly feedback on why a parse_addr attempt failed
pub struct ParseAddrErr {
err_msg: ~str,
}
/**
* Convert a `IpAddr` to a str
*
* # Arguments
*
* * ip - a `extra::net::ip::IpAddr`
*/
pub fn format_addr(ip: &IpAddr) -> ~str {
match *ip {
Ipv4(ref addr) => unsafe {
let result = uv_ip4_name(addr);
if result == ~"" {
fail!("failed to convert inner sockaddr_in address to str")
}
result
},
Ipv6(ref addr) => unsafe {
let result = uv_ip6_name(addr);
if result == ~"" {
fail!("failed to convert inner sockaddr_in address to str")
}
result
}
}
}
/**
* Get the associated port
*
* # Arguments
* * ip - a `extra::net::ip::IpAddr`
*/
pub fn get_port(ip: &IpAddr) -> uint {
match *ip {
Ipv4(ref addr) => unsafe {
uv_ip4_port(addr)
},
Ipv6(ref addr) => unsafe {
uv_ip6_port(addr)
}
}
}
/// Represents errors returned from `net::ip::get_addr()`
enum IpGetAddrErr {
GetAddrUnknownError
}
/**
* Attempts name resolution on the provided `node` string
*
* # Arguments
*
* * `node` - a string representing some host address
* * `iotask` - a `uv::iotask` used to interact with the underlying event loop
*
* # Returns
*
* A `result<~[ip_addr], ip_get_addr_err>` instance that will contain
* a vector of `ip_addr` results, in the case of success, or an error
* object in the case of failure
*/
pub fn get_addr(node: &str, iotask: &iotask)
-> result::Result<~[IpAddr], IpGetAddrErr> {
let (output_po, output_ch) = stream();
let mut output_ch = Some(SharedChan::new(output_ch));
do str::as_buf(node) |node_ptr, len| {
let output_ch = output_ch.take_unwrap();
debug!("slice len %?", len);
let handle = create_uv_getaddrinfo_t();
let handle_ptr: *uv_getaddrinfo_t = &handle;
let handle_data = GetAddrData {
output_ch: output_ch.clone()
};
let handle_data_ptr: *GetAddrData = &handle_data;
do interact(iotask) |loop_ptr| {
unsafe {
let result = uv_getaddrinfo(
loop_ptr,
handle_ptr,
get_addr_cb,
node_ptr,
ptr::null(),
ptr::null());
match result {
0i32 => {
set_data_for_req(handle_ptr, handle_data_ptr);
}
_ => {
output_ch.send(result::Err(GetAddrUnknownError));
}
}
}
};
output_po.recv()
}
}
pub mod v4 {
use net::ip::{IpAddr, Ipv4, ParseAddrErr};
use uv::ll;
use uv_ip4_addr = uv::ll::ip4_addr;
use uv_ip4_name = uv::ll::ip4_name;
use std::cast::transmute;
use std::result;
use std::uint;
/**
* Convert a str to `ip_addr`
*
* # Failure
*
* Fails if the string is not a valid IPv4 address
*
* # Arguments
*
* * ip - a string of the format `x.x.x.x`
*
* # Returns
*
* * an `ip_addr` of the `ipv4` variant
*/
pub fn parse_addr(ip: &str) -> IpAddr {
match try_parse_addr(ip) {
result::Ok(addr) => addr,
result::Err(ref err_data) => fail!(copy err_data.err_msg)
}
}
// the simple, old style numberic representation of
// ipv4
pub struct Ipv4Rep { a: u8, b: u8, c: u8, d: u8 }
pub trait AsUnsafeU32 {
unsafe fn as_u32(&self) -> u32;
}
impl AsUnsafeU32 for Ipv4Rep {
// this is pretty dastardly, i know
unsafe fn as_u32(&self) -> u32 {
let this: &mut u32 = transmute(self);
*this
}
}
pub fn parse_to_ipv4_rep(ip: &str) -> result::Result<Ipv4Rep, ~str> {
let parts: ~[uint] = ip.split_iter('.').transform(|s| {
match uint::from_str(s) {
Some(n) if n <= 255 => n,
_ => 256
}
}).collect();
if parts.len() != 4 {
Err(fmt!("'%s' doesn't have 4 parts", ip))
} else if parts.iter().any(|x| *x == 256u) {
Err(fmt!("invalid octal in addr '%s'", ip))
} else {
Ok(Ipv4Rep {
a: parts[0] as u8, b: parts[1] as u8,
c: parts[2] as u8, d: parts[3] as u8,
})
}
}
pub fn try_parse_addr(ip: &str) -> result::Result<IpAddr,ParseAddrErr> {
unsafe {
let INADDR_NONE = ll::get_INADDR_NONE();
let ip_rep_result = parse_to_ipv4_rep(ip);
if result::is_err(&ip_rep_result) {
let err_str = result::get_err(&ip_rep_result);
return result::Err(ParseAddrErr { err_msg: err_str })
}
// ipv4_rep.as_u32 is unsafe :/
let input_is_inaddr_none =
result::get(&ip_rep_result).as_u32() == INADDR_NONE;
let new_addr = uv_ip4_addr(ip, 22);
let reformatted_name = uv_ip4_name(&new_addr);
debug!("try_parse_addr: input ip: %s reparsed ip: %s",
ip, reformatted_name);
let ref_ip_rep_result = parse_to_ipv4_rep(reformatted_name);
if result::is_err(&ref_ip_rep_result) {
let err_str = result::get_err(&ref_ip_rep_result);
return Err(ParseAddrErr { err_msg: err_str })
}
if result::get(&ref_ip_rep_result).as_u32() == INADDR_NONE &&
!input_is_inaddr_none {
Err(ParseAddrErr {
err_msg: ~"uv_ip4_name produced invalid result.",
})
} else {
Ok(Ipv4(copy(new_addr)))
}
}
}
}
pub mod v6 {
use net::ip::{IpAddr, Ipv6, ParseAddrErr};
use uv_ip6_addr = uv::ll::ip6_addr;
use uv_ip6_name = uv::ll::ip6_name;
use std::result;
/**
* Convert a str to `ip_addr`
*
* # Failure
*
* Fails if the string is not a valid IPv6 address
*
* # Arguments
*
* * ip - an ipv6 string. See RFC2460 for spec.
*
* # Returns
*
* * an `ip_addr` of the `ipv6` variant
*/
pub fn parse_addr(ip: &str) -> IpAddr {
match try_parse_addr(ip) {
result::Ok(addr) => addr,
result::Err(err_data) => fail!(copy err_data.err_msg)
}
}
pub fn try_parse_addr(ip: &str) -> result::Result<IpAddr,ParseAddrErr> {
unsafe {
// need to figure out how to establish a parse failure..
let new_addr = uv_ip6_addr(ip, 22);
let reparsed_name = uv_ip6_name(&new_addr);
debug!("v6::try_parse_addr ip: '%s' reparsed '%s'",
ip, reparsed_name);
// '::' appears to be uv_ip6_name() returns for bogus
// parses..
if ip != &"::" && reparsed_name == ~"::" {
Err(ParseAddrErr { err_msg:fmt!("failed to parse '%s'", ip) })
}
else {
Ok(Ipv6(new_addr))
}
}
}
}
struct GetAddrData {
output_ch: SharedChan<result::Result<~[IpAddr],IpGetAddrErr>>
}
extern fn get_addr_cb(handle: *uv_getaddrinfo_t,
status: libc::c_int,
res: *addrinfo) {
unsafe {
debug!("in get_addr_cb");
let handle_data = get_data_for_req(handle) as
*GetAddrData;
let output_ch = (*handle_data).output_ch.clone();
if status == 0i32 {
if res != (ptr::null::<addrinfo>()) {
let mut out_vec = ~[];
debug!("initial addrinfo: %?", res);
let mut curr_addr = res;
loop {
let new_ip_addr = if ll::is_ipv4_addrinfo(curr_addr) {
Ipv4(copy((
*ll::addrinfo_as_sockaddr_in(curr_addr))))
}
else if ll::is_ipv6_addrinfo(curr_addr) {
Ipv6(copy((
*ll::addrinfo_as_sockaddr_in6(curr_addr))))
}
else {
debug!("curr_addr is not of family AF_INET or \
AF_INET6. Error.");
output_ch.send(
result::Err(GetAddrUnknownError));
break;
};
out_vec.push(new_ip_addr);
let next_addr = ll::get_next_addrinfo(curr_addr);
if next_addr == ptr::null::<addrinfo>() as *addrinfo {
debug!("null next_addr encountered. no mas");
break;
}
else {
curr_addr = next_addr;
debug!("next_addr addrinfo: %?", curr_addr);
}
}
debug!("successful process addrinfo result, len: %?",
out_vec.len());
output_ch.send(result::Ok(out_vec));
}
else {
debug!("addrinfo pointer is NULL");
output_ch.send(
result::Err(GetAddrUnknownError));
}
}
else {
debug!("status != 0 error in get_addr_cb");
output_ch.send(
result::Err(GetAddrUnknownError));
}
if res != (ptr::null::<addrinfo>()) {
uv_freeaddrinfo(res);
}
debug!("leaving get_addr_cb");
}
}
#[cfg(test)]
mod test {
use net::ip::*;
use net::ip::v4;
use net::ip::v6;
use uv;
use std::result;
#[test]
fn test_ip_ipv4_parse_and_format_ip() {
let localhost_str = ~"127.0.0.1";
assert!(format_addr(&v4::parse_addr(localhost_str))
== localhost_str)
}
#[test]
fn test_ip_ipv6_parse_and_format_ip() {
let localhost_str = ~"::1";
let format_result = format_addr(&v6::parse_addr(localhost_str));
debug!("results: expected: '%s' actual: '%s'",
localhost_str, format_result);
assert_eq!(format_result, localhost_str);
}
#[test]
fn test_ip_ipv4_bad_parse() {
match v4::try_parse_addr("b4df00d") {
result::Err(ref err_info) => {
debug!("got error as expected %?", err_info);
assert!(true);
}
result::Ok(ref addr) => {
fail!("Expected failure, but got addr %?", addr);
}
}
}
#[test]
#[ignore(target_os="win32")]
fn test_ip_ipv6_bad_parse() {
match v6::try_parse_addr("::,~2234k;") {
result::Err(ref err_info) => {
debug!("got error as expected %?", err_info);
assert!(true);
}
result::Ok(ref addr) => {
fail!("Expected failure, but got addr %?", addr);
}
}
}
#[test]
#[ignore(reason = "valgrind says it's leaky")]
fn test_ip_get_addr() {
let localhost_name = ~"localhost";
let iotask = &uv::global_loop::get();
let ga_result = get_addr(localhost_name, iotask);
if result::is_err(&ga_result) {
fail!("got err result from net::ip::get_addr();")
}
// note really sure how to reliably test/assert
// this.. mostly just wanting to see it work, atm.
let results = result::unwrap(ga_result);
debug!("test_get_addr: Number of results for %s: %?",
localhost_name, results.len());
for results.iter().advance |r| {
let ipv_prefix = match *r {
Ipv4(_) => ~"IPv4",
Ipv6(_) => ~"IPv6"
};
debug!("test_get_addr: result %s: '%s'",
ipv_prefix, format_addr(r));
}
// at least one result.. this is going to vary from system
// to system, based on stuff like the contents of /etc/hosts
assert!(!results.is_empty());
}
#[test]
#[ignore(reason = "valgrind says it's leaky")]
fn test_ip_get_addr_bad_input() {
let localhost_name = ~"sjkl234m,./sdf";
let iotask = &uv::global_loop::get();
let ga_result = get_addr(localhost_name, iotask);
assert!(result::is_err(&ga_result));
}
}
| 31.183445 | 78 | 0.522563 |
ff953bcfb6c52e08234ca7a098ee2db039b35f42
| 1,991 |
use nu_test_support::fs::{file_contents, Stub::FileWithContent};
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn figures_out_intelligently_where_to_write_out_with_metadata() {
Playground::setup("save_test_1", |dirs, sandbox| {
sandbox.with_files(vec![FileWithContent(
"cargo_sample.toml",
r#"
[package]
name = "nu"
version = "0.1.1"
authors = ["Yehuda Katz <[email protected]>"]
description = "A shell for the GitHub era"
license = "ISC"
edition = "2018"
"#,
)]);
let subject_file = dirs.test().join("cargo_sample.toml");
nu!(
cwd: dirs.root(),
"open save_test_1/cargo_sample.toml | save"
);
let actual = file_contents(&subject_file);
assert!(actual.contains("0.1.1"));
})
}
#[test]
fn writes_out_csv() {
Playground::setup("save_test_2", |dirs, sandbox| {
sandbox.with_files(vec![]);
let expected_file = dirs.test().join("cargo_sample.csv");
nu!(
cwd: dirs.root(),
r#"echo [[name, version, description, license, edition]; [nu, "0.14", "A new type of shell", "MIT", "2018"]] | save save_test_2/cargo_sample.csv"#,
);
let actual = file_contents(expected_file);
println!("{}", actual);
assert!(actual.contains("nu,0.14,A new type of shell,MIT,2018"));
})
}
#[test]
fn save_append_will_create_file_if_not_exists() {
Playground::setup("save_test_3", |dirs, sandbox| {
sandbox.with_files(vec![]);
let expected_file = dirs.test().join("new-file.txt");
nu!(
cwd: dirs.root(),
r#"echo hello | save --raw --append save_test_3/new-file.txt"#,
);
let actual = file_contents(expected_file);
println!("{}", actual);
assert!(actual == "hello");
})
}
| 29.279412 | 159 | 0.557007 |
db502663f12d870b94e719a380866d70f5207a5c
| 78,427 |
// Copyright 2014-2016 bluss and ndarray developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::ptr as std_ptr;
use std::slice;
use rawpointer::PointerExt;
use crate::imp_prelude::*;
use crate::arraytraits;
use crate::dimension;
use crate::dimension::IntoDimension;
use crate::dimension::{
abs_index, axes_of, do_slice, merge_axes, size_of_shape_checked, stride_offset, Axes,
};
use crate::error::{self, ErrorKind, ShapeError};
use crate::itertools::zip;
use crate::zip::Zip;
use crate::iter::{
AxisChunksIter, AxisChunksIterMut, AxisIter, AxisIterMut, ExactChunks, ExactChunksMut,
IndexedIter, IndexedIterMut, Iter, IterMut, Lanes, LanesMut, Windows,
};
use crate::slice::MultiSlice;
use crate::stacking::stack;
use crate::{NdIndex, Slice, SliceInfo, SliceOrIndex};
/// # Methods For All Array Types
impl<A, S, D> ArrayBase<S, D>
where
S: RawData<Elem = A>,
D: Dimension,
{
/// Return the total number of elements in the array.
pub fn len(&self) -> usize {
self.dim.size()
}
/// Return the length of `axis`.
///
/// The axis should be in the range `Axis(` 0 .. *n* `)` where *n* is the
/// number of dimensions (axes) of the array.
///
/// ***Panics*** if the axis is out of bounds.
pub fn len_of(&self, axis: Axis) -> usize {
self.dim[axis.index()]
}
/// Return whether the array has any elements
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Return the number of dimensions (axes) in the array
pub fn ndim(&self) -> usize {
self.dim.ndim()
}
/// Return the shape of the array in its “pattern” form,
/// an integer in the one-dimensional case, tuple in the n-dimensional cases
/// and so on.
pub fn dim(&self) -> D::Pattern {
self.dim.clone().into_pattern()
}
/// Return the shape of the array as it stored in the array.
///
/// This is primarily useful for passing to other `ArrayBase`
/// functions, such as when creating another array of the same
/// shape and dimensionality.
///
/// ```
/// use ndarray::Array;
///
/// let a = Array::from_elem((2, 3), 5.);
///
/// // Create an array of zeros that's the same shape and dimensionality as `a`.
/// let b = Array::<f64, _>::zeros(a.raw_dim());
/// ```
pub fn raw_dim(&self) -> D {
self.dim.clone()
}
/// Return the shape of the array as a slice.
///
/// Note that you probably don't want to use this to create an array of the
/// same shape as another array because creating an array with e.g.
/// [`Array::zeros()`](ArrayBase::zeros) using a shape of type `&[usize]`
/// results in a dynamic-dimensional array. If you want to create an array
/// that has the same shape and dimensionality as another array, use
/// [`.raw_dim()`](ArrayBase::raw_dim) instead:
///
/// ```rust
/// use ndarray::{Array, Array2};
///
/// let a = Array2::<i32>::zeros((3, 4));
/// let shape = a.shape();
/// assert_eq!(shape, &[3, 4]);
///
/// // Since `a.shape()` returned `&[usize]`, we get an `ArrayD` instance:
/// let b = Array::zeros(shape);
/// assert_eq!(a.clone().into_dyn(), b);
///
/// // To get the same dimension type, use `.raw_dim()` instead:
/// let c = Array::zeros(a.raw_dim());
/// assert_eq!(a, c);
/// ```
pub fn shape(&self) -> &[usize] {
self.dim.slice()
}
/// Return the strides of the array as a slice.
pub fn strides(&self) -> &[isize] {
let s = self.strides.slice();
// reinterpret unsigned integer as signed
unsafe { slice::from_raw_parts(s.as_ptr() as *const _, s.len()) }
}
/// Return the stride of `axis`.
///
/// The axis should be in the range `Axis(` 0 .. *n* `)` where *n* is the
/// number of dimensions (axes) of the array.
///
/// ***Panics*** if the axis is out of bounds.
pub fn stride_of(&self, axis: Axis) -> isize {
// strides are reinterpreted as isize
self.strides[axis.index()] as isize
}
/// Return a read-only view of the array
pub fn view(&self) -> ArrayView<'_, A, D>
where
S: Data,
{
debug_assert!(self.pointer_is_inbounds());
unsafe { ArrayView::new(self.ptr, self.dim.clone(), self.strides.clone()) }
}
/// Return a read-write view of the array
pub fn view_mut(&mut self) -> ArrayViewMut<'_, A, D>
where
S: DataMut,
{
self.ensure_unique();
unsafe { ArrayViewMut::new(self.ptr, self.dim.clone(), self.strides.clone()) }
}
/// Return an uniquely owned copy of the array.
///
/// If the input array is contiguous and its strides are positive, then the
/// output array will have the same memory layout. Otherwise, the layout of
/// the output array is unspecified. If you need a particular layout, you
/// can allocate a new array with the desired memory layout and
/// [`.assign()`](#method.assign) the data. Alternatively, you can collect
/// an iterator, like this for a result in standard layout:
///
/// ```
/// # use ndarray::prelude::*;
/// # let arr = Array::from_shape_vec((2, 2).f(), vec![1, 2, 3, 4]).unwrap();
/// # let owned = {
/// Array::from_shape_vec(arr.raw_dim(), arr.iter().cloned().collect()).unwrap()
/// # };
/// # assert!(owned.is_standard_layout());
/// # assert_eq!(arr, owned);
/// ```
///
/// or this for a result in column-major (Fortran) layout:
///
/// ```
/// # use ndarray::prelude::*;
/// # let arr = Array::from_shape_vec((2, 2), vec![1, 2, 3, 4]).unwrap();
/// # let owned = {
/// Array::from_shape_vec(arr.raw_dim().f(), arr.t().iter().cloned().collect()).unwrap()
/// # };
/// # assert!(owned.t().is_standard_layout());
/// # assert_eq!(arr, owned);
/// ```
pub fn to_owned(&self) -> Array<A, D>
where
A: Clone,
S: Data,
{
if let Some(slc) = self.as_slice_memory_order() {
unsafe {
Array::from_shape_vec_unchecked(
self.dim.clone().strides(self.strides.clone()),
slc.to_vec(),
)
}
} else {
self.map(|x| x.clone())
}
}
/// Return a shared ownership (copy on write) array.
pub fn to_shared(&self) -> ArcArray<A, D>
where
A: Clone,
S: Data,
{
// FIXME: Avoid copying if it’s already an ArcArray.
self.to_owned().into_shared()
}
/// Turn the array into a uniquely owned array, cloning the array elements
/// if necessary.
pub fn into_owned(self) -> Array<A, D>
where
A: Clone,
S: Data,
{
S::into_owned(self)
}
/// Turn the array into a shared ownership (copy on write) array,
/// without any copying.
pub fn into_shared(self) -> ArcArray<A, D>
where
S: DataOwned,
{
let data = self.data.into_shared();
ArrayBase {
data,
ptr: self.ptr,
dim: self.dim,
strides: self.strides,
}
}
/// Returns a reference to the first element of the array, or `None` if it
/// is empty.
pub fn first(&self) -> Option<&A>
where
S: Data,
{
if self.is_empty() {
None
} else {
Some(unsafe { &*self.as_ptr() })
}
}
/// Returns a mutable reference to the first element of the array, or
/// `None` if it is empty.
pub fn first_mut(&mut self) -> Option<&mut A>
where
S: DataMut,
{
if self.is_empty() {
None
} else {
Some(unsafe { &mut *self.as_mut_ptr() })
}
}
/// Return an iterator of references to the elements of the array.
///
/// Elements are visited in the *logical order* of the array, which
/// is where the rightmost index is varying the fastest.
///
/// Iterator element type is `&A`.
pub fn iter(&self) -> Iter<'_, A, D>
where
S: Data,
{
debug_assert!(self.pointer_is_inbounds());
self.view().into_iter_()
}
/// Return an iterator of mutable references to the elements of the array.
///
/// Elements are visited in the *logical order* of the array, which
/// is where the rightmost index is varying the fastest.
///
/// Iterator element type is `&mut A`.
pub fn iter_mut(&mut self) -> IterMut<'_, A, D>
where
S: DataMut,
{
self.view_mut().into_iter_()
}
/// Return an iterator of indexes and references to the elements of the array.
///
/// Elements are visited in the *logical order* of the array, which
/// is where the rightmost index is varying the fastest.
///
/// Iterator element type is `(D::Pattern, &A)`.
///
/// See also [`Zip::indexed`](struct.Zip.html)
pub fn indexed_iter(&self) -> IndexedIter<'_, A, D>
where
S: Data,
{
IndexedIter::new(self.view().into_elements_base())
}
/// Return an iterator of indexes and mutable references to the elements of the array.
///
/// Elements are visited in the *logical order* of the array, which
/// is where the rightmost index is varying the fastest.
///
/// Iterator element type is `(D::Pattern, &mut A)`.
pub fn indexed_iter_mut(&mut self) -> IndexedIterMut<'_, A, D>
where
S: DataMut,
{
IndexedIterMut::new(self.view_mut().into_elements_base())
}
/// Return a sliced view of the array.
///
/// See [*Slicing*](#slicing) for full documentation.
/// See also [`SliceInfo`] and [`D::SliceArg`].
///
/// [`SliceInfo`]: struct.SliceInfo.html
/// [`D::SliceArg`]: trait.Dimension.html#associatedtype.SliceArg
///
/// **Panics** if an index is out of bounds or step size is zero.<br>
/// (**Panics** if `D` is `IxDyn` and `info` does not match the number of array axes.)
pub fn slice<Do>(&self, info: &SliceInfo<D::SliceArg, Do>) -> ArrayView<'_, A, Do>
where
Do: Dimension,
S: Data,
{
self.view().slice_move(info)
}
/// Return a sliced read-write view of the array.
///
/// See [*Slicing*](#slicing) for full documentation.
/// See also [`SliceInfo`] and [`D::SliceArg`].
///
/// [`SliceInfo`]: struct.SliceInfo.html
/// [`D::SliceArg`]: trait.Dimension.html#associatedtype.SliceArg
///
/// **Panics** if an index is out of bounds or step size is zero.<br>
/// (**Panics** if `D` is `IxDyn` and `info` does not match the number of array axes.)
pub fn slice_mut<Do>(&mut self, info: &SliceInfo<D::SliceArg, Do>) -> ArrayViewMut<'_, A, Do>
where
Do: Dimension,
S: DataMut,
{
self.view_mut().slice_move(info)
}
/// Return multiple disjoint, sliced, mutable views of the array.
///
/// See [*Slicing*](#slicing) for full documentation.
/// See also [`SliceInfo`] and [`D::SliceArg`].
///
/// [`SliceInfo`]: struct.SliceInfo.html
/// [`D::SliceArg`]: trait.Dimension.html#associatedtype.SliceArg
///
/// **Panics** if any of the following occur:
///
/// * if any of the views would intersect (i.e. if any element would appear in multiple slices)
/// * if an index is out of bounds or step size is zero
/// * if `D` is `IxDyn` and `info` does not match the number of array axes
///
/// # Example
///
/// ```
/// use ndarray::{arr2, s};
///
/// let mut a = arr2(&[[1, 2, 3], [4, 5, 6]]);
/// let (mut edges, mut middle) = a.multi_slice_mut((s![.., ..;2], s![.., 1]));
/// edges.fill(1);
/// middle.fill(0);
/// assert_eq!(a, arr2(&[[1, 0, 1], [1, 0, 1]]));
/// ```
pub fn multi_slice_mut<'a, M>(&'a mut self, info: M) -> M::Output
where
M: MultiSlice<'a, A, D>,
S: DataMut,
{
info.multi_slice_move(self.view_mut())
}
/// Slice the array, possibly changing the number of dimensions.
///
/// See [*Slicing*](#slicing) for full documentation.
/// See also [`SliceInfo`] and [`D::SliceArg`].
///
/// [`SliceInfo`]: struct.SliceInfo.html
/// [`D::SliceArg`]: trait.Dimension.html#associatedtype.SliceArg
///
/// **Panics** if an index is out of bounds or step size is zero.<br>
/// (**Panics** if `D` is `IxDyn` and `info` does not match the number of array axes.)
pub fn slice_move<Do>(mut self, info: &SliceInfo<D::SliceArg, Do>) -> ArrayBase<S, Do>
where
Do: Dimension,
{
// Slice and collapse in-place without changing the number of dimensions.
self.slice_collapse(&*info);
let indices: &[SliceOrIndex] = (**info).as_ref();
// Copy the dim and strides that remain after removing the subview axes.
let out_ndim = info.out_ndim();
let mut new_dim = Do::zeros(out_ndim);
let mut new_strides = Do::zeros(out_ndim);
izip!(self.dim.slice(), self.strides.slice(), indices)
.filter_map(|(d, s, slice_or_index)| match slice_or_index {
SliceOrIndex::Slice { .. } => Some((d, s)),
SliceOrIndex::Index(_) => None,
})
.zip(izip!(new_dim.slice_mut(), new_strides.slice_mut()))
.for_each(|((d, s), (new_d, new_s))| {
*new_d = *d;
*new_s = *s;
});
ArrayBase {
ptr: self.ptr,
data: self.data,
dim: new_dim,
strides: new_strides,
}
}
/// Slice the array in place without changing the number of dimensions.
///
/// Note that [`&SliceInfo`](struct.SliceInfo.html) (produced by the
/// [`s![]`](macro.s!.html) macro) will usually coerce into `&D::SliceArg`
/// automatically, but in some cases (e.g. if `D` is `IxDyn`), you may need
/// to call `.as_ref()`.
///
/// See [*Slicing*](#slicing) for full documentation.
/// See also [`D::SliceArg`].
///
/// [`D::SliceArg`]: trait.Dimension.html#associatedtype.SliceArg
///
/// **Panics** if an index is out of bounds or step size is zero.<br>
/// (**Panics** if `D` is `IxDyn` and `indices` does not match the number of array axes.)
pub fn slice_collapse(&mut self, indices: &D::SliceArg) {
let indices: &[SliceOrIndex] = indices.as_ref();
assert_eq!(indices.len(), self.ndim());
indices
.iter()
.enumerate()
.for_each(|(axis, &slice_or_index)| match slice_or_index {
SliceOrIndex::Slice { start, end, step } => {
self.slice_axis_inplace(Axis(axis), Slice { start, end, step })
}
SliceOrIndex::Index(index) => {
let i_usize = abs_index(self.len_of(Axis(axis)), index);
self.collapse_axis(Axis(axis), i_usize)
}
});
}
/// Slice the array in place without changing the number of dimensions.
///
/// **Panics** if an index is out of bounds or step size is zero.<br>
/// (**Panics** if `D` is `IxDyn` and `indices` does not match the number of array axes.)
#[deprecated(note = "renamed to `slice_collapse`", since = "0.12.1")]
pub fn slice_inplace(&mut self, indices: &D::SliceArg) {
self.slice_collapse(indices)
}
/// Return a view of the array, sliced along the specified axis.
///
/// **Panics** if an index is out of bounds or step size is zero.<br>
/// **Panics** if `axis` is out of bounds.
pub fn slice_axis(&self, axis: Axis, indices: Slice) -> ArrayView<'_, A, D>
where
S: Data,
{
let mut view = self.view();
view.slice_axis_inplace(axis, indices);
view
}
/// Return a mutable view of the array, sliced along the specified axis.
///
/// **Panics** if an index is out of bounds or step size is zero.<br>
/// **Panics** if `axis` is out of bounds.
pub fn slice_axis_mut(&mut self, axis: Axis, indices: Slice) -> ArrayViewMut<'_, A, D>
where
S: DataMut,
{
let mut view_mut = self.view_mut();
view_mut.slice_axis_inplace(axis, indices);
view_mut
}
/// Slice the array in place along the specified axis.
///
/// **Panics** if an index is out of bounds or step size is zero.<br>
/// **Panics** if `axis` is out of bounds.
pub fn slice_axis_inplace(&mut self, axis: Axis, indices: Slice) {
let offset = do_slice(
&mut self.dim.slice_mut()[axis.index()],
&mut self.strides.slice_mut()[axis.index()],
indices,
);
unsafe {
self.ptr = self.ptr.offset(offset);
}
debug_assert!(self.pointer_is_inbounds());
}
/// Return a reference to the element at `index`, or return `None`
/// if the index is out of bounds.
///
/// Arrays also support indexing syntax: `array[index]`.
///
/// ```
/// use ndarray::arr2;
///
/// let a = arr2(&[[1., 2.],
/// [3., 4.]]);
///
/// assert!(
/// a.get((0, 1)) == Some(&2.) &&
/// a.get((0, 2)) == None &&
/// a[(0, 1)] == 2. &&
/// a[[0, 1]] == 2.
/// );
/// ```
pub fn get<I>(&self, index: I) -> Option<&A>
where
I: NdIndex<D>,
S: Data,
{
unsafe { self.get_ptr(index).map(|ptr| &*ptr) }
}
pub(crate) fn get_ptr<I>(&self, index: I) -> Option<*const A>
where
I: NdIndex<D>,
{
let ptr = self.ptr;
index
.index_checked(&self.dim, &self.strides)
.map(move |offset| unsafe { ptr.as_ptr().offset(offset) as *const _ })
}
/// Return a mutable reference to the element at `index`, or return `None`
/// if the index is out of bounds.
pub fn get_mut<I>(&mut self, index: I) -> Option<&mut A>
where
S: DataMut,
I: NdIndex<D>,
{
unsafe { self.get_ptr_mut(index).map(|ptr| &mut *ptr) }
}
pub(crate) fn get_ptr_mut<I>(&mut self, index: I) -> Option<*mut A>
where
S: RawDataMut,
I: NdIndex<D>,
{
// const and mut are separate to enforce &mutness as well as the
// extra code in as_mut_ptr
let ptr = self.as_mut_ptr();
index
.index_checked(&self.dim, &self.strides)
.map(move |offset| unsafe { ptr.offset(offset) })
}
/// Perform *unchecked* array indexing.
///
/// Return a reference to the element at `index`.
///
/// **Note:** only unchecked for non-debug builds of ndarray.
///
/// # Safety
///
/// The caller must ensure that the index is in-bounds.
#[inline]
pub unsafe fn uget<I>(&self, index: I) -> &A
where
S: Data,
I: NdIndex<D>,
{
arraytraits::debug_bounds_check(self, &index);
let off = index.index_unchecked(&self.strides);
&*self.ptr.as_ptr().offset(off)
}
/// Perform *unchecked* array indexing.
///
/// Return a mutable reference to the element at `index`.
///
/// **Note:** Only unchecked for non-debug builds of ndarray.
///
/// # Safety
///
/// The caller must ensure that:
///
/// 1. the index is in-bounds and
///
/// 2. the data is uniquely held by the array. (This property is guaranteed
/// for `Array` and `ArrayViewMut`, but not for `ArcArray` or `CowArray`.)
#[inline]
pub unsafe fn uget_mut<I>(&mut self, index: I) -> &mut A
where
S: DataMut,
I: NdIndex<D>,
{
debug_assert!(self.data.is_unique());
arraytraits::debug_bounds_check(self, &index);
let off = index.index_unchecked(&self.strides);
&mut *self.ptr.as_ptr().offset(off)
}
/// Swap elements at indices `index1` and `index2`.
///
/// Indices may be equal.
///
/// ***Panics*** if an index is out of bounds.
pub fn swap<I>(&mut self, index1: I, index2: I)
where
S: DataMut,
I: NdIndex<D>,
{
let ptr1: *mut _ = &mut self[index1];
let ptr2: *mut _ = &mut self[index2];
unsafe {
std_ptr::swap(ptr1, ptr2);
}
}
/// Swap elements *unchecked* at indices `index1` and `index2`.
///
/// Indices may be equal.
///
/// **Note:** only unchecked for non-debug builds of ndarray.
///
/// # Safety
///
/// The caller must ensure that:
///
/// 1. both `index1 and `index2` are in-bounds and
///
/// 2. the data is uniquely held by the array. (This property is guaranteed
/// for `Array` and `ArrayViewMut`, but not for `ArcArray` or `CowArray`.)
pub unsafe fn uswap<I>(&mut self, index1: I, index2: I)
where
S: DataMut,
I: NdIndex<D>,
{
debug_assert!(self.data.is_unique());
arraytraits::debug_bounds_check(self, &index1);
arraytraits::debug_bounds_check(self, &index2);
let off1 = index1.index_unchecked(&self.strides);
let off2 = index2.index_unchecked(&self.strides);
std_ptr::swap(
self.ptr.as_ptr().offset(off1),
self.ptr.as_ptr().offset(off2),
);
}
// `get` for zero-dimensional arrays
// panics if dimension is not zero. otherwise an element is always present.
fn get_0d(&self) -> &A
where
S: Data,
{
assert!(self.ndim() == 0);
unsafe { &*self.as_ptr() }
}
/// Returns a view restricted to `index` along the axis, with the axis
/// removed.
///
/// See [*Subviews*](#subviews) for full documentation.
///
/// **Panics** if `axis` or `index` is out of bounds.
///
/// ```
/// use ndarray::{arr2, ArrayView, Axis};
///
/// let a = arr2(&[[1., 2. ], // ... axis 0, row 0
/// [3., 4. ], // --- axis 0, row 1
/// [5., 6. ]]); // ... axis 0, row 2
/// // . \
/// // . axis 1, column 1
/// // axis 1, column 0
/// assert!(
/// a.index_axis(Axis(0), 1) == ArrayView::from(&[3., 4.]) &&
/// a.index_axis(Axis(1), 1) == ArrayView::from(&[2., 4., 6.])
/// );
/// ```
pub fn index_axis(&self, axis: Axis, index: usize) -> ArrayView<'_, A, D::Smaller>
where
S: Data,
D: RemoveAxis,
{
self.view().index_axis_move(axis, index)
}
/// Returns a mutable view restricted to `index` along the axis, with the
/// axis removed.
///
/// **Panics** if `axis` or `index` is out of bounds.
///
/// ```
/// use ndarray::{arr2, aview2, Axis};
///
/// let mut a = arr2(&[[1., 2. ],
/// [3., 4. ]]);
/// // . \
/// // . axis 1, column 1
/// // axis 1, column 0
///
/// {
/// let mut column1 = a.index_axis_mut(Axis(1), 1);
/// column1 += 10.;
/// }
///
/// assert!(
/// a == aview2(&[[1., 12.],
/// [3., 14.]])
/// );
/// ```
pub fn index_axis_mut(&mut self, axis: Axis, index: usize) -> ArrayViewMut<'_, A, D::Smaller>
where
S: DataMut,
D: RemoveAxis,
{
self.view_mut().index_axis_move(axis, index)
}
/// Collapses the array to `index` along the axis and removes the axis.
///
/// See [`.index_axis()`](#method.index_axis) and [*Subviews*](#subviews) for full documentation.
///
/// **Panics** if `axis` or `index` is out of bounds.
pub fn index_axis_move(mut self, axis: Axis, index: usize) -> ArrayBase<S, D::Smaller>
where
D: RemoveAxis,
{
self.collapse_axis(axis, index);
let dim = self.dim.remove_axis(axis);
let strides = self.strides.remove_axis(axis);
ArrayBase {
ptr: self.ptr,
data: self.data,
dim,
strides,
}
}
/// Selects `index` along the axis, collapsing the axis into length one.
///
/// **Panics** if `axis` or `index` is out of bounds.
pub fn collapse_axis(&mut self, axis: Axis, index: usize) {
let offset = dimension::do_collapse_axis(&mut self.dim, &self.strides, axis.index(), index);
self.ptr = unsafe { self.ptr.offset(offset) };
debug_assert!(self.pointer_is_inbounds());
}
/// Along `axis`, select the subview `index` and return a
/// view with that axis removed.
///
/// **Panics** if `axis` or `index` is out of bounds.
#[deprecated(note = "renamed to `index_axis`", since = "0.12.1")]
pub fn subview(&self, axis: Axis, index: Ix) -> ArrayView<'_, A, D::Smaller>
where
S: Data,
D: RemoveAxis,
{
self.index_axis(axis, index)
}
/// Along `axis`, select the subview `index` and return a read-write view
/// with the axis removed.
///
/// **Panics** if `axis` or `index` is out of bounds.
#[deprecated(note = "renamed to `index_axis_mut`", since = "0.12.1")]
pub fn subview_mut(&mut self, axis: Axis, index: Ix) -> ArrayViewMut<'_, A, D::Smaller>
where
S: DataMut,
D: RemoveAxis,
{
self.index_axis_mut(axis, index)
}
/// Collapse dimension `axis` into length one,
/// and select the subview of `index` along that axis.
///
/// **Panics** if `index` is past the length of the axis.
#[deprecated(note = "renamed to `collapse_axis`", since = "0.12.1")]
pub fn subview_inplace(&mut self, axis: Axis, index: Ix) {
self.collapse_axis(axis, index)
}
/// Along `axis`, select the subview `index` and return `self`
/// with that axis removed.
#[deprecated(note = "renamed to `index_axis_move`", since = "0.12.1")]
pub fn into_subview(self, axis: Axis, index: Ix) -> ArrayBase<S, D::Smaller>
where
D: RemoveAxis,
{
self.index_axis_move(axis, index)
}
/// Along `axis`, select arbitrary subviews corresponding to `indices`
/// and and copy them into a new array.
///
/// **Panics** if `axis` or an element of `indices` is out of bounds.
///
/// ```
/// use ndarray::{arr2, Axis};
///
/// let x = arr2(&[[0., 1.],
/// [2., 3.],
/// [4., 5.],
/// [6., 7.],
/// [8., 9.]]);
///
/// let r = x.select(Axis(0), &[0, 4, 3]);
/// assert!(
/// r == arr2(&[[0., 1.],
/// [8., 9.],
/// [6., 7.]])
///);
/// ```
pub fn select(&self, axis: Axis, indices: &[Ix]) -> Array<A, D>
where
A: Copy,
S: Data,
D: RemoveAxis,
{
let mut subs = vec![self.view(); indices.len()];
for (&i, sub) in zip(indices, &mut subs[..]) {
sub.collapse_axis(axis, i);
}
if subs.is_empty() {
let mut dim = self.raw_dim();
dim.set_axis(axis, 0);
unsafe { Array::from_shape_vec_unchecked(dim, vec![]) }
} else {
stack(axis, &subs).unwrap()
}
}
/// Return a producer and iterable that traverses over the *generalized*
/// rows of the array. For a 2D array these are the regular rows.
///
/// This is equivalent to `.lanes(Axis(n - 1))` where *n* is `self.ndim()`.
///
/// For an array of dimensions *a* × *b* × *c* × ... × *l* × *m*
/// it has *a* × *b* × *c* × ... × *l* rows each of length *m*.
///
/// For example, in a 2 × 2 × 3 array, each row is 3 elements long
/// and there are 2 × 2 = 4 rows in total.
///
/// Iterator element is `ArrayView1<A>` (1D array view).
///
/// ```
/// use ndarray::{arr3, Axis, arr1};
///
/// let a = arr3(&[[[ 0, 1, 2], // -- row 0, 0
/// [ 3, 4, 5]], // -- row 0, 1
/// [[ 6, 7, 8], // -- row 1, 0
/// [ 9, 10, 11]]]); // -- row 1, 1
///
/// // `genrows` will yield the four generalized rows of the array.
/// for row in a.genrows() {
/// /* loop body */
/// }
/// ```
pub fn genrows(&self) -> Lanes<'_, A, D::Smaller>
where
S: Data,
{
let mut n = self.ndim();
if n == 0 {
n += 1;
}
Lanes::new(self.view(), Axis(n - 1))
}
/// Return a producer and iterable that traverses over the *generalized*
/// rows of the array and yields mutable array views.
///
/// Iterator element is `ArrayView1<A>` (1D read-write array view).
pub fn genrows_mut(&mut self) -> LanesMut<'_, A, D::Smaller>
where
S: DataMut,
{
let mut n = self.ndim();
if n == 0 {
n += 1;
}
LanesMut::new(self.view_mut(), Axis(n - 1))
}
/// Return a producer and iterable that traverses over the *generalized*
/// columns of the array. For a 2D array these are the regular columns.
///
/// This is equivalent to `.lanes(Axis(0))`.
///
/// For an array of dimensions *a* × *b* × *c* × ... × *l* × *m*
/// it has *b* × *c* × ... × *l* × *m* columns each of length *a*.
///
/// For example, in a 2 × 2 × 3 array, each column is 2 elements long
/// and there are 2 × 3 = 6 columns in total.
///
/// Iterator element is `ArrayView1<A>` (1D array view).
///
/// ```
/// use ndarray::{arr3, Axis, arr1};
///
/// // The generalized columns of a 3D array:
/// // are directed along the 0th axis: 0 and 6, 1 and 7 and so on...
/// let a = arr3(&[[[ 0, 1, 2], [ 3, 4, 5]],
/// [[ 6, 7, 8], [ 9, 10, 11]]]);
///
/// // Here `gencolumns` will yield the six generalized columns of the array.
/// for row in a.gencolumns() {
/// /* loop body */
/// }
/// ```
pub fn gencolumns(&self) -> Lanes<'_, A, D::Smaller>
where
S: Data,
{
Lanes::new(self.view(), Axis(0))
}
/// Return a producer and iterable that traverses over the *generalized*
/// columns of the array and yields mutable array views.
///
/// Iterator element is `ArrayView1<A>` (1D read-write array view).
pub fn gencolumns_mut(&mut self) -> LanesMut<'_, A, D::Smaller>
where
S: DataMut,
{
LanesMut::new(self.view_mut(), Axis(0))
}
/// Return a producer and iterable that traverses over all 1D lanes
/// pointing in the direction of `axis`.
///
/// When the pointing in the direction of the first axis, they are *columns*,
/// in the direction of the last axis *rows*; in general they are all
/// *lanes* and are one dimensional.
///
/// Iterator element is `ArrayView1<A>` (1D array view).
///
/// ```
/// use ndarray::{arr3, aview1, Axis};
///
/// let a = arr3(&[[[ 0, 1, 2],
/// [ 3, 4, 5]],
/// [[ 6, 7, 8],
/// [ 9, 10, 11]]]);
///
/// let inner0 = a.lanes(Axis(0));
/// let inner1 = a.lanes(Axis(1));
/// let inner2 = a.lanes(Axis(2));
///
/// // The first lane for axis 0 is [0, 6]
/// assert_eq!(inner0.into_iter().next().unwrap(), aview1(&[0, 6]));
/// // The first lane for axis 1 is [0, 3]
/// assert_eq!(inner1.into_iter().next().unwrap(), aview1(&[0, 3]));
/// // The first lane for axis 2 is [0, 1, 2]
/// assert_eq!(inner2.into_iter().next().unwrap(), aview1(&[0, 1, 2]));
/// ```
pub fn lanes(&self, axis: Axis) -> Lanes<'_, A, D::Smaller>
where
S: Data,
{
Lanes::new(self.view(), axis)
}
/// Return a producer and iterable that traverses over all 1D lanes
/// pointing in the direction of `axis`.
///
/// Iterator element is `ArrayViewMut1<A>` (1D read-write array view).
pub fn lanes_mut(&mut self, axis: Axis) -> LanesMut<'_, A, D::Smaller>
where
S: DataMut,
{
LanesMut::new(self.view_mut(), axis)
}
/// Return an iterator that traverses over the outermost dimension
/// and yields each subview.
///
/// This is equivalent to `.axis_iter(Axis(0))`.
///
/// Iterator element is `ArrayView<A, D::Smaller>` (read-only array view).
#[allow(deprecated)]
pub fn outer_iter(&self) -> AxisIter<'_, A, D::Smaller>
where
S: Data,
D: RemoveAxis,
{
self.view().into_outer_iter()
}
/// Return an iterator that traverses over the outermost dimension
/// and yields each subview.
///
/// This is equivalent to `.axis_iter_mut(Axis(0))`.
///
/// Iterator element is `ArrayViewMut<A, D::Smaller>` (read-write array view).
#[allow(deprecated)]
pub fn outer_iter_mut(&mut self) -> AxisIterMut<'_, A, D::Smaller>
where
S: DataMut,
D: RemoveAxis,
{
self.view_mut().into_outer_iter()
}
/// Return an iterator that traverses over `axis`
/// and yields each subview along it.
///
/// For example, in a 3 × 4 × 5 array, with `axis` equal to `Axis(2)`,
/// the iterator element
/// is a 3 × 4 subview (and there are 5 in total), as shown
/// in the picture below.
///
/// Iterator element is `ArrayView<A, D::Smaller>` (read-only array view).
///
/// See [*Subviews*](#subviews) for full documentation.
///
/// **Panics** if `axis` is out of bounds.
///
/// <img src="https://rust-ndarray.github.io/ndarray/images/axis_iter_3_4_5.svg" height="250px">
pub fn axis_iter(&self, axis: Axis) -> AxisIter<'_, A, D::Smaller>
where
S: Data,
D: RemoveAxis,
{
AxisIter::new(self.view(), axis)
}
/// Return an iterator that traverses over `axis`
/// and yields each mutable subview along it.
///
/// Iterator element is `ArrayViewMut<A, D::Smaller>`
/// (read-write array view).
///
/// **Panics** if `axis` is out of bounds.
pub fn axis_iter_mut(&mut self, axis: Axis) -> AxisIterMut<'_, A, D::Smaller>
where
S: DataMut,
D: RemoveAxis,
{
AxisIterMut::new(self.view_mut(), axis)
}
/// Return an iterator that traverses over `axis` by chunks of `size`,
/// yielding non-overlapping views along that axis.
///
/// Iterator element is `ArrayView<A, D>`
///
/// The last view may have less elements if `size` does not divide
/// the axis' dimension.
///
/// **Panics** if `axis` is out of bounds or if `size` is zero.
///
/// ```
/// use ndarray::Array;
/// use ndarray::{arr3, Axis};
/// use std::iter::FromIterator;
///
/// let a = Array::from_iter(0..28).into_shape((2, 7, 2)).unwrap();
/// let mut iter = a.axis_chunks_iter(Axis(1), 2);
///
/// // first iteration yields a 2 × 2 × 2 view
/// assert_eq!(iter.next().unwrap(),
/// arr3(&[[[ 0, 1], [ 2, 3]],
/// [[14, 15], [16, 17]]]));
///
/// // however the last element is a 2 × 1 × 2 view since 7 % 2 == 1
/// assert_eq!(iter.next_back().unwrap(), arr3(&[[[12, 13]],
/// [[26, 27]]]));
/// ```
pub fn axis_chunks_iter(&self, axis: Axis, size: usize) -> AxisChunksIter<'_, A, D>
where
S: Data,
{
AxisChunksIter::new(self.view(), axis, size)
}
/// Return an iterator that traverses over `axis` by chunks of `size`,
/// yielding non-overlapping read-write views along that axis.
///
/// Iterator element is `ArrayViewMut<A, D>`
///
/// **Panics** if `axis` is out of bounds or if `size` is zero.
pub fn axis_chunks_iter_mut(&mut self, axis: Axis, size: usize) -> AxisChunksIterMut<'_, A, D>
where
S: DataMut,
{
AxisChunksIterMut::new(self.view_mut(), axis, size)
}
/// Return an exact chunks producer (and iterable).
///
/// It produces the whole chunks of a given n-dimensional chunk size,
/// skipping the remainder along each dimension that doesn't fit evenly.
///
/// The produced element is a `ArrayView<A, D>` with exactly the dimension
/// `chunk_size`.
///
/// **Panics** if any dimension of `chunk_size` is zero<br>
/// (**Panics** if `D` is `IxDyn` and `chunk_size` does not match the
/// number of array axes.)
pub fn exact_chunks<E>(&self, chunk_size: E) -> ExactChunks<'_, A, D>
where
E: IntoDimension<Dim = D>,
S: Data,
{
ExactChunks::new(self.view(), chunk_size)
}
/// Return an exact chunks producer (and iterable).
///
/// It produces the whole chunks of a given n-dimensional chunk size,
/// skipping the remainder along each dimension that doesn't fit evenly.
///
/// The produced element is a `ArrayViewMut<A, D>` with exactly
/// the dimension `chunk_size`.
///
/// **Panics** if any dimension of `chunk_size` is zero<br>
/// (**Panics** if `D` is `IxDyn` and `chunk_size` does not match the
/// number of array axes.)
///
/// ```rust
/// use ndarray::Array;
/// use ndarray::arr2;
/// let mut a = Array::zeros((6, 7));
///
/// // Fill each 2 × 2 chunk with the index of where it appeared in iteration
/// for (i, mut chunk) in a.exact_chunks_mut((2, 2)).into_iter().enumerate() {
/// chunk.fill(i);
/// }
///
/// // The resulting array is:
/// assert_eq!(
/// a,
/// arr2(&[[0, 0, 1, 1, 2, 2, 0],
/// [0, 0, 1, 1, 2, 2, 0],
/// [3, 3, 4, 4, 5, 5, 0],
/// [3, 3, 4, 4, 5, 5, 0],
/// [6, 6, 7, 7, 8, 8, 0],
/// [6, 6, 7, 7, 8, 8, 0]]));
/// ```
pub fn exact_chunks_mut<E>(&mut self, chunk_size: E) -> ExactChunksMut<'_, A, D>
where
E: IntoDimension<Dim = D>,
S: DataMut,
{
ExactChunksMut::new(self.view_mut(), chunk_size)
}
/// Return a window producer and iterable.
///
/// The windows are all distinct overlapping views of size `window_size`
/// that fit into the array's shape.
///
/// Will yield over no elements if window size is larger
/// than the actual array size of any dimension.
///
/// The produced element is an `ArrayView<A, D>` with exactly the dimension
/// `window_size`.
///
/// **Panics** if any dimension of `window_size` is zero.<br>
/// (**Panics** if `D` is `IxDyn` and `window_size` does not match the
/// number of array axes.)
///
/// This is an illustration of the 2×2 windows in a 3×4 array:
///
/// ```text
/// ──▶ Axis(1)
///
/// │ ┏━━━━━┳━━━━━┱─────┬─────┐ ┌─────┲━━━━━┳━━━━━┱─────┐ ┌─────┬─────┲━━━━━┳━━━━━┓
/// ▼ ┃ a₀₀ ┃ a₀₁ ┃ │ │ │ ┃ a₀₁ ┃ a₀₂ ┃ │ │ │ ┃ a₀₂ ┃ a₀₃ ┃
/// Axis(0) ┣━━━━━╋━━━━━╉─────┼─────┤ ├─────╊━━━━━╋━━━━━╉─────┤ ├─────┼─────╊━━━━━╋━━━━━┫
/// ┃ a₁₀ ┃ a₁₁ ┃ │ │ │ ┃ a₁₁ ┃ a₁₂ ┃ │ │ │ ┃ a₁₂ ┃ a₁₃ ┃
/// ┡━━━━━╇━━━━━╃─────┼─────┤ ├─────╄━━━━━╇━━━━━╃─────┤ ├─────┼─────╄━━━━━╇━━━━━┩
/// │ │ │ │ │ │ │ │ │ │ │ │ │ │ │
/// └─────┴─────┴─────┴─────┘ └─────┴─────┴─────┴─────┘ └─────┴─────┴─────┴─────┘
///
/// ┌─────┬─────┬─────┬─────┐ ┌─────┬─────┬─────┬─────┐ ┌─────┬─────┬─────┬─────┐
/// │ │ │ │ │ │ │ │ │ │ │ │ │ │ │
/// ┢━━━━━╈━━━━━╅─────┼─────┤ ├─────╆━━━━━╈━━━━━╅─────┤ ├─────┼─────╆━━━━━╈━━━━━┪
/// ┃ a₁₀ ┃ a₁₁ ┃ │ │ │ ┃ a₁₁ ┃ a₁₂ ┃ │ │ │ ┃ a₁₂ ┃ a₁₃ ┃
/// ┣━━━━━╋━━━━━╉─────┼─────┤ ├─────╊━━━━━╋━━━━━╉─────┤ ├─────┼─────╊━━━━━╋━━━━━┫
/// ┃ a₂₀ ┃ a₂₁ ┃ │ │ │ ┃ a₂₁ ┃ a₂₂ ┃ │ │ │ ┃ a₂₂ ┃ a₂₃ ┃
/// ┗━━━━━┻━━━━━┹─────┴─────┘ └─────┺━━━━━┻━━━━━┹─────┘ └─────┴─────┺━━━━━┻━━━━━┛
/// ```
pub fn windows<E>(&self, window_size: E) -> Windows<'_, A, D>
where
E: IntoDimension<Dim = D>,
S: Data,
{
Windows::new(self.view(), window_size)
}
// Return (length, stride) for diagonal
fn diag_params(&self) -> (Ix, Ixs) {
/* empty shape has len 1 */
let len = self.dim.slice().iter().cloned().min().unwrap_or(1);
let stride = self.strides().iter().sum();
(len, stride)
}
/// Return an view of the diagonal elements of the array.
///
/// The diagonal is simply the sequence indexed by *(0, 0, .., 0)*,
/// *(1, 1, ..., 1)* etc as long as all axes have elements.
pub fn diag(&self) -> ArrayView1<'_, A>
where
S: Data,
{
self.view().into_diag()
}
/// Return a read-write view over the diagonal elements of the array.
pub fn diag_mut(&mut self) -> ArrayViewMut1<'_, A>
where
S: DataMut,
{
self.view_mut().into_diag()
}
/// Return the diagonal as a one-dimensional array.
pub fn into_diag(self) -> ArrayBase<S, Ix1> {
let (len, stride) = self.diag_params();
ArrayBase {
data: self.data,
ptr: self.ptr,
dim: Ix1(len),
strides: Ix1(stride as Ix),
}
}
/// Try to make the array unshared.
///
/// This is equivalent to `.ensure_unique()` if `S: DataMut`.
///
/// This method is mostly only useful with unsafe code.
fn try_ensure_unique(&mut self)
where
S: RawDataMut,
{
debug_assert!(self.pointer_is_inbounds());
S::try_ensure_unique(self);
debug_assert!(self.pointer_is_inbounds());
}
/// Make the array unshared.
///
/// This method is mostly only useful with unsafe code.
fn ensure_unique(&mut self)
where
S: DataMut,
{
debug_assert!(self.pointer_is_inbounds());
S::ensure_unique(self);
debug_assert!(self.pointer_is_inbounds());
}
/// Return `true` if the array data is laid out in contiguous “C order” in
/// memory (where the last index is the most rapidly varying).
///
/// Return `false` otherwise, i.e the array is possibly not
/// contiguous in memory, it has custom strides, etc.
pub fn is_standard_layout(&self) -> bool {
fn is_standard_layout<D: Dimension>(dim: &D, strides: &D) -> bool {
if let Some(1) = D::NDIM {
return strides[0] == 1 || dim[0] <= 1;
}
if dim.slice().iter().any(|&d| d == 0) {
return true;
}
let defaults = dim.default_strides();
// check all dimensions -- a dimension of length 1 can have unequal strides
for (&dim, &s, &ds) in izip!(dim.slice(), strides.slice(), defaults.slice()) {
if dim != 1 && s != ds {
return false;
}
}
true
}
is_standard_layout(&self.dim, &self.strides)
}
fn is_contiguous(&self) -> bool {
D::is_contiguous(&self.dim, &self.strides)
}
/// Return a standard-layout array containing the data, cloning if
/// necessary.
///
/// If `self` is in standard layout, a COW view of the data is returned
/// without cloning. Otherwise, the data is cloned, and the returned array
/// owns the cloned data.
///
/// ```
/// use ndarray::Array2;
///
/// let standard = Array2::<f64>::zeros((3, 4));
/// assert!(standard.is_standard_layout());
/// let cow_view = standard.as_standard_layout();
/// assert!(cow_view.is_view());
/// assert!(cow_view.is_standard_layout());
///
/// let fortran = standard.reversed_axes();
/// assert!(!fortran.is_standard_layout());
/// let cow_owned = fortran.as_standard_layout();
/// assert!(cow_owned.is_owned());
/// assert!(cow_owned.is_standard_layout());
/// ```
pub fn as_standard_layout(&self) -> CowArray<'_, A, D>
where
S: Data<Elem = A>,
A: Clone,
{
if self.is_standard_layout() {
CowArray::from(self.view())
} else {
let v: Vec<A> = self.iter().cloned().collect();
let dim = self.dim.clone();
assert_eq!(v.len(), dim.size());
let owned_array: Array<A, D> = unsafe {
// Safe because the shape and element type are from the existing array
// and the strides are the default strides.
Array::from_shape_vec_unchecked(dim, v)
};
CowArray::from(owned_array)
}
}
/// Return a pointer to the first element in the array.
///
/// Raw access to array elements needs to follow the strided indexing
/// scheme: an element at multi-index *I* in an array with strides *S* is
/// located at offset
///
/// *Σ<sub>0 ≤ k < d</sub> I<sub>k</sub> × S<sub>k</sub>*
///
/// where *d* is `self.ndim()`.
#[inline(always)]
pub fn as_ptr(&self) -> *const A {
self.ptr.as_ptr() as *const A
}
/// Return a mutable pointer to the first element in the array.
#[inline(always)]
pub fn as_mut_ptr(&mut self) -> *mut A
where
S: RawDataMut,
{
self.try_ensure_unique(); // for RcArray
self.ptr.as_ptr()
}
/// Return a raw view of the array.
#[inline]
pub fn raw_view(&self) -> RawArrayView<A, D> {
unsafe { RawArrayView::new(self.ptr, self.dim.clone(), self.strides.clone()) }
}
/// Return a raw mutable view of the array.
#[inline]
pub fn raw_view_mut(&mut self) -> RawArrayViewMut<A, D>
where
S: RawDataMut,
{
self.try_ensure_unique(); // for RcArray
unsafe { RawArrayViewMut::new(self.ptr, self.dim.clone(), self.strides.clone()) }
}
/// Return the array’s data as a slice, if it is contiguous and in standard order.
/// Return `None` otherwise.
///
/// If this function returns `Some(_)`, then the element order in the slice
/// corresponds to the logical order of the array’s elements.
pub fn as_slice(&self) -> Option<&[A]>
where
S: Data,
{
if self.is_standard_layout() {
unsafe { Some(slice::from_raw_parts(self.ptr.as_ptr(), self.len())) }
} else {
None
}
}
/// Return the array’s data as a slice, if it is contiguous and in standard order.
/// Return `None` otherwise.
pub fn as_slice_mut(&mut self) -> Option<&mut [A]>
where
S: DataMut,
{
if self.is_standard_layout() {
self.ensure_unique();
unsafe { Some(slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len())) }
} else {
None
}
}
/// Return the array’s data as a slice if it is contiguous,
/// return `None` otherwise.
///
/// If this function returns `Some(_)`, then the elements in the slice
/// have whatever order the elements have in memory.
///
/// Implementation notes: Does not yet support negatively strided arrays.
pub fn as_slice_memory_order(&self) -> Option<&[A]>
where
S: Data,
{
if self.is_contiguous() {
unsafe { Some(slice::from_raw_parts(self.ptr.as_ptr(), self.len())) }
} else {
None
}
}
/// Return the array’s data as a slice if it is contiguous,
/// return `None` otherwise.
pub fn as_slice_memory_order_mut(&mut self) -> Option<&mut [A]>
where
S: DataMut,
{
if self.is_contiguous() {
self.ensure_unique();
unsafe { Some(slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len())) }
} else {
None
}
}
/// Transform the array into `shape`; any shape with the same number of
/// elements is accepted, but the source array or view must be in standard
/// or column-major (Fortran) layout.
///
/// **Errors** if the shapes don't have the same number of elements.<br>
/// **Errors** if the input array is not c- or f-contiguous.
///
/// ```
/// use ndarray::{aview1, aview2};
///
/// assert!(
/// aview1(&[1., 2., 3., 4.]).into_shape((2, 2)).unwrap()
/// == aview2(&[[1., 2.],
/// [3., 4.]])
/// );
/// ```
pub fn into_shape<E>(self, shape: E) -> Result<ArrayBase<S, E::Dim>, ShapeError>
where
E: IntoDimension,
{
let shape = shape.into_dimension();
if size_of_shape_checked(&shape) != Ok(self.dim.size()) {
return Err(error::incompatible_shapes(&self.dim, &shape));
}
// Check if contiguous, if not => copy all, else just adapt strides
if self.is_standard_layout() {
Ok(ArrayBase {
data: self.data,
ptr: self.ptr,
strides: shape.default_strides(),
dim: shape,
})
} else if self.ndim() > 1 && self.raw_view().reversed_axes().is_standard_layout() {
Ok(ArrayBase {
data: self.data,
ptr: self.ptr,
strides: shape.fortran_strides(),
dim: shape,
})
} else {
Err(error::from_kind(error::ErrorKind::IncompatibleLayout))
}
}
/// *Note: Reshape is for `ArcArray` only. Use `.into_shape()` for
/// other arrays and array views.*
///
/// Transform the array into `shape`; any shape with the same number of
/// elements is accepted.
///
/// May clone all elements if needed to arrange elements in standard
/// layout (and break sharing).
///
/// **Panics** if shapes are incompatible.
///
/// ```
/// use ndarray::{rcarr1, rcarr2};
///
/// assert!(
/// rcarr1(&[1., 2., 3., 4.]).reshape((2, 2))
/// == rcarr2(&[[1., 2.],
/// [3., 4.]])
/// );
/// ```
pub fn reshape<E>(&self, shape: E) -> ArrayBase<S, E::Dim>
where
S: DataShared + DataOwned,
A: Clone,
E: IntoDimension,
{
let shape = shape.into_dimension();
if size_of_shape_checked(&shape) != Ok(self.dim.size()) {
panic!(
"ndarray: incompatible shapes in reshape, attempted from: {:?}, to: {:?}",
self.dim.slice(),
shape.slice()
)
}
// Check if contiguous, if not => copy all, else just adapt strides
if self.is_standard_layout() {
let cl = self.clone();
ArrayBase {
data: cl.data,
ptr: cl.ptr,
strides: shape.default_strides(),
dim: shape,
}
} else {
let v = self.iter().cloned().collect::<Vec<A>>();
unsafe { ArrayBase::from_shape_vec_unchecked(shape, v) }
}
}
/// Convert any array or array view to a dynamic dimensional array or
/// array view (respectively).
///
/// ```
/// use ndarray::{arr2, ArrayD};
///
/// let array: ArrayD<i32> = arr2(&[[1, 2],
/// [3, 4]]).into_dyn();
/// ```
pub fn into_dyn(self) -> ArrayBase<S, IxDyn> {
ArrayBase {
data: self.data,
ptr: self.ptr,
dim: self.dim.into_dyn(),
strides: self.strides.into_dyn(),
}
}
/// Convert an array or array view to another with the same type, but
/// different dimensionality type. Errors if the dimensions don't agree.
///
/// ```
/// use ndarray::{ArrayD, Ix2, IxDyn};
///
/// // Create a dynamic dimensionality array and convert it to an Array2
/// // (Ix2 dimension type).
///
/// let array = ArrayD::<f64>::zeros(IxDyn(&[10, 10]));
///
/// assert!(array.into_dimensionality::<Ix2>().is_ok());
/// ```
pub fn into_dimensionality<D2>(self) -> Result<ArrayBase<S, D2>, ShapeError>
where
D2: Dimension,
{
if let Some(dim) = D2::from_dimension(&self.dim) {
if let Some(strides) = D2::from_dimension(&self.strides) {
return Ok(ArrayBase {
data: self.data,
ptr: self.ptr,
dim,
strides,
});
}
}
Err(ShapeError::from_kind(ErrorKind::IncompatibleShape))
}
/// Act like a larger size and/or shape array by *broadcasting*
/// into a larger shape, if possible.
///
/// Return `None` if shapes can not be broadcast together.
///
/// ***Background***
///
/// * Two axes are compatible if they are equal, or one of them is 1.
/// * In this instance, only the axes of the smaller side (self) can be 1.
///
/// Compare axes beginning with the *last* axis of each shape.
///
/// For example (1, 2, 4) can be broadcast into (7, 6, 2, 4)
/// because its axes are either equal or 1 (or missing);
/// while (2, 2) can *not* be broadcast into (2, 4).
///
/// The implementation creates a view with strides set to zero for the
/// axes that are to be repeated.
///
/// The broadcasting documentation for Numpy has more information.
///
/// ```
/// use ndarray::{aview1, aview2};
///
/// assert!(
/// aview1(&[1., 0.]).broadcast((10, 2)).unwrap()
/// == aview2(&[[1., 0.]; 10])
/// );
/// ```
pub fn broadcast<E>(&self, dim: E) -> Option<ArrayView<'_, A, E::Dim>>
where
E: IntoDimension,
S: Data,
{
/// Return new stride when trying to grow `from` into shape `to`
///
/// Broadcasting works by returning a "fake stride" where elements
/// to repeat are in axes with 0 stride, so that several indexes point
/// to the same element.
///
/// **Note:** Cannot be used for mutable iterators, since repeating
/// elements would create aliasing pointers.
fn upcast<D: Dimension, E: Dimension>(to: &D, from: &E, stride: &E) -> Option<D> {
// Make sure the product of non-zero axis lengths does not exceed
// `isize::MAX`. This is the only safety check we need to perform
// because all the other constraints of `ArrayBase` are guaranteed
// to be met since we're starting from a valid `ArrayBase`.
let _ = size_of_shape_checked(to).ok()?;
let mut new_stride = to.clone();
// begin at the back (the least significant dimension)
// size of the axis has to either agree or `from` has to be 1
if to.ndim() < from.ndim() {
return None;
}
{
let mut new_stride_iter = new_stride.slice_mut().iter_mut().rev();
for ((er, es), dr) in from
.slice()
.iter()
.rev()
.zip(stride.slice().iter().rev())
.zip(new_stride_iter.by_ref())
{
/* update strides */
if *dr == *er {
/* keep stride */
*dr = *es;
} else if *er == 1 {
/* dead dimension, zero stride */
*dr = 0
} else {
return None;
}
}
/* set remaining strides to zero */
for dr in new_stride_iter {
*dr = 0;
}
}
Some(new_stride)
}
let dim = dim.into_dimension();
// Note: zero strides are safe precisely because we return an read-only view
let broadcast_strides = match upcast(&dim, &self.dim, &self.strides) {
Some(st) => st,
None => return None,
};
unsafe { Some(ArrayView::new(self.ptr, dim, broadcast_strides)) }
}
/// Swap axes `ax` and `bx`.
///
/// This does not move any data, it just adjusts the array’s dimensions
/// and strides.
///
/// **Panics** if the axes are out of bounds.
///
/// ```
/// use ndarray::arr2;
///
/// let mut a = arr2(&[[1., 2., 3.]]);
/// a.swap_axes(0, 1);
/// assert!(
/// a == arr2(&[[1.], [2.], [3.]])
/// );
/// ```
pub fn swap_axes(&mut self, ax: usize, bx: usize) {
self.dim.slice_mut().swap(ax, bx);
self.strides.slice_mut().swap(ax, bx);
}
/// Permute the axes.
///
/// This does not move any data, it just adjusts the array’s dimensions
/// and strides.
///
/// *i* in the *j*-th place in the axes sequence means `self`'s *i*-th axis
/// becomes `self.permuted_axes()`'s *j*-th axis
///
/// **Panics** if any of the axes are out of bounds, if an axis is missing,
/// or if an axis is repeated more than once.
///
/// # Examples
///
/// ```
/// use ndarray::{arr2, Array3};
///
/// let a = arr2(&[[0, 1], [2, 3]]);
/// assert_eq!(a.view().permuted_axes([1, 0]), a.t());
///
/// let b = Array3::<u8>::zeros((1, 2, 3));
/// assert_eq!(b.permuted_axes([1, 0, 2]).shape(), &[2, 1, 3]);
/// ```
pub fn permuted_axes<T>(self, axes: T) -> ArrayBase<S, D>
where
T: IntoDimension<Dim = D>,
{
let axes = axes.into_dimension();
// Ensure that each axis is used exactly once.
let mut usage_counts = D::zeros(self.ndim());
for axis in axes.slice() {
usage_counts[*axis] += 1;
}
for count in usage_counts.slice() {
assert_eq!(*count, 1, "each axis must be listed exactly once");
}
// Determine the new shape and strides.
let mut new_dim = usage_counts; // reuse to avoid an allocation
let mut new_strides = D::zeros(self.ndim());
{
let dim = self.dim.slice();
let strides = self.strides.slice();
for (new_axis, &axis) in axes.slice().iter().enumerate() {
new_dim[new_axis] = dim[axis];
new_strides[new_axis] = strides[axis];
}
}
ArrayBase {
dim: new_dim,
strides: new_strides,
..self
}
}
/// Transpose the array by reversing axes.
///
/// Transposition reverses the order of the axes (dimensions and strides)
/// while retaining the same data.
pub fn reversed_axes(mut self) -> ArrayBase<S, D> {
self.dim.slice_mut().reverse();
self.strides.slice_mut().reverse();
self
}
/// Return a transposed view of the array.
///
/// This is a shorthand for `self.view().reversed_axes()`.
///
/// See also the more general methods `.reversed_axes()` and `.swap_axes()`.
pub fn t(&self) -> ArrayView<'_, A, D>
where
S: Data,
{
self.view().reversed_axes()
}
/// Return an iterator over the length and stride of each axis.
pub fn axes(&self) -> Axes<'_, D> {
axes_of(&self.dim, &self.strides)
}
/*
/// Return the axis with the least stride (by absolute value)
pub fn min_stride_axis(&self) -> Axis {
self.dim.min_stride_axis(&self.strides)
}
*/
/// Return the axis with the greatest stride (by absolute value),
/// preferring axes with len > 1.
pub fn max_stride_axis(&self) -> Axis {
self.dim.max_stride_axis(&self.strides)
}
/// Reverse the stride of `axis`.
///
/// ***Panics*** if the axis is out of bounds.
pub fn invert_axis(&mut self, axis: Axis) {
unsafe {
let s = self.strides.axis(axis) as Ixs;
let m = self.dim.axis(axis);
if m != 0 {
self.ptr = self.ptr.offset(stride_offset(m - 1, s as Ix));
}
self.strides.set_axis(axis, (-s) as Ix);
}
}
/// If possible, merge in the axis `take` to `into`.
///
/// Returns `true` iff the axes are now merged.
///
/// This method merges the axes if movement along the two original axes
/// (moving fastest along the `into` axis) can be equivalently represented
/// as movement along one (merged) axis. Merging the axes preserves this
/// order in the merged axis. If `take` and `into` are the same axis, then
/// the axis is "merged" if its length is ≤ 1.
///
/// If the return value is `true`, then the following hold:
///
/// * The new length of the `into` axis is the product of the original
/// lengths of the two axes.
///
/// * The new length of the `take` axis is 0 if the product of the original
/// lengths of the two axes is 0, and 1 otherwise.
///
/// If the return value is `false`, then merging is not possible, and the
/// original shape and strides have been preserved.
///
/// Note that the ordering constraint means that if it's possible to merge
/// `take` into `into`, it's usually not possible to merge `into` into
/// `take`, and vice versa.
///
/// ```
/// use ndarray::Array3;
/// use ndarray::Axis;
///
/// let mut a = Array3::<f64>::zeros((2, 3, 4));
/// assert!(a.merge_axes(Axis(1), Axis(2)));
/// assert_eq!(a.shape(), &[2, 1, 12]);
/// ```
///
/// ***Panics*** if an axis is out of bounds.
pub fn merge_axes(&mut self, take: Axis, into: Axis) -> bool {
merge_axes(&mut self.dim, &mut self.strides, take, into)
}
/// Insert new array axis at `axis` and return the result.
///
/// ```
/// use ndarray::{Array3, Axis, arr1, arr2};
///
/// // Convert a 1-D array into a row vector (2-D).
/// let a = arr1(&[1, 2, 3]);
/// let row = a.insert_axis(Axis(0));
/// assert_eq!(row, arr2(&[[1, 2, 3]]));
///
/// // Convert a 1-D array into a column vector (2-D).
/// let b = arr1(&[1, 2, 3]);
/// let col = b.insert_axis(Axis(1));
/// assert_eq!(col, arr2(&[[1], [2], [3]]));
///
/// // The new axis always has length 1.
/// let b = Array3::<f64>::zeros((3, 4, 5));
/// assert_eq!(b.insert_axis(Axis(2)).shape(), &[3, 4, 1, 5]);
/// ```
///
/// ***Panics*** if the axis is out of bounds.
pub fn insert_axis(self, axis: Axis) -> ArrayBase<S, D::Larger> {
assert!(axis.index() <= self.ndim());
let ArrayBase {
ptr,
data,
dim,
strides,
} = self;
ArrayBase {
ptr,
data,
dim: dim.insert_axis(axis),
strides: strides.insert_axis(axis),
}
}
/// Remove array axis `axis` and return the result.
///
/// **Panics** if the axis is out of bounds or its length is zero.
#[deprecated(note = "use `.index_axis_move(Axis(_), 0)` instead", since = "0.12.1")]
pub fn remove_axis(self, axis: Axis) -> ArrayBase<S, D::Smaller>
where
D: RemoveAxis,
{
self.index_axis_move(axis, 0)
}
fn pointer_is_inbounds(&self) -> bool {
match self.data._data_slice() {
None => {
// special case for non-owned views
true
}
Some(slc) => {
let ptr = slc.as_ptr() as *mut A;
let end = unsafe { ptr.add(slc.len()) };
self.ptr.as_ptr() >= ptr && self.ptr.as_ptr() <= end
}
}
}
/// Perform an elementwise assigment to `self` from `rhs`.
///
/// If their shapes disagree, `rhs` is broadcast to the shape of `self`.
///
/// **Panics** if broadcasting isn’t possible.
pub fn assign<E: Dimension, S2>(&mut self, rhs: &ArrayBase<S2, E>)
where
S: DataMut,
A: Clone,
S2: Data<Elem = A>,
{
self.zip_mut_with(rhs, |x, y| *x = y.clone());
}
/// Perform an elementwise assigment to `self` from element `x`.
pub fn fill(&mut self, x: A)
where
S: DataMut,
A: Clone,
{
self.unordered_foreach_mut(move |elt| *elt = x.clone());
}
fn zip_mut_with_same_shape<B, S2, E, F>(&mut self, rhs: &ArrayBase<S2, E>, mut f: F)
where
S: DataMut,
S2: Data<Elem = B>,
E: Dimension,
F: FnMut(&mut A, &B),
{
debug_assert_eq!(self.shape(), rhs.shape());
if self.dim.strides_equivalent(&self.strides, &rhs.strides) {
if let Some(self_s) = self.as_slice_memory_order_mut() {
if let Some(rhs_s) = rhs.as_slice_memory_order() {
for (s, r) in self_s.iter_mut().zip(rhs_s) {
f(s, &r);
}
return;
}
}
}
// Otherwise, fall back to the outer iter
self.zip_mut_with_by_rows(rhs, f);
}
// zip two arrays where they have different layout or strides
#[inline(always)]
fn zip_mut_with_by_rows<B, S2, E, F>(&mut self, rhs: &ArrayBase<S2, E>, mut f: F)
where
S: DataMut,
S2: Data<Elem = B>,
E: Dimension,
F: FnMut(&mut A, &B),
{
debug_assert_eq!(self.shape(), rhs.shape());
debug_assert_ne!(self.ndim(), 0);
// break the arrays up into their inner rows
let n = self.ndim();
let dim = self.raw_dim();
Zip::from(LanesMut::new(self.view_mut(), Axis(n - 1)))
.and(Lanes::new(rhs.broadcast_assume(dim), Axis(n - 1)))
.apply(move |s_row, r_row| Zip::from(s_row).and(r_row).apply(|a, b| f(a, b)));
}
fn zip_mut_with_elem<B, F>(&mut self, rhs_elem: &B, mut f: F)
where
S: DataMut,
F: FnMut(&mut A, &B),
{
self.unordered_foreach_mut(move |elt| f(elt, rhs_elem));
}
/// Traverse two arrays in unspecified order, in lock step,
/// calling the closure `f` on each element pair.
///
/// If their shapes disagree, `rhs` is broadcast to the shape of `self`.
///
/// **Panics** if broadcasting isn’t possible.
#[inline]
pub fn zip_mut_with<B, S2, E, F>(&mut self, rhs: &ArrayBase<S2, E>, f: F)
where
S: DataMut,
S2: Data<Elem = B>,
E: Dimension,
F: FnMut(&mut A, &B),
{
if rhs.dim.ndim() == 0 {
// Skip broadcast from 0-dim array
self.zip_mut_with_elem(rhs.get_0d(), f);
} else if self.dim.ndim() == rhs.dim.ndim() && self.shape() == rhs.shape() {
self.zip_mut_with_same_shape(rhs, f);
} else {
let rhs_broadcast = rhs.broadcast_unwrap(self.raw_dim());
self.zip_mut_with_by_rows(&rhs_broadcast, f);
}
}
/// Traverse the array elements and apply a fold,
/// returning the resulting value.
///
/// Elements are visited in arbitrary order.
pub fn fold<'a, F, B>(&'a self, init: B, f: F) -> B
where
F: FnMut(B, &'a A) -> B,
A: 'a,
S: Data,
{
if let Some(slc) = self.as_slice_memory_order() {
slc.iter().fold(init, f)
} else {
let mut v = self.view();
// put the narrowest axis at the last position
match v.ndim() {
0 | 1 => {}
2 => {
if self.len_of(Axis(1)) <= 1
|| self.len_of(Axis(0)) > 1
&& self.stride_of(Axis(0)).abs() < self.stride_of(Axis(1)).abs()
{
v.swap_axes(0, 1);
}
}
n => {
let last = n - 1;
let narrow_axis = v
.axes()
.filter(|ax| ax.len() > 1)
.min_by_key(|ax| ax.stride().abs())
.map_or(last, |ax| ax.axis().index());
v.swap_axes(last, narrow_axis);
}
}
v.into_elements_base().fold(init, f)
}
}
/// Call `f` by reference on each element and create a new array
/// with the new values.
///
/// Elements are visited in arbitrary order.
///
/// Return an array with the same shape as `self`.
///
/// ```
/// use ndarray::arr2;
///
/// let a = arr2(&[[ 0., 1.],
/// [-1., 2.]]);
/// assert!(
/// a.map(|x| *x >= 1.0)
/// == arr2(&[[false, true],
/// [false, true]])
/// );
/// ```
pub fn map<'a, B, F>(&'a self, f: F) -> Array<B, D>
where
F: FnMut(&'a A) -> B,
A: 'a,
S: Data,
{
if let Some(slc) = self.as_slice_memory_order() {
let v = crate::iterators::to_vec_mapped(slc.iter(), f);
unsafe {
ArrayBase::from_shape_vec_unchecked(
self.dim.clone().strides(self.strides.clone()),
v,
)
}
} else {
let v = crate::iterators::to_vec_mapped(self.iter(), f);
unsafe { ArrayBase::from_shape_vec_unchecked(self.dim.clone(), v) }
}
}
/// Call `f` on a mutable reference of each element and create a new array
/// with the new values.
///
/// Elements are visited in arbitrary order.
///
/// Return an array with the same shape as `self`.
pub fn map_mut<'a, B, F>(&'a mut self, f: F) -> Array<B, D>
where
F: FnMut(&'a mut A) -> B,
A: 'a,
S: DataMut,
{
let dim = self.dim.clone();
if self.is_contiguous() {
let strides = self.strides.clone();
let slc = self.as_slice_memory_order_mut().unwrap();
let v = crate::iterators::to_vec_mapped(slc.iter_mut(), f);
unsafe { ArrayBase::from_shape_vec_unchecked(dim.strides(strides), v) }
} else {
let v = crate::iterators::to_vec_mapped(self.iter_mut(), f);
unsafe { ArrayBase::from_shape_vec_unchecked(dim, v) }
}
}
/// Call `f` by **v**alue on each element and create a new array
/// with the new values.
///
/// Elements are visited in arbitrary order.
///
/// Return an array with the same shape as `self`.
///
/// ```
/// use ndarray::arr2;
///
/// let a = arr2(&[[ 0., 1.],
/// [-1., 2.]]);
/// assert!(
/// a.mapv(f32::abs) == arr2(&[[0., 1.],
/// [1., 2.]])
/// );
/// ```
pub fn mapv<B, F>(&self, mut f: F) -> Array<B, D>
where
F: FnMut(A) -> B,
A: Clone,
S: Data,
{
self.map(move |x| f(x.clone()))
}
/// Call `f` by **v**alue on each element, update the array with the new values
/// and return it.
///
/// Elements are visited in arbitrary order.
pub fn mapv_into<F>(mut self, f: F) -> Self
where
S: DataMut,
F: FnMut(A) -> A,
A: Clone,
{
self.mapv_inplace(f);
self
}
/// Modify the array in place by calling `f` by mutable reference on each element.
///
/// Elements are visited in arbitrary order.
pub fn map_inplace<F>(&mut self, f: F)
where
S: DataMut,
F: FnMut(&mut A),
{
self.unordered_foreach_mut(f);
}
/// Modify the array in place by calling `f` by **v**alue on each element.
/// The array is updated with the new values.
///
/// Elements are visited in arbitrary order.
///
/// ```
/// use approx::assert_abs_diff_eq;
/// use ndarray::arr2;
///
/// # #[cfg(feature = "approx")] {
/// let mut a = arr2(&[[ 0., 1.],
/// [-1., 2.]]);
/// a.mapv_inplace(f32::exp);
/// assert_abs_diff_eq!(
/// a,
/// arr2(&[[1.00000, 2.71828],
/// [0.36788, 7.38906]]),
/// epsilon = 1e-5,
/// );
/// # }
/// ```
pub fn mapv_inplace<F>(&mut self, mut f: F)
where
S: DataMut,
F: FnMut(A) -> A,
A: Clone,
{
self.unordered_foreach_mut(move |x| *x = f(x.clone()));
}
/// Visit each element in the array by calling `f` by reference
/// on each element.
///
/// Elements are visited in arbitrary order.
pub fn visit<'a, F>(&'a self, mut f: F)
where
F: FnMut(&'a A),
A: 'a,
S: Data,
{
self.fold((), move |(), elt| f(elt))
}
/// Fold along an axis.
///
/// Combine the elements of each subview with the previous using the `fold`
/// function and initial value `init`.
///
/// Return the result as an `Array`.
///
/// **Panics** if `axis` is out of bounds.
pub fn fold_axis<B, F>(&self, axis: Axis, init: B, mut fold: F) -> Array<B, D::Smaller>
where
D: RemoveAxis,
F: FnMut(&B, &A) -> B,
B: Clone,
S: Data,
{
let mut res = Array::from_elem(self.raw_dim().remove_axis(axis), init);
for subview in self.axis_iter(axis) {
res.zip_mut_with(&subview, |x, y| *x = fold(x, y));
}
res
}
/// Reduce the values along an axis into just one value, producing a new
/// array with one less dimension.
///
/// Elements are visited in arbitrary order.
///
/// Return the result as an `Array`.
///
/// **Panics** if `axis` is out of bounds.
pub fn map_axis<'a, B, F>(&'a self, axis: Axis, mut mapping: F) -> Array<B, D::Smaller>
where
D: RemoveAxis,
F: FnMut(ArrayView1<'a, A>) -> B,
A: 'a,
S: Data,
{
let view_len = self.len_of(axis);
let view_stride = self.strides.axis(axis);
if view_len == 0 {
let new_dim = self.dim.remove_axis(axis);
Array::from_shape_simple_fn(new_dim, move || mapping(ArrayView::from(&[])))
} else {
// use the 0th subview as a map to each 1d array view extended from
// the 0th element.
self.index_axis(axis, 0).map(|first_elt| unsafe {
mapping(ArrayView::new_(first_elt, Ix1(view_len), Ix1(view_stride)))
})
}
}
/// Reduce the values along an axis into just one value, producing a new
/// array with one less dimension.
/// 1-dimensional lanes are passed as mutable references to the reducer,
/// allowing for side-effects.
///
/// Elements are visited in arbitrary order.
///
/// Return the result as an `Array`.
///
/// **Panics** if `axis` is out of bounds.
pub fn map_axis_mut<'a, B, F>(&'a mut self, axis: Axis, mut mapping: F) -> Array<B, D::Smaller>
where
D: RemoveAxis,
F: FnMut(ArrayViewMut1<'a, A>) -> B,
A: 'a,
S: DataMut,
{
let view_len = self.len_of(axis);
let view_stride = self.strides.axis(axis);
if view_len == 0 {
let new_dim = self.dim.remove_axis(axis);
Array::from_shape_simple_fn(new_dim, move || mapping(ArrayViewMut::from(&mut [])))
} else {
// use the 0th subview as a map to each 1d array view extended from
// the 0th element.
self.index_axis_mut(axis, 0).map_mut(|first_elt| unsafe {
mapping(ArrayViewMut::new_(
first_elt,
Ix1(view_len),
Ix1(view_stride),
))
})
}
}
/// Iterates over pairs of consecutive elements along the axis.
///
/// The first argument to the closure is an element, and the second
/// argument is the next element along the axis. Iteration is guaranteed to
/// proceed in order along the specified axis, but in all other respects
/// the iteration order is unspecified.
///
/// # Example
///
/// For example, this can be used to compute the cumulative sum along an
/// axis:
///
/// ```
/// use ndarray::{array, Axis};
///
/// let mut arr = array![
/// [[1, 2], [3, 4], [5, 6]],
/// [[7, 8], [9, 10], [11, 12]],
/// ];
/// arr.accumulate_axis_inplace(Axis(1), |&prev, curr| *curr += prev);
/// assert_eq!(
/// arr,
/// array![
/// [[1, 2], [4, 6], [9, 12]],
/// [[7, 8], [16, 18], [27, 30]],
/// ],
/// );
/// ```
pub fn accumulate_axis_inplace<F>(&mut self, axis: Axis, mut f: F)
where
F: FnMut(&A, &mut A),
S: DataMut,
{
if self.len_of(axis) <= 1 {
return;
}
let mut curr = self.raw_view_mut(); // mut borrow of the array here
let mut prev = curr.raw_view(); // derive further raw views from the same borrow
prev.slice_axis_inplace(axis, Slice::from(..-1));
curr.slice_axis_inplace(axis, Slice::from(1..));
// This implementation relies on `Zip` iterating along `axis` in order.
Zip::from(prev).and(curr).apply(|prev, curr| unsafe {
// These pointer dereferences and borrows are safe because:
//
// 1. They're pointers to elements in the array.
//
// 2. `S: DataMut` guarantees that elements are safe to borrow
// mutably and that they don't alias.
//
// 3. The lifetimes of the borrows last only for the duration
// of the call to `f`, so aliasing across calls to `f`
// cannot occur.
f(&*prev, &mut *curr)
});
}
}
| 33.44435 | 101 | 0.516876 |
fbb4df2fe07e06f8a751b817ad5e74cba44f97a5
| 4,043 |
use std::io::{Result, Write};
use analysis;
use library;
use analysis::special_functions::Type;
use env::Env;
use super::{function, general, trait_impls};
pub fn generate(w: &mut Write, env: &Env, analysis: &analysis::record::Info) -> Result<()> {
let type_ = analysis.type_(&env.library);
try!(general::start_comments(w, &env.config));
try!(general::uses(w, env, &analysis.imports));
if analysis.use_boxed_functions {
if let Some(ref glib_get_type) = analysis.glib_get_type {
try!(general::define_auto_boxed_type(
w,
&analysis.name,
&type_.c_type,
glib_get_type,
&analysis.derives,
));
} else {
panic!(
"Record {} has record_boxed=true but don't have glib:get_type function",
analysis.name
);
}
} else if let (Some(ref_fn), Some(unref_fn)) = (
analysis.specials.get(&Type::Ref),
analysis.specials.get(&Type::Unref),
) {
try!(general::define_shared_type(
w,
&analysis.name,
&type_.c_type,
ref_fn,
unref_fn,
&analysis.glib_get_type,
&analysis.derives,
));
} else if let (Some(copy_fn), Some(free_fn)) = (
analysis.specials.get(&Type::Copy),
analysis.specials.get(&Type::Free),
) {
try!(general::define_boxed_type(
w,
&analysis.name,
&type_.c_type,
copy_fn,
free_fn,
&analysis.glib_get_type,
&analysis.derives,
));
} else if let Some(ref glib_get_type) = analysis.glib_get_type {
try!(general::define_auto_boxed_type(
w,
&analysis.name,
&type_.c_type,
glib_get_type,
&analysis.derives,
));
} else {
panic!(
"Missing memory management functions for {}",
analysis.full_name
);
}
if analysis.functions.iter().any(|f| !f.visibility.hidden()) {
try!(writeln!(w));
try!(write!(w, "impl {} {{", analysis.name));
for func_analysis in &analysis.functions {
try!(function::generate(w, env, func_analysis, false, false, 1));
}
try!(writeln!(w, "}}"));
}
try!(general::declare_default_from_new(
w,
env,
&analysis.name,
&analysis.functions
));
try!(trait_impls::generate(
w,
&analysis.name,
&analysis.functions,
&analysis.specials,
None,
));
if analysis.concurrency != library::Concurrency::None {
try!(writeln!(w));
}
match analysis.concurrency {
library::Concurrency::Send | library::Concurrency::SendSync => {
try!(writeln!(w, "unsafe impl Send for {} {{}}", analysis.name));
}
library::Concurrency::SendUnique => {
panic!("SendUnique concurrency can only be autogenerated for GObject subclasses");
}
_ => (),
}
if analysis.concurrency == library::Concurrency::SendSync {
try!(writeln!(w, "unsafe impl Sync for {} {{}}", analysis.name));
}
Ok(())
}
pub fn generate_reexports(
env: &Env,
analysis: &analysis::record::Info,
module_name: &str,
contents: &mut Vec<String>,
) {
let cfg_condition = general::cfg_condition_string(&analysis.cfg_condition, false, 0);
let version_cfg = general::version_condition_string(env, analysis.version, false, 0);
let mut cfg = String::new();
if let Some(s) = cfg_condition {
cfg.push_str(&s);
cfg.push('\n');
};
if let Some(s) = version_cfg {
cfg.push_str(&s);
cfg.push('\n');
};
contents.push("".to_owned());
contents.push(format!("{}mod {};", cfg, module_name));
contents.push(format!(
"{}pub use self::{}::{};",
cfg,
module_name,
analysis.name
));
}
| 28.076389 | 94 | 0.539204 |
1457db63d8d0e878a41e4db4f7dd456f4a6cc9b5
| 39,461 |
//! Parsing interface for parsing a token stream into a syntax tree node.
//!
//! Parsing in Syn is built on parser functions that take in a [`ParseStream`]
//! and produce a [`Result<T>`] where `T` is some syntax tree node. Underlying
//! these parser functions is a lower level mechanism built around the
//! [`Cursor`] type. `Cursor` is a cheaply copyable cursor over a range of
//! tokens in a token stream.
//!
//! [`ParseStream`]: type.ParseStream.html
//! [`Result<T>`]: type.Result.html
//! [`Cursor`]: ../buffer/index.html
//!
//! # Example
//!
//! Here is a snippet of parsing code to get a feel for the style of the
//! library. We define data structures for a subset of Rust syntax including
//! enums (not shown) and structs, then provide implementations of the [`Parse`]
//! trait to parse these syntax tree data structures from a token stream.
//!
//! Once `Parse` impls have been defined, they can be called conveniently from a
//! procedural macro through [`parse_macro_input!`] as shown at the bottom of
//! the snippet. If the caller provides syntactically invalid input to the
//! procedural macro, they will receive a helpful compiler error message
//! pointing out the exact token that triggered the failure to parse.
//!
//! [`parse_macro_input!`]: ../macro.parse_macro_input.html
//!
//! ```edition2018
//! extern crate proc_macro;
//!
//! use proc_macro::TokenStream;
//! use syn::{braced, parse_macro_input, token, Field, Ident, Result, Token};
//! use syn::parse::{Parse, ParseStream};
//! use syn::punctuated::Punctuated;
//!
//! enum Item {
//! Struct(ItemStruct),
//! Enum(ItemEnum),
//! }
//!
//! struct ItemStruct {
//! struct_token: Token![struct],
//! ident: Ident,
//! brace_token: token::Brace,
//! fields: Punctuated<Field, Token![,]>,
//! }
//! #
//! # enum ItemEnum {}
//!
//! impl Parse for Item {
//! fn parse(input: ParseStream) -> Result<Self> {
//! let lookahead = input.lookahead1();
//! if lookahead.peek(Token![struct]) {
//! input.parse().map(Item::Struct)
//! } else if lookahead.peek(Token![enum]) {
//! input.parse().map(Item::Enum)
//! } else {
//! Err(lookahead.error())
//! }
//! }
//! }
//!
//! impl Parse for ItemStruct {
//! fn parse(input: ParseStream) -> Result<Self> {
//! let content;
//! Ok(ItemStruct {
//! struct_token: input.parse()?,
//! ident: input.parse()?,
//! brace_token: braced!(content in input),
//! fields: content.parse_terminated(Field::parse_named)?,
//! })
//! }
//! }
//! #
//! # impl Parse for ItemEnum {
//! # fn parse(input: ParseStream) -> Result<Self> {
//! # unimplemented!()
//! # }
//! # }
//!
//! # const IGNORE: &str = stringify! {
//! #[proc_macro]
//! # };
//! pub fn my_macro(tokens: TokenStream) -> TokenStream {
//! let input = parse_macro_input!(tokens as Item);
//!
//! /* ... */
//! # "".parse().unwrap()
//! }
//! ```
//!
//! # The `syn::parse*` functions
//!
//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
//! as an entry point for parsing syntax tree nodes that can be parsed in an
//! obvious default way. These functions can return any syntax tree node that
//! implements the [`Parse`] trait, which includes most types in Syn.
//!
//! [`syn::parse`]: ../fn.parse.html
//! [`syn::parse2`]: ../fn.parse2.html
//! [`syn::parse_str`]: ../fn.parse_str.html
//! [`Parse`]: trait.Parse.html
//!
//! ```edition2018
//! use syn::Type;
//!
//! # fn run_parser() -> syn::Result<()> {
//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
//! # Ok(())
//! # }
//! #
//! # fn main() {
//! # run_parser().unwrap();
//! # }
//! ```
//!
//! The [`parse_quote!`] macro also uses this approach.
//!
//! [`parse_quote!`]: ../macro.parse_quote.html
//!
//! # The `Parser` trait
//!
//! Some types can be parsed in several ways depending on context. For example
//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
//! may or may not allow trailing punctuation, and parsing it the wrong way
//! would either reject valid input or accept invalid input.
//!
//! [`Attribute`]: ../struct.Attribute.html
//! [`Punctuated`]: ../punctuated/index.html
//!
//! The `Parse` trait is not implemented in these cases because there is no good
//! behavior to consider the default.
//!
//! ```edition2018,compile_fail
//! # extern crate proc_macro;
//! #
//! # use syn::punctuated::Punctuated;
//! # use syn::{PathSegment, Result, Token};
//! #
//! # fn f(tokens: proc_macro::TokenStream) -> Result<()> {
//! #
//! // Can't parse `Punctuated` without knowing whether trailing punctuation
//! // should be allowed in this context.
//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
//! #
//! # Ok(())
//! # }
//! ```
//!
//! In these cases the types provide a choice of parser functions rather than a
//! single `Parse` implementation, and those parser functions can be invoked
//! through the [`Parser`] trait.
//!
//! [`Parser`]: trait.Parser.html
//!
//! ```edition2018
//! extern crate proc_macro;
//!
//! use proc_macro::TokenStream;
//! use syn::parse::Parser;
//! use syn::punctuated::Punctuated;
//! use syn::{Attribute, Expr, PathSegment, Result, Token};
//!
//! fn call_some_parser_methods(input: TokenStream) -> Result<()> {
//! // Parse a nonempty sequence of path segments separated by `::` punctuation
//! // with no trailing punctuation.
//! let tokens = input.clone();
//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
//! let _path = parser.parse(tokens)?;
//!
//! // Parse a possibly empty sequence of expressions terminated by commas with
//! // an optional trailing punctuation.
//! let tokens = input.clone();
//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
//! let _args = parser.parse(tokens)?;
//!
//! // Parse zero or more outer attributes but not inner attributes.
//! let tokens = input.clone();
//! let parser = Attribute::parse_outer;
//! let _attrs = parser.parse(tokens)?;
//!
//! Ok(())
//! }
//! ```
//!
//! ---
//!
//! *This module is available if Syn is built with the `"parsing"` feature.*
#[path = "discouraged.rs"]
pub mod discouraged;
use std::cell::Cell;
use std::fmt::{self, Debug, Display};
use std::marker::PhantomData;
use std::mem;
use std::ops::Deref;
use std::rc::Rc;
use std::str::FromStr;
#[cfg(all(
not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
feature = "proc-macro"
))]
use proc_macro;
use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
use buffer::{Cursor, TokenBuffer};
use error;
use lookahead;
use private;
use punctuated::Punctuated;
use token::Token;
pub use error::{Error, Result};
pub use lookahead::{Lookahead1, Peek};
/// Parsing interface implemented by all types that can be parsed in a default
/// way from a token stream.
pub trait Parse: Sized {
fn parse(input: ParseStream) -> Result<Self>;
}
/// Input to a Syn parser function.
///
/// See the methods of this type under the documentation of [`ParseBuffer`]. For
/// an overview of parsing in Syn, refer to the [module documentation].
///
/// [module documentation]: self
pub type ParseStream<'a> = &'a ParseBuffer<'a>;
/// Cursor position within a buffered token stream.
///
/// This type is more commonly used through the type alias [`ParseStream`] which
/// is an alias for `&ParseBuffer`.
///
/// `ParseStream` is the input type for all parser functions in Syn. They have
/// the signature `fn(ParseStream) -> Result<T>`.
///
/// ## Calling a parser function
///
/// There is no public way to construct a `ParseBuffer`. Instead, if you are
/// looking to invoke a parser function that requires `ParseStream` as input,
/// you will need to go through one of the public parsing entry points.
///
/// - The [`parse_macro_input!`] macro if parsing input of a procedural macro;
/// - One of [the `syn::parse*` functions][syn-parse]; or
/// - A method of the [`Parser`] trait.
///
/// [syn-parse]: index.html#the-synparse-functions
pub struct ParseBuffer<'a> {
scope: Span,
// Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
// The rest of the code in this module needs to be careful that only a
// cursor derived from this `cell` is ever assigned to this `cell`.
//
// Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
// ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
// than 'a, and then assign a Cursor<'short> into the Cell.
//
// By extension, it would not be safe to expose an API that accepts a
// Cursor<'a> and trusts that it lives as long as the cursor currently in
// the cell.
cell: Cell<Cursor<'static>>,
marker: PhantomData<Cursor<'a>>,
unexpected: Rc<Cell<Option<Span>>>,
}
impl<'a> Drop for ParseBuffer<'a> {
fn drop(&mut self) {
if !self.is_empty() && self.unexpected.get().is_none() {
self.unexpected.set(Some(self.cursor().span()));
}
}
}
impl<'a> Display for ParseBuffer<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.cursor().token_stream(), f)
}
}
impl<'a> Debug for ParseBuffer<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(&self.cursor().token_stream(), f)
}
}
/// Cursor state associated with speculative parsing.
///
/// This type is the input of the closure provided to [`ParseStream::step`].
///
/// [`ParseStream::step`]: ParseBuffer::step
///
/// # Example
///
/// ```edition2018
/// use proc_macro2::TokenTree;
/// use syn::Result;
/// use syn::parse::ParseStream;
///
/// // This function advances the stream past the next occurrence of `@`. If
/// // no `@` is present in the stream, the stream position is unchanged and
/// // an error is returned.
/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
/// input.step(|cursor| {
/// let mut rest = *cursor;
/// while let Some((tt, next)) = rest.token_tree() {
/// match &tt {
/// TokenTree::Punct(punct) if punct.as_char() == '@' => {
/// return Ok(((), next));
/// }
/// _ => rest = next,
/// }
/// }
/// Err(cursor.error("no `@` was found after this point"))
/// })
/// }
/// #
/// # fn remainder_after_skipping_past_next_at(
/// # input: ParseStream,
/// # ) -> Result<proc_macro2::TokenStream> {
/// # skip_past_next_at(input)?;
/// # input.parse()
/// # }
/// #
/// # fn main() {
/// # use syn::parse::Parser;
/// # let remainder = remainder_after_skipping_past_next_at
/// # .parse_str("a @ b c")
/// # .unwrap();
/// # assert_eq!(remainder.to_string(), "b c");
/// # }
/// ```
#[derive(Copy, Clone)]
pub struct StepCursor<'c, 'a> {
scope: Span,
// This field is covariant in 'c.
cursor: Cursor<'c>,
// This field is contravariant in 'c. Together these make StepCursor
// invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
// different lifetime but can upcast into a StepCursor with a shorter
// lifetime 'a.
//
// As long as we only ever construct a StepCursor for which 'c outlives 'a,
// this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
// outlives 'a.
marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
}
impl<'c, 'a> Deref for StepCursor<'c, 'a> {
type Target = Cursor<'c>;
fn deref(&self) -> &Self::Target {
&self.cursor
}
}
impl<'c, 'a> StepCursor<'c, 'a> {
/// Triggers an error at the current position of the parse stream.
///
/// The `ParseStream::step` invocation will return this same error without
/// advancing the stream state.
pub fn error<T: Display>(self, message: T) -> Error {
error::new_at(self.scope, self.cursor, message)
}
}
impl private {
pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
// Refer to the comments within the StepCursor definition. We use the
// fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
// Cursor is covariant in its lifetime parameter so we can cast a
// Cursor<'c> to one with the shorter lifetime Cursor<'a>.
let _ = proof;
unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
}
}
fn skip(input: ParseStream) -> bool {
input
.step(|cursor| {
if let Some((_lifetime, rest)) = cursor.lifetime() {
Ok((true, rest))
} else if let Some((_token, rest)) = cursor.token_tree() {
Ok((true, rest))
} else {
Ok((false, *cursor))
}
})
.unwrap()
}
impl private {
pub fn new_parse_buffer(
scope: Span,
cursor: Cursor,
unexpected: Rc<Cell<Option<Span>>>,
) -> ParseBuffer {
ParseBuffer {
scope: scope,
// See comment on `cell` in the struct definition.
cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
marker: PhantomData,
unexpected: unexpected,
}
}
pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
buffer.unexpected.clone()
}
}
impl<'a> ParseBuffer<'a> {
/// Parses a syntax tree node of type `T`, advancing the position of our
/// parse stream past it.
pub fn parse<T: Parse>(&self) -> Result<T> {
T::parse(self)
}
/// Calls the given parser function to parse a syntax tree node of type `T`
/// from this stream.
///
/// # Example
///
/// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
/// zero or more outer attributes.
///
/// [`Attribute::parse_outer`]: crate::Attribute::parse_outer
///
/// ```edition2018
/// use syn::{Attribute, Ident, Result, Token};
/// use syn::parse::{Parse, ParseStream};
///
/// // Parses a unit struct with attributes.
/// //
/// // #[path = "s.tmpl"]
/// // struct S;
/// struct UnitStruct {
/// attrs: Vec<Attribute>,
/// struct_token: Token![struct],
/// name: Ident,
/// semi_token: Token![;],
/// }
///
/// impl Parse for UnitStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(UnitStruct {
/// attrs: input.call(Attribute::parse_outer)?,
/// struct_token: input.parse()?,
/// name: input.parse()?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// ```
pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
function(self)
}
/// Looks at the next token in the parse stream to determine whether it
/// matches the requested type of token.
///
/// Does not advance the position of the parse stream.
///
/// # Syntax
///
/// Note that this method does not use turbofish syntax. Pass the peek type
/// inside of parentheses.
///
/// - `input.peek(Token![struct])`
/// - `input.peek(Token![==])`
/// - `input.peek(Ident)` *(does not accept keywords)*
/// - `input.peek(Ident::peek_any)`
/// - `input.peek(Lifetime)`
/// - `input.peek(token::Brace)`
///
/// # Example
///
/// In this example we finish parsing the list of supertraits when the next
/// token in the input is either `where` or an opening curly brace.
///
/// ```edition2018
/// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parses a trait definition containing no associated items.
/// //
/// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
/// struct MarkerTrait {
/// trait_token: Token![trait],
/// ident: Ident,
/// generics: Generics,
/// colon_token: Option<Token![:]>,
/// supertraits: Punctuated<TypeParamBound, Token![+]>,
/// brace_token: token::Brace,
/// }
///
/// impl Parse for MarkerTrait {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let trait_token: Token![trait] = input.parse()?;
/// let ident: Ident = input.parse()?;
/// let mut generics: Generics = input.parse()?;
/// let colon_token: Option<Token![:]> = input.parse()?;
///
/// let mut supertraits = Punctuated::new();
/// if colon_token.is_some() {
/// loop {
/// supertraits.push_value(input.parse()?);
/// if input.peek(Token![where]) || input.peek(token::Brace) {
/// break;
/// }
/// supertraits.push_punct(input.parse()?);
/// }
/// }
///
/// generics.where_clause = input.parse()?;
/// let content;
/// let empty_brace_token = braced!(content in input);
///
/// Ok(MarkerTrait {
/// trait_token: trait_token,
/// ident: ident,
/// generics: generics,
/// colon_token: colon_token,
/// supertraits: supertraits,
/// brace_token: empty_brace_token,
/// })
/// }
/// }
/// ```
pub fn peek<T: Peek>(&self, token: T) -> bool {
let _ = token;
T::Token::peek(self.cursor())
}
/// Looks at the second-next token in the parse stream.
///
/// This is commonly useful as a way to implement contextual keywords.
///
/// # Example
///
/// This example needs to use `peek2` because the symbol `union` is not a
/// keyword in Rust. We can't use just `peek` and decide to parse a union if
/// the very next token is `union`, because someone is free to write a `mod
/// union` and a macro invocation that looks like `union::some_macro! { ...
/// }`. In other words `union` is a contextual keyword.
///
/// ```edition2018
/// use syn::{Ident, ItemUnion, Macro, Result, Token};
/// use syn::parse::{Parse, ParseStream};
///
/// // Parses either a union or a macro invocation.
/// enum UnionOrMacro {
/// // union MaybeUninit<T> { uninit: (), value: T }
/// Union(ItemUnion),
/// // lazy_static! { ... }
/// Macro(Macro),
/// }
///
/// impl Parse for UnionOrMacro {
/// fn parse(input: ParseStream) -> Result<Self> {
/// if input.peek(Token![union]) && input.peek2(Ident) {
/// input.parse().map(UnionOrMacro::Union)
/// } else {
/// input.parse().map(UnionOrMacro::Macro)
/// }
/// }
/// }
/// ```
pub fn peek2<T: Peek>(&self, token: T) -> bool {
let ahead = self.fork();
skip(&ahead) && ahead.peek(token)
}
/// Looks at the third-next token in the parse stream.
pub fn peek3<T: Peek>(&self, token: T) -> bool {
let ahead = self.fork();
skip(&ahead) && skip(&ahead) && ahead.peek(token)
}
/// Parses zero or more occurrences of `T` separated by punctuation of type
/// `P`, with optional trailing punctuation.
///
/// Parsing continues until the end of this parse stream. The entire content
/// of this parse stream must consist of `T` and `P`.
///
/// # Example
///
/// ```edition2018
/// # use quote::quote;
/// #
/// use syn::{parenthesized, token, Ident, Result, Token, Type};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parse a simplified tuple struct syntax like:
/// //
/// // struct S(A, B);
/// struct TupleStruct {
/// struct_token: Token![struct],
/// ident: Ident,
/// paren_token: token::Paren,
/// fields: Punctuated<Type, Token![,]>,
/// semi_token: Token![;],
/// }
///
/// impl Parse for TupleStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let content;
/// Ok(TupleStruct {
/// struct_token: input.parse()?,
/// ident: input.parse()?,
/// paren_token: parenthesized!(content in input),
/// fields: content.parse_terminated(Type::parse)?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// #
/// # fn main() {
/// # let input = quote! {
/// # struct S(A, B);
/// # };
/// # syn::parse2::<TupleStruct>(input).unwrap();
/// # }
/// ```
pub fn parse_terminated<T, P: Parse>(
&self,
parser: fn(ParseStream) -> Result<T>,
) -> Result<Punctuated<T, P>> {
Punctuated::parse_terminated_with(self, parser)
}
/// Returns whether there are tokens remaining in this stream.
///
/// This method returns true at the end of the content of a set of
/// delimiters, as well as at the very end of the complete macro input.
///
/// # Example
///
/// ```edition2018
/// use syn::{braced, token, Ident, Item, Result, Token};
/// use syn::parse::{Parse, ParseStream};
///
/// // Parses a Rust `mod m { ... }` containing zero or more items.
/// struct Mod {
/// mod_token: Token![mod],
/// name: Ident,
/// brace_token: token::Brace,
/// items: Vec<Item>,
/// }
///
/// impl Parse for Mod {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let content;
/// Ok(Mod {
/// mod_token: input.parse()?,
/// name: input.parse()?,
/// brace_token: braced!(content in input),
/// items: {
/// let mut items = Vec::new();
/// while !content.is_empty() {
/// items.push(content.parse()?);
/// }
/// items
/// },
/// })
/// }
/// }
/// ```
pub fn is_empty(&self) -> bool {
self.cursor().eof()
}
/// Constructs a helper for peeking at the next token in this stream and
/// building an error message if it is not one of a set of expected tokens.
///
/// # Example
///
/// ```edition2018
/// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam};
/// use syn::parse::{Parse, ParseStream};
///
/// // A generic parameter, a single one of the comma-separated elements inside
/// // angle brackets in:
/// //
/// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
/// //
/// // On invalid input, lookahead gives us a reasonable error message.
/// //
/// // error: expected one of: identifier, lifetime, `const`
/// // |
/// // 5 | fn f<!Sized>() {}
/// // | ^
/// enum GenericParam {
/// Type(TypeParam),
/// Lifetime(LifetimeDef),
/// Const(ConstParam),
/// }
///
/// impl Parse for GenericParam {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let lookahead = input.lookahead1();
/// if lookahead.peek(Ident) {
/// input.parse().map(GenericParam::Type)
/// } else if lookahead.peek(Lifetime) {
/// input.parse().map(GenericParam::Lifetime)
/// } else if lookahead.peek(Token![const]) {
/// input.parse().map(GenericParam::Const)
/// } else {
/// Err(lookahead.error())
/// }
/// }
/// }
/// ```
pub fn lookahead1(&self) -> Lookahead1<'a> {
lookahead::new(self.scope, self.cursor())
}
/// Forks a parse stream so that parsing tokens out of either the original
/// or the fork does not advance the position of the other.
///
/// # Performance
///
/// Forking a parse stream is a cheap fixed amount of work and does not
/// involve copying token buffers. Where you might hit performance problems
/// is if your macro ends up parsing a large amount of content more than
/// once.
///
/// ```edition2018
/// # use syn::{Expr, Result};
/// # use syn::parse::ParseStream;
/// #
/// # fn bad(input: ParseStream) -> Result<Expr> {
/// // Do not do this.
/// if input.fork().parse::<Expr>().is_ok() {
/// return input.parse::<Expr>();
/// }
/// # unimplemented!()
/// # }
/// ```
///
/// As a rule, avoid parsing an unbounded amount of tokens out of a forked
/// parse stream. Only use a fork when the amount of work performed against
/// the fork is small and bounded.
///
/// When complex speculative parsing against the forked stream is
/// unavoidable, use [`parse::discouraged::Speculative`] to advance the
/// original stream once the fork's parse is determined to have been
/// successful.
///
/// For a lower level way to perform speculative parsing at the token level,
/// consider using [`ParseStream::step`] instead.
///
/// [`parse::discouraged::Speculative`]: discouraged::Speculative
/// [`ParseStream::step`]: ParseBuffer::step
///
/// # Example
///
/// The parse implementation shown here parses possibly restricted `pub`
/// visibilities.
///
/// - `pub`
/// - `pub(crate)`
/// - `pub(self)`
/// - `pub(super)`
/// - `pub(in some::path)`
///
/// To handle the case of visibilities inside of tuple structs, the parser
/// needs to distinguish parentheses that specify visibility restrictions
/// from parentheses that form part of a tuple type.
///
/// ```edition2018
/// # struct A;
/// # struct B;
/// # struct C;
/// #
/// struct S(pub(crate) A, pub (B, C));
/// ```
///
/// In this example input the first tuple struct element of `S` has
/// `pub(crate)` visibility while the second tuple struct element has `pub`
/// visibility; the parentheses around `(B, C)` are part of the type rather
/// than part of a visibility restriction.
///
/// The parser uses a forked parse stream to check the first token inside of
/// parentheses after the `pub` keyword. This is a small bounded amount of
/// work performed against the forked parse stream.
///
/// ```edition2018
/// use syn::{parenthesized, token, Ident, Path, Result, Token};
/// use syn::ext::IdentExt;
/// use syn::parse::{Parse, ParseStream};
///
/// struct PubVisibility {
/// pub_token: Token![pub],
/// restricted: Option<Restricted>,
/// }
///
/// struct Restricted {
/// paren_token: token::Paren,
/// in_token: Option<Token![in]>,
/// path: Path,
/// }
///
/// impl Parse for PubVisibility {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let pub_token: Token![pub] = input.parse()?;
///
/// if input.peek(token::Paren) {
/// let ahead = input.fork();
/// let mut content;
/// parenthesized!(content in ahead);
///
/// if content.peek(Token![crate])
/// || content.peek(Token![self])
/// || content.peek(Token![super])
/// {
/// return Ok(PubVisibility {
/// pub_token: pub_token,
/// restricted: Some(Restricted {
/// paren_token: parenthesized!(content in input),
/// in_token: None,
/// path: Path::from(content.call(Ident::parse_any)?),
/// }),
/// });
/// } else if content.peek(Token![in]) {
/// return Ok(PubVisibility {
/// pub_token: pub_token,
/// restricted: Some(Restricted {
/// paren_token: parenthesized!(content in input),
/// in_token: Some(content.parse()?),
/// path: content.call(Path::parse_mod_style)?,
/// }),
/// });
/// }
/// }
///
/// Ok(PubVisibility {
/// pub_token: pub_token,
/// restricted: None,
/// })
/// }
/// }
/// ```
pub fn fork(&self) -> Self {
ParseBuffer {
scope: self.scope,
cell: self.cell.clone(),
marker: PhantomData,
// Not the parent's unexpected. Nothing cares whether the clone
// parses all the way.
unexpected: Rc::new(Cell::new(None)),
}
}
/// Triggers an error at the current position of the parse stream.
///
/// # Example
///
/// ```edition2018
/// use syn::{Expr, Result, Token};
/// use syn::parse::{Parse, ParseStream};
///
/// // Some kind of loop: `while` or `for` or `loop`.
/// struct Loop {
/// expr: Expr,
/// }
///
/// impl Parse for Loop {
/// fn parse(input: ParseStream) -> Result<Self> {
/// if input.peek(Token![while])
/// || input.peek(Token![for])
/// || input.peek(Token![loop])
/// {
/// Ok(Loop {
/// expr: input.parse()?,
/// })
/// } else {
/// Err(input.error("expected some kind of loop"))
/// }
/// }
/// }
/// ```
pub fn error<T: Display>(&self, message: T) -> Error {
error::new_at(self.scope, self.cursor(), message)
}
/// Speculatively parses tokens from this parse stream, advancing the
/// position of this stream only if parsing succeeds.
///
/// This is a powerful low-level API used for defining the `Parse` impls of
/// the basic built-in token types. It is not something that will be used
/// widely outside of the Syn codebase.
///
/// # Example
///
/// ```edition2018
/// use proc_macro2::TokenTree;
/// use syn::Result;
/// use syn::parse::ParseStream;
///
/// // This function advances the stream past the next occurrence of `@`. If
/// // no `@` is present in the stream, the stream position is unchanged and
/// // an error is returned.
/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
/// input.step(|cursor| {
/// let mut rest = *cursor;
/// while let Some((tt, next)) = rest.token_tree() {
/// match &tt {
/// TokenTree::Punct(punct) if punct.as_char() == '@' => {
/// return Ok(((), next));
/// }
/// _ => rest = next,
/// }
/// }
/// Err(cursor.error("no `@` was found after this point"))
/// })
/// }
/// #
/// # fn remainder_after_skipping_past_next_at(
/// # input: ParseStream,
/// # ) -> Result<proc_macro2::TokenStream> {
/// # skip_past_next_at(input)?;
/// # input.parse()
/// # }
/// #
/// # fn main() {
/// # use syn::parse::Parser;
/// # let remainder = remainder_after_skipping_past_next_at
/// # .parse_str("a @ b c")
/// # .unwrap();
/// # assert_eq!(remainder.to_string(), "b c");
/// # }
/// ```
pub fn step<F, R>(&self, function: F) -> Result<R>
where
F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
{
// Since the user's function is required to work for any 'c, we know
// that the Cursor<'c> they return is either derived from the input
// StepCursor<'c, 'a> or from a Cursor<'static>.
//
// It would not be legal to write this function without the invariant
// lifetime 'c in StepCursor<'c, 'a>. If this function were written only
// in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
// a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
// `step` on their ParseBuffer<'short> with a closure that returns
// Cursor<'short>, and we would wrongly write that Cursor<'short> into
// the Cell intended to hold Cursor<'a>.
//
// In some cases it may be necessary for R to contain a Cursor<'a>.
// Within Syn we solve this using `private::advance_step_cursor` which
// uses the existence of a StepCursor<'c, 'a> as proof that it is safe
// to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it
// would be safe to expose that API as a method on StepCursor.
let (node, rest) = function(StepCursor {
scope: self.scope,
cursor: self.cell.get(),
marker: PhantomData,
})?;
self.cell.set(rest);
Ok(node)
}
/// Provides low-level access to the token representation underlying this
/// parse stream.
///
/// Cursors are immutable so no operations you perform against the cursor
/// will affect the state of this parse stream.
pub fn cursor(&self) -> Cursor<'a> {
self.cell.get()
}
fn check_unexpected(&self) -> Result<()> {
match self.unexpected.get() {
Some(span) => Err(Error::new(span, "unexpected token")),
None => Ok(()),
}
}
}
impl<T: Parse> Parse for Box<T> {
fn parse(input: ParseStream) -> Result<Self> {
input.parse().map(Box::new)
}
}
impl<T: Parse + Token> Parse for Option<T> {
fn parse(input: ParseStream) -> Result<Self> {
if T::peek(input.cursor()) {
Ok(Some(input.parse()?))
} else {
Ok(None)
}
}
}
impl Parse for TokenStream {
fn parse(input: ParseStream) -> Result<Self> {
input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
}
}
impl Parse for TokenTree {
fn parse(input: ParseStream) -> Result<Self> {
input.step(|cursor| match cursor.token_tree() {
Some((tt, rest)) => Ok((tt, rest)),
None => Err(cursor.error("expected token tree")),
})
}
}
impl Parse for Group {
fn parse(input: ParseStream) -> Result<Self> {
input.step(|cursor| {
for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
if let Some((inside, span, rest)) = cursor.group(*delim) {
let mut group = Group::new(*delim, inside.token_stream());
group.set_span(span);
return Ok((group, rest));
}
}
Err(cursor.error("expected group token"))
})
}
}
impl Parse for Punct {
fn parse(input: ParseStream) -> Result<Self> {
input.step(|cursor| match cursor.punct() {
Some((punct, rest)) => Ok((punct, rest)),
None => Err(cursor.error("expected punctuation token")),
})
}
}
impl Parse for Literal {
fn parse(input: ParseStream) -> Result<Self> {
input.step(|cursor| match cursor.literal() {
Some((literal, rest)) => Ok((literal, rest)),
None => Err(cursor.error("expected literal token")),
})
}
}
/// Parser that can parse Rust tokens into a particular syntax tree node.
///
/// Refer to the [module documentation] for details about parsing in Syn.
///
/// [module documentation]: self
///
/// *This trait is available if Syn is built with the `"parsing"` feature.*
pub trait Parser: Sized {
type Output;
/// Parse a proc-macro2 token stream into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the stream, an error is returned.
fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
/// Parse tokens of source code into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the stream, an error is returned.
///
/// *This method is available if Syn is built with both the `"parsing"` and
/// `"proc-macro"` features.*
#[cfg(all(
not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
feature = "proc-macro"
))]
fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
self.parse2(proc_macro2::TokenStream::from(tokens))
}
/// Parse a string of Rust code into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the string, an error is returned.
///
/// # Hygiene
///
/// Every span in the resulting syntax tree will be set to resolve at the
/// macro call site.
fn parse_str(self, s: &str) -> Result<Self::Output> {
self.parse2(proc_macro2::TokenStream::from_str(s)?)
}
// Not public API.
#[doc(hidden)]
fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> {
let _ = scope;
self.parse2(tokens)
}
}
fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
let scope = Span::call_site();
let cursor = tokens.begin();
let unexpected = Rc::new(Cell::new(None));
private::new_parse_buffer(scope, cursor, unexpected)
}
impl<F, T> Parser for F
where
F: FnOnce(ParseStream) -> Result<T>,
{
type Output = T;
fn parse2(self, tokens: TokenStream) -> Result<T> {
let buf = TokenBuffer::new2(tokens);
let state = tokens_to_parse_buffer(&buf);
let node = self(&state)?;
state.check_unexpected()?;
if state.is_empty() {
Ok(node)
} else {
Err(state.error("unexpected token"))
}
}
#[doc(hidden)]
fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> {
let buf = TokenBuffer::new2(tokens);
let cursor = buf.begin();
let unexpected = Rc::new(Cell::new(None));
let state = private::new_parse_buffer(scope, cursor, unexpected);
let node = self(&state)?;
state.check_unexpected()?;
if state.is_empty() {
Ok(node)
} else {
Err(state.error("unexpected token"))
}
}
}
impl private {
pub fn parse_scoped<F: Parser>(f: F, scope: Span, tokens: TokenStream) -> Result<F::Output> {
f.__parse_scoped(scope, tokens)
}
}
| 34.373693 | 97 | 0.549378 |
5b296c0744efe0bc04ff1b2c9fb429a3f019a817
| 293,040 |
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum SelectiveAuth {
#[allow(missing_docs)] // documentation missing in model
Disabled,
#[allow(missing_docs)] // documentation missing in model
Enabled,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for SelectiveAuth {
fn from(s: &str) -> Self {
match s {
"Disabled" => SelectiveAuth::Disabled,
"Enabled" => SelectiveAuth::Enabled,
other => SelectiveAuth::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for SelectiveAuth {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(SelectiveAuth::from(s))
}
}
impl SelectiveAuth {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
SelectiveAuth::Disabled => "Disabled",
SelectiveAuth::Enabled => "Enabled",
SelectiveAuth::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["Disabled", "Enabled"]
}
}
impl AsRef<str> for SelectiveAuth {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Contains information about a Remote Authentication Dial In User Service (RADIUS) server.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RadiusSettings {
/// <p>An array of strings that contains the fully qualified domain name (FQDN) or IP addresses of the RADIUS server endpoints, or the FQDN or IP addresses of your RADIUS server load balancer.</p>
pub radius_servers: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The port that your RADIUS server is using for communications. Your self-managed network must allow inbound traffic over this port from the Directory Service servers.</p>
pub radius_port: i32,
/// <p>The amount of time, in seconds, to wait for the RADIUS server to respond.</p>
pub radius_timeout: i32,
/// <p>The maximum number of times that communication with the RADIUS server is attempted.</p>
pub radius_retries: i32,
/// <p>Required for enabling RADIUS on the directory.</p>
pub shared_secret: std::option::Option<std::string::String>,
/// <p>The protocol specified for your RADIUS endpoints.</p>
pub authentication_protocol: std::option::Option<crate::model::RadiusAuthenticationProtocol>,
/// <p>Not currently used.</p>
pub display_label: std::option::Option<std::string::String>,
/// <p>Not currently used.</p>
pub use_same_username: bool,
}
impl RadiusSettings {
/// <p>An array of strings that contains the fully qualified domain name (FQDN) or IP addresses of the RADIUS server endpoints, or the FQDN or IP addresses of your RADIUS server load balancer.</p>
pub fn radius_servers(&self) -> std::option::Option<&[std::string::String]> {
self.radius_servers.as_deref()
}
/// <p>The port that your RADIUS server is using for communications. Your self-managed network must allow inbound traffic over this port from the Directory Service servers.</p>
pub fn radius_port(&self) -> i32 {
self.radius_port
}
/// <p>The amount of time, in seconds, to wait for the RADIUS server to respond.</p>
pub fn radius_timeout(&self) -> i32 {
self.radius_timeout
}
/// <p>The maximum number of times that communication with the RADIUS server is attempted.</p>
pub fn radius_retries(&self) -> i32 {
self.radius_retries
}
/// <p>Required for enabling RADIUS on the directory.</p>
pub fn shared_secret(&self) -> std::option::Option<&str> {
self.shared_secret.as_deref()
}
/// <p>The protocol specified for your RADIUS endpoints.</p>
pub fn authentication_protocol(
&self,
) -> std::option::Option<&crate::model::RadiusAuthenticationProtocol> {
self.authentication_protocol.as_ref()
}
/// <p>Not currently used.</p>
pub fn display_label(&self) -> std::option::Option<&str> {
self.display_label.as_deref()
}
/// <p>Not currently used.</p>
pub fn use_same_username(&self) -> bool {
self.use_same_username
}
}
impl std::fmt::Debug for RadiusSettings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RadiusSettings");
formatter.field("radius_servers", &self.radius_servers);
formatter.field("radius_port", &self.radius_port);
formatter.field("radius_timeout", &self.radius_timeout);
formatter.field("radius_retries", &self.radius_retries);
formatter.field("shared_secret", &"*** Sensitive Data Redacted ***");
formatter.field("authentication_protocol", &self.authentication_protocol);
formatter.field("display_label", &self.display_label);
formatter.field("use_same_username", &self.use_same_username);
formatter.finish()
}
}
/// See [`RadiusSettings`](crate::model::RadiusSettings)
pub mod radius_settings {
/// A builder for [`RadiusSettings`](crate::model::RadiusSettings)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) radius_servers: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) radius_port: std::option::Option<i32>,
pub(crate) radius_timeout: std::option::Option<i32>,
pub(crate) radius_retries: std::option::Option<i32>,
pub(crate) shared_secret: std::option::Option<std::string::String>,
pub(crate) authentication_protocol:
std::option::Option<crate::model::RadiusAuthenticationProtocol>,
pub(crate) display_label: std::option::Option<std::string::String>,
pub(crate) use_same_username: std::option::Option<bool>,
}
impl Builder {
/// Appends an item to `radius_servers`.
///
/// To override the contents of this collection use [`set_radius_servers`](Self::set_radius_servers).
///
/// <p>An array of strings that contains the fully qualified domain name (FQDN) or IP addresses of the RADIUS server endpoints, or the FQDN or IP addresses of your RADIUS server load balancer.</p>
pub fn radius_servers(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.radius_servers.unwrap_or_default();
v.push(input.into());
self.radius_servers = Some(v);
self
}
/// <p>An array of strings that contains the fully qualified domain name (FQDN) or IP addresses of the RADIUS server endpoints, or the FQDN or IP addresses of your RADIUS server load balancer.</p>
pub fn set_radius_servers(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.radius_servers = input;
self
}
/// <p>The port that your RADIUS server is using for communications. Your self-managed network must allow inbound traffic over this port from the Directory Service servers.</p>
pub fn radius_port(mut self, input: i32) -> Self {
self.radius_port = Some(input);
self
}
/// <p>The port that your RADIUS server is using for communications. Your self-managed network must allow inbound traffic over this port from the Directory Service servers.</p>
pub fn set_radius_port(mut self, input: std::option::Option<i32>) -> Self {
self.radius_port = input;
self
}
/// <p>The amount of time, in seconds, to wait for the RADIUS server to respond.</p>
pub fn radius_timeout(mut self, input: i32) -> Self {
self.radius_timeout = Some(input);
self
}
/// <p>The amount of time, in seconds, to wait for the RADIUS server to respond.</p>
pub fn set_radius_timeout(mut self, input: std::option::Option<i32>) -> Self {
self.radius_timeout = input;
self
}
/// <p>The maximum number of times that communication with the RADIUS server is attempted.</p>
pub fn radius_retries(mut self, input: i32) -> Self {
self.radius_retries = Some(input);
self
}
/// <p>The maximum number of times that communication with the RADIUS server is attempted.</p>
pub fn set_radius_retries(mut self, input: std::option::Option<i32>) -> Self {
self.radius_retries = input;
self
}
/// <p>Required for enabling RADIUS on the directory.</p>
pub fn shared_secret(mut self, input: impl Into<std::string::String>) -> Self {
self.shared_secret = Some(input.into());
self
}
/// <p>Required for enabling RADIUS on the directory.</p>
pub fn set_shared_secret(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.shared_secret = input;
self
}
/// <p>The protocol specified for your RADIUS endpoints.</p>
pub fn authentication_protocol(
mut self,
input: crate::model::RadiusAuthenticationProtocol,
) -> Self {
self.authentication_protocol = Some(input);
self
}
/// <p>The protocol specified for your RADIUS endpoints.</p>
pub fn set_authentication_protocol(
mut self,
input: std::option::Option<crate::model::RadiusAuthenticationProtocol>,
) -> Self {
self.authentication_protocol = input;
self
}
/// <p>Not currently used.</p>
pub fn display_label(mut self, input: impl Into<std::string::String>) -> Self {
self.display_label = Some(input.into());
self
}
/// <p>Not currently used.</p>
pub fn set_display_label(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.display_label = input;
self
}
/// <p>Not currently used.</p>
pub fn use_same_username(mut self, input: bool) -> Self {
self.use_same_username = Some(input);
self
}
/// <p>Not currently used.</p>
pub fn set_use_same_username(mut self, input: std::option::Option<bool>) -> Self {
self.use_same_username = input;
self
}
/// Consumes the builder and constructs a [`RadiusSettings`](crate::model::RadiusSettings)
pub fn build(self) -> crate::model::RadiusSettings {
crate::model::RadiusSettings {
radius_servers: self.radius_servers,
radius_port: self.radius_port.unwrap_or_default(),
radius_timeout: self.radius_timeout.unwrap_or_default(),
radius_retries: self.radius_retries.unwrap_or_default(),
shared_secret: self.shared_secret,
authentication_protocol: self.authentication_protocol,
display_label: self.display_label,
use_same_username: self.use_same_username.unwrap_or_default(),
}
}
}
}
impl RadiusSettings {
/// Creates a new builder-style object to manufacture [`RadiusSettings`](crate::model::RadiusSettings)
pub fn builder() -> crate::model::radius_settings::Builder {
crate::model::radius_settings::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum RadiusAuthenticationProtocol {
#[allow(missing_docs)] // documentation missing in model
Chap,
#[allow(missing_docs)] // documentation missing in model
Mschapv1,
#[allow(missing_docs)] // documentation missing in model
Mschapv2,
#[allow(missing_docs)] // documentation missing in model
Pap,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for RadiusAuthenticationProtocol {
fn from(s: &str) -> Self {
match s {
"CHAP" => RadiusAuthenticationProtocol::Chap,
"MS-CHAPv1" => RadiusAuthenticationProtocol::Mschapv1,
"MS-CHAPv2" => RadiusAuthenticationProtocol::Mschapv2,
"PAP" => RadiusAuthenticationProtocol::Pap,
other => RadiusAuthenticationProtocol::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for RadiusAuthenticationProtocol {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(RadiusAuthenticationProtocol::from(s))
}
}
impl RadiusAuthenticationProtocol {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
RadiusAuthenticationProtocol::Chap => "CHAP",
RadiusAuthenticationProtocol::Mschapv1 => "MS-CHAPv1",
RadiusAuthenticationProtocol::Mschapv2 => "MS-CHAPv2",
RadiusAuthenticationProtocol::Pap => "PAP",
RadiusAuthenticationProtocol::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["CHAP", "MS-CHAPv1", "MS-CHAPv2", "PAP"]
}
}
impl AsRef<str> for RadiusAuthenticationProtocol {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Identifier that contains details about the directory consumer account with whom the directory is being unshared.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UnshareTarget {
/// <p>Identifier of the directory consumer account.</p>
pub id: std::option::Option<std::string::String>,
/// <p>Type of identifier to be used in the <i>Id</i> field.</p>
pub r#type: std::option::Option<crate::model::TargetType>,
}
impl UnshareTarget {
/// <p>Identifier of the directory consumer account.</p>
pub fn id(&self) -> std::option::Option<&str> {
self.id.as_deref()
}
/// <p>Type of identifier to be used in the <i>Id</i> field.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::TargetType> {
self.r#type.as_ref()
}
}
impl std::fmt::Debug for UnshareTarget {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UnshareTarget");
formatter.field("id", &self.id);
formatter.field("r#type", &self.r#type);
formatter.finish()
}
}
/// See [`UnshareTarget`](crate::model::UnshareTarget)
pub mod unshare_target {
/// A builder for [`UnshareTarget`](crate::model::UnshareTarget)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) id: std::option::Option<std::string::String>,
pub(crate) r#type: std::option::Option<crate::model::TargetType>,
}
impl Builder {
/// <p>Identifier of the directory consumer account.</p>
pub fn id(mut self, input: impl Into<std::string::String>) -> Self {
self.id = Some(input.into());
self
}
/// <p>Identifier of the directory consumer account.</p>
pub fn set_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.id = input;
self
}
/// <p>Type of identifier to be used in the <i>Id</i> field.</p>
pub fn r#type(mut self, input: crate::model::TargetType) -> Self {
self.r#type = Some(input);
self
}
/// <p>Type of identifier to be used in the <i>Id</i> field.</p>
pub fn set_type(mut self, input: std::option::Option<crate::model::TargetType>) -> Self {
self.r#type = input;
self
}
/// Consumes the builder and constructs a [`UnshareTarget`](crate::model::UnshareTarget)
pub fn build(self) -> crate::model::UnshareTarget {
crate::model::UnshareTarget {
id: self.id,
r#type: self.r#type,
}
}
}
}
impl UnshareTarget {
/// Creates a new builder-style object to manufacture [`UnshareTarget`](crate::model::UnshareTarget)
pub fn builder() -> crate::model::unshare_target::Builder {
crate::model::unshare_target::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum TargetType {
#[allow(missing_docs)] // documentation missing in model
Account,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for TargetType {
fn from(s: &str) -> Self {
match s {
"ACCOUNT" => TargetType::Account,
other => TargetType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for TargetType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(TargetType::from(s))
}
}
impl TargetType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
TargetType::Account => "ACCOUNT",
TargetType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["ACCOUNT"]
}
}
impl AsRef<str> for TargetType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ShareMethod {
#[allow(missing_docs)] // documentation missing in model
Handshake,
#[allow(missing_docs)] // documentation missing in model
Organizations,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ShareMethod {
fn from(s: &str) -> Self {
match s {
"HANDSHAKE" => ShareMethod::Handshake,
"ORGANIZATIONS" => ShareMethod::Organizations,
other => ShareMethod::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ShareMethod {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ShareMethod::from(s))
}
}
impl ShareMethod {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ShareMethod::Handshake => "HANDSHAKE",
ShareMethod::Organizations => "ORGANIZATIONS",
ShareMethod::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["HANDSHAKE", "ORGANIZATIONS"]
}
}
impl AsRef<str> for ShareMethod {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Identifier that contains details about the directory consumer account.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ShareTarget {
/// <p>Identifier of the directory consumer account.</p>
pub id: std::option::Option<std::string::String>,
/// <p>Type of identifier to be used in the <code>Id</code> field.</p>
pub r#type: std::option::Option<crate::model::TargetType>,
}
impl ShareTarget {
/// <p>Identifier of the directory consumer account.</p>
pub fn id(&self) -> std::option::Option<&str> {
self.id.as_deref()
}
/// <p>Type of identifier to be used in the <code>Id</code> field.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::TargetType> {
self.r#type.as_ref()
}
}
impl std::fmt::Debug for ShareTarget {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ShareTarget");
formatter.field("id", &self.id);
formatter.field("r#type", &self.r#type);
formatter.finish()
}
}
/// See [`ShareTarget`](crate::model::ShareTarget)
pub mod share_target {
/// A builder for [`ShareTarget`](crate::model::ShareTarget)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) id: std::option::Option<std::string::String>,
pub(crate) r#type: std::option::Option<crate::model::TargetType>,
}
impl Builder {
/// <p>Identifier of the directory consumer account.</p>
pub fn id(mut self, input: impl Into<std::string::String>) -> Self {
self.id = Some(input.into());
self
}
/// <p>Identifier of the directory consumer account.</p>
pub fn set_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.id = input;
self
}
/// <p>Type of identifier to be used in the <code>Id</code> field.</p>
pub fn r#type(mut self, input: crate::model::TargetType) -> Self {
self.r#type = Some(input);
self
}
/// <p>Type of identifier to be used in the <code>Id</code> field.</p>
pub fn set_type(mut self, input: std::option::Option<crate::model::TargetType>) -> Self {
self.r#type = input;
self
}
/// Consumes the builder and constructs a [`ShareTarget`](crate::model::ShareTarget)
pub fn build(self) -> crate::model::ShareTarget {
crate::model::ShareTarget {
id: self.id,
r#type: self.r#type,
}
}
}
}
impl ShareTarget {
/// Creates a new builder-style object to manufacture [`ShareTarget`](crate::model::ShareTarget)
pub fn builder() -> crate::model::share_target::Builder {
crate::model::share_target::Builder::default()
}
}
/// <p>Contains information about the client certificate authentication settings for the <code>RegisterCertificate</code> and <code>DescribeCertificate</code> operations. </p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ClientCertAuthSettings {
/// <p>Specifies the URL of the default OCSP server used to check for revocation status. A secondary value to any OCSP address found in the AIA extension of the user certificate.</p>
pub ocsp_url: std::option::Option<std::string::String>,
}
impl ClientCertAuthSettings {
/// <p>Specifies the URL of the default OCSP server used to check for revocation status. A secondary value to any OCSP address found in the AIA extension of the user certificate.</p>
pub fn ocsp_url(&self) -> std::option::Option<&str> {
self.ocsp_url.as_deref()
}
}
impl std::fmt::Debug for ClientCertAuthSettings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ClientCertAuthSettings");
formatter.field("ocsp_url", &self.ocsp_url);
formatter.finish()
}
}
/// See [`ClientCertAuthSettings`](crate::model::ClientCertAuthSettings)
pub mod client_cert_auth_settings {
/// A builder for [`ClientCertAuthSettings`](crate::model::ClientCertAuthSettings)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) ocsp_url: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Specifies the URL of the default OCSP server used to check for revocation status. A secondary value to any OCSP address found in the AIA extension of the user certificate.</p>
pub fn ocsp_url(mut self, input: impl Into<std::string::String>) -> Self {
self.ocsp_url = Some(input.into());
self
}
/// <p>Specifies the URL of the default OCSP server used to check for revocation status. A secondary value to any OCSP address found in the AIA extension of the user certificate.</p>
pub fn set_ocsp_url(mut self, input: std::option::Option<std::string::String>) -> Self {
self.ocsp_url = input;
self
}
/// Consumes the builder and constructs a [`ClientCertAuthSettings`](crate::model::ClientCertAuthSettings)
pub fn build(self) -> crate::model::ClientCertAuthSettings {
crate::model::ClientCertAuthSettings {
ocsp_url: self.ocsp_url,
}
}
}
}
impl ClientCertAuthSettings {
/// Creates a new builder-style object to manufacture [`ClientCertAuthSettings`](crate::model::ClientCertAuthSettings)
pub fn builder() -> crate::model::client_cert_auth_settings::Builder {
crate::model::client_cert_auth_settings::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum CertificateType {
#[allow(missing_docs)] // documentation missing in model
ClientCertAuth,
#[allow(missing_docs)] // documentation missing in model
ClientLdaps,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for CertificateType {
fn from(s: &str) -> Self {
match s {
"ClientCertAuth" => CertificateType::ClientCertAuth,
"ClientLDAPS" => CertificateType::ClientLdaps,
other => CertificateType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for CertificateType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(CertificateType::from(s))
}
}
impl CertificateType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
CertificateType::ClientCertAuth => "ClientCertAuth",
CertificateType::ClientLdaps => "ClientLDAPS",
CertificateType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["ClientCertAuth", "ClientLDAPS"]
}
}
impl AsRef<str> for CertificateType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Metadata assigned to a directory consisting of a key-value pair.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct Tag {
/// <p>Required name of the tag. The string value can be Unicode characters and cannot be prefixed with "aws:". The string can contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$").</p>
pub key: std::option::Option<std::string::String>,
/// <p>The optional value of the tag. The string value can be Unicode characters. The string can contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$").</p>
pub value: std::option::Option<std::string::String>,
}
impl Tag {
/// <p>Required name of the tag. The string value can be Unicode characters and cannot be prefixed with "aws:". The string can contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$").</p>
pub fn key(&self) -> std::option::Option<&str> {
self.key.as_deref()
}
/// <p>The optional value of the tag. The string value can be Unicode characters. The string can contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$").</p>
pub fn value(&self) -> std::option::Option<&str> {
self.value.as_deref()
}
}
impl std::fmt::Debug for Tag {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("Tag");
formatter.field("key", &self.key);
formatter.field("value", &self.value);
formatter.finish()
}
}
/// See [`Tag`](crate::model::Tag)
pub mod tag {
/// A builder for [`Tag`](crate::model::Tag)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) key: std::option::Option<std::string::String>,
pub(crate) value: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Required name of the tag. The string value can be Unicode characters and cannot be prefixed with "aws:". The string can contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$").</p>
pub fn key(mut self, input: impl Into<std::string::String>) -> Self {
self.key = Some(input.into());
self
}
/// <p>Required name of the tag. The string value can be Unicode characters and cannot be prefixed with "aws:". The string can contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$").</p>
pub fn set_key(mut self, input: std::option::Option<std::string::String>) -> Self {
self.key = input;
self
}
/// <p>The optional value of the tag. The string value can be Unicode characters. The string can contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$").</p>
pub fn value(mut self, input: impl Into<std::string::String>) -> Self {
self.value = Some(input.into());
self
}
/// <p>The optional value of the tag. The string value can be Unicode characters. The string can contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$").</p>
pub fn set_value(mut self, input: std::option::Option<std::string::String>) -> Self {
self.value = input;
self
}
/// Consumes the builder and constructs a [`Tag`](crate::model::Tag)
pub fn build(self) -> crate::model::Tag {
crate::model::Tag {
key: self.key,
value: self.value,
}
}
}
}
impl Tag {
/// Creates a new builder-style object to manufacture [`Tag`](crate::model::Tag)
pub fn builder() -> crate::model::tag::Builder {
crate::model::tag::Builder::default()
}
}
/// <p>Information about a schema extension.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct SchemaExtensionInfo {
/// <p>The identifier of the directory to which the schema extension is applied.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The identifier of the schema extension.</p>
pub schema_extension_id: std::option::Option<std::string::String>,
/// <p>A description of the schema extension.</p>
pub description: std::option::Option<std::string::String>,
/// <p>The current status of the schema extension.</p>
pub schema_extension_status: std::option::Option<crate::model::SchemaExtensionStatus>,
/// <p>The reason for the <code>SchemaExtensionStatus</code>.</p>
pub schema_extension_status_reason: std::option::Option<std::string::String>,
/// <p>The date and time that the schema extension started being applied to the directory.</p>
pub start_date_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The date and time that the schema extension was completed.</p>
pub end_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl SchemaExtensionInfo {
/// <p>The identifier of the directory to which the schema extension is applied.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The identifier of the schema extension.</p>
pub fn schema_extension_id(&self) -> std::option::Option<&str> {
self.schema_extension_id.as_deref()
}
/// <p>A description of the schema extension.</p>
pub fn description(&self) -> std::option::Option<&str> {
self.description.as_deref()
}
/// <p>The current status of the schema extension.</p>
pub fn schema_extension_status(
&self,
) -> std::option::Option<&crate::model::SchemaExtensionStatus> {
self.schema_extension_status.as_ref()
}
/// <p>The reason for the <code>SchemaExtensionStatus</code>.</p>
pub fn schema_extension_status_reason(&self) -> std::option::Option<&str> {
self.schema_extension_status_reason.as_deref()
}
/// <p>The date and time that the schema extension started being applied to the directory.</p>
pub fn start_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.start_date_time.as_ref()
}
/// <p>The date and time that the schema extension was completed.</p>
pub fn end_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.end_date_time.as_ref()
}
}
impl std::fmt::Debug for SchemaExtensionInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("SchemaExtensionInfo");
formatter.field("directory_id", &self.directory_id);
formatter.field("schema_extension_id", &self.schema_extension_id);
formatter.field("description", &self.description);
formatter.field("schema_extension_status", &self.schema_extension_status);
formatter.field(
"schema_extension_status_reason",
&self.schema_extension_status_reason,
);
formatter.field("start_date_time", &self.start_date_time);
formatter.field("end_date_time", &self.end_date_time);
formatter.finish()
}
}
/// See [`SchemaExtensionInfo`](crate::model::SchemaExtensionInfo)
pub mod schema_extension_info {
/// A builder for [`SchemaExtensionInfo`](crate::model::SchemaExtensionInfo)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) schema_extension_id: std::option::Option<std::string::String>,
pub(crate) description: std::option::Option<std::string::String>,
pub(crate) schema_extension_status:
std::option::Option<crate::model::SchemaExtensionStatus>,
pub(crate) schema_extension_status_reason: std::option::Option<std::string::String>,
pub(crate) start_date_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) end_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl Builder {
/// <p>The identifier of the directory to which the schema extension is applied.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory to which the schema extension is applied.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The identifier of the schema extension.</p>
pub fn schema_extension_id(mut self, input: impl Into<std::string::String>) -> Self {
self.schema_extension_id = Some(input.into());
self
}
/// <p>The identifier of the schema extension.</p>
pub fn set_schema_extension_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.schema_extension_id = input;
self
}
/// <p>A description of the schema extension.</p>
pub fn description(mut self, input: impl Into<std::string::String>) -> Self {
self.description = Some(input.into());
self
}
/// <p>A description of the schema extension.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.description = input;
self
}
/// <p>The current status of the schema extension.</p>
pub fn schema_extension_status(
mut self,
input: crate::model::SchemaExtensionStatus,
) -> Self {
self.schema_extension_status = Some(input);
self
}
/// <p>The current status of the schema extension.</p>
pub fn set_schema_extension_status(
mut self,
input: std::option::Option<crate::model::SchemaExtensionStatus>,
) -> Self {
self.schema_extension_status = input;
self
}
/// <p>The reason for the <code>SchemaExtensionStatus</code>.</p>
pub fn schema_extension_status_reason(
mut self,
input: impl Into<std::string::String>,
) -> Self {
self.schema_extension_status_reason = Some(input.into());
self
}
/// <p>The reason for the <code>SchemaExtensionStatus</code>.</p>
pub fn set_schema_extension_status_reason(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.schema_extension_status_reason = input;
self
}
/// <p>The date and time that the schema extension started being applied to the directory.</p>
pub fn start_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.start_date_time = Some(input);
self
}
/// <p>The date and time that the schema extension started being applied to the directory.</p>
pub fn set_start_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.start_date_time = input;
self
}
/// <p>The date and time that the schema extension was completed.</p>
pub fn end_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.end_date_time = Some(input);
self
}
/// <p>The date and time that the schema extension was completed.</p>
pub fn set_end_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.end_date_time = input;
self
}
/// Consumes the builder and constructs a [`SchemaExtensionInfo`](crate::model::SchemaExtensionInfo)
pub fn build(self) -> crate::model::SchemaExtensionInfo {
crate::model::SchemaExtensionInfo {
directory_id: self.directory_id,
schema_extension_id: self.schema_extension_id,
description: self.description,
schema_extension_status: self.schema_extension_status,
schema_extension_status_reason: self.schema_extension_status_reason,
start_date_time: self.start_date_time,
end_date_time: self.end_date_time,
}
}
}
}
impl SchemaExtensionInfo {
/// Creates a new builder-style object to manufacture [`SchemaExtensionInfo`](crate::model::SchemaExtensionInfo)
pub fn builder() -> crate::model::schema_extension_info::Builder {
crate::model::schema_extension_info::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum SchemaExtensionStatus {
#[allow(missing_docs)] // documentation missing in model
CancelInProgress,
#[allow(missing_docs)] // documentation missing in model
Cancelled,
#[allow(missing_docs)] // documentation missing in model
Completed,
#[allow(missing_docs)] // documentation missing in model
CreatingSnapshot,
#[allow(missing_docs)] // documentation missing in model
Failed,
#[allow(missing_docs)] // documentation missing in model
Initializing,
#[allow(missing_docs)] // documentation missing in model
Replicating,
#[allow(missing_docs)] // documentation missing in model
RollbackInProgress,
#[allow(missing_docs)] // documentation missing in model
UpdatingSchema,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for SchemaExtensionStatus {
fn from(s: &str) -> Self {
match s {
"CancelInProgress" => SchemaExtensionStatus::CancelInProgress,
"Cancelled" => SchemaExtensionStatus::Cancelled,
"Completed" => SchemaExtensionStatus::Completed,
"CreatingSnapshot" => SchemaExtensionStatus::CreatingSnapshot,
"Failed" => SchemaExtensionStatus::Failed,
"Initializing" => SchemaExtensionStatus::Initializing,
"Replicating" => SchemaExtensionStatus::Replicating,
"RollbackInProgress" => SchemaExtensionStatus::RollbackInProgress,
"UpdatingSchema" => SchemaExtensionStatus::UpdatingSchema,
other => SchemaExtensionStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for SchemaExtensionStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(SchemaExtensionStatus::from(s))
}
}
impl SchemaExtensionStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
SchemaExtensionStatus::CancelInProgress => "CancelInProgress",
SchemaExtensionStatus::Cancelled => "Cancelled",
SchemaExtensionStatus::Completed => "Completed",
SchemaExtensionStatus::CreatingSnapshot => "CreatingSnapshot",
SchemaExtensionStatus::Failed => "Failed",
SchemaExtensionStatus::Initializing => "Initializing",
SchemaExtensionStatus::Replicating => "Replicating",
SchemaExtensionStatus::RollbackInProgress => "RollbackInProgress",
SchemaExtensionStatus::UpdatingSchema => "UpdatingSchema",
SchemaExtensionStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"CancelInProgress",
"Cancelled",
"Completed",
"CreatingSnapshot",
"Failed",
"Initializing",
"Replicating",
"RollbackInProgress",
"UpdatingSchema",
]
}
}
impl AsRef<str> for SchemaExtensionStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Represents a log subscription, which tracks real-time data from a chosen log group to a specified destination.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct LogSubscription {
/// <p>Identifier (ID) of the directory that you want to associate with the log subscription.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The name of the log group.</p>
pub log_group_name: std::option::Option<std::string::String>,
/// <p>The date and time that the log subscription was created.</p>
pub subscription_created_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl LogSubscription {
/// <p>Identifier (ID) of the directory that you want to associate with the log subscription.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The name of the log group.</p>
pub fn log_group_name(&self) -> std::option::Option<&str> {
self.log_group_name.as_deref()
}
/// <p>The date and time that the log subscription was created.</p>
pub fn subscription_created_date_time(
&self,
) -> std::option::Option<&aws_smithy_types::DateTime> {
self.subscription_created_date_time.as_ref()
}
}
impl std::fmt::Debug for LogSubscription {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("LogSubscription");
formatter.field("directory_id", &self.directory_id);
formatter.field("log_group_name", &self.log_group_name);
formatter.field(
"subscription_created_date_time",
&self.subscription_created_date_time,
);
formatter.finish()
}
}
/// See [`LogSubscription`](crate::model::LogSubscription)
pub mod log_subscription {
/// A builder for [`LogSubscription`](crate::model::LogSubscription)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) log_group_name: std::option::Option<std::string::String>,
pub(crate) subscription_created_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl Builder {
/// <p>Identifier (ID) of the directory that you want to associate with the log subscription.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier (ID) of the directory that you want to associate with the log subscription.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The name of the log group.</p>
pub fn log_group_name(mut self, input: impl Into<std::string::String>) -> Self {
self.log_group_name = Some(input.into());
self
}
/// <p>The name of the log group.</p>
pub fn set_log_group_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.log_group_name = input;
self
}
/// <p>The date and time that the log subscription was created.</p>
pub fn subscription_created_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.subscription_created_date_time = Some(input);
self
}
/// <p>The date and time that the log subscription was created.</p>
pub fn set_subscription_created_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.subscription_created_date_time = input;
self
}
/// Consumes the builder and constructs a [`LogSubscription`](crate::model::LogSubscription)
pub fn build(self) -> crate::model::LogSubscription {
crate::model::LogSubscription {
directory_id: self.directory_id,
log_group_name: self.log_group_name,
subscription_created_date_time: self.subscription_created_date_time,
}
}
}
}
impl LogSubscription {
/// Creates a new builder-style object to manufacture [`LogSubscription`](crate::model::LogSubscription)
pub fn builder() -> crate::model::log_subscription::Builder {
crate::model::log_subscription::Builder::default()
}
}
/// <p>Information about one or more IP address blocks.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct IpRouteInfo {
/// <p>Identifier (ID) of the directory associated with the IP addresses.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>IP address block in the <code>IpRoute</code>.</p>
pub cidr_ip: std::option::Option<std::string::String>,
/// <p>The status of the IP address block.</p>
pub ip_route_status_msg: std::option::Option<crate::model::IpRouteStatusMsg>,
/// <p>The date and time the address block was added to the directory.</p>
pub added_date_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The reason for the IpRouteStatusMsg.</p>
pub ip_route_status_reason: std::option::Option<std::string::String>,
/// <p>Description of the <code>IpRouteInfo</code>.</p>
pub description: std::option::Option<std::string::String>,
}
impl IpRouteInfo {
/// <p>Identifier (ID) of the directory associated with the IP addresses.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>IP address block in the <code>IpRoute</code>.</p>
pub fn cidr_ip(&self) -> std::option::Option<&str> {
self.cidr_ip.as_deref()
}
/// <p>The status of the IP address block.</p>
pub fn ip_route_status_msg(&self) -> std::option::Option<&crate::model::IpRouteStatusMsg> {
self.ip_route_status_msg.as_ref()
}
/// <p>The date and time the address block was added to the directory.</p>
pub fn added_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.added_date_time.as_ref()
}
/// <p>The reason for the IpRouteStatusMsg.</p>
pub fn ip_route_status_reason(&self) -> std::option::Option<&str> {
self.ip_route_status_reason.as_deref()
}
/// <p>Description of the <code>IpRouteInfo</code>.</p>
pub fn description(&self) -> std::option::Option<&str> {
self.description.as_deref()
}
}
impl std::fmt::Debug for IpRouteInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("IpRouteInfo");
formatter.field("directory_id", &self.directory_id);
formatter.field("cidr_ip", &self.cidr_ip);
formatter.field("ip_route_status_msg", &self.ip_route_status_msg);
formatter.field("added_date_time", &self.added_date_time);
formatter.field("ip_route_status_reason", &self.ip_route_status_reason);
formatter.field("description", &self.description);
formatter.finish()
}
}
/// See [`IpRouteInfo`](crate::model::IpRouteInfo)
pub mod ip_route_info {
/// A builder for [`IpRouteInfo`](crate::model::IpRouteInfo)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) cidr_ip: std::option::Option<std::string::String>,
pub(crate) ip_route_status_msg: std::option::Option<crate::model::IpRouteStatusMsg>,
pub(crate) added_date_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) ip_route_status_reason: std::option::Option<std::string::String>,
pub(crate) description: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Identifier (ID) of the directory associated with the IP addresses.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier (ID) of the directory associated with the IP addresses.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>IP address block in the <code>IpRoute</code>.</p>
pub fn cidr_ip(mut self, input: impl Into<std::string::String>) -> Self {
self.cidr_ip = Some(input.into());
self
}
/// <p>IP address block in the <code>IpRoute</code>.</p>
pub fn set_cidr_ip(mut self, input: std::option::Option<std::string::String>) -> Self {
self.cidr_ip = input;
self
}
/// <p>The status of the IP address block.</p>
pub fn ip_route_status_msg(mut self, input: crate::model::IpRouteStatusMsg) -> Self {
self.ip_route_status_msg = Some(input);
self
}
/// <p>The status of the IP address block.</p>
pub fn set_ip_route_status_msg(
mut self,
input: std::option::Option<crate::model::IpRouteStatusMsg>,
) -> Self {
self.ip_route_status_msg = input;
self
}
/// <p>The date and time the address block was added to the directory.</p>
pub fn added_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.added_date_time = Some(input);
self
}
/// <p>The date and time the address block was added to the directory.</p>
pub fn set_added_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.added_date_time = input;
self
}
/// <p>The reason for the IpRouteStatusMsg.</p>
pub fn ip_route_status_reason(mut self, input: impl Into<std::string::String>) -> Self {
self.ip_route_status_reason = Some(input.into());
self
}
/// <p>The reason for the IpRouteStatusMsg.</p>
pub fn set_ip_route_status_reason(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.ip_route_status_reason = input;
self
}
/// <p>Description of the <code>IpRouteInfo</code>.</p>
pub fn description(mut self, input: impl Into<std::string::String>) -> Self {
self.description = Some(input.into());
self
}
/// <p>Description of the <code>IpRouteInfo</code>.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.description = input;
self
}
/// Consumes the builder and constructs a [`IpRouteInfo`](crate::model::IpRouteInfo)
pub fn build(self) -> crate::model::IpRouteInfo {
crate::model::IpRouteInfo {
directory_id: self.directory_id,
cidr_ip: self.cidr_ip,
ip_route_status_msg: self.ip_route_status_msg,
added_date_time: self.added_date_time,
ip_route_status_reason: self.ip_route_status_reason,
description: self.description,
}
}
}
}
impl IpRouteInfo {
/// Creates a new builder-style object to manufacture [`IpRouteInfo`](crate::model::IpRouteInfo)
pub fn builder() -> crate::model::ip_route_info::Builder {
crate::model::ip_route_info::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum IpRouteStatusMsg {
#[allow(missing_docs)] // documentation missing in model
AddFailed,
#[allow(missing_docs)] // documentation missing in model
Added,
#[allow(missing_docs)] // documentation missing in model
Adding,
#[allow(missing_docs)] // documentation missing in model
RemoveFailed,
#[allow(missing_docs)] // documentation missing in model
Removed,
#[allow(missing_docs)] // documentation missing in model
Removing,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for IpRouteStatusMsg {
fn from(s: &str) -> Self {
match s {
"AddFailed" => IpRouteStatusMsg::AddFailed,
"Added" => IpRouteStatusMsg::Added,
"Adding" => IpRouteStatusMsg::Adding,
"RemoveFailed" => IpRouteStatusMsg::RemoveFailed,
"Removed" => IpRouteStatusMsg::Removed,
"Removing" => IpRouteStatusMsg::Removing,
other => IpRouteStatusMsg::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for IpRouteStatusMsg {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(IpRouteStatusMsg::from(s))
}
}
impl IpRouteStatusMsg {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
IpRouteStatusMsg::AddFailed => "AddFailed",
IpRouteStatusMsg::Added => "Added",
IpRouteStatusMsg::Adding => "Adding",
IpRouteStatusMsg::RemoveFailed => "RemoveFailed",
IpRouteStatusMsg::Removed => "Removed",
IpRouteStatusMsg::Removing => "Removing",
IpRouteStatusMsg::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"AddFailed",
"Added",
"Adding",
"RemoveFailed",
"Removed",
"Removing",
]
}
}
impl AsRef<str> for IpRouteStatusMsg {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Contains general information about a certificate.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CertificateInfo {
/// <p>The identifier of the certificate.</p>
pub certificate_id: std::option::Option<std::string::String>,
/// <p>The common name for the certificate.</p>
pub common_name: std::option::Option<std::string::String>,
/// <p>The state of the certificate.</p>
pub state: std::option::Option<crate::model::CertificateState>,
/// <p>The date and time when the certificate will expire.</p>
pub expiry_date_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The function that the registered certificate performs. Valid values include <code>ClientLDAPS</code> or <code>ClientCertAuth</code>. The default value is <code>ClientLDAPS</code>.</p>
pub r#type: std::option::Option<crate::model::CertificateType>,
}
impl CertificateInfo {
/// <p>The identifier of the certificate.</p>
pub fn certificate_id(&self) -> std::option::Option<&str> {
self.certificate_id.as_deref()
}
/// <p>The common name for the certificate.</p>
pub fn common_name(&self) -> std::option::Option<&str> {
self.common_name.as_deref()
}
/// <p>The state of the certificate.</p>
pub fn state(&self) -> std::option::Option<&crate::model::CertificateState> {
self.state.as_ref()
}
/// <p>The date and time when the certificate will expire.</p>
pub fn expiry_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.expiry_date_time.as_ref()
}
/// <p>The function that the registered certificate performs. Valid values include <code>ClientLDAPS</code> or <code>ClientCertAuth</code>. The default value is <code>ClientLDAPS</code>.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::CertificateType> {
self.r#type.as_ref()
}
}
impl std::fmt::Debug for CertificateInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CertificateInfo");
formatter.field("certificate_id", &self.certificate_id);
formatter.field("common_name", &self.common_name);
formatter.field("state", &self.state);
formatter.field("expiry_date_time", &self.expiry_date_time);
formatter.field("r#type", &self.r#type);
formatter.finish()
}
}
/// See [`CertificateInfo`](crate::model::CertificateInfo)
pub mod certificate_info {
/// A builder for [`CertificateInfo`](crate::model::CertificateInfo)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_id: std::option::Option<std::string::String>,
pub(crate) common_name: std::option::Option<std::string::String>,
pub(crate) state: std::option::Option<crate::model::CertificateState>,
pub(crate) expiry_date_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) r#type: std::option::Option<crate::model::CertificateType>,
}
impl Builder {
/// <p>The identifier of the certificate.</p>
pub fn certificate_id(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_id = Some(input.into());
self
}
/// <p>The identifier of the certificate.</p>
pub fn set_certificate_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_id = input;
self
}
/// <p>The common name for the certificate.</p>
pub fn common_name(mut self, input: impl Into<std::string::String>) -> Self {
self.common_name = Some(input.into());
self
}
/// <p>The common name for the certificate.</p>
pub fn set_common_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.common_name = input;
self
}
/// <p>The state of the certificate.</p>
pub fn state(mut self, input: crate::model::CertificateState) -> Self {
self.state = Some(input);
self
}
/// <p>The state of the certificate.</p>
pub fn set_state(
mut self,
input: std::option::Option<crate::model::CertificateState>,
) -> Self {
self.state = input;
self
}
/// <p>The date and time when the certificate will expire.</p>
pub fn expiry_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.expiry_date_time = Some(input);
self
}
/// <p>The date and time when the certificate will expire.</p>
pub fn set_expiry_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.expiry_date_time = input;
self
}
/// <p>The function that the registered certificate performs. Valid values include <code>ClientLDAPS</code> or <code>ClientCertAuth</code>. The default value is <code>ClientLDAPS</code>.</p>
pub fn r#type(mut self, input: crate::model::CertificateType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The function that the registered certificate performs. Valid values include <code>ClientLDAPS</code> or <code>ClientCertAuth</code>. The default value is <code>ClientLDAPS</code>.</p>
pub fn set_type(
mut self,
input: std::option::Option<crate::model::CertificateType>,
) -> Self {
self.r#type = input;
self
}
/// Consumes the builder and constructs a [`CertificateInfo`](crate::model::CertificateInfo)
pub fn build(self) -> crate::model::CertificateInfo {
crate::model::CertificateInfo {
certificate_id: self.certificate_id,
common_name: self.common_name,
state: self.state,
expiry_date_time: self.expiry_date_time,
r#type: self.r#type,
}
}
}
}
impl CertificateInfo {
/// Creates a new builder-style object to manufacture [`CertificateInfo`](crate::model::CertificateInfo)
pub fn builder() -> crate::model::certificate_info::Builder {
crate::model::certificate_info::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum CertificateState {
#[allow(missing_docs)] // documentation missing in model
DeregisterFailed,
#[allow(missing_docs)] // documentation missing in model
Deregistered,
#[allow(missing_docs)] // documentation missing in model
Deregistering,
#[allow(missing_docs)] // documentation missing in model
RegisterFailed,
#[allow(missing_docs)] // documentation missing in model
Registered,
#[allow(missing_docs)] // documentation missing in model
Registering,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for CertificateState {
fn from(s: &str) -> Self {
match s {
"DeregisterFailed" => CertificateState::DeregisterFailed,
"Deregistered" => CertificateState::Deregistered,
"Deregistering" => CertificateState::Deregistering,
"RegisterFailed" => CertificateState::RegisterFailed,
"Registered" => CertificateState::Registered,
"Registering" => CertificateState::Registering,
other => CertificateState::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for CertificateState {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(CertificateState::from(s))
}
}
impl CertificateState {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
CertificateState::DeregisterFailed => "DeregisterFailed",
CertificateState::Deregistered => "Deregistered",
CertificateState::Deregistering => "Deregistering",
CertificateState::RegisterFailed => "RegisterFailed",
CertificateState::Registered => "Registered",
CertificateState::Registering => "Registering",
CertificateState::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"DeregisterFailed",
"Deregistered",
"Deregistering",
"RegisterFailed",
"Registered",
"Registering",
]
}
}
impl AsRef<str> for CertificateState {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Contains manual snapshot limit information for a directory.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct SnapshotLimits {
/// <p>The maximum number of manual snapshots allowed.</p>
pub manual_snapshots_limit: std::option::Option<i32>,
/// <p>The current number of manual snapshots of the directory.</p>
pub manual_snapshots_current_count: std::option::Option<i32>,
/// <p>Indicates if the manual snapshot limit has been reached.</p>
pub manual_snapshots_limit_reached: bool,
}
impl SnapshotLimits {
/// <p>The maximum number of manual snapshots allowed.</p>
pub fn manual_snapshots_limit(&self) -> std::option::Option<i32> {
self.manual_snapshots_limit
}
/// <p>The current number of manual snapshots of the directory.</p>
pub fn manual_snapshots_current_count(&self) -> std::option::Option<i32> {
self.manual_snapshots_current_count
}
/// <p>Indicates if the manual snapshot limit has been reached.</p>
pub fn manual_snapshots_limit_reached(&self) -> bool {
self.manual_snapshots_limit_reached
}
}
impl std::fmt::Debug for SnapshotLimits {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("SnapshotLimits");
formatter.field("manual_snapshots_limit", &self.manual_snapshots_limit);
formatter.field(
"manual_snapshots_current_count",
&self.manual_snapshots_current_count,
);
formatter.field(
"manual_snapshots_limit_reached",
&self.manual_snapshots_limit_reached,
);
formatter.finish()
}
}
/// See [`SnapshotLimits`](crate::model::SnapshotLimits)
pub mod snapshot_limits {
/// A builder for [`SnapshotLimits`](crate::model::SnapshotLimits)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) manual_snapshots_limit: std::option::Option<i32>,
pub(crate) manual_snapshots_current_count: std::option::Option<i32>,
pub(crate) manual_snapshots_limit_reached: std::option::Option<bool>,
}
impl Builder {
/// <p>The maximum number of manual snapshots allowed.</p>
pub fn manual_snapshots_limit(mut self, input: i32) -> Self {
self.manual_snapshots_limit = Some(input);
self
}
/// <p>The maximum number of manual snapshots allowed.</p>
pub fn set_manual_snapshots_limit(mut self, input: std::option::Option<i32>) -> Self {
self.manual_snapshots_limit = input;
self
}
/// <p>The current number of manual snapshots of the directory.</p>
pub fn manual_snapshots_current_count(mut self, input: i32) -> Self {
self.manual_snapshots_current_count = Some(input);
self
}
/// <p>The current number of manual snapshots of the directory.</p>
pub fn set_manual_snapshots_current_count(
mut self,
input: std::option::Option<i32>,
) -> Self {
self.manual_snapshots_current_count = input;
self
}
/// <p>Indicates if the manual snapshot limit has been reached.</p>
pub fn manual_snapshots_limit_reached(mut self, input: bool) -> Self {
self.manual_snapshots_limit_reached = Some(input);
self
}
/// <p>Indicates if the manual snapshot limit has been reached.</p>
pub fn set_manual_snapshots_limit_reached(
mut self,
input: std::option::Option<bool>,
) -> Self {
self.manual_snapshots_limit_reached = input;
self
}
/// Consumes the builder and constructs a [`SnapshotLimits`](crate::model::SnapshotLimits)
pub fn build(self) -> crate::model::SnapshotLimits {
crate::model::SnapshotLimits {
manual_snapshots_limit: self.manual_snapshots_limit,
manual_snapshots_current_count: self.manual_snapshots_current_count,
manual_snapshots_limit_reached: self
.manual_snapshots_limit_reached
.unwrap_or_default(),
}
}
}
}
impl SnapshotLimits {
/// Creates a new builder-style object to manufacture [`SnapshotLimits`](crate::model::SnapshotLimits)
pub fn builder() -> crate::model::snapshot_limits::Builder {
crate::model::snapshot_limits::Builder::default()
}
}
/// <p>Contains directory limit information for a Region.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DirectoryLimits {
/// <p>The maximum number of cloud directories allowed in the Region.</p>
pub cloud_only_directories_limit: std::option::Option<i32>,
/// <p>The current number of cloud directories in the Region.</p>
pub cloud_only_directories_current_count: std::option::Option<i32>,
/// <p>Indicates if the cloud directory limit has been reached.</p>
pub cloud_only_directories_limit_reached: bool,
/// <p>The maximum number of Managed Microsoft AD directories allowed in the region.</p>
pub cloud_only_microsoft_ad_limit: std::option::Option<i32>,
/// <p>The current number of Managed Microsoft AD directories in the region.</p>
pub cloud_only_microsoft_ad_current_count: std::option::Option<i32>,
/// <p>Indicates if the Managed Microsoft AD directory limit has been reached.</p>
pub cloud_only_microsoft_ad_limit_reached: bool,
/// <p>The maximum number of connected directories allowed in the Region.</p>
pub connected_directories_limit: std::option::Option<i32>,
/// <p>The current number of connected directories in the Region.</p>
pub connected_directories_current_count: std::option::Option<i32>,
/// <p>Indicates if the connected directory limit has been reached.</p>
pub connected_directories_limit_reached: bool,
}
impl DirectoryLimits {
/// <p>The maximum number of cloud directories allowed in the Region.</p>
pub fn cloud_only_directories_limit(&self) -> std::option::Option<i32> {
self.cloud_only_directories_limit
}
/// <p>The current number of cloud directories in the Region.</p>
pub fn cloud_only_directories_current_count(&self) -> std::option::Option<i32> {
self.cloud_only_directories_current_count
}
/// <p>Indicates if the cloud directory limit has been reached.</p>
pub fn cloud_only_directories_limit_reached(&self) -> bool {
self.cloud_only_directories_limit_reached
}
/// <p>The maximum number of Managed Microsoft AD directories allowed in the region.</p>
pub fn cloud_only_microsoft_ad_limit(&self) -> std::option::Option<i32> {
self.cloud_only_microsoft_ad_limit
}
/// <p>The current number of Managed Microsoft AD directories in the region.</p>
pub fn cloud_only_microsoft_ad_current_count(&self) -> std::option::Option<i32> {
self.cloud_only_microsoft_ad_current_count
}
/// <p>Indicates if the Managed Microsoft AD directory limit has been reached.</p>
pub fn cloud_only_microsoft_ad_limit_reached(&self) -> bool {
self.cloud_only_microsoft_ad_limit_reached
}
/// <p>The maximum number of connected directories allowed in the Region.</p>
pub fn connected_directories_limit(&self) -> std::option::Option<i32> {
self.connected_directories_limit
}
/// <p>The current number of connected directories in the Region.</p>
pub fn connected_directories_current_count(&self) -> std::option::Option<i32> {
self.connected_directories_current_count
}
/// <p>Indicates if the connected directory limit has been reached.</p>
pub fn connected_directories_limit_reached(&self) -> bool {
self.connected_directories_limit_reached
}
}
impl std::fmt::Debug for DirectoryLimits {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DirectoryLimits");
formatter.field(
"cloud_only_directories_limit",
&self.cloud_only_directories_limit,
);
formatter.field(
"cloud_only_directories_current_count",
&self.cloud_only_directories_current_count,
);
formatter.field(
"cloud_only_directories_limit_reached",
&self.cloud_only_directories_limit_reached,
);
formatter.field(
"cloud_only_microsoft_ad_limit",
&self.cloud_only_microsoft_ad_limit,
);
formatter.field(
"cloud_only_microsoft_ad_current_count",
&self.cloud_only_microsoft_ad_current_count,
);
formatter.field(
"cloud_only_microsoft_ad_limit_reached",
&self.cloud_only_microsoft_ad_limit_reached,
);
formatter.field(
"connected_directories_limit",
&self.connected_directories_limit,
);
formatter.field(
"connected_directories_current_count",
&self.connected_directories_current_count,
);
formatter.field(
"connected_directories_limit_reached",
&self.connected_directories_limit_reached,
);
formatter.finish()
}
}
/// See [`DirectoryLimits`](crate::model::DirectoryLimits)
pub mod directory_limits {
/// A builder for [`DirectoryLimits`](crate::model::DirectoryLimits)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) cloud_only_directories_limit: std::option::Option<i32>,
pub(crate) cloud_only_directories_current_count: std::option::Option<i32>,
pub(crate) cloud_only_directories_limit_reached: std::option::Option<bool>,
pub(crate) cloud_only_microsoft_ad_limit: std::option::Option<i32>,
pub(crate) cloud_only_microsoft_ad_current_count: std::option::Option<i32>,
pub(crate) cloud_only_microsoft_ad_limit_reached: std::option::Option<bool>,
pub(crate) connected_directories_limit: std::option::Option<i32>,
pub(crate) connected_directories_current_count: std::option::Option<i32>,
pub(crate) connected_directories_limit_reached: std::option::Option<bool>,
}
impl Builder {
/// <p>The maximum number of cloud directories allowed in the Region.</p>
pub fn cloud_only_directories_limit(mut self, input: i32) -> Self {
self.cloud_only_directories_limit = Some(input);
self
}
/// <p>The maximum number of cloud directories allowed in the Region.</p>
pub fn set_cloud_only_directories_limit(mut self, input: std::option::Option<i32>) -> Self {
self.cloud_only_directories_limit = input;
self
}
/// <p>The current number of cloud directories in the Region.</p>
pub fn cloud_only_directories_current_count(mut self, input: i32) -> Self {
self.cloud_only_directories_current_count = Some(input);
self
}
/// <p>The current number of cloud directories in the Region.</p>
pub fn set_cloud_only_directories_current_count(
mut self,
input: std::option::Option<i32>,
) -> Self {
self.cloud_only_directories_current_count = input;
self
}
/// <p>Indicates if the cloud directory limit has been reached.</p>
pub fn cloud_only_directories_limit_reached(mut self, input: bool) -> Self {
self.cloud_only_directories_limit_reached = Some(input);
self
}
/// <p>Indicates if the cloud directory limit has been reached.</p>
pub fn set_cloud_only_directories_limit_reached(
mut self,
input: std::option::Option<bool>,
) -> Self {
self.cloud_only_directories_limit_reached = input;
self
}
/// <p>The maximum number of Managed Microsoft AD directories allowed in the region.</p>
pub fn cloud_only_microsoft_ad_limit(mut self, input: i32) -> Self {
self.cloud_only_microsoft_ad_limit = Some(input);
self
}
/// <p>The maximum number of Managed Microsoft AD directories allowed in the region.</p>
pub fn set_cloud_only_microsoft_ad_limit(
mut self,
input: std::option::Option<i32>,
) -> Self {
self.cloud_only_microsoft_ad_limit = input;
self
}
/// <p>The current number of Managed Microsoft AD directories in the region.</p>
pub fn cloud_only_microsoft_ad_current_count(mut self, input: i32) -> Self {
self.cloud_only_microsoft_ad_current_count = Some(input);
self
}
/// <p>The current number of Managed Microsoft AD directories in the region.</p>
pub fn set_cloud_only_microsoft_ad_current_count(
mut self,
input: std::option::Option<i32>,
) -> Self {
self.cloud_only_microsoft_ad_current_count = input;
self
}
/// <p>Indicates if the Managed Microsoft AD directory limit has been reached.</p>
pub fn cloud_only_microsoft_ad_limit_reached(mut self, input: bool) -> Self {
self.cloud_only_microsoft_ad_limit_reached = Some(input);
self
}
/// <p>Indicates if the Managed Microsoft AD directory limit has been reached.</p>
pub fn set_cloud_only_microsoft_ad_limit_reached(
mut self,
input: std::option::Option<bool>,
) -> Self {
self.cloud_only_microsoft_ad_limit_reached = input;
self
}
/// <p>The maximum number of connected directories allowed in the Region.</p>
pub fn connected_directories_limit(mut self, input: i32) -> Self {
self.connected_directories_limit = Some(input);
self
}
/// <p>The maximum number of connected directories allowed in the Region.</p>
pub fn set_connected_directories_limit(mut self, input: std::option::Option<i32>) -> Self {
self.connected_directories_limit = input;
self
}
/// <p>The current number of connected directories in the Region.</p>
pub fn connected_directories_current_count(mut self, input: i32) -> Self {
self.connected_directories_current_count = Some(input);
self
}
/// <p>The current number of connected directories in the Region.</p>
pub fn set_connected_directories_current_count(
mut self,
input: std::option::Option<i32>,
) -> Self {
self.connected_directories_current_count = input;
self
}
/// <p>Indicates if the connected directory limit has been reached.</p>
pub fn connected_directories_limit_reached(mut self, input: bool) -> Self {
self.connected_directories_limit_reached = Some(input);
self
}
/// <p>Indicates if the connected directory limit has been reached.</p>
pub fn set_connected_directories_limit_reached(
mut self,
input: std::option::Option<bool>,
) -> Self {
self.connected_directories_limit_reached = input;
self
}
/// Consumes the builder and constructs a [`DirectoryLimits`](crate::model::DirectoryLimits)
pub fn build(self) -> crate::model::DirectoryLimits {
crate::model::DirectoryLimits {
cloud_only_directories_limit: self.cloud_only_directories_limit,
cloud_only_directories_current_count: self.cloud_only_directories_current_count,
cloud_only_directories_limit_reached: self
.cloud_only_directories_limit_reached
.unwrap_or_default(),
cloud_only_microsoft_ad_limit: self.cloud_only_microsoft_ad_limit,
cloud_only_microsoft_ad_current_count: self.cloud_only_microsoft_ad_current_count,
cloud_only_microsoft_ad_limit_reached: self
.cloud_only_microsoft_ad_limit_reached
.unwrap_or_default(),
connected_directories_limit: self.connected_directories_limit,
connected_directories_current_count: self.connected_directories_current_count,
connected_directories_limit_reached: self
.connected_directories_limit_reached
.unwrap_or_default(),
}
}
}
}
impl DirectoryLimits {
/// Creates a new builder-style object to manufacture [`DirectoryLimits`](crate::model::DirectoryLimits)
pub fn builder() -> crate::model::directory_limits::Builder {
crate::model::directory_limits::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum LdapsType {
#[allow(missing_docs)] // documentation missing in model
Client,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for LdapsType {
fn from(s: &str) -> Self {
match s {
"Client" => LdapsType::Client,
other => LdapsType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for LdapsType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(LdapsType::from(s))
}
}
impl LdapsType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
LdapsType::Client => "Client",
LdapsType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["Client"]
}
}
impl AsRef<str> for LdapsType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ClientAuthenticationType {
#[allow(missing_docs)] // documentation missing in model
SmartCard,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ClientAuthenticationType {
fn from(s: &str) -> Self {
match s {
"SmartCard" => ClientAuthenticationType::SmartCard,
other => ClientAuthenticationType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ClientAuthenticationType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ClientAuthenticationType::from(s))
}
}
impl ClientAuthenticationType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ClientAuthenticationType::SmartCard => "SmartCard",
ClientAuthenticationType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["SmartCard"]
}
}
impl AsRef<str> for ClientAuthenticationType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Describes a trust relationship between an Managed Microsoft AD directory and an external domain.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct Trust {
/// <p>The Directory ID of the Amazon Web Services directory involved in the trust relationship.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The unique ID of the trust relationship.</p>
pub trust_id: std::option::Option<std::string::String>,
/// <p>The Fully Qualified Domain Name (FQDN) of the external domain involved in the trust relationship.</p>
pub remote_domain_name: std::option::Option<std::string::String>,
/// <p>The trust relationship type. <code>Forest</code> is the default.</p>
pub trust_type: std::option::Option<crate::model::TrustType>,
/// <p>The trust relationship direction.</p>
pub trust_direction: std::option::Option<crate::model::TrustDirection>,
/// <p>The trust relationship state.</p>
pub trust_state: std::option::Option<crate::model::TrustState>,
/// <p>The date and time that the trust relationship was created.</p>
pub created_date_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The date and time that the trust relationship was last updated.</p>
pub last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The date and time that the TrustState was last updated.</p>
pub state_last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The reason for the TrustState.</p>
pub trust_state_reason: std::option::Option<std::string::String>,
/// <p>Current state of selective authentication for the trust.</p>
pub selective_auth: std::option::Option<crate::model::SelectiveAuth>,
}
impl Trust {
/// <p>The Directory ID of the Amazon Web Services directory involved in the trust relationship.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The unique ID of the trust relationship.</p>
pub fn trust_id(&self) -> std::option::Option<&str> {
self.trust_id.as_deref()
}
/// <p>The Fully Qualified Domain Name (FQDN) of the external domain involved in the trust relationship.</p>
pub fn remote_domain_name(&self) -> std::option::Option<&str> {
self.remote_domain_name.as_deref()
}
/// <p>The trust relationship type. <code>Forest</code> is the default.</p>
pub fn trust_type(&self) -> std::option::Option<&crate::model::TrustType> {
self.trust_type.as_ref()
}
/// <p>The trust relationship direction.</p>
pub fn trust_direction(&self) -> std::option::Option<&crate::model::TrustDirection> {
self.trust_direction.as_ref()
}
/// <p>The trust relationship state.</p>
pub fn trust_state(&self) -> std::option::Option<&crate::model::TrustState> {
self.trust_state.as_ref()
}
/// <p>The date and time that the trust relationship was created.</p>
pub fn created_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.created_date_time.as_ref()
}
/// <p>The date and time that the trust relationship was last updated.</p>
pub fn last_updated_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.last_updated_date_time.as_ref()
}
/// <p>The date and time that the TrustState was last updated.</p>
pub fn state_last_updated_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.state_last_updated_date_time.as_ref()
}
/// <p>The reason for the TrustState.</p>
pub fn trust_state_reason(&self) -> std::option::Option<&str> {
self.trust_state_reason.as_deref()
}
/// <p>Current state of selective authentication for the trust.</p>
pub fn selective_auth(&self) -> std::option::Option<&crate::model::SelectiveAuth> {
self.selective_auth.as_ref()
}
}
impl std::fmt::Debug for Trust {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("Trust");
formatter.field("directory_id", &self.directory_id);
formatter.field("trust_id", &self.trust_id);
formatter.field("remote_domain_name", &self.remote_domain_name);
formatter.field("trust_type", &self.trust_type);
formatter.field("trust_direction", &self.trust_direction);
formatter.field("trust_state", &self.trust_state);
formatter.field("created_date_time", &self.created_date_time);
formatter.field("last_updated_date_time", &self.last_updated_date_time);
formatter.field(
"state_last_updated_date_time",
&self.state_last_updated_date_time,
);
formatter.field("trust_state_reason", &self.trust_state_reason);
formatter.field("selective_auth", &self.selective_auth);
formatter.finish()
}
}
/// See [`Trust`](crate::model::Trust)
pub mod trust {
/// A builder for [`Trust`](crate::model::Trust)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) trust_id: std::option::Option<std::string::String>,
pub(crate) remote_domain_name: std::option::Option<std::string::String>,
pub(crate) trust_type: std::option::Option<crate::model::TrustType>,
pub(crate) trust_direction: std::option::Option<crate::model::TrustDirection>,
pub(crate) trust_state: std::option::Option<crate::model::TrustState>,
pub(crate) created_date_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) state_last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) trust_state_reason: std::option::Option<std::string::String>,
pub(crate) selective_auth: std::option::Option<crate::model::SelectiveAuth>,
}
impl Builder {
/// <p>The Directory ID of the Amazon Web Services directory involved in the trust relationship.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The Directory ID of the Amazon Web Services directory involved in the trust relationship.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The unique ID of the trust relationship.</p>
pub fn trust_id(mut self, input: impl Into<std::string::String>) -> Self {
self.trust_id = Some(input.into());
self
}
/// <p>The unique ID of the trust relationship.</p>
pub fn set_trust_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.trust_id = input;
self
}
/// <p>The Fully Qualified Domain Name (FQDN) of the external domain involved in the trust relationship.</p>
pub fn remote_domain_name(mut self, input: impl Into<std::string::String>) -> Self {
self.remote_domain_name = Some(input.into());
self
}
/// <p>The Fully Qualified Domain Name (FQDN) of the external domain involved in the trust relationship.</p>
pub fn set_remote_domain_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.remote_domain_name = input;
self
}
/// <p>The trust relationship type. <code>Forest</code> is the default.</p>
pub fn trust_type(mut self, input: crate::model::TrustType) -> Self {
self.trust_type = Some(input);
self
}
/// <p>The trust relationship type. <code>Forest</code> is the default.</p>
pub fn set_trust_type(
mut self,
input: std::option::Option<crate::model::TrustType>,
) -> Self {
self.trust_type = input;
self
}
/// <p>The trust relationship direction.</p>
pub fn trust_direction(mut self, input: crate::model::TrustDirection) -> Self {
self.trust_direction = Some(input);
self
}
/// <p>The trust relationship direction.</p>
pub fn set_trust_direction(
mut self,
input: std::option::Option<crate::model::TrustDirection>,
) -> Self {
self.trust_direction = input;
self
}
/// <p>The trust relationship state.</p>
pub fn trust_state(mut self, input: crate::model::TrustState) -> Self {
self.trust_state = Some(input);
self
}
/// <p>The trust relationship state.</p>
pub fn set_trust_state(
mut self,
input: std::option::Option<crate::model::TrustState>,
) -> Self {
self.trust_state = input;
self
}
/// <p>The date and time that the trust relationship was created.</p>
pub fn created_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.created_date_time = Some(input);
self
}
/// <p>The date and time that the trust relationship was created.</p>
pub fn set_created_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.created_date_time = input;
self
}
/// <p>The date and time that the trust relationship was last updated.</p>
pub fn last_updated_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.last_updated_date_time = Some(input);
self
}
/// <p>The date and time that the trust relationship was last updated.</p>
pub fn set_last_updated_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.last_updated_date_time = input;
self
}
/// <p>The date and time that the TrustState was last updated.</p>
pub fn state_last_updated_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.state_last_updated_date_time = Some(input);
self
}
/// <p>The date and time that the TrustState was last updated.</p>
pub fn set_state_last_updated_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.state_last_updated_date_time = input;
self
}
/// <p>The reason for the TrustState.</p>
pub fn trust_state_reason(mut self, input: impl Into<std::string::String>) -> Self {
self.trust_state_reason = Some(input.into());
self
}
/// <p>The reason for the TrustState.</p>
pub fn set_trust_state_reason(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.trust_state_reason = input;
self
}
/// <p>Current state of selective authentication for the trust.</p>
pub fn selective_auth(mut self, input: crate::model::SelectiveAuth) -> Self {
self.selective_auth = Some(input);
self
}
/// <p>Current state of selective authentication for the trust.</p>
pub fn set_selective_auth(
mut self,
input: std::option::Option<crate::model::SelectiveAuth>,
) -> Self {
self.selective_auth = input;
self
}
/// Consumes the builder and constructs a [`Trust`](crate::model::Trust)
pub fn build(self) -> crate::model::Trust {
crate::model::Trust {
directory_id: self.directory_id,
trust_id: self.trust_id,
remote_domain_name: self.remote_domain_name,
trust_type: self.trust_type,
trust_direction: self.trust_direction,
trust_state: self.trust_state,
created_date_time: self.created_date_time,
last_updated_date_time: self.last_updated_date_time,
state_last_updated_date_time: self.state_last_updated_date_time,
trust_state_reason: self.trust_state_reason,
selective_auth: self.selective_auth,
}
}
}
}
impl Trust {
/// Creates a new builder-style object to manufacture [`Trust`](crate::model::Trust)
pub fn builder() -> crate::model::trust::Builder {
crate::model::trust::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum TrustState {
#[allow(missing_docs)] // documentation missing in model
Created,
#[allow(missing_docs)] // documentation missing in model
Creating,
#[allow(missing_docs)] // documentation missing in model
Deleted,
#[allow(missing_docs)] // documentation missing in model
Deleting,
#[allow(missing_docs)] // documentation missing in model
Failed,
#[allow(missing_docs)] // documentation missing in model
UpdateFailed,
#[allow(missing_docs)] // documentation missing in model
Updated,
#[allow(missing_docs)] // documentation missing in model
Updating,
#[allow(missing_docs)] // documentation missing in model
Verified,
#[allow(missing_docs)] // documentation missing in model
VerifyFailed,
#[allow(missing_docs)] // documentation missing in model
Verifying,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for TrustState {
fn from(s: &str) -> Self {
match s {
"Created" => TrustState::Created,
"Creating" => TrustState::Creating,
"Deleted" => TrustState::Deleted,
"Deleting" => TrustState::Deleting,
"Failed" => TrustState::Failed,
"UpdateFailed" => TrustState::UpdateFailed,
"Updated" => TrustState::Updated,
"Updating" => TrustState::Updating,
"Verified" => TrustState::Verified,
"VerifyFailed" => TrustState::VerifyFailed,
"Verifying" => TrustState::Verifying,
other => TrustState::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for TrustState {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(TrustState::from(s))
}
}
impl TrustState {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
TrustState::Created => "Created",
TrustState::Creating => "Creating",
TrustState::Deleted => "Deleted",
TrustState::Deleting => "Deleting",
TrustState::Failed => "Failed",
TrustState::UpdateFailed => "UpdateFailed",
TrustState::Updated => "Updated",
TrustState::Updating => "Updating",
TrustState::Verified => "Verified",
TrustState::VerifyFailed => "VerifyFailed",
TrustState::Verifying => "Verifying",
TrustState::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"Created",
"Creating",
"Deleted",
"Deleting",
"Failed",
"UpdateFailed",
"Updated",
"Updating",
"Verified",
"VerifyFailed",
"Verifying",
]
}
}
impl AsRef<str> for TrustState {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum TrustDirection {
#[allow(missing_docs)] // documentation missing in model
OneWayIncoming,
#[allow(missing_docs)] // documentation missing in model
OneWayOutgoing,
#[allow(missing_docs)] // documentation missing in model
TwoWay,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for TrustDirection {
fn from(s: &str) -> Self {
match s {
"One-Way: Incoming" => TrustDirection::OneWayIncoming,
"One-Way: Outgoing" => TrustDirection::OneWayOutgoing,
"Two-Way" => TrustDirection::TwoWay,
other => TrustDirection::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for TrustDirection {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(TrustDirection::from(s))
}
}
impl TrustDirection {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
TrustDirection::OneWayIncoming => "One-Way: Incoming",
TrustDirection::OneWayOutgoing => "One-Way: Outgoing",
TrustDirection::TwoWay => "Two-Way",
TrustDirection::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["One-Way: Incoming", "One-Way: Outgoing", "Two-Way"]
}
}
impl AsRef<str> for TrustDirection {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum TrustType {
#[allow(missing_docs)] // documentation missing in model
External,
#[allow(missing_docs)] // documentation missing in model
Forest,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for TrustType {
fn from(s: &str) -> Self {
match s {
"External" => TrustType::External,
"Forest" => TrustType::Forest,
other => TrustType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for TrustType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(TrustType::from(s))
}
}
impl TrustType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
TrustType::External => "External",
TrustType::Forest => "Forest",
TrustType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["External", "Forest"]
}
}
impl AsRef<str> for TrustType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Describes a directory snapshot.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct Snapshot {
/// <p>The directory identifier.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The snapshot identifier.</p>
pub snapshot_id: std::option::Option<std::string::String>,
/// <p>The snapshot type.</p>
pub r#type: std::option::Option<crate::model::SnapshotType>,
/// <p>The descriptive name of the snapshot.</p>
pub name: std::option::Option<std::string::String>,
/// <p>The snapshot status.</p>
pub status: std::option::Option<crate::model::SnapshotStatus>,
/// <p>The date and time that the snapshot was taken.</p>
pub start_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl Snapshot {
/// <p>The directory identifier.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The snapshot identifier.</p>
pub fn snapshot_id(&self) -> std::option::Option<&str> {
self.snapshot_id.as_deref()
}
/// <p>The snapshot type.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::SnapshotType> {
self.r#type.as_ref()
}
/// <p>The descriptive name of the snapshot.</p>
pub fn name(&self) -> std::option::Option<&str> {
self.name.as_deref()
}
/// <p>The snapshot status.</p>
pub fn status(&self) -> std::option::Option<&crate::model::SnapshotStatus> {
self.status.as_ref()
}
/// <p>The date and time that the snapshot was taken.</p>
pub fn start_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.start_time.as_ref()
}
}
impl std::fmt::Debug for Snapshot {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("Snapshot");
formatter.field("directory_id", &self.directory_id);
formatter.field("snapshot_id", &self.snapshot_id);
formatter.field("r#type", &self.r#type);
formatter.field("name", &self.name);
formatter.field("status", &self.status);
formatter.field("start_time", &self.start_time);
formatter.finish()
}
}
/// See [`Snapshot`](crate::model::Snapshot)
pub mod snapshot {
/// A builder for [`Snapshot`](crate::model::Snapshot)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) snapshot_id: std::option::Option<std::string::String>,
pub(crate) r#type: std::option::Option<crate::model::SnapshotType>,
pub(crate) name: std::option::Option<std::string::String>,
pub(crate) status: std::option::Option<crate::model::SnapshotStatus>,
pub(crate) start_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl Builder {
/// <p>The directory identifier.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The directory identifier.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The snapshot identifier.</p>
pub fn snapshot_id(mut self, input: impl Into<std::string::String>) -> Self {
self.snapshot_id = Some(input.into());
self
}
/// <p>The snapshot identifier.</p>
pub fn set_snapshot_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.snapshot_id = input;
self
}
/// <p>The snapshot type.</p>
pub fn r#type(mut self, input: crate::model::SnapshotType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The snapshot type.</p>
pub fn set_type(mut self, input: std::option::Option<crate::model::SnapshotType>) -> Self {
self.r#type = input;
self
}
/// <p>The descriptive name of the snapshot.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.name = Some(input.into());
self
}
/// <p>The descriptive name of the snapshot.</p>
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.name = input;
self
}
/// <p>The snapshot status.</p>
pub fn status(mut self, input: crate::model::SnapshotStatus) -> Self {
self.status = Some(input);
self
}
/// <p>The snapshot status.</p>
pub fn set_status(
mut self,
input: std::option::Option<crate::model::SnapshotStatus>,
) -> Self {
self.status = input;
self
}
/// <p>The date and time that the snapshot was taken.</p>
pub fn start_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.start_time = Some(input);
self
}
/// <p>The date and time that the snapshot was taken.</p>
pub fn set_start_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.start_time = input;
self
}
/// Consumes the builder and constructs a [`Snapshot`](crate::model::Snapshot)
pub fn build(self) -> crate::model::Snapshot {
crate::model::Snapshot {
directory_id: self.directory_id,
snapshot_id: self.snapshot_id,
r#type: self.r#type,
name: self.name,
status: self.status,
start_time: self.start_time,
}
}
}
}
impl Snapshot {
/// Creates a new builder-style object to manufacture [`Snapshot`](crate::model::Snapshot)
pub fn builder() -> crate::model::snapshot::Builder {
crate::model::snapshot::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum SnapshotStatus {
#[allow(missing_docs)] // documentation missing in model
Completed,
#[allow(missing_docs)] // documentation missing in model
Creating,
#[allow(missing_docs)] // documentation missing in model
Failed,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for SnapshotStatus {
fn from(s: &str) -> Self {
match s {
"Completed" => SnapshotStatus::Completed,
"Creating" => SnapshotStatus::Creating,
"Failed" => SnapshotStatus::Failed,
other => SnapshotStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for SnapshotStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(SnapshotStatus::from(s))
}
}
impl SnapshotStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
SnapshotStatus::Completed => "Completed",
SnapshotStatus::Creating => "Creating",
SnapshotStatus::Failed => "Failed",
SnapshotStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["Completed", "Creating", "Failed"]
}
}
impl AsRef<str> for SnapshotStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum SnapshotType {
#[allow(missing_docs)] // documentation missing in model
Auto,
#[allow(missing_docs)] // documentation missing in model
Manual,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for SnapshotType {
fn from(s: &str) -> Self {
match s {
"Auto" => SnapshotType::Auto,
"Manual" => SnapshotType::Manual,
other => SnapshotType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for SnapshotType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(SnapshotType::from(s))
}
}
impl SnapshotType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
SnapshotType::Auto => "Auto",
SnapshotType::Manual => "Manual",
SnapshotType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["Auto", "Manual"]
}
}
impl AsRef<str> for SnapshotType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Details about the shared directory in the directory owner account for which the share request in the directory consumer account has been accepted.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct SharedDirectory {
/// <p>Identifier of the directory owner account, which contains the directory that has been shared to the consumer account.</p>
pub owner_account_id: std::option::Option<std::string::String>,
/// <p>Identifier of the directory in the directory owner account. </p>
pub owner_directory_id: std::option::Option<std::string::String>,
/// <p>The method used when sharing a directory to determine whether the directory should be shared within your Amazon Web Services organization (<code>ORGANIZATIONS</code>) or with any Amazon Web Services account by sending a shared directory request (<code>HANDSHAKE</code>).</p>
pub share_method: std::option::Option<crate::model::ShareMethod>,
/// <p>Identifier of the directory consumer account that has access to the shared directory (<code>OwnerDirectoryId</code>) in the directory owner account.</p>
pub shared_account_id: std::option::Option<std::string::String>,
/// <p>Identifier of the shared directory in the directory consumer account. This identifier is different for each directory owner account.</p>
pub shared_directory_id: std::option::Option<std::string::String>,
/// <p>Current directory status of the shared Managed Microsoft AD directory.</p>
pub share_status: std::option::Option<crate::model::ShareStatus>,
/// <p>A directory share request that is sent by the directory owner to the directory consumer. The request includes a typed message to help the directory consumer administrator determine whether to approve or reject the share invitation.</p>
pub share_notes: std::option::Option<std::string::String>,
/// <p>The date and time that the shared directory was created.</p>
pub created_date_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The date and time that the shared directory was last updated.</p>
pub last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl SharedDirectory {
/// <p>Identifier of the directory owner account, which contains the directory that has been shared to the consumer account.</p>
pub fn owner_account_id(&self) -> std::option::Option<&str> {
self.owner_account_id.as_deref()
}
/// <p>Identifier of the directory in the directory owner account. </p>
pub fn owner_directory_id(&self) -> std::option::Option<&str> {
self.owner_directory_id.as_deref()
}
/// <p>The method used when sharing a directory to determine whether the directory should be shared within your Amazon Web Services organization (<code>ORGANIZATIONS</code>) or with any Amazon Web Services account by sending a shared directory request (<code>HANDSHAKE</code>).</p>
pub fn share_method(&self) -> std::option::Option<&crate::model::ShareMethod> {
self.share_method.as_ref()
}
/// <p>Identifier of the directory consumer account that has access to the shared directory (<code>OwnerDirectoryId</code>) in the directory owner account.</p>
pub fn shared_account_id(&self) -> std::option::Option<&str> {
self.shared_account_id.as_deref()
}
/// <p>Identifier of the shared directory in the directory consumer account. This identifier is different for each directory owner account.</p>
pub fn shared_directory_id(&self) -> std::option::Option<&str> {
self.shared_directory_id.as_deref()
}
/// <p>Current directory status of the shared Managed Microsoft AD directory.</p>
pub fn share_status(&self) -> std::option::Option<&crate::model::ShareStatus> {
self.share_status.as_ref()
}
/// <p>A directory share request that is sent by the directory owner to the directory consumer. The request includes a typed message to help the directory consumer administrator determine whether to approve or reject the share invitation.</p>
pub fn share_notes(&self) -> std::option::Option<&str> {
self.share_notes.as_deref()
}
/// <p>The date and time that the shared directory was created.</p>
pub fn created_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.created_date_time.as_ref()
}
/// <p>The date and time that the shared directory was last updated.</p>
pub fn last_updated_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.last_updated_date_time.as_ref()
}
}
impl std::fmt::Debug for SharedDirectory {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("SharedDirectory");
formatter.field("owner_account_id", &self.owner_account_id);
formatter.field("owner_directory_id", &self.owner_directory_id);
formatter.field("share_method", &self.share_method);
formatter.field("shared_account_id", &self.shared_account_id);
formatter.field("shared_directory_id", &self.shared_directory_id);
formatter.field("share_status", &self.share_status);
formatter.field("share_notes", &"*** Sensitive Data Redacted ***");
formatter.field("created_date_time", &self.created_date_time);
formatter.field("last_updated_date_time", &self.last_updated_date_time);
formatter.finish()
}
}
/// See [`SharedDirectory`](crate::model::SharedDirectory)
pub mod shared_directory {
/// A builder for [`SharedDirectory`](crate::model::SharedDirectory)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) owner_account_id: std::option::Option<std::string::String>,
pub(crate) owner_directory_id: std::option::Option<std::string::String>,
pub(crate) share_method: std::option::Option<crate::model::ShareMethod>,
pub(crate) shared_account_id: std::option::Option<std::string::String>,
pub(crate) shared_directory_id: std::option::Option<std::string::String>,
pub(crate) share_status: std::option::Option<crate::model::ShareStatus>,
pub(crate) share_notes: std::option::Option<std::string::String>,
pub(crate) created_date_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl Builder {
/// <p>Identifier of the directory owner account, which contains the directory that has been shared to the consumer account.</p>
pub fn owner_account_id(mut self, input: impl Into<std::string::String>) -> Self {
self.owner_account_id = Some(input.into());
self
}
/// <p>Identifier of the directory owner account, which contains the directory that has been shared to the consumer account.</p>
pub fn set_owner_account_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.owner_account_id = input;
self
}
/// <p>Identifier of the directory in the directory owner account. </p>
pub fn owner_directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.owner_directory_id = Some(input.into());
self
}
/// <p>Identifier of the directory in the directory owner account. </p>
pub fn set_owner_directory_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.owner_directory_id = input;
self
}
/// <p>The method used when sharing a directory to determine whether the directory should be shared within your Amazon Web Services organization (<code>ORGANIZATIONS</code>) or with any Amazon Web Services account by sending a shared directory request (<code>HANDSHAKE</code>).</p>
pub fn share_method(mut self, input: crate::model::ShareMethod) -> Self {
self.share_method = Some(input);
self
}
/// <p>The method used when sharing a directory to determine whether the directory should be shared within your Amazon Web Services organization (<code>ORGANIZATIONS</code>) or with any Amazon Web Services account by sending a shared directory request (<code>HANDSHAKE</code>).</p>
pub fn set_share_method(
mut self,
input: std::option::Option<crate::model::ShareMethod>,
) -> Self {
self.share_method = input;
self
}
/// <p>Identifier of the directory consumer account that has access to the shared directory (<code>OwnerDirectoryId</code>) in the directory owner account.</p>
pub fn shared_account_id(mut self, input: impl Into<std::string::String>) -> Self {
self.shared_account_id = Some(input.into());
self
}
/// <p>Identifier of the directory consumer account that has access to the shared directory (<code>OwnerDirectoryId</code>) in the directory owner account.</p>
pub fn set_shared_account_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.shared_account_id = input;
self
}
/// <p>Identifier of the shared directory in the directory consumer account. This identifier is different for each directory owner account.</p>
pub fn shared_directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.shared_directory_id = Some(input.into());
self
}
/// <p>Identifier of the shared directory in the directory consumer account. This identifier is different for each directory owner account.</p>
pub fn set_shared_directory_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.shared_directory_id = input;
self
}
/// <p>Current directory status of the shared Managed Microsoft AD directory.</p>
pub fn share_status(mut self, input: crate::model::ShareStatus) -> Self {
self.share_status = Some(input);
self
}
/// <p>Current directory status of the shared Managed Microsoft AD directory.</p>
pub fn set_share_status(
mut self,
input: std::option::Option<crate::model::ShareStatus>,
) -> Self {
self.share_status = input;
self
}
/// <p>A directory share request that is sent by the directory owner to the directory consumer. The request includes a typed message to help the directory consumer administrator determine whether to approve or reject the share invitation.</p>
pub fn share_notes(mut self, input: impl Into<std::string::String>) -> Self {
self.share_notes = Some(input.into());
self
}
/// <p>A directory share request that is sent by the directory owner to the directory consumer. The request includes a typed message to help the directory consumer administrator determine whether to approve or reject the share invitation.</p>
pub fn set_share_notes(mut self, input: std::option::Option<std::string::String>) -> Self {
self.share_notes = input;
self
}
/// <p>The date and time that the shared directory was created.</p>
pub fn created_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.created_date_time = Some(input);
self
}
/// <p>The date and time that the shared directory was created.</p>
pub fn set_created_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.created_date_time = input;
self
}
/// <p>The date and time that the shared directory was last updated.</p>
pub fn last_updated_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.last_updated_date_time = Some(input);
self
}
/// <p>The date and time that the shared directory was last updated.</p>
pub fn set_last_updated_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.last_updated_date_time = input;
self
}
/// Consumes the builder and constructs a [`SharedDirectory`](crate::model::SharedDirectory)
pub fn build(self) -> crate::model::SharedDirectory {
crate::model::SharedDirectory {
owner_account_id: self.owner_account_id,
owner_directory_id: self.owner_directory_id,
share_method: self.share_method,
shared_account_id: self.shared_account_id,
shared_directory_id: self.shared_directory_id,
share_status: self.share_status,
share_notes: self.share_notes,
created_date_time: self.created_date_time,
last_updated_date_time: self.last_updated_date_time,
}
}
}
}
impl SharedDirectory {
/// Creates a new builder-style object to manufacture [`SharedDirectory`](crate::model::SharedDirectory)
pub fn builder() -> crate::model::shared_directory::Builder {
crate::model::shared_directory::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ShareStatus {
#[allow(missing_docs)] // documentation missing in model
Deleted,
#[allow(missing_docs)] // documentation missing in model
Deleting,
#[allow(missing_docs)] // documentation missing in model
PendingAcceptance,
#[allow(missing_docs)] // documentation missing in model
RejectFailed,
#[allow(missing_docs)] // documentation missing in model
Rejected,
#[allow(missing_docs)] // documentation missing in model
Rejecting,
#[allow(missing_docs)] // documentation missing in model
ShareFailed,
#[allow(missing_docs)] // documentation missing in model
Shared,
#[allow(missing_docs)] // documentation missing in model
Sharing,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ShareStatus {
fn from(s: &str) -> Self {
match s {
"Deleted" => ShareStatus::Deleted,
"Deleting" => ShareStatus::Deleting,
"PendingAcceptance" => ShareStatus::PendingAcceptance,
"RejectFailed" => ShareStatus::RejectFailed,
"Rejected" => ShareStatus::Rejected,
"Rejecting" => ShareStatus::Rejecting,
"ShareFailed" => ShareStatus::ShareFailed,
"Shared" => ShareStatus::Shared,
"Sharing" => ShareStatus::Sharing,
other => ShareStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ShareStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ShareStatus::from(s))
}
}
impl ShareStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ShareStatus::Deleted => "Deleted",
ShareStatus::Deleting => "Deleting",
ShareStatus::PendingAcceptance => "PendingAcceptance",
ShareStatus::RejectFailed => "RejectFailed",
ShareStatus::Rejected => "Rejected",
ShareStatus::Rejecting => "Rejecting",
ShareStatus::ShareFailed => "ShareFailed",
ShareStatus::Shared => "Shared",
ShareStatus::Sharing => "Sharing",
ShareStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"Deleted",
"Deleting",
"PendingAcceptance",
"RejectFailed",
"Rejected",
"Rejecting",
"ShareFailed",
"Shared",
"Sharing",
]
}
}
impl AsRef<str> for ShareStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>The replicated Region information for a directory.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RegionDescription {
/// <p>The identifier of the directory.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The name of the Region. For example, <code>us-east-1</code>.</p>
pub region_name: std::option::Option<std::string::String>,
/// <p>Specifies whether the Region is the primary Region or an additional Region.</p>
pub region_type: std::option::Option<crate::model::RegionType>,
/// <p>The status of the replication process for the specified Region.</p>
pub status: std::option::Option<crate::model::DirectoryStage>,
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
pub vpc_settings: std::option::Option<crate::model::DirectoryVpcSettings>,
/// <p>The desired number of domain controllers in the specified Region for the specified directory.</p>
pub desired_number_of_domain_controllers: i32,
/// <p>Specifies when the Region replication began.</p>
pub launch_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The date and time that the Region status was last updated.</p>
pub status_last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The date and time that the Region description was last updated.</p>
pub last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl RegionDescription {
/// <p>The identifier of the directory.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The name of the Region. For example, <code>us-east-1</code>.</p>
pub fn region_name(&self) -> std::option::Option<&str> {
self.region_name.as_deref()
}
/// <p>Specifies whether the Region is the primary Region or an additional Region.</p>
pub fn region_type(&self) -> std::option::Option<&crate::model::RegionType> {
self.region_type.as_ref()
}
/// <p>The status of the replication process for the specified Region.</p>
pub fn status(&self) -> std::option::Option<&crate::model::DirectoryStage> {
self.status.as_ref()
}
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
pub fn vpc_settings(&self) -> std::option::Option<&crate::model::DirectoryVpcSettings> {
self.vpc_settings.as_ref()
}
/// <p>The desired number of domain controllers in the specified Region for the specified directory.</p>
pub fn desired_number_of_domain_controllers(&self) -> i32 {
self.desired_number_of_domain_controllers
}
/// <p>Specifies when the Region replication began.</p>
pub fn launch_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.launch_time.as_ref()
}
/// <p>The date and time that the Region status was last updated.</p>
pub fn status_last_updated_date_time(
&self,
) -> std::option::Option<&aws_smithy_types::DateTime> {
self.status_last_updated_date_time.as_ref()
}
/// <p>The date and time that the Region description was last updated.</p>
pub fn last_updated_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.last_updated_date_time.as_ref()
}
}
impl std::fmt::Debug for RegionDescription {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RegionDescription");
formatter.field("directory_id", &self.directory_id);
formatter.field("region_name", &self.region_name);
formatter.field("region_type", &self.region_type);
formatter.field("status", &self.status);
formatter.field("vpc_settings", &self.vpc_settings);
formatter.field(
"desired_number_of_domain_controllers",
&self.desired_number_of_domain_controllers,
);
formatter.field("launch_time", &self.launch_time);
formatter.field(
"status_last_updated_date_time",
&self.status_last_updated_date_time,
);
formatter.field("last_updated_date_time", &self.last_updated_date_time);
formatter.finish()
}
}
/// See [`RegionDescription`](crate::model::RegionDescription)
pub mod region_description {
/// A builder for [`RegionDescription`](crate::model::RegionDescription)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) region_name: std::option::Option<std::string::String>,
pub(crate) region_type: std::option::Option<crate::model::RegionType>,
pub(crate) status: std::option::Option<crate::model::DirectoryStage>,
pub(crate) vpc_settings: std::option::Option<crate::model::DirectoryVpcSettings>,
pub(crate) desired_number_of_domain_controllers: std::option::Option<i32>,
pub(crate) launch_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) status_last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl Builder {
/// <p>The identifier of the directory.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The name of the Region. For example, <code>us-east-1</code>.</p>
pub fn region_name(mut self, input: impl Into<std::string::String>) -> Self {
self.region_name = Some(input.into());
self
}
/// <p>The name of the Region. For example, <code>us-east-1</code>.</p>
pub fn set_region_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.region_name = input;
self
}
/// <p>Specifies whether the Region is the primary Region or an additional Region.</p>
pub fn region_type(mut self, input: crate::model::RegionType) -> Self {
self.region_type = Some(input);
self
}
/// <p>Specifies whether the Region is the primary Region or an additional Region.</p>
pub fn set_region_type(
mut self,
input: std::option::Option<crate::model::RegionType>,
) -> Self {
self.region_type = input;
self
}
/// <p>The status of the replication process for the specified Region.</p>
pub fn status(mut self, input: crate::model::DirectoryStage) -> Self {
self.status = Some(input);
self
}
/// <p>The status of the replication process for the specified Region.</p>
pub fn set_status(
mut self,
input: std::option::Option<crate::model::DirectoryStage>,
) -> Self {
self.status = input;
self
}
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
pub fn vpc_settings(mut self, input: crate::model::DirectoryVpcSettings) -> Self {
self.vpc_settings = Some(input);
self
}
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
pub fn set_vpc_settings(
mut self,
input: std::option::Option<crate::model::DirectoryVpcSettings>,
) -> Self {
self.vpc_settings = input;
self
}
/// <p>The desired number of domain controllers in the specified Region for the specified directory.</p>
pub fn desired_number_of_domain_controllers(mut self, input: i32) -> Self {
self.desired_number_of_domain_controllers = Some(input);
self
}
/// <p>The desired number of domain controllers in the specified Region for the specified directory.</p>
pub fn set_desired_number_of_domain_controllers(
mut self,
input: std::option::Option<i32>,
) -> Self {
self.desired_number_of_domain_controllers = input;
self
}
/// <p>Specifies when the Region replication began.</p>
pub fn launch_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.launch_time = Some(input);
self
}
/// <p>Specifies when the Region replication began.</p>
pub fn set_launch_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.launch_time = input;
self
}
/// <p>The date and time that the Region status was last updated.</p>
pub fn status_last_updated_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.status_last_updated_date_time = Some(input);
self
}
/// <p>The date and time that the Region status was last updated.</p>
pub fn set_status_last_updated_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.status_last_updated_date_time = input;
self
}
/// <p>The date and time that the Region description was last updated.</p>
pub fn last_updated_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.last_updated_date_time = Some(input);
self
}
/// <p>The date and time that the Region description was last updated.</p>
pub fn set_last_updated_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.last_updated_date_time = input;
self
}
/// Consumes the builder and constructs a [`RegionDescription`](crate::model::RegionDescription)
pub fn build(self) -> crate::model::RegionDescription {
crate::model::RegionDescription {
directory_id: self.directory_id,
region_name: self.region_name,
region_type: self.region_type,
status: self.status,
vpc_settings: self.vpc_settings,
desired_number_of_domain_controllers: self
.desired_number_of_domain_controllers
.unwrap_or_default(),
launch_time: self.launch_time,
status_last_updated_date_time: self.status_last_updated_date_time,
last_updated_date_time: self.last_updated_date_time,
}
}
}
}
impl RegionDescription {
/// Creates a new builder-style object to manufacture [`RegionDescription`](crate::model::RegionDescription)
pub fn builder() -> crate::model::region_description::Builder {
crate::model::region_description::Builder::default()
}
}
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DirectoryVpcSettings {
/// <p>The identifier of the VPC in which to create the directory.</p>
pub vpc_id: std::option::Option<std::string::String>,
/// <p>The identifiers of the subnets for the directory servers. The two subnets must be in different Availability Zones. Directory Service creates a directory server and a DNS server in each of these subnets.</p>
pub subnet_ids: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl DirectoryVpcSettings {
/// <p>The identifier of the VPC in which to create the directory.</p>
pub fn vpc_id(&self) -> std::option::Option<&str> {
self.vpc_id.as_deref()
}
/// <p>The identifiers of the subnets for the directory servers. The two subnets must be in different Availability Zones. Directory Service creates a directory server and a DNS server in each of these subnets.</p>
pub fn subnet_ids(&self) -> std::option::Option<&[std::string::String]> {
self.subnet_ids.as_deref()
}
}
impl std::fmt::Debug for DirectoryVpcSettings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DirectoryVpcSettings");
formatter.field("vpc_id", &self.vpc_id);
formatter.field("subnet_ids", &self.subnet_ids);
formatter.finish()
}
}
/// See [`DirectoryVpcSettings`](crate::model::DirectoryVpcSettings)
pub mod directory_vpc_settings {
/// A builder for [`DirectoryVpcSettings`](crate::model::DirectoryVpcSettings)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) vpc_id: std::option::Option<std::string::String>,
pub(crate) subnet_ids: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl Builder {
/// <p>The identifier of the VPC in which to create the directory.</p>
pub fn vpc_id(mut self, input: impl Into<std::string::String>) -> Self {
self.vpc_id = Some(input.into());
self
}
/// <p>The identifier of the VPC in which to create the directory.</p>
pub fn set_vpc_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.vpc_id = input;
self
}
/// Appends an item to `subnet_ids`.
///
/// To override the contents of this collection use [`set_subnet_ids`](Self::set_subnet_ids).
///
/// <p>The identifiers of the subnets for the directory servers. The two subnets must be in different Availability Zones. Directory Service creates a directory server and a DNS server in each of these subnets.</p>
pub fn subnet_ids(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.subnet_ids.unwrap_or_default();
v.push(input.into());
self.subnet_ids = Some(v);
self
}
/// <p>The identifiers of the subnets for the directory servers. The two subnets must be in different Availability Zones. Directory Service creates a directory server and a DNS server in each of these subnets.</p>
pub fn set_subnet_ids(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.subnet_ids = input;
self
}
/// Consumes the builder and constructs a [`DirectoryVpcSettings`](crate::model::DirectoryVpcSettings)
pub fn build(self) -> crate::model::DirectoryVpcSettings {
crate::model::DirectoryVpcSettings {
vpc_id: self.vpc_id,
subnet_ids: self.subnet_ids,
}
}
}
}
impl DirectoryVpcSettings {
/// Creates a new builder-style object to manufacture [`DirectoryVpcSettings`](crate::model::DirectoryVpcSettings)
pub fn builder() -> crate::model::directory_vpc_settings::Builder {
crate::model::directory_vpc_settings::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum DirectoryStage {
#[allow(missing_docs)] // documentation missing in model
Active,
#[allow(missing_docs)] // documentation missing in model
Created,
#[allow(missing_docs)] // documentation missing in model
Creating,
#[allow(missing_docs)] // documentation missing in model
Deleted,
#[allow(missing_docs)] // documentation missing in model
Deleting,
#[allow(missing_docs)] // documentation missing in model
Failed,
#[allow(missing_docs)] // documentation missing in model
Impaired,
#[allow(missing_docs)] // documentation missing in model
Inoperable,
#[allow(missing_docs)] // documentation missing in model
Requested,
#[allow(missing_docs)] // documentation missing in model
Restorefailed,
#[allow(missing_docs)] // documentation missing in model
Restoring,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for DirectoryStage {
fn from(s: &str) -> Self {
match s {
"Active" => DirectoryStage::Active,
"Created" => DirectoryStage::Created,
"Creating" => DirectoryStage::Creating,
"Deleted" => DirectoryStage::Deleted,
"Deleting" => DirectoryStage::Deleting,
"Failed" => DirectoryStage::Failed,
"Impaired" => DirectoryStage::Impaired,
"Inoperable" => DirectoryStage::Inoperable,
"Requested" => DirectoryStage::Requested,
"RestoreFailed" => DirectoryStage::Restorefailed,
"Restoring" => DirectoryStage::Restoring,
other => DirectoryStage::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for DirectoryStage {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(DirectoryStage::from(s))
}
}
impl DirectoryStage {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
DirectoryStage::Active => "Active",
DirectoryStage::Created => "Created",
DirectoryStage::Creating => "Creating",
DirectoryStage::Deleted => "Deleted",
DirectoryStage::Deleting => "Deleting",
DirectoryStage::Failed => "Failed",
DirectoryStage::Impaired => "Impaired",
DirectoryStage::Inoperable => "Inoperable",
DirectoryStage::Requested => "Requested",
DirectoryStage::Restorefailed => "RestoreFailed",
DirectoryStage::Restoring => "Restoring",
DirectoryStage::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"Active",
"Created",
"Creating",
"Deleted",
"Deleting",
"Failed",
"Impaired",
"Inoperable",
"Requested",
"RestoreFailed",
"Restoring",
]
}
}
impl AsRef<str> for DirectoryStage {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum RegionType {
#[allow(missing_docs)] // documentation missing in model
Additional,
#[allow(missing_docs)] // documentation missing in model
Primary,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for RegionType {
fn from(s: &str) -> Self {
match s {
"Additional" => RegionType::Additional,
"Primary" => RegionType::Primary,
other => RegionType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for RegionType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(RegionType::from(s))
}
}
impl RegionType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
RegionType::Additional => "Additional",
RegionType::Primary => "Primary",
RegionType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["Additional", "Primary"]
}
}
impl AsRef<str> for RegionType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Contains general information about the LDAPS settings.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct LdapsSettingInfo {
/// <p>The state of the LDAPS settings.</p>
pub ldaps_status: std::option::Option<crate::model::LdapsStatus>,
/// <p>Describes a state change for LDAPS.</p>
pub ldaps_status_reason: std::option::Option<std::string::String>,
/// <p>The date and time when the LDAPS settings were last updated.</p>
pub last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl LdapsSettingInfo {
/// <p>The state of the LDAPS settings.</p>
pub fn ldaps_status(&self) -> std::option::Option<&crate::model::LdapsStatus> {
self.ldaps_status.as_ref()
}
/// <p>Describes a state change for LDAPS.</p>
pub fn ldaps_status_reason(&self) -> std::option::Option<&str> {
self.ldaps_status_reason.as_deref()
}
/// <p>The date and time when the LDAPS settings were last updated.</p>
pub fn last_updated_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.last_updated_date_time.as_ref()
}
}
impl std::fmt::Debug for LdapsSettingInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("LdapsSettingInfo");
formatter.field("ldaps_status", &self.ldaps_status);
formatter.field("ldaps_status_reason", &self.ldaps_status_reason);
formatter.field("last_updated_date_time", &self.last_updated_date_time);
formatter.finish()
}
}
/// See [`LdapsSettingInfo`](crate::model::LdapsSettingInfo)
pub mod ldaps_setting_info {
/// A builder for [`LdapsSettingInfo`](crate::model::LdapsSettingInfo)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) ldaps_status: std::option::Option<crate::model::LdapsStatus>,
pub(crate) ldaps_status_reason: std::option::Option<std::string::String>,
pub(crate) last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl Builder {
/// <p>The state of the LDAPS settings.</p>
pub fn ldaps_status(mut self, input: crate::model::LdapsStatus) -> Self {
self.ldaps_status = Some(input);
self
}
/// <p>The state of the LDAPS settings.</p>
pub fn set_ldaps_status(
mut self,
input: std::option::Option<crate::model::LdapsStatus>,
) -> Self {
self.ldaps_status = input;
self
}
/// <p>Describes a state change for LDAPS.</p>
pub fn ldaps_status_reason(mut self, input: impl Into<std::string::String>) -> Self {
self.ldaps_status_reason = Some(input.into());
self
}
/// <p>Describes a state change for LDAPS.</p>
pub fn set_ldaps_status_reason(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.ldaps_status_reason = input;
self
}
/// <p>The date and time when the LDAPS settings were last updated.</p>
pub fn last_updated_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.last_updated_date_time = Some(input);
self
}
/// <p>The date and time when the LDAPS settings were last updated.</p>
pub fn set_last_updated_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.last_updated_date_time = input;
self
}
/// Consumes the builder and constructs a [`LdapsSettingInfo`](crate::model::LdapsSettingInfo)
pub fn build(self) -> crate::model::LdapsSettingInfo {
crate::model::LdapsSettingInfo {
ldaps_status: self.ldaps_status,
ldaps_status_reason: self.ldaps_status_reason,
last_updated_date_time: self.last_updated_date_time,
}
}
}
}
impl LdapsSettingInfo {
/// Creates a new builder-style object to manufacture [`LdapsSettingInfo`](crate::model::LdapsSettingInfo)
pub fn builder() -> crate::model::ldaps_setting_info::Builder {
crate::model::ldaps_setting_info::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum LdapsStatus {
#[allow(missing_docs)] // documentation missing in model
Disabled,
#[allow(missing_docs)] // documentation missing in model
EnableFailed,
#[allow(missing_docs)] // documentation missing in model
Enabled,
#[allow(missing_docs)] // documentation missing in model
Enabling,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for LdapsStatus {
fn from(s: &str) -> Self {
match s {
"Disabled" => LdapsStatus::Disabled,
"EnableFailed" => LdapsStatus::EnableFailed,
"Enabled" => LdapsStatus::Enabled,
"Enabling" => LdapsStatus::Enabling,
other => LdapsStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for LdapsStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(LdapsStatus::from(s))
}
}
impl LdapsStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
LdapsStatus::Disabled => "Disabled",
LdapsStatus::EnableFailed => "EnableFailed",
LdapsStatus::Enabled => "Enabled",
LdapsStatus::Enabling => "Enabling",
LdapsStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["Disabled", "EnableFailed", "Enabled", "Enabling"]
}
}
impl AsRef<str> for LdapsStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Information about Amazon SNS topic and Directory Service directory associations.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct EventTopic {
/// <p>The Directory ID of an Directory Service directory that will publish status messages to an Amazon SNS topic.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The name of an Amazon SNS topic the receives status messages from the directory.</p>
pub topic_name: std::option::Option<std::string::String>,
/// <p>The Amazon SNS topic ARN (Amazon Resource Name).</p>
pub topic_arn: std::option::Option<std::string::String>,
/// <p>The date and time of when you associated your directory with the Amazon SNS topic.</p>
pub created_date_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The topic registration status.</p>
pub status: std::option::Option<crate::model::TopicStatus>,
}
impl EventTopic {
/// <p>The Directory ID of an Directory Service directory that will publish status messages to an Amazon SNS topic.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The name of an Amazon SNS topic the receives status messages from the directory.</p>
pub fn topic_name(&self) -> std::option::Option<&str> {
self.topic_name.as_deref()
}
/// <p>The Amazon SNS topic ARN (Amazon Resource Name).</p>
pub fn topic_arn(&self) -> std::option::Option<&str> {
self.topic_arn.as_deref()
}
/// <p>The date and time of when you associated your directory with the Amazon SNS topic.</p>
pub fn created_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.created_date_time.as_ref()
}
/// <p>The topic registration status.</p>
pub fn status(&self) -> std::option::Option<&crate::model::TopicStatus> {
self.status.as_ref()
}
}
impl std::fmt::Debug for EventTopic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("EventTopic");
formatter.field("directory_id", &self.directory_id);
formatter.field("topic_name", &self.topic_name);
formatter.field("topic_arn", &self.topic_arn);
formatter.field("created_date_time", &self.created_date_time);
formatter.field("status", &self.status);
formatter.finish()
}
}
/// See [`EventTopic`](crate::model::EventTopic)
pub mod event_topic {
/// A builder for [`EventTopic`](crate::model::EventTopic)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) topic_name: std::option::Option<std::string::String>,
pub(crate) topic_arn: std::option::Option<std::string::String>,
pub(crate) created_date_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) status: std::option::Option<crate::model::TopicStatus>,
}
impl Builder {
/// <p>The Directory ID of an Directory Service directory that will publish status messages to an Amazon SNS topic.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The Directory ID of an Directory Service directory that will publish status messages to an Amazon SNS topic.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The name of an Amazon SNS topic the receives status messages from the directory.</p>
pub fn topic_name(mut self, input: impl Into<std::string::String>) -> Self {
self.topic_name = Some(input.into());
self
}
/// <p>The name of an Amazon SNS topic the receives status messages from the directory.</p>
pub fn set_topic_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.topic_name = input;
self
}
/// <p>The Amazon SNS topic ARN (Amazon Resource Name).</p>
pub fn topic_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.topic_arn = Some(input.into());
self
}
/// <p>The Amazon SNS topic ARN (Amazon Resource Name).</p>
pub fn set_topic_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.topic_arn = input;
self
}
/// <p>The date and time of when you associated your directory with the Amazon SNS topic.</p>
pub fn created_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.created_date_time = Some(input);
self
}
/// <p>The date and time of when you associated your directory with the Amazon SNS topic.</p>
pub fn set_created_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.created_date_time = input;
self
}
/// <p>The topic registration status.</p>
pub fn status(mut self, input: crate::model::TopicStatus) -> Self {
self.status = Some(input);
self
}
/// <p>The topic registration status.</p>
pub fn set_status(mut self, input: std::option::Option<crate::model::TopicStatus>) -> Self {
self.status = input;
self
}
/// Consumes the builder and constructs a [`EventTopic`](crate::model::EventTopic)
pub fn build(self) -> crate::model::EventTopic {
crate::model::EventTopic {
directory_id: self.directory_id,
topic_name: self.topic_name,
topic_arn: self.topic_arn,
created_date_time: self.created_date_time,
status: self.status,
}
}
}
}
impl EventTopic {
/// Creates a new builder-style object to manufacture [`EventTopic`](crate::model::EventTopic)
pub fn builder() -> crate::model::event_topic::Builder {
crate::model::event_topic::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum TopicStatus {
#[allow(missing_docs)] // documentation missing in model
Deleted,
#[allow(missing_docs)] // documentation missing in model
Failed,
#[allow(missing_docs)] // documentation missing in model
Registered,
#[allow(missing_docs)] // documentation missing in model
TopicNotFound,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for TopicStatus {
fn from(s: &str) -> Self {
match s {
"Deleted" => TopicStatus::Deleted,
"Failed" => TopicStatus::Failed,
"Registered" => TopicStatus::Registered,
"Topic not found" => TopicStatus::TopicNotFound,
other => TopicStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for TopicStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(TopicStatus::from(s))
}
}
impl TopicStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
TopicStatus::Deleted => "Deleted",
TopicStatus::Failed => "Failed",
TopicStatus::Registered => "Registered",
TopicStatus::TopicNotFound => "Topic not found",
TopicStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["Deleted", "Failed", "Registered", "Topic not found"]
}
}
impl AsRef<str> for TopicStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Contains information about the domain controllers for a specified directory.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DomainController {
/// <p>Identifier of the directory where the domain controller resides.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>Identifies a specific domain controller in the directory.</p>
pub domain_controller_id: std::option::Option<std::string::String>,
/// <p>The IP address of the domain controller.</p>
pub dns_ip_addr: std::option::Option<std::string::String>,
/// <p>The identifier of the VPC that contains the domain controller.</p>
pub vpc_id: std::option::Option<std::string::String>,
/// <p>Identifier of the subnet in the VPC that contains the domain controller.</p>
pub subnet_id: std::option::Option<std::string::String>,
/// <p>The Availability Zone where the domain controller is located.</p>
pub availability_zone: std::option::Option<std::string::String>,
/// <p>The status of the domain controller.</p>
pub status: std::option::Option<crate::model::DomainControllerStatus>,
/// <p>A description of the domain controller state.</p>
pub status_reason: std::option::Option<std::string::String>,
/// <p>Specifies when the domain controller was created.</p>
pub launch_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The date and time that the status was last updated.</p>
pub status_last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl DomainController {
/// <p>Identifier of the directory where the domain controller resides.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>Identifies a specific domain controller in the directory.</p>
pub fn domain_controller_id(&self) -> std::option::Option<&str> {
self.domain_controller_id.as_deref()
}
/// <p>The IP address of the domain controller.</p>
pub fn dns_ip_addr(&self) -> std::option::Option<&str> {
self.dns_ip_addr.as_deref()
}
/// <p>The identifier of the VPC that contains the domain controller.</p>
pub fn vpc_id(&self) -> std::option::Option<&str> {
self.vpc_id.as_deref()
}
/// <p>Identifier of the subnet in the VPC that contains the domain controller.</p>
pub fn subnet_id(&self) -> std::option::Option<&str> {
self.subnet_id.as_deref()
}
/// <p>The Availability Zone where the domain controller is located.</p>
pub fn availability_zone(&self) -> std::option::Option<&str> {
self.availability_zone.as_deref()
}
/// <p>The status of the domain controller.</p>
pub fn status(&self) -> std::option::Option<&crate::model::DomainControllerStatus> {
self.status.as_ref()
}
/// <p>A description of the domain controller state.</p>
pub fn status_reason(&self) -> std::option::Option<&str> {
self.status_reason.as_deref()
}
/// <p>Specifies when the domain controller was created.</p>
pub fn launch_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.launch_time.as_ref()
}
/// <p>The date and time that the status was last updated.</p>
pub fn status_last_updated_date_time(
&self,
) -> std::option::Option<&aws_smithy_types::DateTime> {
self.status_last_updated_date_time.as_ref()
}
}
impl std::fmt::Debug for DomainController {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DomainController");
formatter.field("directory_id", &self.directory_id);
formatter.field("domain_controller_id", &self.domain_controller_id);
formatter.field("dns_ip_addr", &self.dns_ip_addr);
formatter.field("vpc_id", &self.vpc_id);
formatter.field("subnet_id", &self.subnet_id);
formatter.field("availability_zone", &self.availability_zone);
formatter.field("status", &self.status);
formatter.field("status_reason", &self.status_reason);
formatter.field("launch_time", &self.launch_time);
formatter.field(
"status_last_updated_date_time",
&self.status_last_updated_date_time,
);
formatter.finish()
}
}
/// See [`DomainController`](crate::model::DomainController)
pub mod domain_controller {
/// A builder for [`DomainController`](crate::model::DomainController)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) domain_controller_id: std::option::Option<std::string::String>,
pub(crate) dns_ip_addr: std::option::Option<std::string::String>,
pub(crate) vpc_id: std::option::Option<std::string::String>,
pub(crate) subnet_id: std::option::Option<std::string::String>,
pub(crate) availability_zone: std::option::Option<std::string::String>,
pub(crate) status: std::option::Option<crate::model::DomainControllerStatus>,
pub(crate) status_reason: std::option::Option<std::string::String>,
pub(crate) launch_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) status_last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl Builder {
/// <p>Identifier of the directory where the domain controller resides.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier of the directory where the domain controller resides.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>Identifies a specific domain controller in the directory.</p>
pub fn domain_controller_id(mut self, input: impl Into<std::string::String>) -> Self {
self.domain_controller_id = Some(input.into());
self
}
/// <p>Identifies a specific domain controller in the directory.</p>
pub fn set_domain_controller_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.domain_controller_id = input;
self
}
/// <p>The IP address of the domain controller.</p>
pub fn dns_ip_addr(mut self, input: impl Into<std::string::String>) -> Self {
self.dns_ip_addr = Some(input.into());
self
}
/// <p>The IP address of the domain controller.</p>
pub fn set_dns_ip_addr(mut self, input: std::option::Option<std::string::String>) -> Self {
self.dns_ip_addr = input;
self
}
/// <p>The identifier of the VPC that contains the domain controller.</p>
pub fn vpc_id(mut self, input: impl Into<std::string::String>) -> Self {
self.vpc_id = Some(input.into());
self
}
/// <p>The identifier of the VPC that contains the domain controller.</p>
pub fn set_vpc_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.vpc_id = input;
self
}
/// <p>Identifier of the subnet in the VPC that contains the domain controller.</p>
pub fn subnet_id(mut self, input: impl Into<std::string::String>) -> Self {
self.subnet_id = Some(input.into());
self
}
/// <p>Identifier of the subnet in the VPC that contains the domain controller.</p>
pub fn set_subnet_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.subnet_id = input;
self
}
/// <p>The Availability Zone where the domain controller is located.</p>
pub fn availability_zone(mut self, input: impl Into<std::string::String>) -> Self {
self.availability_zone = Some(input.into());
self
}
/// <p>The Availability Zone where the domain controller is located.</p>
pub fn set_availability_zone(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.availability_zone = input;
self
}
/// <p>The status of the domain controller.</p>
pub fn status(mut self, input: crate::model::DomainControllerStatus) -> Self {
self.status = Some(input);
self
}
/// <p>The status of the domain controller.</p>
pub fn set_status(
mut self,
input: std::option::Option<crate::model::DomainControllerStatus>,
) -> Self {
self.status = input;
self
}
/// <p>A description of the domain controller state.</p>
pub fn status_reason(mut self, input: impl Into<std::string::String>) -> Self {
self.status_reason = Some(input.into());
self
}
/// <p>A description of the domain controller state.</p>
pub fn set_status_reason(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.status_reason = input;
self
}
/// <p>Specifies when the domain controller was created.</p>
pub fn launch_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.launch_time = Some(input);
self
}
/// <p>Specifies when the domain controller was created.</p>
pub fn set_launch_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.launch_time = input;
self
}
/// <p>The date and time that the status was last updated.</p>
pub fn status_last_updated_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.status_last_updated_date_time = Some(input);
self
}
/// <p>The date and time that the status was last updated.</p>
pub fn set_status_last_updated_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.status_last_updated_date_time = input;
self
}
/// Consumes the builder and constructs a [`DomainController`](crate::model::DomainController)
pub fn build(self) -> crate::model::DomainController {
crate::model::DomainController {
directory_id: self.directory_id,
domain_controller_id: self.domain_controller_id,
dns_ip_addr: self.dns_ip_addr,
vpc_id: self.vpc_id,
subnet_id: self.subnet_id,
availability_zone: self.availability_zone,
status: self.status,
status_reason: self.status_reason,
launch_time: self.launch_time,
status_last_updated_date_time: self.status_last_updated_date_time,
}
}
}
}
impl DomainController {
/// Creates a new builder-style object to manufacture [`DomainController`](crate::model::DomainController)
pub fn builder() -> crate::model::domain_controller::Builder {
crate::model::domain_controller::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum DomainControllerStatus {
#[allow(missing_docs)] // documentation missing in model
Active,
#[allow(missing_docs)] // documentation missing in model
Creating,
#[allow(missing_docs)] // documentation missing in model
Deleted,
#[allow(missing_docs)] // documentation missing in model
Deleting,
#[allow(missing_docs)] // documentation missing in model
Failed,
#[allow(missing_docs)] // documentation missing in model
Impaired,
#[allow(missing_docs)] // documentation missing in model
Restoring,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for DomainControllerStatus {
fn from(s: &str) -> Self {
match s {
"Active" => DomainControllerStatus::Active,
"Creating" => DomainControllerStatus::Creating,
"Deleted" => DomainControllerStatus::Deleted,
"Deleting" => DomainControllerStatus::Deleting,
"Failed" => DomainControllerStatus::Failed,
"Impaired" => DomainControllerStatus::Impaired,
"Restoring" => DomainControllerStatus::Restoring,
other => DomainControllerStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for DomainControllerStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(DomainControllerStatus::from(s))
}
}
impl DomainControllerStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
DomainControllerStatus::Active => "Active",
DomainControllerStatus::Creating => "Creating",
DomainControllerStatus::Deleted => "Deleted",
DomainControllerStatus::Deleting => "Deleting",
DomainControllerStatus::Failed => "Failed",
DomainControllerStatus::Impaired => "Impaired",
DomainControllerStatus::Restoring => "Restoring",
DomainControllerStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"Active",
"Creating",
"Deleted",
"Deleting",
"Failed",
"Impaired",
"Restoring",
]
}
}
impl AsRef<str> for DomainControllerStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Contains information about an Directory Service directory.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DirectoryDescription {
/// <p>The directory identifier.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The fully qualified name of the directory.</p>
pub name: std::option::Option<std::string::String>,
/// <p>The short name of the directory.</p>
pub short_name: std::option::Option<std::string::String>,
/// <p>The directory size.</p>
pub size: std::option::Option<crate::model::DirectorySize>,
/// <p>The edition associated with this directory.</p>
pub edition: std::option::Option<crate::model::DirectoryEdition>,
/// <p>The alias for the directory. If no alias has been created for the directory, the alias is the directory identifier, such as <code>d-XXXXXXXXXX</code>.</p>
pub alias: std::option::Option<std::string::String>,
/// <p>The access URL for the directory, such as <code>http://
/// <alias>
/// .awsapps.com
/// </alias></code>. If no alias has been created for the directory, <code>
/// <alias></alias></code> is the directory identifier, such as <code>d-XXXXXXXXXX</code>.</p>
pub access_url: std::option::Option<std::string::String>,
/// <p>The description for the directory.</p>
pub description: std::option::Option<std::string::String>,
/// <p>The IP addresses of the DNS servers for the directory. For a Simple AD or Microsoft AD directory, these are the IP addresses of the Simple AD or Microsoft AD directory servers. For an AD Connector directory, these are the IP addresses of the DNS servers or domain controllers in your self-managed directory to which the AD Connector is connected.</p>
pub dns_ip_addrs: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The current stage of the directory.</p>
pub stage: std::option::Option<crate::model::DirectoryStage>,
/// <p>Current directory status of the shared Managed Microsoft AD directory.</p>
pub share_status: std::option::Option<crate::model::ShareStatus>,
/// <p>The method used when sharing a directory to determine whether the directory should be shared within your Amazon Web Services organization (<code>ORGANIZATIONS</code>) or with any Amazon Web Services account by sending a shared directory request (<code>HANDSHAKE</code>).</p>
pub share_method: std::option::Option<crate::model::ShareMethod>,
/// <p>A directory share request that is sent by the directory owner to the directory consumer. The request includes a typed message to help the directory consumer administrator determine whether to approve or reject the share invitation.</p>
pub share_notes: std::option::Option<std::string::String>,
/// <p>Specifies when the directory was created.</p>
pub launch_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The date and time that the stage was last updated.</p>
pub stage_last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The directory size.</p>
pub r#type: std::option::Option<crate::model::DirectoryType>,
/// <p>A <code>DirectoryVpcSettingsDescription</code> object that contains additional information about a directory. This member is only present if the directory is a Simple AD or Managed Microsoft AD directory.</p>
pub vpc_settings: std::option::Option<crate::model::DirectoryVpcSettingsDescription>,
/// <p>A <code>DirectoryConnectSettingsDescription</code> object that contains additional information about an AD Connector directory. This member is only present if the directory is an AD Connector directory.</p>
pub connect_settings: std::option::Option<crate::model::DirectoryConnectSettingsDescription>,
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server configured for this directory.</p>
pub radius_settings: std::option::Option<crate::model::RadiusSettings>,
/// <p>The status of the RADIUS MFA server connection.</p>
pub radius_status: std::option::Option<crate::model::RadiusStatus>,
/// <p>Additional information about the directory stage.</p>
pub stage_reason: std::option::Option<std::string::String>,
/// <p>Indicates if single sign-on is enabled for the directory. For more information, see <code>EnableSso</code> and <code>DisableSso</code>.</p>
pub sso_enabled: bool,
/// <p>The desired number of domain controllers in the directory if the directory is Microsoft AD.</p>
pub desired_number_of_domain_controllers: i32,
/// <p>Describes the Managed Microsoft AD directory in the directory owner account.</p>
pub owner_directory_description: std::option::Option<crate::model::OwnerDirectoryDescription>,
/// <p>Lists the Regions where the directory has replicated.</p>
pub regions_info: std::option::Option<crate::model::RegionsInfo>,
}
impl DirectoryDescription {
/// <p>The directory identifier.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The fully qualified name of the directory.</p>
pub fn name(&self) -> std::option::Option<&str> {
self.name.as_deref()
}
/// <p>The short name of the directory.</p>
pub fn short_name(&self) -> std::option::Option<&str> {
self.short_name.as_deref()
}
/// <p>The directory size.</p>
pub fn size(&self) -> std::option::Option<&crate::model::DirectorySize> {
self.size.as_ref()
}
/// <p>The edition associated with this directory.</p>
pub fn edition(&self) -> std::option::Option<&crate::model::DirectoryEdition> {
self.edition.as_ref()
}
/// <p>The alias for the directory. If no alias has been created for the directory, the alias is the directory identifier, such as <code>d-XXXXXXXXXX</code>.</p>
pub fn alias(&self) -> std::option::Option<&str> {
self.alias.as_deref()
}
/// <p>The access URL for the directory, such as <code>http://
/// <alias>
/// .awsapps.com
/// </alias></code>. If no alias has been created for the directory, <code>
/// <alias></alias></code> is the directory identifier, such as <code>d-XXXXXXXXXX</code>.</p>
pub fn access_url(&self) -> std::option::Option<&str> {
self.access_url.as_deref()
}
/// <p>The description for the directory.</p>
pub fn description(&self) -> std::option::Option<&str> {
self.description.as_deref()
}
/// <p>The IP addresses of the DNS servers for the directory. For a Simple AD or Microsoft AD directory, these are the IP addresses of the Simple AD or Microsoft AD directory servers. For an AD Connector directory, these are the IP addresses of the DNS servers or domain controllers in your self-managed directory to which the AD Connector is connected.</p>
pub fn dns_ip_addrs(&self) -> std::option::Option<&[std::string::String]> {
self.dns_ip_addrs.as_deref()
}
/// <p>The current stage of the directory.</p>
pub fn stage(&self) -> std::option::Option<&crate::model::DirectoryStage> {
self.stage.as_ref()
}
/// <p>Current directory status of the shared Managed Microsoft AD directory.</p>
pub fn share_status(&self) -> std::option::Option<&crate::model::ShareStatus> {
self.share_status.as_ref()
}
/// <p>The method used when sharing a directory to determine whether the directory should be shared within your Amazon Web Services organization (<code>ORGANIZATIONS</code>) or with any Amazon Web Services account by sending a shared directory request (<code>HANDSHAKE</code>).</p>
pub fn share_method(&self) -> std::option::Option<&crate::model::ShareMethod> {
self.share_method.as_ref()
}
/// <p>A directory share request that is sent by the directory owner to the directory consumer. The request includes a typed message to help the directory consumer administrator determine whether to approve or reject the share invitation.</p>
pub fn share_notes(&self) -> std::option::Option<&str> {
self.share_notes.as_deref()
}
/// <p>Specifies when the directory was created.</p>
pub fn launch_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.launch_time.as_ref()
}
/// <p>The date and time that the stage was last updated.</p>
pub fn stage_last_updated_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.stage_last_updated_date_time.as_ref()
}
/// <p>The directory size.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::DirectoryType> {
self.r#type.as_ref()
}
/// <p>A <code>DirectoryVpcSettingsDescription</code> object that contains additional information about a directory. This member is only present if the directory is a Simple AD or Managed Microsoft AD directory.</p>
pub fn vpc_settings(
&self,
) -> std::option::Option<&crate::model::DirectoryVpcSettingsDescription> {
self.vpc_settings.as_ref()
}
/// <p>A <code>DirectoryConnectSettingsDescription</code> object that contains additional information about an AD Connector directory. This member is only present if the directory is an AD Connector directory.</p>
pub fn connect_settings(
&self,
) -> std::option::Option<&crate::model::DirectoryConnectSettingsDescription> {
self.connect_settings.as_ref()
}
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server configured for this directory.</p>
pub fn radius_settings(&self) -> std::option::Option<&crate::model::RadiusSettings> {
self.radius_settings.as_ref()
}
/// <p>The status of the RADIUS MFA server connection.</p>
pub fn radius_status(&self) -> std::option::Option<&crate::model::RadiusStatus> {
self.radius_status.as_ref()
}
/// <p>Additional information about the directory stage.</p>
pub fn stage_reason(&self) -> std::option::Option<&str> {
self.stage_reason.as_deref()
}
/// <p>Indicates if single sign-on is enabled for the directory. For more information, see <code>EnableSso</code> and <code>DisableSso</code>.</p>
pub fn sso_enabled(&self) -> bool {
self.sso_enabled
}
/// <p>The desired number of domain controllers in the directory if the directory is Microsoft AD.</p>
pub fn desired_number_of_domain_controllers(&self) -> i32 {
self.desired_number_of_domain_controllers
}
/// <p>Describes the Managed Microsoft AD directory in the directory owner account.</p>
pub fn owner_directory_description(
&self,
) -> std::option::Option<&crate::model::OwnerDirectoryDescription> {
self.owner_directory_description.as_ref()
}
/// <p>Lists the Regions where the directory has replicated.</p>
pub fn regions_info(&self) -> std::option::Option<&crate::model::RegionsInfo> {
self.regions_info.as_ref()
}
}
impl std::fmt::Debug for DirectoryDescription {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DirectoryDescription");
formatter.field("directory_id", &self.directory_id);
formatter.field("name", &self.name);
formatter.field("short_name", &self.short_name);
formatter.field("size", &self.size);
formatter.field("edition", &self.edition);
formatter.field("alias", &self.alias);
formatter.field("access_url", &self.access_url);
formatter.field("description", &self.description);
formatter.field("dns_ip_addrs", &self.dns_ip_addrs);
formatter.field("stage", &self.stage);
formatter.field("share_status", &self.share_status);
formatter.field("share_method", &self.share_method);
formatter.field("share_notes", &"*** Sensitive Data Redacted ***");
formatter.field("launch_time", &self.launch_time);
formatter.field(
"stage_last_updated_date_time",
&self.stage_last_updated_date_time,
);
formatter.field("r#type", &self.r#type);
formatter.field("vpc_settings", &self.vpc_settings);
formatter.field("connect_settings", &self.connect_settings);
formatter.field("radius_settings", &self.radius_settings);
formatter.field("radius_status", &self.radius_status);
formatter.field("stage_reason", &self.stage_reason);
formatter.field("sso_enabled", &self.sso_enabled);
formatter.field(
"desired_number_of_domain_controllers",
&self.desired_number_of_domain_controllers,
);
formatter.field(
"owner_directory_description",
&self.owner_directory_description,
);
formatter.field("regions_info", &self.regions_info);
formatter.finish()
}
}
/// See [`DirectoryDescription`](crate::model::DirectoryDescription)
pub mod directory_description {
/// A builder for [`DirectoryDescription`](crate::model::DirectoryDescription)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) name: std::option::Option<std::string::String>,
pub(crate) short_name: std::option::Option<std::string::String>,
pub(crate) size: std::option::Option<crate::model::DirectorySize>,
pub(crate) edition: std::option::Option<crate::model::DirectoryEdition>,
pub(crate) alias: std::option::Option<std::string::String>,
pub(crate) access_url: std::option::Option<std::string::String>,
pub(crate) description: std::option::Option<std::string::String>,
pub(crate) dns_ip_addrs: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) stage: std::option::Option<crate::model::DirectoryStage>,
pub(crate) share_status: std::option::Option<crate::model::ShareStatus>,
pub(crate) share_method: std::option::Option<crate::model::ShareMethod>,
pub(crate) share_notes: std::option::Option<std::string::String>,
pub(crate) launch_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) stage_last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) r#type: std::option::Option<crate::model::DirectoryType>,
pub(crate) vpc_settings: std::option::Option<crate::model::DirectoryVpcSettingsDescription>,
pub(crate) connect_settings:
std::option::Option<crate::model::DirectoryConnectSettingsDescription>,
pub(crate) radius_settings: std::option::Option<crate::model::RadiusSettings>,
pub(crate) radius_status: std::option::Option<crate::model::RadiusStatus>,
pub(crate) stage_reason: std::option::Option<std::string::String>,
pub(crate) sso_enabled: std::option::Option<bool>,
pub(crate) desired_number_of_domain_controllers: std::option::Option<i32>,
pub(crate) owner_directory_description:
std::option::Option<crate::model::OwnerDirectoryDescription>,
pub(crate) regions_info: std::option::Option<crate::model::RegionsInfo>,
}
impl Builder {
/// <p>The directory identifier.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The directory identifier.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The fully qualified name of the directory.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.name = Some(input.into());
self
}
/// <p>The fully qualified name of the directory.</p>
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.name = input;
self
}
/// <p>The short name of the directory.</p>
pub fn short_name(mut self, input: impl Into<std::string::String>) -> Self {
self.short_name = Some(input.into());
self
}
/// <p>The short name of the directory.</p>
pub fn set_short_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.short_name = input;
self
}
/// <p>The directory size.</p>
pub fn size(mut self, input: crate::model::DirectorySize) -> Self {
self.size = Some(input);
self
}
/// <p>The directory size.</p>
pub fn set_size(mut self, input: std::option::Option<crate::model::DirectorySize>) -> Self {
self.size = input;
self
}
/// <p>The edition associated with this directory.</p>
pub fn edition(mut self, input: crate::model::DirectoryEdition) -> Self {
self.edition = Some(input);
self
}
/// <p>The edition associated with this directory.</p>
pub fn set_edition(
mut self,
input: std::option::Option<crate::model::DirectoryEdition>,
) -> Self {
self.edition = input;
self
}
/// <p>The alias for the directory. If no alias has been created for the directory, the alias is the directory identifier, such as <code>d-XXXXXXXXXX</code>.</p>
pub fn alias(mut self, input: impl Into<std::string::String>) -> Self {
self.alias = Some(input.into());
self
}
/// <p>The alias for the directory. If no alias has been created for the directory, the alias is the directory identifier, such as <code>d-XXXXXXXXXX</code>.</p>
pub fn set_alias(mut self, input: std::option::Option<std::string::String>) -> Self {
self.alias = input;
self
}
/// <p>The access URL for the directory, such as <code>http://
/// <alias>
/// .awsapps.com
/// </alias></code>. If no alias has been created for the directory, <code>
/// <alias></alias></code> is the directory identifier, such as <code>d-XXXXXXXXXX</code>.</p>
pub fn access_url(mut self, input: impl Into<std::string::String>) -> Self {
self.access_url = Some(input.into());
self
}
/// <p>The access URL for the directory, such as <code>http://
/// <alias>
/// .awsapps.com
/// </alias></code>. If no alias has been created for the directory, <code>
/// <alias></alias></code> is the directory identifier, such as <code>d-XXXXXXXXXX</code>.</p>
pub fn set_access_url(mut self, input: std::option::Option<std::string::String>) -> Self {
self.access_url = input;
self
}
/// <p>The description for the directory.</p>
pub fn description(mut self, input: impl Into<std::string::String>) -> Self {
self.description = Some(input.into());
self
}
/// <p>The description for the directory.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.description = input;
self
}
/// Appends an item to `dns_ip_addrs`.
///
/// To override the contents of this collection use [`set_dns_ip_addrs`](Self::set_dns_ip_addrs).
///
/// <p>The IP addresses of the DNS servers for the directory. For a Simple AD or Microsoft AD directory, these are the IP addresses of the Simple AD or Microsoft AD directory servers. For an AD Connector directory, these are the IP addresses of the DNS servers or domain controllers in your self-managed directory to which the AD Connector is connected.</p>
pub fn dns_ip_addrs(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.dns_ip_addrs.unwrap_or_default();
v.push(input.into());
self.dns_ip_addrs = Some(v);
self
}
/// <p>The IP addresses of the DNS servers for the directory. For a Simple AD or Microsoft AD directory, these are the IP addresses of the Simple AD or Microsoft AD directory servers. For an AD Connector directory, these are the IP addresses of the DNS servers or domain controllers in your self-managed directory to which the AD Connector is connected.</p>
pub fn set_dns_ip_addrs(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.dns_ip_addrs = input;
self
}
/// <p>The current stage of the directory.</p>
pub fn stage(mut self, input: crate::model::DirectoryStage) -> Self {
self.stage = Some(input);
self
}
/// <p>The current stage of the directory.</p>
pub fn set_stage(
mut self,
input: std::option::Option<crate::model::DirectoryStage>,
) -> Self {
self.stage = input;
self
}
/// <p>Current directory status of the shared Managed Microsoft AD directory.</p>
pub fn share_status(mut self, input: crate::model::ShareStatus) -> Self {
self.share_status = Some(input);
self
}
/// <p>Current directory status of the shared Managed Microsoft AD directory.</p>
pub fn set_share_status(
mut self,
input: std::option::Option<crate::model::ShareStatus>,
) -> Self {
self.share_status = input;
self
}
/// <p>The method used when sharing a directory to determine whether the directory should be shared within your Amazon Web Services organization (<code>ORGANIZATIONS</code>) or with any Amazon Web Services account by sending a shared directory request (<code>HANDSHAKE</code>).</p>
pub fn share_method(mut self, input: crate::model::ShareMethod) -> Self {
self.share_method = Some(input);
self
}
/// <p>The method used when sharing a directory to determine whether the directory should be shared within your Amazon Web Services organization (<code>ORGANIZATIONS</code>) or with any Amazon Web Services account by sending a shared directory request (<code>HANDSHAKE</code>).</p>
pub fn set_share_method(
mut self,
input: std::option::Option<crate::model::ShareMethod>,
) -> Self {
self.share_method = input;
self
}
/// <p>A directory share request that is sent by the directory owner to the directory consumer. The request includes a typed message to help the directory consumer administrator determine whether to approve or reject the share invitation.</p>
pub fn share_notes(mut self, input: impl Into<std::string::String>) -> Self {
self.share_notes = Some(input.into());
self
}
/// <p>A directory share request that is sent by the directory owner to the directory consumer. The request includes a typed message to help the directory consumer administrator determine whether to approve or reject the share invitation.</p>
pub fn set_share_notes(mut self, input: std::option::Option<std::string::String>) -> Self {
self.share_notes = input;
self
}
/// <p>Specifies when the directory was created.</p>
pub fn launch_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.launch_time = Some(input);
self
}
/// <p>Specifies when the directory was created.</p>
pub fn set_launch_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.launch_time = input;
self
}
/// <p>The date and time that the stage was last updated.</p>
pub fn stage_last_updated_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.stage_last_updated_date_time = Some(input);
self
}
/// <p>The date and time that the stage was last updated.</p>
pub fn set_stage_last_updated_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.stage_last_updated_date_time = input;
self
}
/// <p>The directory size.</p>
pub fn r#type(mut self, input: crate::model::DirectoryType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The directory size.</p>
pub fn set_type(mut self, input: std::option::Option<crate::model::DirectoryType>) -> Self {
self.r#type = input;
self
}
/// <p>A <code>DirectoryVpcSettingsDescription</code> object that contains additional information about a directory. This member is only present if the directory is a Simple AD or Managed Microsoft AD directory.</p>
pub fn vpc_settings(
mut self,
input: crate::model::DirectoryVpcSettingsDescription,
) -> Self {
self.vpc_settings = Some(input);
self
}
/// <p>A <code>DirectoryVpcSettingsDescription</code> object that contains additional information about a directory. This member is only present if the directory is a Simple AD or Managed Microsoft AD directory.</p>
pub fn set_vpc_settings(
mut self,
input: std::option::Option<crate::model::DirectoryVpcSettingsDescription>,
) -> Self {
self.vpc_settings = input;
self
}
/// <p>A <code>DirectoryConnectSettingsDescription</code> object that contains additional information about an AD Connector directory. This member is only present if the directory is an AD Connector directory.</p>
pub fn connect_settings(
mut self,
input: crate::model::DirectoryConnectSettingsDescription,
) -> Self {
self.connect_settings = Some(input);
self
}
/// <p>A <code>DirectoryConnectSettingsDescription</code> object that contains additional information about an AD Connector directory. This member is only present if the directory is an AD Connector directory.</p>
pub fn set_connect_settings(
mut self,
input: std::option::Option<crate::model::DirectoryConnectSettingsDescription>,
) -> Self {
self.connect_settings = input;
self
}
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server configured for this directory.</p>
pub fn radius_settings(mut self, input: crate::model::RadiusSettings) -> Self {
self.radius_settings = Some(input);
self
}
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server configured for this directory.</p>
pub fn set_radius_settings(
mut self,
input: std::option::Option<crate::model::RadiusSettings>,
) -> Self {
self.radius_settings = input;
self
}
/// <p>The status of the RADIUS MFA server connection.</p>
pub fn radius_status(mut self, input: crate::model::RadiusStatus) -> Self {
self.radius_status = Some(input);
self
}
/// <p>The status of the RADIUS MFA server connection.</p>
pub fn set_radius_status(
mut self,
input: std::option::Option<crate::model::RadiusStatus>,
) -> Self {
self.radius_status = input;
self
}
/// <p>Additional information about the directory stage.</p>
pub fn stage_reason(mut self, input: impl Into<std::string::String>) -> Self {
self.stage_reason = Some(input.into());
self
}
/// <p>Additional information about the directory stage.</p>
pub fn set_stage_reason(mut self, input: std::option::Option<std::string::String>) -> Self {
self.stage_reason = input;
self
}
/// <p>Indicates if single sign-on is enabled for the directory. For more information, see <code>EnableSso</code> and <code>DisableSso</code>.</p>
pub fn sso_enabled(mut self, input: bool) -> Self {
self.sso_enabled = Some(input);
self
}
/// <p>Indicates if single sign-on is enabled for the directory. For more information, see <code>EnableSso</code> and <code>DisableSso</code>.</p>
pub fn set_sso_enabled(mut self, input: std::option::Option<bool>) -> Self {
self.sso_enabled = input;
self
}
/// <p>The desired number of domain controllers in the directory if the directory is Microsoft AD.</p>
pub fn desired_number_of_domain_controllers(mut self, input: i32) -> Self {
self.desired_number_of_domain_controllers = Some(input);
self
}
/// <p>The desired number of domain controllers in the directory if the directory is Microsoft AD.</p>
pub fn set_desired_number_of_domain_controllers(
mut self,
input: std::option::Option<i32>,
) -> Self {
self.desired_number_of_domain_controllers = input;
self
}
/// <p>Describes the Managed Microsoft AD directory in the directory owner account.</p>
pub fn owner_directory_description(
mut self,
input: crate::model::OwnerDirectoryDescription,
) -> Self {
self.owner_directory_description = Some(input);
self
}
/// <p>Describes the Managed Microsoft AD directory in the directory owner account.</p>
pub fn set_owner_directory_description(
mut self,
input: std::option::Option<crate::model::OwnerDirectoryDescription>,
) -> Self {
self.owner_directory_description = input;
self
}
/// <p>Lists the Regions where the directory has replicated.</p>
pub fn regions_info(mut self, input: crate::model::RegionsInfo) -> Self {
self.regions_info = Some(input);
self
}
/// <p>Lists the Regions where the directory has replicated.</p>
pub fn set_regions_info(
mut self,
input: std::option::Option<crate::model::RegionsInfo>,
) -> Self {
self.regions_info = input;
self
}
/// Consumes the builder and constructs a [`DirectoryDescription`](crate::model::DirectoryDescription)
pub fn build(self) -> crate::model::DirectoryDescription {
crate::model::DirectoryDescription {
directory_id: self.directory_id,
name: self.name,
short_name: self.short_name,
size: self.size,
edition: self.edition,
alias: self.alias,
access_url: self.access_url,
description: self.description,
dns_ip_addrs: self.dns_ip_addrs,
stage: self.stage,
share_status: self.share_status,
share_method: self.share_method,
share_notes: self.share_notes,
launch_time: self.launch_time,
stage_last_updated_date_time: self.stage_last_updated_date_time,
r#type: self.r#type,
vpc_settings: self.vpc_settings,
connect_settings: self.connect_settings,
radius_settings: self.radius_settings,
radius_status: self.radius_status,
stage_reason: self.stage_reason,
sso_enabled: self.sso_enabled.unwrap_or_default(),
desired_number_of_domain_controllers: self
.desired_number_of_domain_controllers
.unwrap_or_default(),
owner_directory_description: self.owner_directory_description,
regions_info: self.regions_info,
}
}
}
}
impl DirectoryDescription {
/// Creates a new builder-style object to manufacture [`DirectoryDescription`](crate::model::DirectoryDescription)
pub fn builder() -> crate::model::directory_description::Builder {
crate::model::directory_description::Builder::default()
}
}
/// <p>Provides information about the Regions that are configured for multi-Region replication.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RegionsInfo {
/// <p>The Region where the Managed Microsoft AD directory was originally created.</p>
pub primary_region: std::option::Option<std::string::String>,
/// <p>Lists the Regions where the directory has been replicated, excluding the primary Region.</p>
pub additional_regions: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl RegionsInfo {
/// <p>The Region where the Managed Microsoft AD directory was originally created.</p>
pub fn primary_region(&self) -> std::option::Option<&str> {
self.primary_region.as_deref()
}
/// <p>Lists the Regions where the directory has been replicated, excluding the primary Region.</p>
pub fn additional_regions(&self) -> std::option::Option<&[std::string::String]> {
self.additional_regions.as_deref()
}
}
impl std::fmt::Debug for RegionsInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RegionsInfo");
formatter.field("primary_region", &self.primary_region);
formatter.field("additional_regions", &self.additional_regions);
formatter.finish()
}
}
/// See [`RegionsInfo`](crate::model::RegionsInfo)
pub mod regions_info {
/// A builder for [`RegionsInfo`](crate::model::RegionsInfo)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) primary_region: std::option::Option<std::string::String>,
pub(crate) additional_regions: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl Builder {
/// <p>The Region where the Managed Microsoft AD directory was originally created.</p>
pub fn primary_region(mut self, input: impl Into<std::string::String>) -> Self {
self.primary_region = Some(input.into());
self
}
/// <p>The Region where the Managed Microsoft AD directory was originally created.</p>
pub fn set_primary_region(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.primary_region = input;
self
}
/// Appends an item to `additional_regions`.
///
/// To override the contents of this collection use [`set_additional_regions`](Self::set_additional_regions).
///
/// <p>Lists the Regions where the directory has been replicated, excluding the primary Region.</p>
pub fn additional_regions(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.additional_regions.unwrap_or_default();
v.push(input.into());
self.additional_regions = Some(v);
self
}
/// <p>Lists the Regions where the directory has been replicated, excluding the primary Region.</p>
pub fn set_additional_regions(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.additional_regions = input;
self
}
/// Consumes the builder and constructs a [`RegionsInfo`](crate::model::RegionsInfo)
pub fn build(self) -> crate::model::RegionsInfo {
crate::model::RegionsInfo {
primary_region: self.primary_region,
additional_regions: self.additional_regions,
}
}
}
}
impl RegionsInfo {
/// Creates a new builder-style object to manufacture [`RegionsInfo`](crate::model::RegionsInfo)
pub fn builder() -> crate::model::regions_info::Builder {
crate::model::regions_info::Builder::default()
}
}
/// <p>Describes the directory owner account details that have been shared to the directory consumer account.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct OwnerDirectoryDescription {
/// <p>Identifier of the Managed Microsoft AD directory in the directory owner account.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>Identifier of the directory owner account.</p>
pub account_id: std::option::Option<std::string::String>,
/// <p>IP address of the directory’s domain controllers.</p>
pub dns_ip_addrs: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>Information about the VPC settings for the directory.</p>
pub vpc_settings: std::option::Option<crate::model::DirectoryVpcSettingsDescription>,
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server.</p>
pub radius_settings: std::option::Option<crate::model::RadiusSettings>,
/// <p>Information about the status of the RADIUS server.</p>
pub radius_status: std::option::Option<crate::model::RadiusStatus>,
}
impl OwnerDirectoryDescription {
/// <p>Identifier of the Managed Microsoft AD directory in the directory owner account.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>Identifier of the directory owner account.</p>
pub fn account_id(&self) -> std::option::Option<&str> {
self.account_id.as_deref()
}
/// <p>IP address of the directory’s domain controllers.</p>
pub fn dns_ip_addrs(&self) -> std::option::Option<&[std::string::String]> {
self.dns_ip_addrs.as_deref()
}
/// <p>Information about the VPC settings for the directory.</p>
pub fn vpc_settings(
&self,
) -> std::option::Option<&crate::model::DirectoryVpcSettingsDescription> {
self.vpc_settings.as_ref()
}
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server.</p>
pub fn radius_settings(&self) -> std::option::Option<&crate::model::RadiusSettings> {
self.radius_settings.as_ref()
}
/// <p>Information about the status of the RADIUS server.</p>
pub fn radius_status(&self) -> std::option::Option<&crate::model::RadiusStatus> {
self.radius_status.as_ref()
}
}
impl std::fmt::Debug for OwnerDirectoryDescription {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("OwnerDirectoryDescription");
formatter.field("directory_id", &self.directory_id);
formatter.field("account_id", &self.account_id);
formatter.field("dns_ip_addrs", &self.dns_ip_addrs);
formatter.field("vpc_settings", &self.vpc_settings);
formatter.field("radius_settings", &self.radius_settings);
formatter.field("radius_status", &self.radius_status);
formatter.finish()
}
}
/// See [`OwnerDirectoryDescription`](crate::model::OwnerDirectoryDescription)
pub mod owner_directory_description {
/// A builder for [`OwnerDirectoryDescription`](crate::model::OwnerDirectoryDescription)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) account_id: std::option::Option<std::string::String>,
pub(crate) dns_ip_addrs: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) vpc_settings: std::option::Option<crate::model::DirectoryVpcSettingsDescription>,
pub(crate) radius_settings: std::option::Option<crate::model::RadiusSettings>,
pub(crate) radius_status: std::option::Option<crate::model::RadiusStatus>,
}
impl Builder {
/// <p>Identifier of the Managed Microsoft AD directory in the directory owner account.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier of the Managed Microsoft AD directory in the directory owner account.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>Identifier of the directory owner account.</p>
pub fn account_id(mut self, input: impl Into<std::string::String>) -> Self {
self.account_id = Some(input.into());
self
}
/// <p>Identifier of the directory owner account.</p>
pub fn set_account_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.account_id = input;
self
}
/// Appends an item to `dns_ip_addrs`.
///
/// To override the contents of this collection use [`set_dns_ip_addrs`](Self::set_dns_ip_addrs).
///
/// <p>IP address of the directory’s domain controllers.</p>
pub fn dns_ip_addrs(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.dns_ip_addrs.unwrap_or_default();
v.push(input.into());
self.dns_ip_addrs = Some(v);
self
}
/// <p>IP address of the directory’s domain controllers.</p>
pub fn set_dns_ip_addrs(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.dns_ip_addrs = input;
self
}
/// <p>Information about the VPC settings for the directory.</p>
pub fn vpc_settings(
mut self,
input: crate::model::DirectoryVpcSettingsDescription,
) -> Self {
self.vpc_settings = Some(input);
self
}
/// <p>Information about the VPC settings for the directory.</p>
pub fn set_vpc_settings(
mut self,
input: std::option::Option<crate::model::DirectoryVpcSettingsDescription>,
) -> Self {
self.vpc_settings = input;
self
}
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server.</p>
pub fn radius_settings(mut self, input: crate::model::RadiusSettings) -> Self {
self.radius_settings = Some(input);
self
}
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server.</p>
pub fn set_radius_settings(
mut self,
input: std::option::Option<crate::model::RadiusSettings>,
) -> Self {
self.radius_settings = input;
self
}
/// <p>Information about the status of the RADIUS server.</p>
pub fn radius_status(mut self, input: crate::model::RadiusStatus) -> Self {
self.radius_status = Some(input);
self
}
/// <p>Information about the status of the RADIUS server.</p>
pub fn set_radius_status(
mut self,
input: std::option::Option<crate::model::RadiusStatus>,
) -> Self {
self.radius_status = input;
self
}
/// Consumes the builder and constructs a [`OwnerDirectoryDescription`](crate::model::OwnerDirectoryDescription)
pub fn build(self) -> crate::model::OwnerDirectoryDescription {
crate::model::OwnerDirectoryDescription {
directory_id: self.directory_id,
account_id: self.account_id,
dns_ip_addrs: self.dns_ip_addrs,
vpc_settings: self.vpc_settings,
radius_settings: self.radius_settings,
radius_status: self.radius_status,
}
}
}
}
impl OwnerDirectoryDescription {
/// Creates a new builder-style object to manufacture [`OwnerDirectoryDescription`](crate::model::OwnerDirectoryDescription)
pub fn builder() -> crate::model::owner_directory_description::Builder {
crate::model::owner_directory_description::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum RadiusStatus {
#[allow(missing_docs)] // documentation missing in model
Completed,
#[allow(missing_docs)] // documentation missing in model
Creating,
#[allow(missing_docs)] // documentation missing in model
Failed,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for RadiusStatus {
fn from(s: &str) -> Self {
match s {
"Completed" => RadiusStatus::Completed,
"Creating" => RadiusStatus::Creating,
"Failed" => RadiusStatus::Failed,
other => RadiusStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for RadiusStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(RadiusStatus::from(s))
}
}
impl RadiusStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
RadiusStatus::Completed => "Completed",
RadiusStatus::Creating => "Creating",
RadiusStatus::Failed => "Failed",
RadiusStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["Completed", "Creating", "Failed"]
}
}
impl AsRef<str> for RadiusStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Contains information about the directory.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DirectoryVpcSettingsDescription {
/// <p>The identifier of the VPC that the directory is in.</p>
pub vpc_id: std::option::Option<std::string::String>,
/// <p>The identifiers of the subnets for the directory servers.</p>
pub subnet_ids: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The domain controller security group identifier for the directory.</p>
pub security_group_id: std::option::Option<std::string::String>,
/// <p>The list of Availability Zones that the directory is in.</p>
pub availability_zones: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl DirectoryVpcSettingsDescription {
/// <p>The identifier of the VPC that the directory is in.</p>
pub fn vpc_id(&self) -> std::option::Option<&str> {
self.vpc_id.as_deref()
}
/// <p>The identifiers of the subnets for the directory servers.</p>
pub fn subnet_ids(&self) -> std::option::Option<&[std::string::String]> {
self.subnet_ids.as_deref()
}
/// <p>The domain controller security group identifier for the directory.</p>
pub fn security_group_id(&self) -> std::option::Option<&str> {
self.security_group_id.as_deref()
}
/// <p>The list of Availability Zones that the directory is in.</p>
pub fn availability_zones(&self) -> std::option::Option<&[std::string::String]> {
self.availability_zones.as_deref()
}
}
impl std::fmt::Debug for DirectoryVpcSettingsDescription {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DirectoryVpcSettingsDescription");
formatter.field("vpc_id", &self.vpc_id);
formatter.field("subnet_ids", &self.subnet_ids);
formatter.field("security_group_id", &self.security_group_id);
formatter.field("availability_zones", &self.availability_zones);
formatter.finish()
}
}
/// See [`DirectoryVpcSettingsDescription`](crate::model::DirectoryVpcSettingsDescription)
pub mod directory_vpc_settings_description {
/// A builder for [`DirectoryVpcSettingsDescription`](crate::model::DirectoryVpcSettingsDescription)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) vpc_id: std::option::Option<std::string::String>,
pub(crate) subnet_ids: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) security_group_id: std::option::Option<std::string::String>,
pub(crate) availability_zones: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl Builder {
/// <p>The identifier of the VPC that the directory is in.</p>
pub fn vpc_id(mut self, input: impl Into<std::string::String>) -> Self {
self.vpc_id = Some(input.into());
self
}
/// <p>The identifier of the VPC that the directory is in.</p>
pub fn set_vpc_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.vpc_id = input;
self
}
/// Appends an item to `subnet_ids`.
///
/// To override the contents of this collection use [`set_subnet_ids`](Self::set_subnet_ids).
///
/// <p>The identifiers of the subnets for the directory servers.</p>
pub fn subnet_ids(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.subnet_ids.unwrap_or_default();
v.push(input.into());
self.subnet_ids = Some(v);
self
}
/// <p>The identifiers of the subnets for the directory servers.</p>
pub fn set_subnet_ids(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.subnet_ids = input;
self
}
/// <p>The domain controller security group identifier for the directory.</p>
pub fn security_group_id(mut self, input: impl Into<std::string::String>) -> Self {
self.security_group_id = Some(input.into());
self
}
/// <p>The domain controller security group identifier for the directory.</p>
pub fn set_security_group_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.security_group_id = input;
self
}
/// Appends an item to `availability_zones`.
///
/// To override the contents of this collection use [`set_availability_zones`](Self::set_availability_zones).
///
/// <p>The list of Availability Zones that the directory is in.</p>
pub fn availability_zones(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.availability_zones.unwrap_or_default();
v.push(input.into());
self.availability_zones = Some(v);
self
}
/// <p>The list of Availability Zones that the directory is in.</p>
pub fn set_availability_zones(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.availability_zones = input;
self
}
/// Consumes the builder and constructs a [`DirectoryVpcSettingsDescription`](crate::model::DirectoryVpcSettingsDescription)
pub fn build(self) -> crate::model::DirectoryVpcSettingsDescription {
crate::model::DirectoryVpcSettingsDescription {
vpc_id: self.vpc_id,
subnet_ids: self.subnet_ids,
security_group_id: self.security_group_id,
availability_zones: self.availability_zones,
}
}
}
}
impl DirectoryVpcSettingsDescription {
/// Creates a new builder-style object to manufacture [`DirectoryVpcSettingsDescription`](crate::model::DirectoryVpcSettingsDescription)
pub fn builder() -> crate::model::directory_vpc_settings_description::Builder {
crate::model::directory_vpc_settings_description::Builder::default()
}
}
/// <p>Contains information about an AD Connector directory.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DirectoryConnectSettingsDescription {
/// <p>The identifier of the VPC that the AD Connector is in.</p>
pub vpc_id: std::option::Option<std::string::String>,
/// <p>A list of subnet identifiers in the VPC that the AD Connector is in.</p>
pub subnet_ids: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The user name of the service account in your self-managed directory.</p>
pub customer_user_name: std::option::Option<std::string::String>,
/// <p>The security group identifier for the AD Connector directory.</p>
pub security_group_id: std::option::Option<std::string::String>,
/// <p>A list of the Availability Zones that the directory is in.</p>
pub availability_zones: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The IP addresses of the AD Connector servers.</p>
pub connect_ips: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl DirectoryConnectSettingsDescription {
/// <p>The identifier of the VPC that the AD Connector is in.</p>
pub fn vpc_id(&self) -> std::option::Option<&str> {
self.vpc_id.as_deref()
}
/// <p>A list of subnet identifiers in the VPC that the AD Connector is in.</p>
pub fn subnet_ids(&self) -> std::option::Option<&[std::string::String]> {
self.subnet_ids.as_deref()
}
/// <p>The user name of the service account in your self-managed directory.</p>
pub fn customer_user_name(&self) -> std::option::Option<&str> {
self.customer_user_name.as_deref()
}
/// <p>The security group identifier for the AD Connector directory.</p>
pub fn security_group_id(&self) -> std::option::Option<&str> {
self.security_group_id.as_deref()
}
/// <p>A list of the Availability Zones that the directory is in.</p>
pub fn availability_zones(&self) -> std::option::Option<&[std::string::String]> {
self.availability_zones.as_deref()
}
/// <p>The IP addresses of the AD Connector servers.</p>
pub fn connect_ips(&self) -> std::option::Option<&[std::string::String]> {
self.connect_ips.as_deref()
}
}
impl std::fmt::Debug for DirectoryConnectSettingsDescription {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DirectoryConnectSettingsDescription");
formatter.field("vpc_id", &self.vpc_id);
formatter.field("subnet_ids", &self.subnet_ids);
formatter.field("customer_user_name", &self.customer_user_name);
formatter.field("security_group_id", &self.security_group_id);
formatter.field("availability_zones", &self.availability_zones);
formatter.field("connect_ips", &self.connect_ips);
formatter.finish()
}
}
/// See [`DirectoryConnectSettingsDescription`](crate::model::DirectoryConnectSettingsDescription)
pub mod directory_connect_settings_description {
/// A builder for [`DirectoryConnectSettingsDescription`](crate::model::DirectoryConnectSettingsDescription)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) vpc_id: std::option::Option<std::string::String>,
pub(crate) subnet_ids: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) customer_user_name: std::option::Option<std::string::String>,
pub(crate) security_group_id: std::option::Option<std::string::String>,
pub(crate) availability_zones: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) connect_ips: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl Builder {
/// <p>The identifier of the VPC that the AD Connector is in.</p>
pub fn vpc_id(mut self, input: impl Into<std::string::String>) -> Self {
self.vpc_id = Some(input.into());
self
}
/// <p>The identifier of the VPC that the AD Connector is in.</p>
pub fn set_vpc_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.vpc_id = input;
self
}
/// Appends an item to `subnet_ids`.
///
/// To override the contents of this collection use [`set_subnet_ids`](Self::set_subnet_ids).
///
/// <p>A list of subnet identifiers in the VPC that the AD Connector is in.</p>
pub fn subnet_ids(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.subnet_ids.unwrap_or_default();
v.push(input.into());
self.subnet_ids = Some(v);
self
}
/// <p>A list of subnet identifiers in the VPC that the AD Connector is in.</p>
pub fn set_subnet_ids(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.subnet_ids = input;
self
}
/// <p>The user name of the service account in your self-managed directory.</p>
pub fn customer_user_name(mut self, input: impl Into<std::string::String>) -> Self {
self.customer_user_name = Some(input.into());
self
}
/// <p>The user name of the service account in your self-managed directory.</p>
pub fn set_customer_user_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.customer_user_name = input;
self
}
/// <p>The security group identifier for the AD Connector directory.</p>
pub fn security_group_id(mut self, input: impl Into<std::string::String>) -> Self {
self.security_group_id = Some(input.into());
self
}
/// <p>The security group identifier for the AD Connector directory.</p>
pub fn set_security_group_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.security_group_id = input;
self
}
/// Appends an item to `availability_zones`.
///
/// To override the contents of this collection use [`set_availability_zones`](Self::set_availability_zones).
///
/// <p>A list of the Availability Zones that the directory is in.</p>
pub fn availability_zones(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.availability_zones.unwrap_or_default();
v.push(input.into());
self.availability_zones = Some(v);
self
}
/// <p>A list of the Availability Zones that the directory is in.</p>
pub fn set_availability_zones(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.availability_zones = input;
self
}
/// Appends an item to `connect_ips`.
///
/// To override the contents of this collection use [`set_connect_ips`](Self::set_connect_ips).
///
/// <p>The IP addresses of the AD Connector servers.</p>
pub fn connect_ips(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.connect_ips.unwrap_or_default();
v.push(input.into());
self.connect_ips = Some(v);
self
}
/// <p>The IP addresses of the AD Connector servers.</p>
pub fn set_connect_ips(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.connect_ips = input;
self
}
/// Consumes the builder and constructs a [`DirectoryConnectSettingsDescription`](crate::model::DirectoryConnectSettingsDescription)
pub fn build(self) -> crate::model::DirectoryConnectSettingsDescription {
crate::model::DirectoryConnectSettingsDescription {
vpc_id: self.vpc_id,
subnet_ids: self.subnet_ids,
customer_user_name: self.customer_user_name,
security_group_id: self.security_group_id,
availability_zones: self.availability_zones,
connect_ips: self.connect_ips,
}
}
}
}
impl DirectoryConnectSettingsDescription {
/// Creates a new builder-style object to manufacture [`DirectoryConnectSettingsDescription`](crate::model::DirectoryConnectSettingsDescription)
pub fn builder() -> crate::model::directory_connect_settings_description::Builder {
crate::model::directory_connect_settings_description::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum DirectoryType {
#[allow(missing_docs)] // documentation missing in model
AdConnector,
#[allow(missing_docs)] // documentation missing in model
MicrosoftAd,
#[allow(missing_docs)] // documentation missing in model
SharedMicrosoftAd,
#[allow(missing_docs)] // documentation missing in model
SimpleAd,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for DirectoryType {
fn from(s: &str) -> Self {
match s {
"ADConnector" => DirectoryType::AdConnector,
"MicrosoftAD" => DirectoryType::MicrosoftAd,
"SharedMicrosoftAD" => DirectoryType::SharedMicrosoftAd,
"SimpleAD" => DirectoryType::SimpleAd,
other => DirectoryType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for DirectoryType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(DirectoryType::from(s))
}
}
impl DirectoryType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
DirectoryType::AdConnector => "ADConnector",
DirectoryType::MicrosoftAd => "MicrosoftAD",
DirectoryType::SharedMicrosoftAd => "SharedMicrosoftAD",
DirectoryType::SimpleAd => "SimpleAD",
DirectoryType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"ADConnector",
"MicrosoftAD",
"SharedMicrosoftAD",
"SimpleAD",
]
}
}
impl AsRef<str> for DirectoryType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum DirectoryEdition {
#[allow(missing_docs)] // documentation missing in model
Enterprise,
#[allow(missing_docs)] // documentation missing in model
Standard,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for DirectoryEdition {
fn from(s: &str) -> Self {
match s {
"Enterprise" => DirectoryEdition::Enterprise,
"Standard" => DirectoryEdition::Standard,
other => DirectoryEdition::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for DirectoryEdition {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(DirectoryEdition::from(s))
}
}
impl DirectoryEdition {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
DirectoryEdition::Enterprise => "Enterprise",
DirectoryEdition::Standard => "Standard",
DirectoryEdition::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["Enterprise", "Standard"]
}
}
impl AsRef<str> for DirectoryEdition {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum DirectorySize {
#[allow(missing_docs)] // documentation missing in model
Large,
#[allow(missing_docs)] // documentation missing in model
Small,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for DirectorySize {
fn from(s: &str) -> Self {
match s {
"Large" => DirectorySize::Large,
"Small" => DirectorySize::Small,
other => DirectorySize::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for DirectorySize {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(DirectorySize::from(s))
}
}
impl DirectorySize {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
DirectorySize::Large => "Large",
DirectorySize::Small => "Small",
DirectorySize::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["Large", "Small"]
}
}
impl AsRef<str> for DirectorySize {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Points to a remote domain with which you are setting up a trust relationship. Conditional forwarders are required in order to set up a trust relationship with another domain.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ConditionalForwarder {
/// <p>The fully qualified domain name (FQDN) of the remote domains pointed to by the conditional forwarder.</p>
pub remote_domain_name: std::option::Option<std::string::String>,
/// <p>The IP addresses of the remote DNS server associated with RemoteDomainName. This is the IP address of the DNS server that your conditional forwarder points to.</p>
pub dns_ip_addrs: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The replication scope of the conditional forwarder. The only allowed value is <code>Domain</code>, which will replicate the conditional forwarder to all of the domain controllers for your Amazon Web Services directory.</p>
pub replication_scope: std::option::Option<crate::model::ReplicationScope>,
}
impl ConditionalForwarder {
/// <p>The fully qualified domain name (FQDN) of the remote domains pointed to by the conditional forwarder.</p>
pub fn remote_domain_name(&self) -> std::option::Option<&str> {
self.remote_domain_name.as_deref()
}
/// <p>The IP addresses of the remote DNS server associated with RemoteDomainName. This is the IP address of the DNS server that your conditional forwarder points to.</p>
pub fn dns_ip_addrs(&self) -> std::option::Option<&[std::string::String]> {
self.dns_ip_addrs.as_deref()
}
/// <p>The replication scope of the conditional forwarder. The only allowed value is <code>Domain</code>, which will replicate the conditional forwarder to all of the domain controllers for your Amazon Web Services directory.</p>
pub fn replication_scope(&self) -> std::option::Option<&crate::model::ReplicationScope> {
self.replication_scope.as_ref()
}
}
impl std::fmt::Debug for ConditionalForwarder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ConditionalForwarder");
formatter.field("remote_domain_name", &self.remote_domain_name);
formatter.field("dns_ip_addrs", &self.dns_ip_addrs);
formatter.field("replication_scope", &self.replication_scope);
formatter.finish()
}
}
/// See [`ConditionalForwarder`](crate::model::ConditionalForwarder)
pub mod conditional_forwarder {
/// A builder for [`ConditionalForwarder`](crate::model::ConditionalForwarder)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) remote_domain_name: std::option::Option<std::string::String>,
pub(crate) dns_ip_addrs: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) replication_scope: std::option::Option<crate::model::ReplicationScope>,
}
impl Builder {
/// <p>The fully qualified domain name (FQDN) of the remote domains pointed to by the conditional forwarder.</p>
pub fn remote_domain_name(mut self, input: impl Into<std::string::String>) -> Self {
self.remote_domain_name = Some(input.into());
self
}
/// <p>The fully qualified domain name (FQDN) of the remote domains pointed to by the conditional forwarder.</p>
pub fn set_remote_domain_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.remote_domain_name = input;
self
}
/// Appends an item to `dns_ip_addrs`.
///
/// To override the contents of this collection use [`set_dns_ip_addrs`](Self::set_dns_ip_addrs).
///
/// <p>The IP addresses of the remote DNS server associated with RemoteDomainName. This is the IP address of the DNS server that your conditional forwarder points to.</p>
pub fn dns_ip_addrs(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.dns_ip_addrs.unwrap_or_default();
v.push(input.into());
self.dns_ip_addrs = Some(v);
self
}
/// <p>The IP addresses of the remote DNS server associated with RemoteDomainName. This is the IP address of the DNS server that your conditional forwarder points to.</p>
pub fn set_dns_ip_addrs(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.dns_ip_addrs = input;
self
}
/// <p>The replication scope of the conditional forwarder. The only allowed value is <code>Domain</code>, which will replicate the conditional forwarder to all of the domain controllers for your Amazon Web Services directory.</p>
pub fn replication_scope(mut self, input: crate::model::ReplicationScope) -> Self {
self.replication_scope = Some(input);
self
}
/// <p>The replication scope of the conditional forwarder. The only allowed value is <code>Domain</code>, which will replicate the conditional forwarder to all of the domain controllers for your Amazon Web Services directory.</p>
pub fn set_replication_scope(
mut self,
input: std::option::Option<crate::model::ReplicationScope>,
) -> Self {
self.replication_scope = input;
self
}
/// Consumes the builder and constructs a [`ConditionalForwarder`](crate::model::ConditionalForwarder)
pub fn build(self) -> crate::model::ConditionalForwarder {
crate::model::ConditionalForwarder {
remote_domain_name: self.remote_domain_name,
dns_ip_addrs: self.dns_ip_addrs,
replication_scope: self.replication_scope,
}
}
}
}
impl ConditionalForwarder {
/// Creates a new builder-style object to manufacture [`ConditionalForwarder`](crate::model::ConditionalForwarder)
pub fn builder() -> crate::model::conditional_forwarder::Builder {
crate::model::conditional_forwarder::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ReplicationScope {
#[allow(missing_docs)] // documentation missing in model
Domain,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ReplicationScope {
fn from(s: &str) -> Self {
match s {
"Domain" => ReplicationScope::Domain,
other => ReplicationScope::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ReplicationScope {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ReplicationScope::from(s))
}
}
impl ReplicationScope {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ReplicationScope::Domain => "Domain",
ReplicationScope::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["Domain"]
}
}
impl AsRef<str> for ReplicationScope {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Contains information about a client authentication method for a directory.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ClientAuthenticationSettingInfo {
/// <p>The type of client authentication for the specified directory. If no type is specified, a list of all client authentication types that are supported for the directory is retrieved. </p>
pub r#type: std::option::Option<crate::model::ClientAuthenticationType>,
/// <p>Whether the client authentication type is enabled or disabled for the specified directory.</p>
pub status: std::option::Option<crate::model::ClientAuthenticationStatus>,
/// <p>The date and time when the status of the client authentication type was last updated.</p>
pub last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl ClientAuthenticationSettingInfo {
/// <p>The type of client authentication for the specified directory. If no type is specified, a list of all client authentication types that are supported for the directory is retrieved. </p>
pub fn r#type(&self) -> std::option::Option<&crate::model::ClientAuthenticationType> {
self.r#type.as_ref()
}
/// <p>Whether the client authentication type is enabled or disabled for the specified directory.</p>
pub fn status(&self) -> std::option::Option<&crate::model::ClientAuthenticationStatus> {
self.status.as_ref()
}
/// <p>The date and time when the status of the client authentication type was last updated.</p>
pub fn last_updated_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.last_updated_date_time.as_ref()
}
}
impl std::fmt::Debug for ClientAuthenticationSettingInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ClientAuthenticationSettingInfo");
formatter.field("r#type", &self.r#type);
formatter.field("status", &self.status);
formatter.field("last_updated_date_time", &self.last_updated_date_time);
formatter.finish()
}
}
/// See [`ClientAuthenticationSettingInfo`](crate::model::ClientAuthenticationSettingInfo)
pub mod client_authentication_setting_info {
/// A builder for [`ClientAuthenticationSettingInfo`](crate::model::ClientAuthenticationSettingInfo)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) r#type: std::option::Option<crate::model::ClientAuthenticationType>,
pub(crate) status: std::option::Option<crate::model::ClientAuthenticationStatus>,
pub(crate) last_updated_date_time: std::option::Option<aws_smithy_types::DateTime>,
}
impl Builder {
/// <p>The type of client authentication for the specified directory. If no type is specified, a list of all client authentication types that are supported for the directory is retrieved. </p>
pub fn r#type(mut self, input: crate::model::ClientAuthenticationType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The type of client authentication for the specified directory. If no type is specified, a list of all client authentication types that are supported for the directory is retrieved. </p>
pub fn set_type(
mut self,
input: std::option::Option<crate::model::ClientAuthenticationType>,
) -> Self {
self.r#type = input;
self
}
/// <p>Whether the client authentication type is enabled or disabled for the specified directory.</p>
pub fn status(mut self, input: crate::model::ClientAuthenticationStatus) -> Self {
self.status = Some(input);
self
}
/// <p>Whether the client authentication type is enabled or disabled for the specified directory.</p>
pub fn set_status(
mut self,
input: std::option::Option<crate::model::ClientAuthenticationStatus>,
) -> Self {
self.status = input;
self
}
/// <p>The date and time when the status of the client authentication type was last updated.</p>
pub fn last_updated_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.last_updated_date_time = Some(input);
self
}
/// <p>The date and time when the status of the client authentication type was last updated.</p>
pub fn set_last_updated_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.last_updated_date_time = input;
self
}
/// Consumes the builder and constructs a [`ClientAuthenticationSettingInfo`](crate::model::ClientAuthenticationSettingInfo)
pub fn build(self) -> crate::model::ClientAuthenticationSettingInfo {
crate::model::ClientAuthenticationSettingInfo {
r#type: self.r#type,
status: self.status,
last_updated_date_time: self.last_updated_date_time,
}
}
}
}
impl ClientAuthenticationSettingInfo {
/// Creates a new builder-style object to manufacture [`ClientAuthenticationSettingInfo`](crate::model::ClientAuthenticationSettingInfo)
pub fn builder() -> crate::model::client_authentication_setting_info::Builder {
crate::model::client_authentication_setting_info::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ClientAuthenticationStatus {
#[allow(missing_docs)] // documentation missing in model
Disabled,
#[allow(missing_docs)] // documentation missing in model
Enabled,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ClientAuthenticationStatus {
fn from(s: &str) -> Self {
match s {
"Disabled" => ClientAuthenticationStatus::Disabled,
"Enabled" => ClientAuthenticationStatus::Enabled,
other => ClientAuthenticationStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ClientAuthenticationStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ClientAuthenticationStatus::from(s))
}
}
impl ClientAuthenticationStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ClientAuthenticationStatus::Disabled => "Disabled",
ClientAuthenticationStatus::Enabled => "Enabled",
ClientAuthenticationStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["Disabled", "Enabled"]
}
}
impl AsRef<str> for ClientAuthenticationStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Information about the certificate.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct Certificate {
/// <p>The identifier of the certificate.</p>
pub certificate_id: std::option::Option<std::string::String>,
/// <p>The state of the certificate.</p>
pub state: std::option::Option<crate::model::CertificateState>,
/// <p>Describes a state change for the certificate.</p>
pub state_reason: std::option::Option<std::string::String>,
/// <p>The common name for the certificate.</p>
pub common_name: std::option::Option<std::string::String>,
/// <p>The date and time that the certificate was registered.</p>
pub registered_date_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The date and time when the certificate will expire.</p>
pub expiry_date_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The function that the registered certificate performs. Valid values include <code>ClientLDAPS</code> or <code>ClientCertAuth</code>. The default value is <code>ClientLDAPS</code>.</p>
pub r#type: std::option::Option<crate::model::CertificateType>,
/// <p>A <code>ClientCertAuthSettings</code> object that contains client certificate authentication settings.</p>
pub client_cert_auth_settings: std::option::Option<crate::model::ClientCertAuthSettings>,
}
impl Certificate {
/// <p>The identifier of the certificate.</p>
pub fn certificate_id(&self) -> std::option::Option<&str> {
self.certificate_id.as_deref()
}
/// <p>The state of the certificate.</p>
pub fn state(&self) -> std::option::Option<&crate::model::CertificateState> {
self.state.as_ref()
}
/// <p>Describes a state change for the certificate.</p>
pub fn state_reason(&self) -> std::option::Option<&str> {
self.state_reason.as_deref()
}
/// <p>The common name for the certificate.</p>
pub fn common_name(&self) -> std::option::Option<&str> {
self.common_name.as_deref()
}
/// <p>The date and time that the certificate was registered.</p>
pub fn registered_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.registered_date_time.as_ref()
}
/// <p>The date and time when the certificate will expire.</p>
pub fn expiry_date_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.expiry_date_time.as_ref()
}
/// <p>The function that the registered certificate performs. Valid values include <code>ClientLDAPS</code> or <code>ClientCertAuth</code>. The default value is <code>ClientLDAPS</code>.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::CertificateType> {
self.r#type.as_ref()
}
/// <p>A <code>ClientCertAuthSettings</code> object that contains client certificate authentication settings.</p>
pub fn client_cert_auth_settings(
&self,
) -> std::option::Option<&crate::model::ClientCertAuthSettings> {
self.client_cert_auth_settings.as_ref()
}
}
impl std::fmt::Debug for Certificate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("Certificate");
formatter.field("certificate_id", &self.certificate_id);
formatter.field("state", &self.state);
formatter.field("state_reason", &self.state_reason);
formatter.field("common_name", &self.common_name);
formatter.field("registered_date_time", &self.registered_date_time);
formatter.field("expiry_date_time", &self.expiry_date_time);
formatter.field("r#type", &self.r#type);
formatter.field("client_cert_auth_settings", &self.client_cert_auth_settings);
formatter.finish()
}
}
/// See [`Certificate`](crate::model::Certificate)
pub mod certificate {
/// A builder for [`Certificate`](crate::model::Certificate)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_id: std::option::Option<std::string::String>,
pub(crate) state: std::option::Option<crate::model::CertificateState>,
pub(crate) state_reason: std::option::Option<std::string::String>,
pub(crate) common_name: std::option::Option<std::string::String>,
pub(crate) registered_date_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) expiry_date_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) r#type: std::option::Option<crate::model::CertificateType>,
pub(crate) client_cert_auth_settings:
std::option::Option<crate::model::ClientCertAuthSettings>,
}
impl Builder {
/// <p>The identifier of the certificate.</p>
pub fn certificate_id(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_id = Some(input.into());
self
}
/// <p>The identifier of the certificate.</p>
pub fn set_certificate_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_id = input;
self
}
/// <p>The state of the certificate.</p>
pub fn state(mut self, input: crate::model::CertificateState) -> Self {
self.state = Some(input);
self
}
/// <p>The state of the certificate.</p>
pub fn set_state(
mut self,
input: std::option::Option<crate::model::CertificateState>,
) -> Self {
self.state = input;
self
}
/// <p>Describes a state change for the certificate.</p>
pub fn state_reason(mut self, input: impl Into<std::string::String>) -> Self {
self.state_reason = Some(input.into());
self
}
/// <p>Describes a state change for the certificate.</p>
pub fn set_state_reason(mut self, input: std::option::Option<std::string::String>) -> Self {
self.state_reason = input;
self
}
/// <p>The common name for the certificate.</p>
pub fn common_name(mut self, input: impl Into<std::string::String>) -> Self {
self.common_name = Some(input.into());
self
}
/// <p>The common name for the certificate.</p>
pub fn set_common_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.common_name = input;
self
}
/// <p>The date and time that the certificate was registered.</p>
pub fn registered_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.registered_date_time = Some(input);
self
}
/// <p>The date and time that the certificate was registered.</p>
pub fn set_registered_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.registered_date_time = input;
self
}
/// <p>The date and time when the certificate will expire.</p>
pub fn expiry_date_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.expiry_date_time = Some(input);
self
}
/// <p>The date and time when the certificate will expire.</p>
pub fn set_expiry_date_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.expiry_date_time = input;
self
}
/// <p>The function that the registered certificate performs. Valid values include <code>ClientLDAPS</code> or <code>ClientCertAuth</code>. The default value is <code>ClientLDAPS</code>.</p>
pub fn r#type(mut self, input: crate::model::CertificateType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The function that the registered certificate performs. Valid values include <code>ClientLDAPS</code> or <code>ClientCertAuth</code>. The default value is <code>ClientLDAPS</code>.</p>
pub fn set_type(
mut self,
input: std::option::Option<crate::model::CertificateType>,
) -> Self {
self.r#type = input;
self
}
/// <p>A <code>ClientCertAuthSettings</code> object that contains client certificate authentication settings.</p>
pub fn client_cert_auth_settings(
mut self,
input: crate::model::ClientCertAuthSettings,
) -> Self {
self.client_cert_auth_settings = Some(input);
self
}
/// <p>A <code>ClientCertAuthSettings</code> object that contains client certificate authentication settings.</p>
pub fn set_client_cert_auth_settings(
mut self,
input: std::option::Option<crate::model::ClientCertAuthSettings>,
) -> Self {
self.client_cert_auth_settings = input;
self
}
/// Consumes the builder and constructs a [`Certificate`](crate::model::Certificate)
pub fn build(self) -> crate::model::Certificate {
crate::model::Certificate {
certificate_id: self.certificate_id,
state: self.state,
state_reason: self.state_reason,
common_name: self.common_name,
registered_date_time: self.registered_date_time,
expiry_date_time: self.expiry_date_time,
r#type: self.r#type,
client_cert_auth_settings: self.client_cert_auth_settings,
}
}
}
}
impl Certificate {
/// Creates a new builder-style object to manufacture [`Certificate`](crate::model::Certificate)
pub fn builder() -> crate::model::certificate::Builder {
crate::model::certificate::Builder::default()
}
}
/// <p>Contains information about a computer account in a directory.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct Computer {
/// <p>The identifier of the computer.</p>
pub computer_id: std::option::Option<std::string::String>,
/// <p>The computer name.</p>
pub computer_name: std::option::Option<std::string::String>,
/// <p>An array of <code>Attribute</code> objects containing the LDAP attributes that belong to the computer account.</p>
pub computer_attributes: std::option::Option<std::vec::Vec<crate::model::Attribute>>,
}
impl Computer {
/// <p>The identifier of the computer.</p>
pub fn computer_id(&self) -> std::option::Option<&str> {
self.computer_id.as_deref()
}
/// <p>The computer name.</p>
pub fn computer_name(&self) -> std::option::Option<&str> {
self.computer_name.as_deref()
}
/// <p>An array of <code>Attribute</code> objects containing the LDAP attributes that belong to the computer account.</p>
pub fn computer_attributes(&self) -> std::option::Option<&[crate::model::Attribute]> {
self.computer_attributes.as_deref()
}
}
impl std::fmt::Debug for Computer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("Computer");
formatter.field("computer_id", &self.computer_id);
formatter.field("computer_name", &self.computer_name);
formatter.field("computer_attributes", &self.computer_attributes);
formatter.finish()
}
}
/// See [`Computer`](crate::model::Computer)
pub mod computer {
/// A builder for [`Computer`](crate::model::Computer)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) computer_id: std::option::Option<std::string::String>,
pub(crate) computer_name: std::option::Option<std::string::String>,
pub(crate) computer_attributes: std::option::Option<std::vec::Vec<crate::model::Attribute>>,
}
impl Builder {
/// <p>The identifier of the computer.</p>
pub fn computer_id(mut self, input: impl Into<std::string::String>) -> Self {
self.computer_id = Some(input.into());
self
}
/// <p>The identifier of the computer.</p>
pub fn set_computer_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.computer_id = input;
self
}
/// <p>The computer name.</p>
pub fn computer_name(mut self, input: impl Into<std::string::String>) -> Self {
self.computer_name = Some(input.into());
self
}
/// <p>The computer name.</p>
pub fn set_computer_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.computer_name = input;
self
}
/// Appends an item to `computer_attributes`.
///
/// To override the contents of this collection use [`set_computer_attributes`](Self::set_computer_attributes).
///
/// <p>An array of <code>Attribute</code> objects containing the LDAP attributes that belong to the computer account.</p>
pub fn computer_attributes(mut self, input: crate::model::Attribute) -> Self {
let mut v = self.computer_attributes.unwrap_or_default();
v.push(input);
self.computer_attributes = Some(v);
self
}
/// <p>An array of <code>Attribute</code> objects containing the LDAP attributes that belong to the computer account.</p>
pub fn set_computer_attributes(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Attribute>>,
) -> Self {
self.computer_attributes = input;
self
}
/// Consumes the builder and constructs a [`Computer`](crate::model::Computer)
pub fn build(self) -> crate::model::Computer {
crate::model::Computer {
computer_id: self.computer_id,
computer_name: self.computer_name,
computer_attributes: self.computer_attributes,
}
}
}
}
impl Computer {
/// Creates a new builder-style object to manufacture [`Computer`](crate::model::Computer)
pub fn builder() -> crate::model::computer::Builder {
crate::model::computer::Builder::default()
}
}
/// <p>Represents a named directory attribute.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct Attribute {
/// <p>The name of the attribute.</p>
pub name: std::option::Option<std::string::String>,
/// <p>The value of the attribute.</p>
pub value: std::option::Option<std::string::String>,
}
impl Attribute {
/// <p>The name of the attribute.</p>
pub fn name(&self) -> std::option::Option<&str> {
self.name.as_deref()
}
/// <p>The value of the attribute.</p>
pub fn value(&self) -> std::option::Option<&str> {
self.value.as_deref()
}
}
impl std::fmt::Debug for Attribute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("Attribute");
formatter.field("name", &self.name);
formatter.field("value", &self.value);
formatter.finish()
}
}
/// See [`Attribute`](crate::model::Attribute)
pub mod attribute {
/// A builder for [`Attribute`](crate::model::Attribute)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) name: std::option::Option<std::string::String>,
pub(crate) value: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The name of the attribute.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.name = Some(input.into());
self
}
/// <p>The name of the attribute.</p>
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.name = input;
self
}
/// <p>The value of the attribute.</p>
pub fn value(mut self, input: impl Into<std::string::String>) -> Self {
self.value = Some(input.into());
self
}
/// <p>The value of the attribute.</p>
pub fn set_value(mut self, input: std::option::Option<std::string::String>) -> Self {
self.value = input;
self
}
/// Consumes the builder and constructs a [`Attribute`](crate::model::Attribute)
pub fn build(self) -> crate::model::Attribute {
crate::model::Attribute {
name: self.name,
value: self.value,
}
}
}
}
impl Attribute {
/// Creates a new builder-style object to manufacture [`Attribute`](crate::model::Attribute)
pub fn builder() -> crate::model::attribute::Builder {
crate::model::attribute::Builder::default()
}
}
/// <p>Contains information for the <code>ConnectDirectory</code> operation when an AD Connector directory is being created.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DirectoryConnectSettings {
/// <p>The identifier of the VPC in which the AD Connector is created.</p>
pub vpc_id: std::option::Option<std::string::String>,
/// <p>A list of subnet identifiers in the VPC in which the AD Connector is created.</p>
pub subnet_ids: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>A list of one or more IP addresses of DNS servers or domain controllers in your self-managed directory.</p>
pub customer_dns_ips: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The user name of an account in your self-managed directory that is used to connect to the directory. This account must have the following permissions:</p>
/// <ul>
/// <li> <p>Read users and groups</p> </li>
/// <li> <p>Create computer objects</p> </li>
/// <li> <p>Join computers to the domain</p> </li>
/// </ul>
pub customer_user_name: std::option::Option<std::string::String>,
}
impl DirectoryConnectSettings {
/// <p>The identifier of the VPC in which the AD Connector is created.</p>
pub fn vpc_id(&self) -> std::option::Option<&str> {
self.vpc_id.as_deref()
}
/// <p>A list of subnet identifiers in the VPC in which the AD Connector is created.</p>
pub fn subnet_ids(&self) -> std::option::Option<&[std::string::String]> {
self.subnet_ids.as_deref()
}
/// <p>A list of one or more IP addresses of DNS servers or domain controllers in your self-managed directory.</p>
pub fn customer_dns_ips(&self) -> std::option::Option<&[std::string::String]> {
self.customer_dns_ips.as_deref()
}
/// <p>The user name of an account in your self-managed directory that is used to connect to the directory. This account must have the following permissions:</p>
/// <ul>
/// <li> <p>Read users and groups</p> </li>
/// <li> <p>Create computer objects</p> </li>
/// <li> <p>Join computers to the domain</p> </li>
/// </ul>
pub fn customer_user_name(&self) -> std::option::Option<&str> {
self.customer_user_name.as_deref()
}
}
impl std::fmt::Debug for DirectoryConnectSettings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DirectoryConnectSettings");
formatter.field("vpc_id", &self.vpc_id);
formatter.field("subnet_ids", &self.subnet_ids);
formatter.field("customer_dns_ips", &self.customer_dns_ips);
formatter.field("customer_user_name", &self.customer_user_name);
formatter.finish()
}
}
/// See [`DirectoryConnectSettings`](crate::model::DirectoryConnectSettings)
pub mod directory_connect_settings {
/// A builder for [`DirectoryConnectSettings`](crate::model::DirectoryConnectSettings)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) vpc_id: std::option::Option<std::string::String>,
pub(crate) subnet_ids: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) customer_dns_ips: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) customer_user_name: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the VPC in which the AD Connector is created.</p>
pub fn vpc_id(mut self, input: impl Into<std::string::String>) -> Self {
self.vpc_id = Some(input.into());
self
}
/// <p>The identifier of the VPC in which the AD Connector is created.</p>
pub fn set_vpc_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.vpc_id = input;
self
}
/// Appends an item to `subnet_ids`.
///
/// To override the contents of this collection use [`set_subnet_ids`](Self::set_subnet_ids).
///
/// <p>A list of subnet identifiers in the VPC in which the AD Connector is created.</p>
pub fn subnet_ids(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.subnet_ids.unwrap_or_default();
v.push(input.into());
self.subnet_ids = Some(v);
self
}
/// <p>A list of subnet identifiers in the VPC in which the AD Connector is created.</p>
pub fn set_subnet_ids(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.subnet_ids = input;
self
}
/// Appends an item to `customer_dns_ips`.
///
/// To override the contents of this collection use [`set_customer_dns_ips`](Self::set_customer_dns_ips).
///
/// <p>A list of one or more IP addresses of DNS servers or domain controllers in your self-managed directory.</p>
pub fn customer_dns_ips(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.customer_dns_ips.unwrap_or_default();
v.push(input.into());
self.customer_dns_ips = Some(v);
self
}
/// <p>A list of one or more IP addresses of DNS servers or domain controllers in your self-managed directory.</p>
pub fn set_customer_dns_ips(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.customer_dns_ips = input;
self
}
/// <p>The user name of an account in your self-managed directory that is used to connect to the directory. This account must have the following permissions:</p>
/// <ul>
/// <li> <p>Read users and groups</p> </li>
/// <li> <p>Create computer objects</p> </li>
/// <li> <p>Join computers to the domain</p> </li>
/// </ul>
pub fn customer_user_name(mut self, input: impl Into<std::string::String>) -> Self {
self.customer_user_name = Some(input.into());
self
}
/// <p>The user name of an account in your self-managed directory that is used to connect to the directory. This account must have the following permissions:</p>
/// <ul>
/// <li> <p>Read users and groups</p> </li>
/// <li> <p>Create computer objects</p> </li>
/// <li> <p>Join computers to the domain</p> </li>
/// </ul>
pub fn set_customer_user_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.customer_user_name = input;
self
}
/// Consumes the builder and constructs a [`DirectoryConnectSettings`](crate::model::DirectoryConnectSettings)
pub fn build(self) -> crate::model::DirectoryConnectSettings {
crate::model::DirectoryConnectSettings {
vpc_id: self.vpc_id,
subnet_ids: self.subnet_ids,
customer_dns_ips: self.customer_dns_ips,
customer_user_name: self.customer_user_name,
}
}
}
}
impl DirectoryConnectSettings {
/// Creates a new builder-style object to manufacture [`DirectoryConnectSettings`](crate::model::DirectoryConnectSettings)
pub fn builder() -> crate::model::directory_connect_settings::Builder {
crate::model::directory_connect_settings::Builder::default()
}
}
/// <p>IP address block. This is often the address block of the DNS server used for your self-managed domain. </p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct IpRoute {
/// <p>IP address block using CIDR format, for example 10.0.0.0/24. This is often the address block of the DNS server used for your self-managed domain. For a single IP address use a CIDR address block with /32. For example 10.0.0.0/32.</p>
pub cidr_ip: std::option::Option<std::string::String>,
/// <p>Description of the address block.</p>
pub description: std::option::Option<std::string::String>,
}
impl IpRoute {
/// <p>IP address block using CIDR format, for example 10.0.0.0/24. This is often the address block of the DNS server used for your self-managed domain. For a single IP address use a CIDR address block with /32. For example 10.0.0.0/32.</p>
pub fn cidr_ip(&self) -> std::option::Option<&str> {
self.cidr_ip.as_deref()
}
/// <p>Description of the address block.</p>
pub fn description(&self) -> std::option::Option<&str> {
self.description.as_deref()
}
}
impl std::fmt::Debug for IpRoute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("IpRoute");
formatter.field("cidr_ip", &self.cidr_ip);
formatter.field("description", &self.description);
formatter.finish()
}
}
/// See [`IpRoute`](crate::model::IpRoute)
pub mod ip_route {
/// A builder for [`IpRoute`](crate::model::IpRoute)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) cidr_ip: std::option::Option<std::string::String>,
pub(crate) description: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>IP address block using CIDR format, for example 10.0.0.0/24. This is often the address block of the DNS server used for your self-managed domain. For a single IP address use a CIDR address block with /32. For example 10.0.0.0/32.</p>
pub fn cidr_ip(mut self, input: impl Into<std::string::String>) -> Self {
self.cidr_ip = Some(input.into());
self
}
/// <p>IP address block using CIDR format, for example 10.0.0.0/24. This is often the address block of the DNS server used for your self-managed domain. For a single IP address use a CIDR address block with /32. For example 10.0.0.0/32.</p>
pub fn set_cidr_ip(mut self, input: std::option::Option<std::string::String>) -> Self {
self.cidr_ip = input;
self
}
/// <p>Description of the address block.</p>
pub fn description(mut self, input: impl Into<std::string::String>) -> Self {
self.description = Some(input.into());
self
}
/// <p>Description of the address block.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.description = input;
self
}
/// Consumes the builder and constructs a [`IpRoute`](crate::model::IpRoute)
pub fn build(self) -> crate::model::IpRoute {
crate::model::IpRoute {
cidr_ip: self.cidr_ip,
description: self.description,
}
}
}
}
impl IpRoute {
/// Creates a new builder-style object to manufacture [`IpRoute`](crate::model::IpRoute)
pub fn builder() -> crate::model::ip_route::Builder {
crate::model::ip_route::Builder::default()
}
}
| 43.953802 | 365 | 0.624768 |
e27469ee318b2ae4aac54b7dcc922e80c7fcc590
| 33,468 |
//! #Introduction
//! This crate focuses on geting system information.
//!
//! For now it supports Linux, Mac OS X and Windows.
//! And now it can get information of kernel/cpu/memory/disk/load/hostname and so on.
//!
extern crate libc;
use std::ffi;
use std::fmt;
use std::io::{self, Read};
use std::fs::File;
#[cfg(any(target_os = "windows", target_vendor = "apple", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
use std::os::raw::c_char;
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
use std::os::raw::{c_int, c_double};
#[cfg(any(target_vendor = "apple", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
use libc::sysctl;
#[cfg(any(target_vendor = "apple", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
use std::mem::size_of_val;
#[cfg(any(target_vendor = "apple", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
use std::ptr::null_mut;
#[cfg(not(target_os = "windows"))]
use libc::timeval;
#[cfg(any(target_os = "solaris", target_os = "illumos"))]
use std::time::SystemTime;
#[cfg(target_os = "linux")]
use std::collections::HashMap;
#[cfg(any(target_os = "solaris", target_os = "illumos"))]
mod kstat;
#[cfg(any(target_vendor = "apple", target_os="freebsd", target_os = "openbsd", target_os = "netbsd"))]
static OS_CTL_KERN: libc::c_int = 1;
#[cfg(any(target_vendor = "apple", target_os="freebsd", target_os = "openbsd", target_os = "netbsd"))]
static OS_KERN_BOOTTIME: libc::c_int = 21;
/// System load average value.
#[repr(C)]
#[derive(Debug)]
pub struct LoadAvg {
/// Average load within one minutes.
pub one: f64,
/// Average load within five minutes.
pub five: f64,
/// Average load within fifteen minutes.
pub fifteen: f64,
}
/// System memory information.
#[repr(C)]
#[derive(Debug)]
pub struct MemInfo {
/// Total physical memory.
pub total: u64,
pub free: u64,
pub avail: u64,
pub buffers: u64,
pub cached: u64,
/// Total swap memory.
pub swap_total: u64,
pub swap_free: u64,
}
/// The os release info of Linux.
///
/// See [man os-release](https://www.freedesktop.org/software/systemd/man/os-release.html).
#[derive(Debug)]
#[derive(Default)]
pub struct LinuxOSReleaseInfo {
/// A lower-case string (no spaces or other characters outside of 0–9, a–z, ".", "_" and "-")
/// identifying the operating system, excluding any version information and suitable for
/// processing by scripts or usage in generated filenames.
///
/// Note that we don't verify that the string is lower-case and can be used in file-names. If
/// the /etc/os-release file has an invalid value, you will get this value.
///
/// If not set, defaults to "ID=linux". Use `self.id()` to fallback to the default.
///
/// Example: "fedora" or "debian".
pub id: Option<String>,
/// A space-separated list of operating system identifiers in the same syntax as the ID=
/// setting. It should list identifiers of operating systems that are closely related to the
/// local operating system in regards to packaging and programming interfaces, for example
/// listing one or more OS identifiers the local OS is a derivative from. An OS should
/// generally only list other OS identifiers it itself is a derivative of, and not any OSes
/// that are derived from it, though symmetric relationships are possible. Build scripts and
/// similar should check this variable if they need to identify the local operating system and
/// the value of ID= is not recognized. Operating systems should be listed in order of how
/// closely the local operating system relates to the listed ones, starting with the closest.
///
/// This field is optional.
///
/// Example: for an operating system with `ID=centos`, an assignment of `ID_LIKE="rhel fedora"`
/// would be appropriate. For an operating system with `ID=ubuntu`, an assignment of
/// `ID_LIKE=debian` is appropriate.
pub id_like: Option<String>,
/// A string identifying the operating system, without a version component, and suitable for
/// presentation to the user.
///
/// If not set, defaults to "NAME=Linux".Use `self.id()` to fallback to the default.
///
/// Example: "Fedora" or "Debian GNU/Linux".
pub name: Option<String>,
/// A pretty operating system name in a format suitable for presentation to the user. May or
/// may not contain a release code name or OS version of some kind, as suitable.
///
/// If not set, defaults to "Linux". Use `self.id()` to fallback to the default.
///
/// Example: "Fedora 17 (Beefy Miracle)".
pub pretty_name: Option<String>,
/// A string identifying the operating system version, excluding any OS name information,
/// possibly including a release code name, and suitable for presentation to the user.
///
/// This field is optional.
///
/// Example: "17" or "17 (Beefy Miracle)"
pub version: Option<String>,
/// A lower-case string (mostly numeric, no spaces or other characters outside of 0–9, a–z,
/// ".", "_" and "-") identifying the operating system version, excluding any OS name
/// information or release code name, and suitable for processing by scripts or usage in
/// generated filenames.
///
/// This field is optional.
///
/// Example: "17" or "11.04".
pub version_id: Option<String>,
/// A lower-case string (no spaces or other characters outside of 0–9, a–z, ".", "_" and "-")
/// identifying the operating system release code name, excluding any OS name information or
/// release version, and suitable for processing by scripts or usage in generated filenames.
///
/// This field is optional and may not be implemented on all systems.
///
/// Examples: "buster", "xenial".
pub version_codename: Option<String>,
/// A suggested presentation color when showing the OS name on the console. This should be
/// specified as string suitable for inclusion in the ESC [ m ANSI/ECMA-48 escape code for
/// setting graphical rendition.
///
/// This field is optional.
///
/// Example: "0;31" for red, "1;34" for light blue, or "0;38;2;60;110;180" for Fedora blue.
pub ansi_color: Option<String>,
/// A string, specifying the name of an icon as defined by freedesktop.org Icon Theme
/// Specification. This can be used by graphical applications to display an operating
/// system's or distributor's logo.
///
/// This field is optional and may not necessarily be implemented on all systems.
///
/// Examples: "LOGO=fedora-logo", "LOGO=distributor-logo-opensuse".
pub logo: Option<String>,
/// A CPE name for the operating system, in URI binding syntax, following the Common Platform
/// Enumeration Specification as proposed by the NIST.
///
/// This field is optional.
///
/// Example: "cpe:/o:fedoraproject:fedora:17".
pub cpe_name: Option<String>,
/// A string uniquely identifying the system image used as the origin for a distribution (it is
/// not updated with system updates). The field can be identical between different VERSION_IDs
/// as BUILD_ID is an only a unique identifier to a specific version. Distributions that
/// release each update as a new version would only need to use VERSION_ID as each build is
/// already distinct based on the VERSION_ID.
///
/// This field is optional.
///
/// Example: "2013-03-20.3" or "BUILD_ID=201303203".
pub build_id: Option<String>,
/// A string identifying a specific variant or edition of the operating system suitable for
/// presentation to the user. This field may be used to inform the user that the configuration
/// of this system is subject to a specific divergent set of rules or default configuration
/// settings.
///
/// This field is optional and may not be implemented on all systems.
///
/// Examples: "Server Edition", "Smart Refrigerator Edition".
///
/// Note: this field is for display purposes only. The VARIANT_ID field should be used for
/// making programmatic decisions.
pub variant: Option<String>,
/// A lower-case string (no spaces or other characters outside of 0–9, a–z, ".", "_" and "-"),
/// identifying a specific variant or edition of the operating system. This may be interpreted
/// by other packages in order to determine a divergent default configuration.
///
/// This field is optional and may not be implemented on all systems.
///
/// Examples: "server", "embedded".
pub variant_id: Option<String>,
/// HOME_URL= should refer to the homepage of the operating system, or alternatively some homepage of
/// the specific version of the operating system.
///
/// These URLs are intended to be exposed in "About this system" UIs behind links with captions
/// such as "About this Operating System", "Obtain Support", "Report a Bug", or "Privacy
/// Policy". The values should be in RFC3986 format, and should be "http:" or "https:" URLs,
/// and possibly "mailto:" or "tel:". Only one URL shall be listed in each setting. If multiple
/// resources need to be referenced, it is recommended to provide an online landing page
/// linking all available resources.
///
/// Example: "https://fedoraproject.org/".
pub home_url: Option<String>,
/// DOCUMENTATION_URL= should refer to the main documentation page for this operating system.
///
/// See also `home_url`.
pub documentation_url: Option<String>,
/// SUPPORT_URL= should refer to the main support page for the operating system, if there is
/// any. This is primarily intended for operating systems which vendors provide support for.
///
/// See also `home_url`.
pub support_url: Option<String>,
/// BUG_REPORT_URL= should refer to the main bug reporting page for the operating system, if
/// there is any. This is primarily intended for operating systems that rely on community QA.
///
/// Example: "https://bugzilla.redhat.com/".
///
/// See also `home_url`.
pub bug_report_url: Option<String>,
/// PRIVACY_POLICY_URL= should refer to the main privacy policy page for the operating system,
/// if there is any. These settings are optional, and providing only some of these settings is
/// common.
///
/// See also `home_url`.
pub privacy_policy_url: Option<String>,
}
macro_rules! os_release_defaults {
(
$(
$(#[$meta:meta])*
$vis:vis fn $field:ident => $default:literal
)*
) => {
$(
$(#[$meta])*
$vis fn $field(&self) -> &str {
match self.$field.as_ref() {
Some(value) => value,
None => $default,
}
}
)*
}
}
impl LinuxOSReleaseInfo {
os_release_defaults!(
/// Returns the value of `self.id` or, if `None`, "linux" (the default value).
pub fn id => "linux"
/// Returns the value of `self.name` or, if `None`, "Linux" (the default value).
pub fn name => "Linux"
/// Returns the value of `self.pretty_name` or, if `None`, "Linux" (the default value).
pub fn pretty_name => "Linux"
);
}
/// Disk information.
#[repr(C)]
#[derive(Debug)]
pub struct DiskInfo {
pub total: u64,
pub free: u64,
}
/// Error types
#[derive(Debug)]
pub enum Error {
UnsupportedSystem,
ExecFailed(io::Error),
IO(io::Error),
SystemTime(std::time::SystemTimeError),
General(String),
Unknown,
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use self::Error::*;
match *self {
UnsupportedSystem => write!(fmt, "System is not supported"),
ExecFailed(ref e) => write!(fmt, "Execution failed: {}", e),
IO(ref e) => write!(fmt, "IO error: {}", e),
SystemTime(ref e) => write!(fmt, "System time error: {}", e),
General(ref e) => write!(fmt, "Error: {}", e),
Unknown => write!(fmt, "An unknown error occurred"),
}
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
use self::Error::*;
match *self {
UnsupportedSystem => "unsupported system",
ExecFailed(_) => "execution failed",
IO(_) => "io error",
SystemTime(_) => "system time",
General(_) => "general error",
Unknown => "unknown error",
}
}
fn cause(&self) -> Option<&dyn std::error::Error> {
use self::Error::*;
match *self {
UnsupportedSystem => None,
ExecFailed(ref e) => Some(e),
IO(ref e) => Some(e),
SystemTime(ref e) => Some(e),
General(_) => None,
Unknown => None,
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Error {
Error::IO(e)
}
}
impl From<std::time::SystemTimeError> for Error {
fn from(e: std::time::SystemTimeError) -> Error {
Error::SystemTime(e)
}
}
impl From<Box<dyn std::error::Error>> for Error {
fn from(e: Box<dyn std::error::Error>) -> Error {
Error::General(e.to_string())
}
}
extern "C" {
#[cfg(any(target_vendor = "apple", target_os = "windows"))]
fn get_os_type() -> *const i8;
#[cfg(any(target_vendor = "apple", target_os = "windows", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
fn get_os_release() -> *const i8;
#[cfg(all(not(any(target_os = "solaris", target_os = "illumos", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")), any(unix, windows)))]
fn get_cpu_num() -> u32;
#[cfg(any(all(target_vendor = "apple", not(any(target_arch = "aarch64", target_arch = "arm"))), target_os = "windows", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
fn get_cpu_speed() -> u64;
#[cfg(target_os = "windows")]
fn get_loadavg() -> LoadAvg;
#[cfg(any(target_vendor = "apple", target_os = "windows", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
fn get_proc_total() -> u64;
#[cfg(any(target_vendor = "apple", target_os = "windows"))]
fn get_mem_info() -> MemInfo;
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
fn get_mem_info_bsd(mi: &mut MemInfo) ->i32;
#[cfg(any(target_os = "linux", target_vendor = "apple", target_os = "windows"))]
fn get_disk_info() -> DiskInfo;
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
fn get_disk_info_bsd(di: &mut DiskInfo) -> i32;
}
/// Get operation system type.
///
/// Such as "Linux", "Darwin", "Windows".
pub fn os_type() -> Result<String, Error> {
#[cfg(target_os = "linux")]
{
let mut s = String::new();
File::open("/proc/sys/kernel/ostype")?.read_to_string(&mut s)?;
s.pop(); // pop '\n'
Ok(s)
}
#[cfg(any(target_vendor = "apple", target_os = "windows"))]
{
let typ = unsafe { ffi::CStr::from_ptr(get_os_type() as *const c_char).to_bytes() };
Ok(String::from_utf8_lossy(typ).into_owned())
}
#[cfg(target_os = "solaris")]
{
Ok("solaris".to_string())
}
#[cfg(target_os = "illumos")]
{
Ok("illumos".to_string())
}
#[cfg(target_os = "freebsd")]
{
Ok("freebsd".to_string())
}
#[cfg(target_os = "openbsd")]
{
Ok("openbsd".to_string())
}
#[cfg(target_os = "netbsd")]
{
Ok("netbsd".to_string())
}
#[cfg(not(any(target_os = "linux", target_vendor = "apple", target_os = "windows", target_os = "solaris", target_os = "illumos", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
{
Err(Error::UnsupportedSystem)
}
}
/// Get operation system release version.
///
/// Such as "3.19.0-gentoo"
pub fn os_release() -> Result<String, Error> {
#[cfg(target_os = "linux")]
{
let mut s = String::new();
File::open("/proc/sys/kernel/osrelease")?.read_to_string(&mut s)?;
s.pop(); // pop '\n'
Ok(s)
}
#[cfg(any(target_vendor = "apple", target_os = "windows", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
{
unsafe {
let rp = get_os_release() as *const c_char;
if rp == std::ptr::null() {
Err(Error::Unknown)
} else {
let typ = ffi::CStr::from_ptr(rp).to_bytes();
Ok(String::from_utf8_lossy(typ).into_owned())
}
}
}
#[cfg(any(target_os = "solaris", target_os = "illumos"))]
{
let release: Option<String> = unsafe {
let mut name: libc::utsname = std::mem::zeroed();
if libc::uname(&mut name) < 0 {
None
} else {
let cstr = std::ffi::CStr::from_ptr(name.release.as_mut_ptr());
Some(cstr.to_string_lossy().to_string())
}
};
match release {
None => Err(Error::Unknown),
Some(release) => Ok(release),
}
}
#[cfg(not(any(target_os = "linux", target_vendor = "apple", target_os = "windows", target_os = "solaris", target_os = "illumos", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
{
Err(Error::UnsupportedSystem)
}
}
/// Get the os release note of Linux
///
/// Information in /etc/os-release, such as name and version of distribution.
///
/// See `LinuxOSReleaseInfo` for more documentation.
pub fn linux_os_release() -> Result<LinuxOSReleaseInfo, Error> {
if !cfg!(target_os = "linux") {
return Err(Error::UnsupportedSystem);
}
let mut s = String::new();
File::open("/etc/os-release")?.read_to_string(&mut s)?;
let mut info: LinuxOSReleaseInfo = Default::default();
for l in s.split('\n') {
match parse_line_for_linux_os_release(l.trim().to_string()) {
Some((key, value)) =>
match (key.as_ref(), value) {
("ID", val) => info.id = Some(val),
("ID_LIKE", val) => info.id_like = Some(val),
("NAME", val) => info.name = Some(val),
("PRETTY_NAME", val) => info.pretty_name = Some(val),
("VERSION", val) => info.version = Some(val),
("VERSION_ID", val) => info.version_id = Some(val),
("VERSION_CODENAME", val) => info.version_codename = Some(val),
("ANSI_COLOR", val) => info.ansi_color = Some(val),
("LOGO", val) => info.logo = Some(val),
("CPE_NAME", val) => info.cpe_name = Some(val),
("BUILD_ID", val) => info.build_id = Some(val),
("VARIANT", val) => info.variant = Some(val),
("VARIANT_ID", val) => info.variant_id = Some(val),
("HOME_URL", val) => info.home_url = Some(val),
("BUG_REPORT_URL", val) => info.bug_report_url = Some(val),
("SUPPORT_URL", val) => info.support_url = Some(val),
("DOCUMENTATION_URL", val) => info.documentation_url = Some(val),
("PRIVACY_POLICY_URL", val) => info.privacy_policy_url = Some(val),
_ => {}
}
None => {}
}
}
Ok(info)
}
fn parse_line_for_linux_os_release(l: String) -> Option<(String, String)> {
let words: Vec<&str> = l.splitn(2, '=').collect();
if words.len() < 2 {
return None
}
let mut trim_value = String::from(words[1]);
if trim_value.starts_with('"') {
trim_value.remove(0);
}
if trim_value.ends_with('"') {
let len = trim_value.len();
trim_value.remove(len - 1);
}
return Some((String::from(words[0]), trim_value))
}
/// Get cpu num quantity.
///
/// Notice, it returns the logical cpu quantity.
pub fn cpu_num() -> Result<u32, Error> {
#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
{
let ret = unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) };
if ret < 1 || ret > std::u32::MAX as i64 {
Err(Error::IO(io::Error::last_os_error()))
} else {
Ok(ret as u32)
}
}
#[cfg(all(not(any(target_os = "solaris", target_os = "illumos", target_os="freebsd", target_os = "openbsd", target_os = "netbsd")), any(unix, windows)))]
{
unsafe { Ok(get_cpu_num()) }
}
#[cfg(not(any(target_os = "solaris", target_os = "illumos", unix, windows)))]
{
Err(Error::UnsupportedSystem)
}
}
/// Get cpu speed.
///
/// Such as 2500, that is 2500 MHz.
pub fn cpu_speed() -> Result<u64, Error> {
#[cfg(any(target_os = "solaris", target_os = "illumos"))]
{
Ok(kstat::cpu_mhz()?)
}
#[cfg(target_os = "linux")]
{
// /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq
let mut s = String::new();
File::open("/proc/cpuinfo")?.read_to_string(&mut s)?;
let find_cpu_mhz = s.split('\n').find(|line|
line.starts_with("cpu MHz\t") ||
line.starts_with("BogoMIPS") ||
line.starts_with("clock\t") ||
line.starts_with("bogomips per cpu")
);
find_cpu_mhz.and_then(|line| line.split(':').last())
.and_then(|val| val.replace("MHz", "").trim().parse::<f64>().ok())
.map(|speed| speed as u64)
.ok_or(Error::Unknown)
}
#[cfg(any(all(target_vendor = "apple", not(any(target_arch = "aarch64", target_arch = "arm"))), target_os = "windows"))]
{
unsafe { Ok(get_cpu_speed()) }
}
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
{
let res: u64 = unsafe { get_cpu_speed() };
match res {
0 => Err(Error::IO(io::Error::last_os_error())),
_ => Ok(res),
}
}
#[cfg(not(any(target_os = "solaris", target_os = "illumos", target_os = "linux", all(target_vendor = "apple", not(any(target_arch = "aarch64", target_arch = "arm"))), target_os = "windows", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
{
Err(Error::UnsupportedSystem)
}
}
/// Get system load average value.
///
/// Notice, on windows, one/five/fifteen of the LoadAvg returned are the current load.
pub fn loadavg() -> Result<LoadAvg, Error> {
#[cfg(target_os = "linux")]
{
let mut s = String::new();
File::open("/proc/loadavg")?.read_to_string(&mut s)?;
let loads = s.trim().split(' ')
.take(3)
.map(|val| val.parse::<f64>().unwrap())
.collect::<Vec<f64>>();
Ok(LoadAvg {
one: loads[0],
five: loads[1],
fifteen: loads[2],
})
}
#[cfg(any(target_os = "solaris", target_os = "illumos", target_vendor = "apple", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
{
let mut l: [c_double; 3] = [0f64; 3];
if unsafe { libc::getloadavg(l.as_mut_ptr(), l.len() as c_int) } < 3 {
Err(Error::Unknown)
} else {
Ok(LoadAvg {
one: l[0],
five: l[1],
fifteen: l[2],
})
}
}
#[cfg(any(target_os = "windows"))]
{
Ok(unsafe { get_loadavg() })
}
#[cfg(not(any(target_os = "linux", target_os = "solaris", target_os = "illumos", target_vendor = "apple", target_os = "windows", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
{
Err(Error::UnsupportedSystem)
}
}
/// Get current processes quantity.
pub fn proc_total() -> Result<u64, Error> {
#[cfg(any(target_os = "solaris", target_os = "illumos"))]
{
Ok(kstat::nproc()?)
}
#[cfg(target_os = "linux")]
{
let mut s = String::new();
File::open("/proc/loadavg")?.read_to_string(&mut s)?;
s.split(' ')
.nth(3)
.and_then(|val| val.split('/').last())
.and_then(|val| val.parse::<u64>().ok())
.ok_or(Error::Unknown)
}
#[cfg(any(target_vendor = "apple", target_os = "windows"))]
{
Ok(unsafe { get_proc_total() })
}
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
{
let res: u64 = unsafe { get_proc_total() };
match res {
0 => Err(Error::IO(io::Error::last_os_error())),
_ => Ok(res),
}
}
#[cfg(not(any(target_os = "linux", target_os = "solaris", target_os = "illumos", target_vendor = "apple", target_os = "windows", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
{
Err(Error::UnsupportedSystem)
}
}
#[cfg(any(target_os = "solaris", target_os = "illumos"))]
fn pagesize() -> Result<u32, Error> {
let ret = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
if ret < 1 || ret > std::u32::MAX as i64 {
Err(Error::Unknown)
} else {
Ok(ret as u32)
}
}
/// Get memory information.
///
/// On Mac OS X and Windows, the buffers and cached variables of the MemInfo returned are zero.
pub fn mem_info() -> Result<MemInfo, Error> {
#[cfg(target_os = "linux")]
{
let mut s = String::new();
File::open("/proc/meminfo")?.read_to_string(&mut s)?;
let mut meminfo_hashmap = HashMap::new();
for line in s.lines() {
let mut split_line = line.split_whitespace();
let label = split_line.next();
let value = split_line.next();
if value.is_some() && label.is_some() {
let label = label.unwrap().split(':').nth(0).ok_or(Error::Unknown)?;
let value = value.unwrap().parse::<u64>().ok().ok_or(Error::Unknown)?;
meminfo_hashmap.insert(label, value);
}
}
let total = *meminfo_hashmap.get("MemTotal").ok_or(Error::Unknown)?;
let free = *meminfo_hashmap.get("MemFree").ok_or(Error::Unknown)?;
let buffers = *meminfo_hashmap.get("Buffers").ok_or(Error::Unknown)?;
let cached = *meminfo_hashmap.get("Cached").ok_or(Error::Unknown)?;
let avail = meminfo_hashmap.get("MemAvailable").map(|v| v.clone()).or_else(|| {
let sreclaimable = *meminfo_hashmap.get("SReclaimable")?;
let shmem = *meminfo_hashmap.get("Shmem")?;
Some(free + buffers + cached + sreclaimable - shmem)
}).ok_or(Error::Unknown)?;
let swap_total = *meminfo_hashmap.get("SwapTotal").ok_or(Error::Unknown)?;
let swap_free = *meminfo_hashmap.get("SwapFree").ok_or(Error::Unknown)?;
Ok(MemInfo {
total,
free,
avail,
buffers,
cached,
swap_total,
swap_free,
})
}
#[cfg(any(target_os = "solaris", target_os = "illumos"))]
{
let pagesize = pagesize()? as u64;
let pages = kstat::pages()?;
return Ok(MemInfo {
total: pages.physmem * pagesize / 1024,
avail: 0,
free: pages.freemem * pagesize / 1024,
cached: 0,
buffers: 0,
swap_total: 0,
swap_free: 0,
});
}
#[cfg(any(target_vendor = "apple", target_os = "windows"))]
{
Ok(unsafe { get_mem_info() })
}
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
{
let mut mi:MemInfo = MemInfo{total: 0, free: 0, avail: 0, buffers: 0,
cached: 0, swap_total: 0, swap_free: 0};
let res: i32 = unsafe { get_mem_info_bsd(&mut mi) };
match res {
-1 => Err(Error::IO(io::Error::last_os_error())),
0 => Ok(mi),
_ => Err(Error::Unknown),
}
}
#[cfg(not(any(target_os = "linux", target_os = "solaris", target_os = "illumos", target_vendor = "apple", target_os = "windows", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
{
Err(Error::UnsupportedSystem)
}
}
/// Get disk information.
///
/// Notice, it just calculate current disk on Windows.
pub fn disk_info() -> Result<DiskInfo, Error> {
#[cfg(any(target_os = "linux", target_vendor = "apple", target_os = "windows"))]
{
Ok(unsafe { get_disk_info() })
}
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
{
let mut di:DiskInfo = DiskInfo{total: 0, free: 0};
let res: i32 = unsafe { get_disk_info_bsd(&mut di) };
match res {
-1 => Err(Error::IO(io::Error::last_os_error())),
0 => Ok(di),
_ => Err(Error::Unknown),
}
}
#[cfg(not(any(target_os = "linux", target_vendor = "apple", target_os = "windows", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
{
Err(Error::UnsupportedSystem)
}
}
/// Get hostname.
#[cfg(target_family = "unix")]
pub fn hostname() -> Result<String, Error> {
unsafe {
let buf_size = libc::sysconf(libc::_SC_HOST_NAME_MAX) as usize;
let mut buf = Vec::<u8>::with_capacity(buf_size + 1);
if libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf_size) < 0 {
return Err(Error::IO(io::Error::last_os_error()));
}
let hostname_len = libc::strnlen(buf.as_ptr() as *const libc::c_char, buf_size);
buf.set_len(hostname_len);
Ok(ffi::CString::new(buf).unwrap().into_string().unwrap())
}
}
#[cfg(target_family = "windows")]
pub fn hostname() -> Result<String, Error> {
use std::process::Command;
Command::new("hostname")
.output()
.map_err(Error::ExecFailed)
.map(|output| String::from_utf8(output.stdout).unwrap().trim().to_string())
}
/// Get system boottime
#[cfg(not(windows))]
pub fn boottime() -> Result<timeval, Error> {
let mut bt = timeval {
tv_sec: 0,
tv_usec: 0
};
#[cfg(any(target_os = "linux", target_os="android"))]
{
let mut s = String::new();
File::open("/proc/uptime")?.read_to_string(&mut s)?;
let secs = s.trim().split(' ')
.take(2)
.map(|val| val.parse::<f64>().unwrap())
.collect::<Vec<f64>>();
bt.tv_sec = secs[0] as libc::time_t;
bt.tv_usec = secs[1] as libc::suseconds_t;
Ok(bt)
}
#[cfg(any(target_vendor = "apple", target_os="freebsd", target_os = "openbsd", target_os = "netbsd"))]
{
let mut mib = [OS_CTL_KERN, OS_KERN_BOOTTIME];
let mut size: libc::size_t = size_of_val(&bt) as libc::size_t;
unsafe {
if sysctl(&mut mib[0], 2,
&mut bt as *mut timeval as *mut libc::c_void,
&mut size, null_mut(), 0) == -1 {
Err(Error::IO(io::Error::last_os_error()))
} else {
Ok(bt)
}
}
}
#[cfg(any(target_os = "solaris", target_os = "illumos"))]
{
let start = kstat::boot_time()?;
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
let now = now.as_secs();
if now < start {
return Err(Error::General("time went backwards".into()));
}
bt.tv_sec = (now - start) as i64;
Ok(bt)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
pub fn test_os_type() {
let typ = os_type().unwrap();
assert!(typ.len() > 0);
println!("os_type(): {}", typ);
}
#[test]
pub fn test_os_release() {
let release = os_release().unwrap();
assert!(release.len() > 0);
println!("os_release(): {}", release);
}
#[test]
pub fn test_cpu_num() {
let num = cpu_num().unwrap();
assert!(num > 0);
println!("cpu_num(): {}", num);
}
#[test]
#[cfg(not(all(target_vendor = "apple", target_arch = "aarch64")))]
pub fn test_cpu_speed() {
let speed = cpu_speed().unwrap();
assert!(speed > 0);
println!("cpu_speed(): {}", speed);
}
#[test]
pub fn test_loadavg() {
let load = loadavg().unwrap();
println!("loadavg(): {:?}", load);
}
#[test]
pub fn test_proc_total() {
let procs = proc_total().unwrap();
assert!(procs > 0);
println!("proc_total(): {}", procs);
}
#[test]
pub fn test_mem_info() {
let mem = mem_info().unwrap();
assert!(mem.total > 0);
println!("mem_info(): {:?}", mem);
}
#[test]
#[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
pub fn test_disk_info() {
let info = disk_info().unwrap();
println!("disk_info(): {:?}", info);
}
#[test]
pub fn test_hostname() {
let host = hostname().unwrap();
assert!(host.len() > 0);
println!("hostname(): {}", host);
}
#[test]
#[cfg(not(windows))]
pub fn test_boottime() {
let bt = boottime().unwrap();
println!("boottime(): {} {}", bt.tv_sec, bt.tv_usec);
assert!(bt.tv_sec > 0 || bt.tv_usec > 0);
}
#[test]
#[cfg(target_os = "linux")]
pub fn test_linux_os_release() {
let os_release = linux_os_release().unwrap();
println!("linux_os_release(): {:?}", os_release.name)
}
}
| 35.642173 | 264 | 0.583722 |
5b1b43b2fb9a7b9bf3b7ffdd88ca6ff6239ddfc5
| 34 |
pub mod backend;
pub mod frontend;
| 17 | 17 | 0.794118 |
3ada8655fd7ef5018e1ab9b5dde94b56e757215a
| 2,826 |
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[macro_export]
macro_rules! calcute {
($lhs_viewer: expr, $rhs_viewer: expr, $builder: expr, $func: expr) => {
for (a, b) in ($lhs_viewer.iter().zip($rhs_viewer.iter())) {
$builder.append($func(a, b));
}
};
}
#[macro_export]
macro_rules! impl_logic_expression {
($name: ident, $method: tt, $func: expr) => {
#[derive(Clone)]
pub struct $name;
impl LogicExpression for $name {
fn eval(columns: &ColumnsWithField, input_rows: usize, nullable: bool) -> Result<ColumnRef> {
let dt = if nullable {
NullableType::new_impl(BooleanType::new_impl())
} else {
BooleanType::new_impl()
};
let lhs = cast_column_field(&columns[0], columns[0].data_type(), &dt)?;
let rhs = cast_column_field(&columns[1], columns[1].data_type(), &dt)?;
if nullable {
let lhs_viewer = bool::try_create_viewer(&lhs)?;
let rhs_viewer = bool::try_create_viewer(&rhs)?;
let lhs_viewer_iter = lhs_viewer.iter();
let rhs_viewer_iter = rhs_viewer.iter();
let mut builder = NullableColumnBuilder::<bool>::with_capacity(input_rows);
for (a, (idx, b)) in lhs_viewer_iter.zip(rhs_viewer_iter.enumerate()) {
let (val, valid) = $func(a, b, lhs_viewer.valid_at(idx), rhs_viewer.valid_at(idx));
builder.append(val, valid);
}
Ok(builder.build(input_rows))
} else {
let lhs_viewer = bool::try_create_viewer(&lhs)?;
let rhs_viewer = bool::try_create_viewer(&rhs)?;
let mut builder = ColumnBuilder::<bool>::with_capacity(input_rows);
calcute!(lhs_viewer, rhs_viewer, builder, |lhs: bool,
rhs: bool|
-> bool {
lhs $method rhs
});
Ok(builder.build(input_rows))
}
}
}
};
}
| 38.189189 | 107 | 0.539986 |
dec6e0cf705ed1796456222487518be67b75fe84
| 1,489 |
use crate::{Endpoint, Middleware, Request, Result};
/// Middleware for add any data to request.
pub struct AddData<T> {
value: T,
}
impl<T: Clone + Send + Sync + 'static> AddData<T> {
/// Create new `AddData` middleware with any value.
pub fn new(value: T) -> Self {
AddData { value }
}
}
impl<E, T> Middleware<E> for AddData<T>
where
E: Endpoint,
T: Clone + Send + Sync + 'static,
{
type Output = AddDataEndpoint<E, T>;
fn transform(&self, ep: E) -> Self::Output {
AddDataEndpoint {
inner: ep,
value: self.value.clone(),
}
}
}
/// Endpoint for AddData middleware.
pub struct AddDataEndpoint<E, T> {
inner: E,
value: T,
}
#[async_trait::async_trait]
impl<E, T> Endpoint for AddDataEndpoint<E, T>
where
E: Endpoint,
T: Clone + Send + Sync + 'static,
{
type Output = E::Output;
async fn call(&self, mut req: Request) -> Result<Self::Output> {
req.extensions_mut().insert(self.value.clone());
self.inner.call(req).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{handler, test::TestClient, EndpointExt};
#[tokio::test]
async fn test_add_data() {
#[handler(internal)]
async fn index(req: &Request) {
assert_eq!(req.extensions().get::<i32>(), Some(&100));
}
let cli = TestClient::new(index.with(AddData::new(100i32)));
cli.get("/").send().await.assert_status_is_ok();
}
}
| 22.560606 | 68 | 0.583613 |
f979697ab1bcf82eb8fc4f2366bc0f92be536bbf
| 22,283 |
//! See `CompletionContext` structure.
use hir::{Local, ScopeDef, Semantics, SemanticsScope, Type};
use ide_db::base_db::{FilePosition, SourceDatabase};
use ide_db::{call_info::ActiveParameter, RootDatabase};
use syntax::{
algo::{find_covering_element, find_node_at_offset},
ast, match_ast, AstNode, NodeOrToken,
SyntaxKind::*,
SyntaxNode, SyntaxToken, TextRange, TextSize,
};
use test_utils::mark;
use text_edit::Indel;
use crate::{
patterns::{
fn_is_prev, for_is_prev2, has_bind_pat_parent, has_block_expr_parent,
has_field_list_parent, has_impl_as_prev_sibling, has_impl_parent,
has_item_list_or_source_file_parent, has_ref_parent, has_trait_as_prev_sibling,
has_trait_parent, if_is_prev, inside_impl_trait_block, is_in_loop_body, is_match_arm,
unsafe_is_prev,
},
CompletionConfig,
};
/// `CompletionContext` is created early during completion to figure out, where
/// exactly is the cursor, syntax-wise.
#[derive(Debug)]
pub(crate) struct CompletionContext<'a> {
pub(super) sema: Semantics<'a, RootDatabase>,
pub(super) scope: SemanticsScope<'a>,
pub(super) db: &'a RootDatabase,
pub(super) config: &'a CompletionConfig,
pub(super) position: FilePosition,
/// The token before the cursor, in the original file.
pub(super) original_token: SyntaxToken,
/// The token before the cursor, in the macro-expanded file.
pub(super) token: SyntaxToken,
pub(super) krate: Option<hir::Crate>,
pub(super) expected_type: Option<Type>,
pub(super) name_ref_syntax: Option<ast::NameRef>,
pub(super) function_syntax: Option<ast::Fn>,
pub(super) use_item_syntax: Option<ast::Use>,
pub(super) record_lit_syntax: Option<ast::RecordExpr>,
pub(super) record_pat_syntax: Option<ast::RecordPat>,
pub(super) record_field_syntax: Option<ast::RecordExprField>,
pub(super) impl_def: Option<ast::Impl>,
/// FIXME: `ActiveParameter` is string-based, which is very very wrong
pub(super) active_parameter: Option<ActiveParameter>,
pub(super) is_param: bool,
/// If a name-binding or reference to a const in a pattern.
/// Irrefutable patterns (like let) are excluded.
pub(super) is_pat_binding_or_const: bool,
pub(super) is_irrefutable_pat_binding: bool,
/// A single-indent path, like `foo`. `::foo` should not be considered a trivial path.
pub(super) is_trivial_path: bool,
/// If not a trivial path, the prefix (qualifier).
pub(super) path_qual: Option<ast::Path>,
pub(super) after_if: bool,
/// `true` if we are a statement or a last expr in the block.
pub(super) can_be_stmt: bool,
/// `true` if we expect an expression at the cursor position.
pub(super) is_expr: bool,
/// Something is typed at the "top" level, in module or impl/trait.
pub(super) is_new_item: bool,
/// The receiver if this is a field or method access, i.e. writing something.<|>
pub(super) dot_receiver: Option<ast::Expr>,
pub(super) dot_receiver_is_ambiguous_float_literal: bool,
/// If this is a call (method or function) in particular, i.e. the () are already there.
pub(super) is_call: bool,
/// Like `is_call`, but for tuple patterns.
pub(super) is_pattern_call: bool,
/// If this is a macro call, i.e. the () are already there.
pub(super) is_macro_call: bool,
pub(super) is_path_type: bool,
pub(super) has_type_args: bool,
pub(super) attribute_under_caret: Option<ast::Attr>,
pub(super) mod_declaration_under_caret: Option<ast::Module>,
pub(super) unsafe_is_prev: bool,
pub(super) if_is_prev: bool,
pub(super) block_expr_parent: bool,
pub(super) bind_pat_parent: bool,
pub(super) ref_pat_parent: bool,
pub(super) in_loop_body: bool,
pub(super) has_trait_parent: bool,
pub(super) has_impl_parent: bool,
pub(super) inside_impl_trait_block: bool,
pub(super) has_field_list_parent: bool,
pub(super) trait_as_prev_sibling: bool,
pub(super) impl_as_prev_sibling: bool,
pub(super) is_match_arm: bool,
pub(super) has_item_list_or_source_file_parent: bool,
pub(super) for_is_prev2: bool,
pub(super) fn_is_prev: bool,
pub(super) locals: Vec<(String, Local)>,
}
impl<'a> CompletionContext<'a> {
pub(super) fn new(
db: &'a RootDatabase,
position: FilePosition,
config: &'a CompletionConfig,
) -> Option<CompletionContext<'a>> {
let sema = Semantics::new(db);
let original_file = sema.parse(position.file_id);
// Insert a fake ident to get a valid parse tree. We will use this file
// to determine context, though the original_file will be used for
// actual completion.
let file_with_fake_ident = {
let parse = db.parse(position.file_id);
let edit = Indel::insert(position.offset, "intellijRulezz".to_string());
parse.reparse(&edit).tree()
};
let fake_ident_token =
file_with_fake_ident.syntax().token_at_offset(position.offset).right_biased().unwrap();
let krate = sema.to_module_def(position.file_id).map(|m| m.krate());
let original_token =
original_file.syntax().token_at_offset(position.offset).left_biased()?;
let token = sema.descend_into_macros(original_token.clone());
let scope = sema.scope_at_offset(&token.parent(), position.offset);
let mut locals = vec![];
scope.process_all_names(&mut |name, scope| {
if let ScopeDef::Local(local) = scope {
locals.push((name.to_string(), local));
}
});
let mut ctx = CompletionContext {
sema,
scope,
db,
config,
original_token,
token,
position,
krate,
expected_type: None,
name_ref_syntax: None,
function_syntax: None,
use_item_syntax: None,
record_lit_syntax: None,
record_pat_syntax: None,
record_field_syntax: None,
impl_def: None,
active_parameter: ActiveParameter::at(db, position),
is_param: false,
is_pat_binding_or_const: false,
is_irrefutable_pat_binding: false,
is_trivial_path: false,
path_qual: None,
after_if: false,
can_be_stmt: false,
is_expr: false,
is_new_item: false,
dot_receiver: None,
is_call: false,
is_pattern_call: false,
is_macro_call: false,
is_path_type: false,
has_type_args: false,
dot_receiver_is_ambiguous_float_literal: false,
attribute_under_caret: None,
mod_declaration_under_caret: None,
unsafe_is_prev: false,
in_loop_body: false,
ref_pat_parent: false,
bind_pat_parent: false,
block_expr_parent: false,
has_trait_parent: false,
has_impl_parent: false,
inside_impl_trait_block: false,
has_field_list_parent: false,
trait_as_prev_sibling: false,
impl_as_prev_sibling: false,
if_is_prev: false,
is_match_arm: false,
has_item_list_or_source_file_parent: false,
for_is_prev2: false,
fn_is_prev: false,
locals,
};
let mut original_file = original_file.syntax().clone();
let mut hypothetical_file = file_with_fake_ident.syntax().clone();
let mut offset = position.offset;
let mut fake_ident_token = fake_ident_token;
// Are we inside a macro call?
while let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
find_node_at_offset::<ast::MacroCall>(&original_file, offset),
find_node_at_offset::<ast::MacroCall>(&hypothetical_file, offset),
) {
if actual_macro_call.path().as_ref().map(|s| s.syntax().text())
!= macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text())
{
break;
}
let hypothetical_args = match macro_call_with_fake_ident.token_tree() {
Some(tt) => tt,
None => break,
};
if let (Some(actual_expansion), Some(hypothetical_expansion)) = (
ctx.sema.expand(&actual_macro_call),
ctx.sema.speculative_expand(
&actual_macro_call,
&hypothetical_args,
fake_ident_token,
),
) {
let new_offset = hypothetical_expansion.1.text_range().start();
if new_offset > actual_expansion.text_range().end() {
break;
}
original_file = actual_expansion;
hypothetical_file = hypothetical_expansion.0;
fake_ident_token = hypothetical_expansion.1;
offset = new_offset;
} else {
break;
}
}
ctx.fill_keyword_patterns(&hypothetical_file, offset);
ctx.fill(&original_file, hypothetical_file, offset);
Some(ctx)
}
/// Checks whether completions in that particular case don't make much sense.
/// Examples:
/// - `fn <|>` -- we expect function name, it's unlikely that "hint" will be helpful.
/// Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
/// - `for _ i<|>` -- obviously, it'll be "in" keyword.
pub(crate) fn no_completion_required(&self) -> bool {
(self.fn_is_prev && !self.inside_impl_trait_block) || self.for_is_prev2
}
/// The range of the identifier that is being completed.
pub(crate) fn source_range(&self) -> TextRange {
// check kind of macro-expanded token, but use range of original token
let kind = self.token.kind();
if kind == IDENT || kind == UNDERSCORE || kind.is_keyword() {
mark::hit!(completes_if_prefix_is_keyword);
self.original_token.text_range()
} else {
TextRange::empty(self.position.offset)
}
}
fn fill_keyword_patterns(&mut self, file_with_fake_ident: &SyntaxNode, offset: TextSize) {
let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
let syntax_element = NodeOrToken::Token(fake_ident_token);
self.block_expr_parent = has_block_expr_parent(syntax_element.clone());
self.unsafe_is_prev = unsafe_is_prev(syntax_element.clone());
self.if_is_prev = if_is_prev(syntax_element.clone());
self.bind_pat_parent = has_bind_pat_parent(syntax_element.clone());
self.ref_pat_parent = has_ref_parent(syntax_element.clone());
self.in_loop_body = is_in_loop_body(syntax_element.clone());
self.has_trait_parent = has_trait_parent(syntax_element.clone());
self.has_impl_parent = has_impl_parent(syntax_element.clone());
self.inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
self.has_field_list_parent = has_field_list_parent(syntax_element.clone());
self.impl_as_prev_sibling = has_impl_as_prev_sibling(syntax_element.clone());
self.trait_as_prev_sibling = has_trait_as_prev_sibling(syntax_element.clone());
self.is_match_arm = is_match_arm(syntax_element.clone());
self.has_item_list_or_source_file_parent =
has_item_list_or_source_file_parent(syntax_element.clone());
self.mod_declaration_under_caret =
find_node_at_offset::<ast::Module>(&file_with_fake_ident, offset)
.filter(|module| module.item_list().is_none());
self.for_is_prev2 = for_is_prev2(syntax_element.clone());
self.fn_is_prev = fn_is_prev(syntax_element.clone());
}
fn fill(
&mut self,
original_file: &SyntaxNode,
file_with_fake_ident: SyntaxNode,
offset: TextSize,
) {
// FIXME: this is wrong in at least two cases:
// * when there's no token `foo(<|>)`
// * when there is a token, but it happens to have type of it's own
self.expected_type = self
.token
.ancestors()
.find_map(|node| {
let ty = match_ast! {
match node {
ast::Pat(it) => self.sema.type_of_pat(&it),
ast::Expr(it) => self.sema.type_of_expr(&it),
_ => return None,
}
};
Some(ty)
})
.flatten();
self.attribute_under_caret = find_node_at_offset(&file_with_fake_ident, offset);
// First, let's try to complete a reference to some declaration.
if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(&file_with_fake_ident, offset) {
// Special case, `trait T { fn foo(i_am_a_name_ref) {} }`.
// See RFC#1685.
if is_node::<ast::Param>(name_ref.syntax()) {
self.is_param = true;
return;
}
// FIXME: remove this (V) duplication and make the check more precise
if name_ref.syntax().ancestors().find_map(ast::RecordPatFieldList::cast).is_some() {
self.record_pat_syntax =
self.sema.find_node_at_offset_with_macros(&original_file, offset);
}
self.classify_name_ref(original_file, name_ref, offset);
}
// Otherwise, see if this is a declaration. We can use heuristics to
// suggest declaration names, see `CompletionKind::Magic`.
if let Some(name) = find_node_at_offset::<ast::Name>(&file_with_fake_ident, offset) {
if let Some(bind_pat) = name.syntax().ancestors().find_map(ast::IdentPat::cast) {
self.is_pat_binding_or_const = true;
if bind_pat.at_token().is_some()
|| bind_pat.ref_token().is_some()
|| bind_pat.mut_token().is_some()
{
self.is_pat_binding_or_const = false;
}
if bind_pat.syntax().parent().and_then(ast::RecordPatFieldList::cast).is_some() {
self.is_pat_binding_or_const = false;
}
if let Some(Some(pat)) = bind_pat.syntax().ancestors().find_map(|node| {
match_ast! {
match node {
ast::LetStmt(it) => Some(it.pat()),
ast::Param(it) => Some(it.pat()),
_ => None,
}
}
}) {
if pat.syntax().text_range().contains_range(bind_pat.syntax().text_range()) {
self.is_pat_binding_or_const = false;
self.is_irrefutable_pat_binding = true;
}
}
}
if is_node::<ast::Param>(name.syntax()) {
self.is_param = true;
return;
}
// FIXME: remove this (^) duplication and make the check more precise
if name.syntax().ancestors().find_map(ast::RecordPatFieldList::cast).is_some() {
self.record_pat_syntax =
self.sema.find_node_at_offset_with_macros(&original_file, offset);
}
}
}
fn classify_name_ref(
&mut self,
original_file: &SyntaxNode,
name_ref: ast::NameRef,
offset: TextSize,
) {
self.name_ref_syntax =
find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
let name_range = name_ref.syntax().text_range();
if ast::RecordExprField::for_field_name(&name_ref).is_some() {
self.record_lit_syntax =
self.sema.find_node_at_offset_with_macros(&original_file, offset);
}
self.impl_def = self
.sema
.ancestors_with_macros(self.token.parent())
.take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
.find_map(ast::Impl::cast);
let top_node = name_ref
.syntax()
.ancestors()
.take_while(|it| it.text_range() == name_range)
.last()
.unwrap();
match top_node.parent().map(|it| it.kind()) {
Some(SOURCE_FILE) | Some(ITEM_LIST) => {
self.is_new_item = true;
return;
}
_ => (),
}
self.use_item_syntax =
self.sema.ancestors_with_macros(self.token.parent()).find_map(ast::Use::cast);
self.function_syntax = self
.sema
.ancestors_with_macros(self.token.parent())
.take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
.find_map(ast::Fn::cast);
self.record_field_syntax = self
.sema
.ancestors_with_macros(self.token.parent())
.take_while(|it| {
it.kind() != SOURCE_FILE && it.kind() != MODULE && it.kind() != CALL_EXPR
})
.find_map(ast::RecordExprField::cast);
let parent = match name_ref.syntax().parent() {
Some(it) => it,
None => return,
};
if let Some(segment) = ast::PathSegment::cast(parent.clone()) {
let path = segment.parent_path();
self.is_call = path
.syntax()
.parent()
.and_then(ast::PathExpr::cast)
.and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
.is_some();
self.is_macro_call = path.syntax().parent().and_then(ast::MacroCall::cast).is_some();
self.is_pattern_call =
path.syntax().parent().and_then(ast::TupleStructPat::cast).is_some();
self.is_path_type = path.syntax().parent().and_then(ast::PathType::cast).is_some();
self.has_type_args = segment.generic_arg_list().is_some();
if let Some(path) = path_or_use_tree_qualifier(&path) {
self.path_qual = path
.segment()
.and_then(|it| {
find_node_with_range::<ast::PathSegment>(
original_file,
it.syntax().text_range(),
)
})
.map(|it| it.parent_path());
return;
}
if let Some(segment) = path.segment() {
if segment.coloncolon_token().is_some() {
return;
}
}
self.is_trivial_path = true;
// Find either enclosing expr statement (thing with `;`) or a
// block. If block, check that we are the last expr.
self.can_be_stmt = name_ref
.syntax()
.ancestors()
.find_map(|node| {
if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
}
if let Some(block) = ast::BlockExpr::cast(node) {
return Some(
block.tail_expr().map(|e| e.syntax().text_range())
== Some(name_ref.syntax().text_range()),
);
}
None
})
.unwrap_or(false);
self.is_expr = path.syntax().parent().and_then(ast::PathExpr::cast).is_some();
if let Some(off) = name_ref.syntax().text_range().start().checked_sub(2.into()) {
if let Some(if_expr) =
self.sema.find_node_at_offset_with_macros::<ast::IfExpr>(original_file, off)
{
if if_expr.syntax().text_range().end() < name_ref.syntax().text_range().start()
{
self.after_if = true;
}
}
}
}
if let Some(field_expr) = ast::FieldExpr::cast(parent.clone()) {
// The receiver comes before the point of insertion of the fake
// ident, so it should have the same range in the non-modified file
self.dot_receiver = field_expr
.expr()
.map(|e| e.syntax().text_range())
.and_then(|r| find_node_with_range(original_file, r));
self.dot_receiver_is_ambiguous_float_literal =
if let Some(ast::Expr::Literal(l)) = &self.dot_receiver {
match l.kind() {
ast::LiteralKind::FloatNumber { .. } => l.token().text().ends_with('.'),
_ => false,
}
} else {
false
};
}
if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
// As above
self.dot_receiver = method_call_expr
.receiver()
.map(|e| e.syntax().text_range())
.and_then(|r| find_node_with_range(original_file, r));
self.is_call = true;
}
}
}
fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
find_covering_element(syntax, range).ancestors().find_map(N::cast)
}
fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
match node.ancestors().find_map(N::cast) {
None => false,
Some(n) => n.syntax().text_range() == node.text_range(),
}
}
fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<ast::Path> {
if let Some(qual) = path.qualifier() {
return Some(qual);
}
let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
use_tree.path()
}
| 42.202652 | 106 | 0.576089 |
2fc82b1c136792034741f92ae68c2d3fce59e6ff
| 3,184 |
// 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.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according to those terms.
//! Basic Windows Type Definitions for minwin partition
use ctypes::{c_char, c_float, c_int, c_long, c_uchar, c_uint, c_ulong, c_ushort, c_void};
use shared::basetsd::{LONG_PTR, UINT_PTR};
use shared::ntdef::{HANDLE, LONG};
pub type ULONG = c_ulong;
pub type PULONG = *mut ULONG;
pub type USHORT = c_ushort;
pub type PUSHORT = *mut USHORT;
pub type UCHAR = c_uchar;
pub type PUCHAR = *mut UCHAR;
pub type PSZ = *mut c_char;
pub const MAX_PATH: usize = 260;
pub const FALSE: BOOL = 0;
pub const TRUE: BOOL = 1;
pub type DWORD = c_ulong;
pub type BOOL = c_int;
pub type BYTE = c_uchar;
pub type WORD = c_ushort;
pub type FLOAT = c_float;
pub type PFLOAT = *mut FLOAT;
pub type PBOOL = *mut BOOL;
pub type LPBOOL = *mut BOOL;
pub type PBYTE = *mut BYTE;
pub type LPBYTE = *mut BYTE;
pub type PINT = *mut c_int;
pub type LPINT = *mut c_int;
pub type PWORD = *mut WORD;
pub type LPWORD = *mut WORD;
pub type LPLONG = *mut c_long;
pub type PDWORD = *mut DWORD;
pub type LPDWORD = *mut DWORD;
pub type LPVOID = *mut c_void;
pub type LPCVOID = *const c_void;
pub type INT = c_int;
pub type UINT = c_uint;
pub type PUINT = *mut c_uint;
pub type WPARAM = UINT_PTR;
pub type LPARAM = LONG_PTR;
pub type LRESULT = LONG_PTR;
#[inline]
pub fn MAKEWORD(a: BYTE, b: BYTE) -> WORD {
(a as WORD) | ((b as WORD) << 8)
}
#[inline]
pub fn MAKELONG(a: WORD, b: WORD) -> LONG {
((a as DWORD) | ((b as DWORD) << 16)) as LONG
}
#[inline]
pub fn LOWORD(l: DWORD) -> WORD {
(l & 0xffff) as WORD
}
#[inline]
pub fn HIWORD(l: DWORD) -> WORD {
((l >> 16) & 0xffff) as WORD
}
#[inline]
pub fn LOBYTE(l: WORD) -> BYTE {
(l & 0xff) as BYTE
}
#[inline]
pub fn HIBYTE(l: WORD) -> BYTE {
((l >> 8) & 0xff) as BYTE
}
pub type SPHANDLE = *mut HANDLE;
pub type LPHANDLE = *mut HANDLE;
pub type HGLOBAL = HANDLE;
pub type HLOCAL = HANDLE;
pub type GLOBALHANDLE = HANDLE;
pub type LOCALHANDLE = HANDLE;
pub enum __some_function {}
/// Pointer to a function with unknown type signature.
pub type FARPROC = *mut __some_function;
/// Pointer to a function with unknown type signature.
pub type NEARPROC = *mut __some_function;
/// Pointer to a function with unknown type signature.
pub type PROC = *mut __some_function;
pub type ATOM = WORD;
DECLARE_HANDLE! {HKEY, HKEY__}
pub type PHKEY = *mut HKEY;
DECLARE_HANDLE! {HMETAFILE, HMETAFILE__}
DECLARE_HANDLE! {HINSTANCE, HINSTANCE__}
pub type HMODULE = HINSTANCE;
DECLARE_HANDLE! {HRGN, HRGN__}
DECLARE_HANDLE! {HRSRC, HRSRC__}
DECLARE_HANDLE! {HSPRITE, HSPRITE__}
DECLARE_HANDLE! {HLSURF, HLSURF__}
DECLARE_HANDLE! {HSTR, HSTR__}
DECLARE_HANDLE! {HTASK, HTASK__}
DECLARE_HANDLE! {HWINSTA, HWINSTA__}
DECLARE_HANDLE! {HKL, HKL__}
pub type HFILE = c_int;
STRUCT! {#[debug] struct FILETIME {
dwLowDateTime: DWORD,
dwHighDateTime: DWORD,
}}
pub type PFILETIME = *mut FILETIME;
pub type LPFILETIME = *mut FILETIME;
| 30.912621 | 92 | 0.707601 |
5dcfeac889e720685fa5d03cfbccc5bddd9ec08f
| 1,404 |
use crate::{
component::text::{State, TextState},
layout::{LayoutDirection, LayoutState},
rendering::{
consts::{DEFAULT_TEXT_SIZE, PADDING, TEXT_ALIGN_TOP},
resource::ResourceAllocator,
solid, RenderContext,
},
};
pub(in crate::rendering) fn render(
context: &mut RenderContext<'_, impl ResourceAllocator>,
[width, height]: [f32; 2],
component: &State,
layout_state: &LayoutState,
) {
context.render_rectangle([0.0, 0.0], [width, height], &component.background);
match &component.text {
TextState::Center(text) => context.render_text_centered(
text,
PADDING,
width - PADDING,
[0.5 * width, TEXT_ALIGN_TOP],
DEFAULT_TEXT_SIZE,
solid(
&component
.left_center_color
.unwrap_or(layout_state.text_color),
),
),
TextState::Split(left, right) => context.render_key_value_component(
&left,
&[],
&right,
false,
[width, height],
component
.left_center_color
.unwrap_or(layout_state.text_color),
component.right_color.unwrap_or(layout_state.text_color),
component.display_two_rows || layout_state.direction == LayoutDirection::Horizontal,
),
}
}
| 31.2 | 96 | 0.56339 |
8921152c670137c774f1b1e72b7b96ee090f5474
| 484 |
use std::process::Command;
use std::process::Stdio;
use crate::config_parser::WatcherConfig;
pub fn launch_command(config: &WatcherConfig) {
let config = &config.command_config;
let mut command = Command::new(config.binary_path.as_str());
command.args(&config.args)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
debug!("{:?}", command);
let mut process = command.spawn()
.expect("!spawn");
process.wait().expect("!wait");
}
| 24.2 | 64 | 0.642562 |
1d4c31878420f3dbbdb6ec71a6fab4467456baf1
| 79,196 |
use lib::*;
use de::{
Deserialize, Deserializer, EnumAccess, Error, SeqAccess, Unexpected, VariantAccess, Visitor,
};
#[cfg(any(core_duration, feature = "std", feature = "alloc"))]
use de::MapAccess;
use de::from_primitive::FromPrimitive;
use private::de::InPlaceSeed;
#[cfg(any(feature = "std", feature = "alloc"))]
use private::de::size_hint;
////////////////////////////////////////////////////////////////////////////////
struct UnitVisitor;
impl<'de> Visitor<'de> for UnitVisitor {
type Value = ();
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("unit")
}
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(())
}
}
impl<'de> Deserialize<'de> for () {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_unit(UnitVisitor)
}
}
#[cfg(feature = "unstable")]
impl<'de> Deserialize<'de> for ! {
fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Err(Error::custom("cannot deserialize `!`"))
}
}
////////////////////////////////////////////////////////////////////////////////
struct BoolVisitor;
impl<'de> Visitor<'de> for BoolVisitor {
type Value = bool;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a boolean")
}
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v)
}
}
impl<'de> Deserialize<'de> for bool {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_bool(BoolVisitor)
}
}
////////////////////////////////////////////////////////////////////////////////
macro_rules! visit_integer_method {
($src_ty:ident, $method:ident, $from_method:ident, $group:ident, $group_ty:ident) => {
#[inline]
fn $method<E>(self, v: $src_ty) -> Result<Self::Value, E>
where
E: Error,
{
match FromPrimitive::$from_method(v) {
Some(v) => Ok(v),
None => Err(Error::invalid_value(Unexpected::$group(v as $group_ty), &self)),
}
}
}
}
macro_rules! visit_float_method {
($src_ty:ident, $method:ident) => {
#[inline]
fn $method<E>(self, v: $src_ty) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v as Self::Value)
}
}
}
macro_rules! impl_deserialize_num {
($ty:ident, $method:ident, $($visit:ident),*) => {
impl<'de> Deserialize<'de> for $ty {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct PrimitiveVisitor;
impl<'de> Visitor<'de> for PrimitiveVisitor {
type Value = $ty;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(stringify!($ty))
}
$(
impl_deserialize_num!($visit $ty);
)*
}
deserializer.$method(PrimitiveVisitor)
}
}
};
(integer $ty:ident) => {
visit_integer_method!(i8, visit_i8, from_i8, Signed, i64);
visit_integer_method!(i16, visit_i16, from_i16, Signed, i64);
visit_integer_method!(i32, visit_i32, from_i32, Signed, i64);
visit_integer_method!(i64, visit_i64, from_i64, Signed, i64);
visit_integer_method!(u8, visit_u8, from_u8, Unsigned, u64);
visit_integer_method!(u16, visit_u16, from_u16, Unsigned, u64);
visit_integer_method!(u32, visit_u32, from_u32, Unsigned, u64);
visit_integer_method!(u64, visit_u64, from_u64, Unsigned, u64);
};
(float $ty:ident) => {
visit_float_method!(f32, visit_f32);
visit_float_method!(f64, visit_f64);
};
}
impl_deserialize_num!(i8, deserialize_i8, integer);
impl_deserialize_num!(i16, deserialize_i16, integer);
impl_deserialize_num!(i32, deserialize_i32, integer);
impl_deserialize_num!(i64, deserialize_i64, integer);
impl_deserialize_num!(isize, deserialize_i64, integer);
impl_deserialize_num!(u8, deserialize_u8, integer);
impl_deserialize_num!(u16, deserialize_u16, integer);
impl_deserialize_num!(u32, deserialize_u32, integer);
impl_deserialize_num!(u64, deserialize_u64, integer);
impl_deserialize_num!(usize, deserialize_u64, integer);
impl_deserialize_num!(f32, deserialize_f32, integer, float);
impl_deserialize_num!(f64, deserialize_f64, integer, float);
serde_if_integer128! {
impl<'de> Deserialize<'de> for i128 {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct PrimitiveVisitor;
impl<'de> Visitor<'de> for PrimitiveVisitor {
type Value = i128;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("i128")
}
impl_deserialize_num!(integer i128);
#[inline]
fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v)
}
#[inline]
fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
where
E: Error,
{
if v <= i128::max_value() as u128 {
Ok(v as i128)
} else {
Err(Error::invalid_value(Unexpected::Other("u128"), &self))
}
}
}
deserializer.deserialize_i128(PrimitiveVisitor)
}
}
impl<'de> Deserialize<'de> for u128 {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct PrimitiveVisitor;
impl<'de> Visitor<'de> for PrimitiveVisitor {
type Value = u128;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("u128")
}
impl_deserialize_num!(integer u128);
#[inline]
fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
where
E: Error,
{
if v >= 0 {
Ok(v as u128)
} else {
Err(Error::invalid_value(Unexpected::Other("i128"), &self))
}
}
#[inline]
fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v)
}
}
deserializer.deserialize_u128(PrimitiveVisitor)
}
}
}
////////////////////////////////////////////////////////////////////////////////
struct CharVisitor;
impl<'de> Visitor<'de> for CharVisitor {
type Value = char;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a character")
}
#[inline]
fn visit_char<E>(self, v: char) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v)
}
#[inline]
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
let mut iter = v.chars();
match (iter.next(), iter.next()) {
(Some(c), None) => Ok(c),
_ => Err(Error::invalid_value(Unexpected::Str(v), &self)),
}
}
}
impl<'de> Deserialize<'de> for char {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_char(CharVisitor)
}
}
////////////////////////////////////////////////////////////////////////////////
#[cfg(any(feature = "std", feature = "alloc"))]
struct StringVisitor;
#[cfg(any(feature = "std", feature = "alloc"))]
struct StringInPlaceVisitor<'a>(&'a mut String);
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'de> Visitor<'de> for StringVisitor {
type Value = String;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v.to_owned())
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v)
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match str::from_utf8(v) {
Ok(s) => Ok(s.to_owned()),
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
}
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
match String::from_utf8(v) {
Ok(s) => Ok(s),
Err(e) => Err(Error::invalid_value(
Unexpected::Bytes(&e.into_bytes()),
&self,
)),
}
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, 'de> Visitor<'de> for StringInPlaceVisitor<'a> {
type Value = ();
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
self.0.clear();
self.0.push_str(v);
Ok(())
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
*self.0 = v;
Ok(())
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match str::from_utf8(v) {
Ok(s) => {
self.0.clear();
self.0.push_str(s);
Ok(())
}
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
}
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
match String::from_utf8(v) {
Ok(s) => {
*self.0 = s;
Ok(())
}
Err(e) => Err(Error::invalid_value(
Unexpected::Bytes(&e.into_bytes()),
&self,
)),
}
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'de> Deserialize<'de> for String {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_string(StringVisitor)
}
fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_string(StringInPlaceVisitor(place))
}
}
////////////////////////////////////////////////////////////////////////////////
struct StrVisitor;
impl<'a> Visitor<'a> for StrVisitor {
type Value = &'a str;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a borrowed string")
}
fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v) // so easy
}
fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
where
E: Error,
{
str::from_utf8(v).map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
}
}
impl<'de: 'a, 'a> Deserialize<'de> for &'a str {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(StrVisitor)
}
}
////////////////////////////////////////////////////////////////////////////////
struct BytesVisitor;
impl<'a> Visitor<'a> for BytesVisitor {
type Value = &'a [u8];
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a borrowed byte array")
}
fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v)
}
fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v.as_bytes())
}
}
impl<'de: 'a, 'a> Deserialize<'de> for &'a [u8] {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_bytes(BytesVisitor)
}
}
////////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "std")]
struct CStringVisitor;
#[cfg(feature = "std")]
impl<'de> Visitor<'de> for CStringVisitor {
type Value = CString;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("byte array")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let len = size_hint::cautious(seq.size_hint());
let mut values = Vec::with_capacity(len);
while let Some(value) = try!(seq.next_element()) {
values.push(value);
}
CString::new(values).map_err(Error::custom)
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
CString::new(v).map_err(Error::custom)
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
CString::new(v).map_err(Error::custom)
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
CString::new(v).map_err(Error::custom)
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
CString::new(v).map_err(Error::custom)
}
}
#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for CString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_byte_buf(CStringVisitor)
}
}
macro_rules! forwarded_impl {
(
$(#[doc = $doc:tt])*
( $($id: ident),* ), $ty: ty, $func: expr
) => {
$(#[doc = $doc])*
impl<'de $(, $id : Deserialize<'de>,)*> Deserialize<'de> for $ty {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Deserialize::deserialize(deserializer).map($func)
}
}
}
}
#[cfg(all(feature = "std", de_boxed_c_str))]
forwarded_impl!((), Box<CStr>, CString::into_boxed_c_str);
#[cfg(core_reverse)]
forwarded_impl!((T), Reverse<T>, Reverse);
////////////////////////////////////////////////////////////////////////////////
struct OptionVisitor<T> {
marker: PhantomData<T>,
}
impl<'de, T> Visitor<'de> for OptionVisitor<T>
where
T: Deserialize<'de>,
{
type Value = Option<T>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("option")
}
#[inline]
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(None)
}
#[inline]
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(None)
}
#[inline]
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
T::deserialize(deserializer).map(Some)
}
#[doc(hidden)]
fn __private_visit_untagged_option<D>(self, deserializer: D) -> Result<Self::Value, ()>
where
D: Deserializer<'de>,
{
Ok(T::deserialize(deserializer).ok())
}
}
impl<'de, T> Deserialize<'de> for Option<T>
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_option(OptionVisitor {
marker: PhantomData,
})
}
// The Some variant's repr is opaque, so we can't play cute tricks with its
// tag to have deserialize_in_place build the content in place unconditionally.
//
// FIXME: investigate whether branching on the old value being Some to
// deserialize_in_place the value is profitable (probably data-dependent?)
}
////////////////////////////////////////////////////////////////////////////////
struct PhantomDataVisitor<T: ?Sized> {
marker: PhantomData<T>,
}
impl<'de, T: ?Sized> Visitor<'de> for PhantomDataVisitor<T> {
type Value = PhantomData<T>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("unit")
}
#[inline]
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(PhantomData)
}
}
impl<'de, T: ?Sized> Deserialize<'de> for PhantomData<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let visitor = PhantomDataVisitor {
marker: PhantomData,
};
deserializer.deserialize_unit_struct("PhantomData", visitor)
}
}
////////////////////////////////////////////////////////////////////////////////
#[cfg(any(feature = "std", feature = "alloc"))]
macro_rules! seq_impl {
(
$ty:ident < T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >,
$access:ident,
$clear:expr,
$with_capacity:expr,
$reserve:expr,
$insert:expr
) => {
impl<'de, T $(, $typaram)*> Deserialize<'de> for $ty<T $(, $typaram)*>
where
T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*,
$($typaram: $bound1 $(+ $bound2)*,)*
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct SeqVisitor<T $(, $typaram)*> {
marker: PhantomData<$ty<T $(, $typaram)*>>,
}
impl<'de, T $(, $typaram)*> Visitor<'de> for SeqVisitor<T $(, $typaram)*>
where
T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*,
$($typaram: $bound1 $(+ $bound2)*,)*
{
type Value = $ty<T $(, $typaram)*>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a sequence")
}
#[inline]
fn visit_seq<A>(self, mut $access: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut values = $with_capacity;
while let Some(value) = try!($access.next_element()) {
$insert(&mut values, value);
}
Ok(values)
}
}
let visitor = SeqVisitor { marker: PhantomData };
deserializer.deserialize_seq(visitor)
}
fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
where
D: Deserializer<'de>,
{
struct SeqInPlaceVisitor<'a, T: 'a $(, $typaram: 'a)*>(&'a mut $ty<T $(, $typaram)*>);
impl<'a, 'de, T $(, $typaram)*> Visitor<'de> for SeqInPlaceVisitor<'a, T $(, $typaram)*>
where
T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*,
$($typaram: $bound1 $(+ $bound2)*,)*
{
type Value = ();
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a sequence")
}
#[inline]
fn visit_seq<A>(mut self, mut $access: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
$clear(&mut self.0);
$reserve(&mut self.0, size_hint::cautious($access.size_hint()));
// FIXME: try to overwrite old values here? (Vec, VecDeque, LinkedList)
while let Some(value) = try!($access.next_element()) {
$insert(&mut self.0, value);
}
Ok(())
}
}
deserializer.deserialize_seq(SeqInPlaceVisitor(place))
}
}
}
}
// Dummy impl of reserve
#[cfg(any(feature = "std", feature = "alloc"))]
fn nop_reserve<T>(_seq: T, _n: usize) {}
#[cfg(any(feature = "std", feature = "alloc"))]
seq_impl!(
BinaryHeap<T: Ord>,
seq,
BinaryHeap::clear,
BinaryHeap::with_capacity(size_hint::cautious(seq.size_hint())),
BinaryHeap::reserve,
BinaryHeap::push);
#[cfg(any(feature = "std", feature = "alloc"))]
seq_impl!(
BTreeSet<T: Eq + Ord>,
seq,
BTreeSet::clear,
BTreeSet::new(),
nop_reserve,
BTreeSet::insert);
#[cfg(any(feature = "std", feature = "alloc"))]
seq_impl!(
LinkedList<T>,
seq,
LinkedList::clear,
LinkedList::new(),
nop_reserve,
LinkedList::push_back
);
#[cfg(feature = "std")]
seq_impl!(
HashSet<T: Eq + Hash, S: BuildHasher + Default>,
seq,
HashSet::clear,
HashSet::with_capacity_and_hasher(size_hint::cautious(seq.size_hint()), S::default()),
HashSet::reserve,
HashSet::insert);
#[cfg(any(feature = "std", feature = "alloc"))]
seq_impl!(
VecDeque<T>,
seq,
VecDeque::clear,
VecDeque::with_capacity(size_hint::cautious(seq.size_hint())),
VecDeque::reserve,
VecDeque::push_back
);
////////////////////////////////////////////////////////////////////////////////
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'de, T> Deserialize<'de> for Vec<T>
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct VecVisitor<T> {
marker: PhantomData<T>,
}
impl<'de, T> Visitor<'de> for VecVisitor<T>
where
T: Deserialize<'de>,
{
type Value = Vec<T>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a sequence")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut values = Vec::with_capacity(size_hint::cautious(seq.size_hint()));
while let Some(value) = try!(seq.next_element()) {
values.push(value);
}
Ok(values)
}
}
let visitor = VecVisitor {
marker: PhantomData,
};
deserializer.deserialize_seq(visitor)
}
fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
where
D: Deserializer<'de>,
{
struct VecInPlaceVisitor<'a, T: 'a>(&'a mut Vec<T>);
impl<'a, 'de, T> Visitor<'de> for VecInPlaceVisitor<'a, T>
where
T: Deserialize<'de>,
{
type Value = ();
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a sequence")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let hint = size_hint::cautious(seq.size_hint());
if let Some(additional) = hint.checked_sub(self.0.len()) {
self.0.reserve(additional);
}
for i in 0..self.0.len() {
let next = {
let next_place = InPlaceSeed(&mut self.0[i]);
try!(seq.next_element_seed(next_place))
};
if next.is_none() {
self.0.truncate(i);
return Ok(());
}
}
while let Some(value) = try!(seq.next_element()) {
self.0.push(value);
}
Ok(())
}
}
deserializer.deserialize_seq(VecInPlaceVisitor(place))
}
}
////////////////////////////////////////////////////////////////////////////////
struct ArrayVisitor<A> {
marker: PhantomData<A>,
}
struct ArrayInPlaceVisitor<'a, A: 'a>(&'a mut A);
impl<A> ArrayVisitor<A> {
fn new() -> Self {
ArrayVisitor {
marker: PhantomData,
}
}
}
impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]> {
type Value = [T; 0];
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("an empty array")
}
#[inline]
fn visit_seq<A>(self, _: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
Ok([])
}
}
// Does not require T: Deserialize<'de>.
impl<'de, T> Deserialize<'de> for [T; 0] {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_tuple(0, ArrayVisitor::<[T; 0]>::new())
}
}
macro_rules! array_impls {
($($len:expr => ($($n:tt)+))+) => {
$(
impl<'de, T> Visitor<'de> for ArrayVisitor<[T; $len]>
where
T: Deserialize<'de>,
{
type Value = [T; $len];
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(concat!("an array of length ", $len))
}
#[inline]
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
Ok([$(
match try!(seq.next_element()) {
Some(val) => val,
None => return Err(Error::invalid_length($n, &self)),
}
),+])
}
}
impl<'a, 'de, T> Visitor<'de> for ArrayInPlaceVisitor<'a, [T; $len]>
where
T: Deserialize<'de>,
{
type Value = ();
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(concat!("an array of length ", $len))
}
#[inline]
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut fail_idx = None;
for (idx, dest) in self.0[..].iter_mut().enumerate() {
if try!(seq.next_element_seed(InPlaceSeed(dest))).is_none() {
fail_idx = Some(idx);
break;
}
}
if let Some(idx) = fail_idx {
return Err(Error::invalid_length(idx, &self));
}
Ok(())
}
}
impl<'de, T> Deserialize<'de> for [T; $len]
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_tuple($len, ArrayVisitor::<[T; $len]>::new())
}
fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_tuple($len, ArrayInPlaceVisitor(place))
}
}
)+
}
}
array_impls! {
1 => (0)
2 => (0 1)
3 => (0 1 2)
4 => (0 1 2 3)
5 => (0 1 2 3 4)
6 => (0 1 2 3 4 5)
7 => (0 1 2 3 4 5 6)
8 => (0 1 2 3 4 5 6 7)
9 => (0 1 2 3 4 5 6 7 8)
10 => (0 1 2 3 4 5 6 7 8 9)
11 => (0 1 2 3 4 5 6 7 8 9 10)
12 => (0 1 2 3 4 5 6 7 8 9 10 11)
13 => (0 1 2 3 4 5 6 7 8 9 10 11 12)
14 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13)
15 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14)
16 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)
17 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16)
18 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17)
19 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18)
20 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19)
21 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20)
22 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21)
23 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22)
24 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23)
25 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24)
26 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25)
27 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26)
28 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27)
29 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28)
30 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29)
31 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30)
32 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31)
}
////////////////////////////////////////////////////////////////////////////////
macro_rules! tuple_impls {
($($len:tt => ($($n:tt $name:ident)+))+) => {
$(
impl<'de, $($name: Deserialize<'de>),+> Deserialize<'de> for ($($name,)+) {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct TupleVisitor<$($name,)+> {
marker: PhantomData<($($name,)+)>,
}
impl<'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleVisitor<$($name,)+> {
type Value = ($($name,)+);
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(concat!("a tuple of size ", $len))
}
#[inline]
#[allow(non_snake_case)]
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
$(
let $name = match try!(seq.next_element()) {
Some(value) => value,
None => return Err(Error::invalid_length($n, &self)),
};
)+
Ok(($($name,)+))
}
}
deserializer.deserialize_tuple($len, TupleVisitor { marker: PhantomData })
}
#[inline]
fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
where
D: Deserializer<'de>,
{
struct TupleInPlaceVisitor<'a, $($name: 'a,)+>(&'a mut ($($name,)+));
impl<'a, 'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleInPlaceVisitor<'a, $($name,)+> {
type Value = ();
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(concat!("a tuple of size ", $len))
}
#[inline]
#[allow(non_snake_case)]
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
$(
if try!(seq.next_element_seed(InPlaceSeed(&mut (self.0).$n))).is_none() {
return Err(Error::invalid_length($n, &self));
}
)+
Ok(())
}
}
deserializer.deserialize_tuple($len, TupleInPlaceVisitor(place))
}
}
)+
}
}
tuple_impls! {
1 => (0 T0)
2 => (0 T0 1 T1)
3 => (0 T0 1 T1 2 T2)
4 => (0 T0 1 T1 2 T2 3 T3)
5 => (0 T0 1 T1 2 T2 3 T3 4 T4)
6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5)
7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6)
8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7)
9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8)
10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9)
11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10)
12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11)
13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12)
14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13)
15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14)
16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15)
}
////////////////////////////////////////////////////////////////////////////////
#[cfg(any(feature = "std", feature = "alloc"))]
macro_rules! map_impl {
(
$ty:ident < K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >,
$access:ident,
$with_capacity:expr
) => {
impl<'de, K, V $(, $typaram)*> Deserialize<'de> for $ty<K, V $(, $typaram)*>
where
K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*,
V: Deserialize<'de>,
$($typaram: $bound1 $(+ $bound2)*),*
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct MapVisitor<K, V $(, $typaram)*> {
marker: PhantomData<$ty<K, V $(, $typaram)*>>,
}
impl<'de, K, V $(, $typaram)*> Visitor<'de> for MapVisitor<K, V $(, $typaram)*>
where
K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*,
V: Deserialize<'de>,
$($typaram: $bound1 $(+ $bound2)*),*
{
type Value = $ty<K, V $(, $typaram)*>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a map")
}
#[inline]
fn visit_map<A>(self, mut $access: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut values = $with_capacity;
while let Some((key, value)) = try!($access.next_entry()) {
values.insert(key, value);
}
Ok(values)
}
}
let visitor = MapVisitor { marker: PhantomData };
deserializer.deserialize_map(visitor)
}
}
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
map_impl!(
BTreeMap<K: Ord, V>,
map,
BTreeMap::new());
#[cfg(feature = "std")]
map_impl!(
HashMap<K: Eq + Hash, V, S: BuildHasher + Default>,
map,
HashMap::with_capacity_and_hasher(size_hint::cautious(map.size_hint()), S::default()));
////////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "std")]
macro_rules! parse_ip_impl {
($expecting:tt $ty:ty; $size:tt) => {
impl<'de> Deserialize<'de> for $ty {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
if deserializer.is_human_readable() {
struct IpAddrVisitor;
impl<'de> Visitor<'de> for IpAddrVisitor {
type Value = $ty;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str($expecting)
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: Error,
{
s.parse().map_err(Error::custom)
}
}
deserializer.deserialize_str(IpAddrVisitor)
} else {
<[u8; $size]>::deserialize(deserializer).map(<$ty>::from)
}
}
}
};
}
#[cfg(feature = "std")]
macro_rules! variant_identifier {
(
$name_kind: ident ( $($variant: ident; $bytes: expr; $index: expr),* )
$expecting_message: expr,
$variants_name: ident
) => {
enum $name_kind {
$( $variant ),*
}
static $variants_name: &'static [&'static str] = &[ $( stringify!($variant) ),*];
impl<'de> Deserialize<'de> for $name_kind {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct KindVisitor;
impl<'de> Visitor<'de> for KindVisitor {
type Value = $name_kind;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str($expecting_message)
}
fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E>
where
E: Error,
{
match value {
$(
$index => Ok($name_kind :: $variant),
)*
_ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self),),
}
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: Error,
{
match value {
$(
stringify!($variant) => Ok($name_kind :: $variant),
)*
_ => Err(Error::unknown_variant(value, $variants_name)),
}
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match value {
$(
$bytes => Ok($name_kind :: $variant),
)*
_ => {
match str::from_utf8(value) {
Ok(value) => Err(Error::unknown_variant(value, $variants_name)),
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),
}
}
}
}
}
deserializer.deserialize_identifier(KindVisitor)
}
}
}
}
#[cfg(feature = "std")]
macro_rules! deserialize_enum {
(
$name: ident $name_kind: ident ( $($variant: ident; $bytes: expr; $index: expr),* )
$expecting_message: expr,
$deserializer: expr
) => {
variant_identifier!{
$name_kind ( $($variant; $bytes; $index),* )
$expecting_message,
VARIANTS
}
struct EnumVisitor;
impl<'de> Visitor<'de> for EnumVisitor {
type Value = $name;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(concat!("a ", stringify!($name)))
}
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
A: EnumAccess<'de>,
{
match try!(data.variant()) {
$(
($name_kind :: $variant, v) => v.newtype_variant().map($name :: $variant),
)*
}
}
}
$deserializer.deserialize_enum(stringify!($name), VARIANTS, EnumVisitor)
}
}
#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for net::IpAddr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
if deserializer.is_human_readable() {
struct IpAddrVisitor;
impl<'de> Visitor<'de> for IpAddrVisitor {
type Value = net::IpAddr;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("IP address")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: Error,
{
s.parse().map_err(Error::custom)
}
}
deserializer.deserialize_str(IpAddrVisitor)
} else {
use lib::net::IpAddr;
deserialize_enum! {
IpAddr IpAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)
"`V4` or `V6`",
deserializer
}
}
}
}
#[cfg(feature = "std")]
parse_ip_impl!("IPv4 address" net::Ipv4Addr; 4);
#[cfg(feature = "std")]
parse_ip_impl!("IPv6 address" net::Ipv6Addr; 16);
#[cfg(feature = "std")]
macro_rules! parse_socket_impl {
($expecting:tt $ty:ty, $new:expr) => {
impl<'de> Deserialize<'de> for $ty {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
if deserializer.is_human_readable() {
struct SocketAddrVisitor;
impl<'de> Visitor<'de> for SocketAddrVisitor {
type Value = $ty;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str($expecting)
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: Error,
{
s.parse().map_err(Error::custom)
}
}
deserializer.deserialize_str(SocketAddrVisitor)
} else {
<(_, u16)>::deserialize(deserializer).map(|(ip, port)| $new(ip, port))
}
}
}
};
}
#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for net::SocketAddr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
if deserializer.is_human_readable() {
struct SocketAddrVisitor;
impl<'de> Visitor<'de> for SocketAddrVisitor {
type Value = net::SocketAddr;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("socket address")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: Error,
{
s.parse().map_err(Error::custom)
}
}
deserializer.deserialize_str(SocketAddrVisitor)
} else {
use lib::net::SocketAddr;
deserialize_enum! {
SocketAddr SocketAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)
"`V4` or `V6`",
deserializer
}
}
}
}
#[cfg(feature = "std")]
parse_socket_impl!("IPv4 socket address" net::SocketAddrV4, net::SocketAddrV4::new);
#[cfg(feature = "std")]
parse_socket_impl!("IPv6 socket address" net::SocketAddrV6, |ip, port| net::SocketAddrV6::new(
ip, port, 0, 0
));
////////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "std")]
struct PathVisitor;
#[cfg(feature = "std")]
impl<'a> Visitor<'a> for PathVisitor {
type Value = &'a Path;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a borrowed path")
}
fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v.as_ref())
}
fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
where
E: Error,
{
str::from_utf8(v)
.map(AsRef::as_ref)
.map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
}
}
#[cfg(feature = "std")]
impl<'de: 'a, 'a> Deserialize<'de> for &'a Path {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(PathVisitor)
}
}
#[cfg(feature = "std")]
struct PathBufVisitor;
#[cfg(feature = "std")]
impl<'de> Visitor<'de> for PathBufVisitor {
type Value = PathBuf;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("path string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(From::from(v))
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
Ok(From::from(v))
}
}
#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for PathBuf {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_string(PathBufVisitor)
}
}
////////////////////////////////////////////////////////////////////////////////
// If this were outside of the serde crate, it would just use:
//
// #[derive(Deserialize)]
// #[serde(variant_identifier)]
#[cfg(all(feature = "std", any(unix, windows)))]
variant_identifier! {
OsStringKind (Unix; b"Unix"; 0, Windows; b"Windows"; 1)
"`Unix` or `Windows`",
OSSTR_VARIANTS
}
#[cfg(all(feature = "std", any(unix, windows)))]
struct OsStringVisitor;
#[cfg(all(feature = "std", any(unix, windows)))]
impl<'de> Visitor<'de> for OsStringVisitor {
type Value = OsString;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("os string")
}
#[cfg(unix)]
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
A: EnumAccess<'de>,
{
use std::os::unix::ffi::OsStringExt;
match try!(data.variant()) {
(OsStringKind::Unix, v) => v.newtype_variant().map(OsString::from_vec),
(OsStringKind::Windows, _) => Err(Error::custom(
"cannot deserialize Windows OS string on Unix",
)),
}
}
#[cfg(windows)]
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
A: EnumAccess<'de>,
{
use std::os::windows::ffi::OsStringExt;
match try!(data.variant()) {
(OsStringKind::Windows, v) => v
.newtype_variant::<Vec<u16>>()
.map(|vec| OsString::from_wide(&vec)),
(OsStringKind::Unix, _) => Err(Error::custom(
"cannot deserialize Unix OS string on Windows",
)),
}
}
}
#[cfg(all(feature = "std", any(unix, windows)))]
impl<'de> Deserialize<'de> for OsString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_enum("OsString", OSSTR_VARIANTS, OsStringVisitor)
}
}
////////////////////////////////////////////////////////////////////////////////
#[cfg(any(feature = "std", feature = "alloc"))]
forwarded_impl!((T), Box<T>, Box::new);
#[cfg(any(feature = "std", feature = "alloc"))]
forwarded_impl!((T), Box<[T]>, Vec::into_boxed_slice);
#[cfg(any(feature = "std", feature = "alloc"))]
forwarded_impl!((), Box<str>, String::into_boxed_str);
#[cfg(all(
not(de_rc_dst),
feature = "rc",
any(feature = "std", feature = "alloc")
))]
forwarded_impl! {
/// This impl requires the [`"rc"`] Cargo feature of Serde.
///
/// Deserializing a data structure containing `Arc` will not attempt to
/// deduplicate `Arc` references to the same data. Every deserialized `Arc`
/// will end up with a strong count of 1.
///
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
(T), Arc<T>, Arc::new
}
#[cfg(all(
not(de_rc_dst),
feature = "rc",
any(feature = "std", feature = "alloc")
))]
forwarded_impl! {
/// This impl requires the [`"rc"`] Cargo feature of Serde.
///
/// Deserializing a data structure containing `Rc` will not attempt to
/// deduplicate `Rc` references to the same data. Every deserialized `Rc`
/// will end up with a strong count of 1.
///
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
(T), Rc<T>, Rc::new
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T>
where
T: ToOwned,
T::Owned: Deserialize<'de>,
{
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
T::Owned::deserialize(deserializer).map(Cow::Owned)
}
}
////////////////////////////////////////////////////////////////////////////////
/// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting
/// `Weak<T>` has a reference count of 0 and cannot be upgraded.
///
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
impl<'de, T: ?Sized> Deserialize<'de> for RcWeak<T>
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
try!(Option::<T>::deserialize(deserializer));
Ok(RcWeak::new())
}
}
/// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting
/// `Weak<T>` has a reference count of 0 and cannot be upgraded.
///
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
impl<'de, T: ?Sized> Deserialize<'de> for ArcWeak<T>
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
try!(Option::<T>::deserialize(deserializer));
Ok(ArcWeak::new())
}
}
////////////////////////////////////////////////////////////////////////////////
#[cfg(all(de_rc_dst, feature = "rc", any(feature = "std", feature = "alloc")))]
macro_rules! box_forwarded_impl {
(
$(#[doc = $doc:tt])*
$t:ident
) => {
$(#[doc = $doc])*
impl<'de, T: ?Sized> Deserialize<'de> for $t<T>
where
Box<T>: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Box::deserialize(deserializer).map(Into::into)
}
}
};
}
#[cfg(all(de_rc_dst, feature = "rc", any(feature = "std", feature = "alloc")))]
box_forwarded_impl! {
/// This impl requires the [`"rc"`] Cargo feature of Serde.
///
/// Deserializing a data structure containing `Rc` will not attempt to
/// deduplicate `Rc` references to the same data. Every deserialized `Rc`
/// will end up with a strong count of 1.
///
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
Rc
}
#[cfg(all(de_rc_dst, feature = "rc", any(feature = "std", feature = "alloc")))]
box_forwarded_impl! {
/// This impl requires the [`"rc"`] Cargo feature of Serde.
///
/// Deserializing a data structure containing `Arc` will not attempt to
/// deduplicate `Arc` references to the same data. Every deserialized `Arc`
/// will end up with a strong count of 1.
///
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
Arc
}
////////////////////////////////////////////////////////////////////////////////
impl<'de, T> Deserialize<'de> for Cell<T>
where
T: Deserialize<'de> + Copy,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
T::deserialize(deserializer).map(Cell::new)
}
}
forwarded_impl!((T), RefCell<T>, RefCell::new);
#[cfg(feature = "std")]
forwarded_impl!((T), Mutex<T>, Mutex::new);
#[cfg(feature = "std")]
forwarded_impl!((T), RwLock<T>, RwLock::new);
////////////////////////////////////////////////////////////////////////////////
// This is a cleaned-up version of the impl generated by:
//
// #[derive(Deserialize)]
// #[serde(deny_unknown_fields)]
// struct Duration {
// secs: u64,
// nanos: u32,
// }
#[cfg(any(core_duration, feature = "std"))]
impl<'de> Deserialize<'de> for Duration {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// If this were outside of the serde crate, it would just use:
//
// #[derive(Deserialize)]
// #[serde(field_identifier, rename_all = "lowercase")]
enum Field {
Secs,
Nanos,
};
impl<'de> Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`secs` or `nanos`")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: Error,
{
match value {
"secs" => Ok(Field::Secs),
"nanos" => Ok(Field::Nanos),
_ => Err(Error::unknown_field(value, FIELDS)),
}
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match value {
b"secs" => Ok(Field::Secs),
b"nanos" => Ok(Field::Nanos),
_ => {
let value = ::export::from_utf8_lossy(value);
Err(Error::unknown_field(&value, FIELDS))
}
}
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct DurationVisitor;
impl<'de> Visitor<'de> for DurationVisitor {
type Value = Duration;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("struct Duration")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let secs: u64 = match try!(seq.next_element()) {
Some(value) => value,
None => {
return Err(Error::invalid_length(0, &self));
}
};
let nanos: u32 = match try!(seq.next_element()) {
Some(value) => value,
None => {
return Err(Error::invalid_length(1, &self));
}
};
Ok(Duration::new(secs, nanos))
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut secs: Option<u64> = None;
let mut nanos: Option<u32> = None;
while let Some(key) = try!(map.next_key()) {
match key {
Field::Secs => {
if secs.is_some() {
return Err(<A::Error as Error>::duplicate_field("secs"));
}
secs = Some(try!(map.next_value()));
}
Field::Nanos => {
if nanos.is_some() {
return Err(<A::Error as Error>::duplicate_field("nanos"));
}
nanos = Some(try!(map.next_value()));
}
}
}
let secs = match secs {
Some(secs) => secs,
None => return Err(<A::Error as Error>::missing_field("secs")),
};
let nanos = match nanos {
Some(nanos) => nanos,
None => return Err(<A::Error as Error>::missing_field("nanos")),
};
Ok(Duration::new(secs, nanos))
}
}
const FIELDS: &'static [&'static str] = &["secs", "nanos"];
deserializer.deserialize_struct("Duration", FIELDS, DurationVisitor)
}
}
////////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for SystemTime {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Reuse duration
enum Field {
Secs,
Nanos,
};
impl<'de> Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`secs_since_epoch` or `nanos_since_epoch`")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: Error,
{
match value {
"secs_since_epoch" => Ok(Field::Secs),
"nanos_since_epoch" => Ok(Field::Nanos),
_ => Err(Error::unknown_field(value, FIELDS)),
}
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match value {
b"secs_since_epoch" => Ok(Field::Secs),
b"nanos_since_epoch" => Ok(Field::Nanos),
_ => {
let value = String::from_utf8_lossy(value);
Err(Error::unknown_field(&value, FIELDS))
}
}
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct DurationVisitor;
impl<'de> Visitor<'de> for DurationVisitor {
type Value = Duration;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("struct SystemTime")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let secs: u64 = match try!(seq.next_element()) {
Some(value) => value,
None => {
return Err(Error::invalid_length(0, &self));
}
};
let nanos: u32 = match try!(seq.next_element()) {
Some(value) => value,
None => {
return Err(Error::invalid_length(1, &self));
}
};
Ok(Duration::new(secs, nanos))
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut secs: Option<u64> = None;
let mut nanos: Option<u32> = None;
while let Some(key) = try!(map.next_key()) {
match key {
Field::Secs => {
if secs.is_some() {
return Err(<A::Error as Error>::duplicate_field(
"secs_since_epoch",
));
}
secs = Some(try!(map.next_value()));
}
Field::Nanos => {
if nanos.is_some() {
return Err(<A::Error as Error>::duplicate_field(
"nanos_since_epoch",
));
}
nanos = Some(try!(map.next_value()));
}
}
}
let secs = match secs {
Some(secs) => secs,
None => return Err(<A::Error as Error>::missing_field("secs_since_epoch")),
};
let nanos = match nanos {
Some(nanos) => nanos,
None => return Err(<A::Error as Error>::missing_field("nanos_since_epoch")),
};
Ok(Duration::new(secs, nanos))
}
}
const FIELDS: &'static [&'static str] = &["secs_since_epoch", "nanos_since_epoch"];
let duration = try!(deserializer.deserialize_struct("SystemTime", FIELDS, DurationVisitor));
Ok(UNIX_EPOCH + duration)
}
}
////////////////////////////////////////////////////////////////////////////////
// Similar to:
//
// #[derive(Deserialize)]
// #[serde(deny_unknown_fields)]
// struct Range {
// start: u64,
// end: u32,
// }
impl<'de, Idx> Deserialize<'de> for Range<Idx>
where
Idx: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (start, end) = deserializer.deserialize_struct(
"Range",
range::FIELDS,
range::RangeVisitor {
expecting: "struct Range",
phantom: PhantomData,
},
)?;
Ok(start..end)
}
}
#[cfg(range_inclusive)]
impl<'de, Idx> Deserialize<'de> for RangeInclusive<Idx>
where
Idx: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (start, end) = deserializer.deserialize_struct(
"RangeInclusive",
range::FIELDS,
range::RangeVisitor {
expecting: "struct RangeInclusive",
phantom: PhantomData,
},
)?;
Ok(RangeInclusive::new(start, end))
}
}
mod range {
use lib::*;
use de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor};
pub const FIELDS: &'static [&'static str] = &["start", "end"];
// If this were outside of the serde crate, it would just use:
//
// #[derive(Deserialize)]
// #[serde(field_identifier, rename_all = "lowercase")]
enum Field {
Start,
End,
}
impl<'de> Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`start` or `end`")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: Error,
{
match value {
"start" => Ok(Field::Start),
"end" => Ok(Field::End),
_ => Err(Error::unknown_field(value, FIELDS)),
}
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match value {
b"start" => Ok(Field::Start),
b"end" => Ok(Field::End),
_ => {
let value = ::export::from_utf8_lossy(value);
Err(Error::unknown_field(&value, FIELDS))
}
}
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
pub struct RangeVisitor<Idx> {
pub expecting: &'static str,
pub phantom: PhantomData<Idx>,
}
impl<'de, Idx> Visitor<'de> for RangeVisitor<Idx>
where
Idx: Deserialize<'de>,
{
type Value = (Idx, Idx);
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(self.expecting)
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let start: Idx = match try!(seq.next_element()) {
Some(value) => value,
None => {
return Err(Error::invalid_length(0, &self));
}
};
let end: Idx = match try!(seq.next_element()) {
Some(value) => value,
None => {
return Err(Error::invalid_length(1, &self));
}
};
Ok((start, end))
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut start: Option<Idx> = None;
let mut end: Option<Idx> = None;
while let Some(key) = try!(map.next_key()) {
match key {
Field::Start => {
if start.is_some() {
return Err(<A::Error as Error>::duplicate_field("start"));
}
start = Some(try!(map.next_value()));
}
Field::End => {
if end.is_some() {
return Err(<A::Error as Error>::duplicate_field("end"));
}
end = Some(try!(map.next_value()));
}
}
}
let start = match start {
Some(start) => start,
None => return Err(<A::Error as Error>::missing_field("start")),
};
let end = match end {
Some(end) => end,
None => return Err(<A::Error as Error>::missing_field("end")),
};
Ok((start, end))
}
}
}
////////////////////////////////////////////////////////////////////////////////
#[cfg(any(ops_bound, collections_bound))]
impl<'de, T> Deserialize<'de> for Bound<T>
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
enum Field {
Unbounded,
Included,
Excluded,
}
impl<'de> Deserialize<'de> for Field {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`Unbounded`, `Included` or `Excluded`")
}
fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E>
where
E: Error,
{
match value {
0 => Ok(Field::Unbounded),
1 => Ok(Field::Included),
2 => Ok(Field::Excluded),
_ => Err(Error::invalid_value(
Unexpected::Unsigned(value as u64),
&self,
)),
}
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: Error,
{
match value {
"Unbounded" => Ok(Field::Unbounded),
"Included" => Ok(Field::Included),
"Excluded" => Ok(Field::Excluded),
_ => Err(Error::unknown_variant(value, VARIANTS)),
}
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match value {
b"Unbounded" => Ok(Field::Unbounded),
b"Included" => Ok(Field::Included),
b"Excluded" => Ok(Field::Excluded),
_ => match str::from_utf8(value) {
Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
Err(_) => {
Err(Error::invalid_value(Unexpected::Bytes(value), &self))
}
},
}
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct BoundVisitor<T>(PhantomData<Bound<T>>);
impl<'de, T> Visitor<'de> for BoundVisitor<T>
where
T: Deserialize<'de>,
{
type Value = Bound<T>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("enum Bound")
}
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
A: EnumAccess<'de>,
{
match try!(data.variant()) {
(Field::Unbounded, v) => v.unit_variant().map(|()| Bound::Unbounded),
(Field::Included, v) => v.newtype_variant().map(Bound::Included),
(Field::Excluded, v) => v.newtype_variant().map(Bound::Excluded),
}
}
}
const VARIANTS: &'static [&'static str] = &["Unbounded", "Included", "Excluded"];
deserializer.deserialize_enum("Bound", VARIANTS, BoundVisitor(PhantomData))
}
}
////////////////////////////////////////////////////////////////////////////////
macro_rules! nonzero_integers {
( $( $T: ident, )+ ) => {
$(
#[cfg(num_nonzero)]
impl<'de> Deserialize<'de> for num::$T {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = try!(Deserialize::deserialize(deserializer));
match <num::$T>::new(value) {
Some(nonzero) => Ok(nonzero),
None => Err(Error::custom("expected a non-zero value")),
}
}
}
)+
};
}
nonzero_integers! {
// Not including signed NonZeroI* since they might be removed
NonZeroU8,
NonZeroU16,
NonZeroU32,
NonZeroU64,
NonZeroUsize,
}
// Currently 128-bit integers do not work on Emscripten targets so we need an
// additional `#[cfg]`
serde_if_integer128! {
nonzero_integers! {
NonZeroU128,
}
}
////////////////////////////////////////////////////////////////////////////////
impl<'de, T, E> Deserialize<'de> for Result<T, E>
where
T: Deserialize<'de>,
E: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// If this were outside of the serde crate, it would just use:
//
// #[derive(Deserialize)]
// #[serde(variant_identifier)]
enum Field {
Ok,
Err,
}
impl<'de> Deserialize<'de> for Field {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`Ok` or `Err`")
}
fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E>
where
E: Error,
{
match value {
0 => Ok(Field::Ok),
1 => Ok(Field::Err),
_ => Err(Error::invalid_value(
Unexpected::Unsigned(value as u64),
&self,
)),
}
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: Error,
{
match value {
"Ok" => Ok(Field::Ok),
"Err" => Ok(Field::Err),
_ => Err(Error::unknown_variant(value, VARIANTS)),
}
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match value {
b"Ok" => Ok(Field::Ok),
b"Err" => Ok(Field::Err),
_ => match str::from_utf8(value) {
Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
Err(_) => {
Err(Error::invalid_value(Unexpected::Bytes(value), &self))
}
},
}
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct ResultVisitor<T, E>(PhantomData<Result<T, E>>);
impl<'de, T, E> Visitor<'de> for ResultVisitor<T, E>
where
T: Deserialize<'de>,
E: Deserialize<'de>,
{
type Value = Result<T, E>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("enum Result")
}
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
A: EnumAccess<'de>,
{
match try!(data.variant()) {
(Field::Ok, v) => v.newtype_variant().map(Ok),
(Field::Err, v) => v.newtype_variant().map(Err),
}
}
}
const VARIANTS: &'static [&'static str] = &["Ok", "Err"];
deserializer.deserialize_enum("Result", VARIANTS, ResultVisitor(PhantomData))
}
}
////////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "std")]
impl<'de, T> Deserialize<'de> for Wrapping<T>
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Deserialize::deserialize(deserializer).map(Wrapping)
}
}
| 31.106049 | 126 | 0.449467 |
b9d4357f1cc89d730a837e051a2d69083f70de0a
| 1,569 |
pub struct IconOutbond {
props: crate::Props,
}
impl yew::Component for IconOutbond {
type Properties = crate::Props;
type Message = ();
fn create(props: Self::Properties, _: yew::prelude::ComponentLink<Self>) -> Self
{
Self { props }
}
fn update(&mut self, _: Self::Message) -> yew::prelude::ShouldRender
{
true
}
fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender
{
false
}
fn view(&self) -> yew::prelude::Html
{
yew::prelude::html! {
<svg
class=self.props.class.unwrap_or("")
width=self.props.size.unwrap_or(24).to_string()
height=self.props.size.unwrap_or(24).to_string()
viewBox="0 0 24 24"
fill=self.props.fill.unwrap_or("none")
stroke=self.props.color.unwrap_or("currentColor")
stroke-width=self.props.stroke_width.unwrap_or(2).to_string()
stroke-linecap=self.props.stroke_linecap.unwrap_or("round")
stroke-linejoin=self.props.stroke_linejoin.unwrap_or("round")
>
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><rect fill="none" height="24" width="24" x="0" y="0"/><path d="M12,2C6.48,2,2,6.48,2,12c0,5.52,4.48,10,10,10s10-4.48,10-10C22,6.48,17.52,2,12,2z M13.88,11.54l-4.96,4.96l-1.41-1.41 l4.96-4.96L10.34,8l5.65,0.01L16,13.66L13.88,11.54z"/><g/><g/><g/></svg>
</svg>
}
}
}
| 34.108696 | 380 | 0.574251 |
6946d872fcad69a315a4ec93c27ad2027f4af702
| 9,801 |
// Copyright (c) 2016 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 super::{sys::UnsafeImage, ImageDescriptorLayouts, ImageDimensions, ImageLayout, SampleCount};
use crate::{
format::{ClearValue, Format, FormatFeatures},
SafeDeref,
};
use std::{
hash::{Hash, Hasher},
sync::Arc,
};
/// Trait for types that represent the way a GPU can access an image.
pub unsafe trait ImageAccess: Send + Sync {
/// Returns the inner unsafe image object used by this image.
fn inner(&self) -> ImageInner;
/// Returns the format of this image.
#[inline]
fn format(&self) -> Format {
self.inner().image.format().unwrap()
}
/// Returns the number of mipmap levels of this image.
#[inline]
fn mip_levels(&self) -> u32 {
// TODO: not necessarily correct because of the new inner() design?
self.inner().image.mip_levels()
}
/// Returns the number of samples of this image.
#[inline]
fn samples(&self) -> SampleCount {
self.inner().image.samples()
}
/// Returns the dimensions of the image.
#[inline]
fn dimensions(&self) -> ImageDimensions {
// TODO: not necessarily correct because of the new inner() design?
self.inner().image.dimensions()
}
/// Returns the features supported by the image's format.
#[inline]
fn format_features(&self) -> &FormatFeatures {
self.inner().image.format_features()
}
/// When images are created their memory layout is initially `Undefined` or `Preinitialized`.
/// This method allows the image memory barrier creation process to signal when an image
/// has been transitioned out of its initial `Undefined` or `Preinitialized` state. This
/// allows vulkano to avoid creating unnecessary image memory barriers between future
/// uses of the image.
///
/// ## Unsafe
///
/// If a user calls this method outside of the intended context and signals that the layout
/// is no longer `Undefined` or `Preinitialized` when it is still in an `Undefined` or
/// `Preinitialized` state, this may result in the vulkan implementation attempting to use
/// an image in an invalid layout. The same problem must be considered by the implementer
/// of the method.
unsafe fn layout_initialized(&self) {}
fn is_layout_initialized(&self) -> bool {
false
}
unsafe fn initial_layout(&self) -> ImageLayout {
self.inner().image.initial_layout()
}
/// Returns the layout that the image has when it is first used in a primary command buffer.
///
/// The first time you use an image in an `AutoCommandBufferBuilder`, vulkano will suppose that
/// the image is in the layout returned by this function. Later when the command buffer is
/// submitted vulkano will check whether the image is actually in this layout, and if it is not
/// the case then an error will be returned.
/// TODO: ^ that check is not yet implemented
fn initial_layout_requirement(&self) -> ImageLayout;
/// Returns the layout that the image must be returned to before the end of the command buffer.
///
/// When an image is used in an `AutoCommandBufferBuilder` vulkano will automatically
/// transition this image to the layout returned by this function at the end of the command
/// buffer, if necessary.
///
/// Except for special cases, this value should likely be the same as the one returned by
/// `initial_layout_requirement` so that the user can submit multiple command buffers that use
/// this image one after the other.
fn final_layout_requirement(&self) -> ImageLayout;
/// Wraps around this `ImageAccess` and returns an identical `ImageAccess` but whose initial
/// layout requirement is either `Undefined` or `Preinitialized`.
#[inline]
unsafe fn forced_undefined_initial_layout(
self,
preinitialized: bool,
) -> Arc<ImageAccessFromUndefinedLayout<Self>>
where
Self: Sized,
{
Arc::new(ImageAccessFromUndefinedLayout {
image: self,
preinitialized,
})
}
/// Returns an [`ImageDescriptorLayouts`] structure specifying the image layout to use
/// in descriptors of various kinds.
///
/// This must return `Some` if the image is to be used to create an image view.
fn descriptor_layouts(&self) -> Option<ImageDescriptorLayouts>;
/// Returns a key that uniquely identifies the memory content of the image.
/// Two ranges that potentially overlap in memory must return the same key.
///
/// The key is shared amongst all buffers and images, which means that you can make several
/// different image objects share the same memory, or make some image objects share memory
/// with buffers, as long as they return the same key.
///
/// Since it is possible to accidentally return the same key for memory ranges that don't
/// overlap, the `conflicts_image` or `conflicts_buffer` function should always be called to
/// verify whether they actually overlap.
fn conflict_key(&self) -> u64;
/// Returns the current mip level that is accessed by the gpu
fn current_mip_levels_access(&self) -> std::ops::Range<u32>;
/// Returns the current array layer that is accessed by the gpu
fn current_array_layers_access(&self) -> std::ops::Range<u32>;
}
/// Inner information about an image.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct ImageInner<'a> {
/// The underlying image object.
pub image: &'a UnsafeImage,
/// The first layer of `image` to consider.
pub first_layer: usize,
/// The number of layers of `image` to consider.
pub num_layers: usize,
/// The first mipmap level of `image` to consider.
pub first_mipmap_level: usize,
/// The number of mipmap levels of `image` to consider.
pub num_mipmap_levels: usize,
}
impl PartialEq for dyn ImageAccess {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.inner() == other.inner()
}
}
impl Eq for dyn ImageAccess {}
impl Hash for dyn ImageAccess {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.inner().hash(state);
}
}
/// Wraps around an object that implements `ImageAccess` and modifies the initial layout
/// requirement to be either `Undefined` or `Preinitialized`.
#[derive(Debug, Copy, Clone)]
pub struct ImageAccessFromUndefinedLayout<I> {
image: I,
preinitialized: bool,
}
unsafe impl<I> ImageAccess for ImageAccessFromUndefinedLayout<I>
where
I: ImageAccess,
{
#[inline]
fn inner(&self) -> ImageInner {
self.image.inner()
}
#[inline]
fn initial_layout_requirement(&self) -> ImageLayout {
if self.preinitialized {
ImageLayout::Preinitialized
} else {
ImageLayout::Undefined
}
}
#[inline]
fn final_layout_requirement(&self) -> ImageLayout {
self.image.final_layout_requirement()
}
#[inline]
fn descriptor_layouts(&self) -> Option<ImageDescriptorLayouts> {
self.image.descriptor_layouts()
}
#[inline]
fn conflict_key(&self) -> u64 {
self.image.conflict_key()
}
fn current_mip_levels_access(&self) -> std::ops::Range<u32> {
self.image.current_mip_levels_access()
}
fn current_array_layers_access(&self) -> std::ops::Range<u32> {
self.image.current_array_layers_access()
}
}
impl<I> PartialEq for ImageAccessFromUndefinedLayout<I>
where
I: ImageAccess,
{
#[inline]
fn eq(&self, other: &Self) -> bool {
self.inner() == other.inner()
}
}
impl<I> Eq for ImageAccessFromUndefinedLayout<I> where I: ImageAccess {}
impl<I> Hash for ImageAccessFromUndefinedLayout<I>
where
I: ImageAccess,
{
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.inner().hash(state);
}
}
/// Extension trait for images. Checks whether the value `T` can be used as a clear value for the
/// given image.
// TODO: isn't that for image views instead?
pub unsafe trait ImageClearValue<T>: ImageAccess {
fn decode(&self, value: T) -> Option<ClearValue>;
}
pub unsafe trait ImageContent<P>: ImageAccess {
/// Checks whether pixels of type `P` match the format of the image.
fn matches_format(&self) -> bool;
}
unsafe impl<T> ImageAccess for T
where
T: SafeDeref + Send + Sync,
T::Target: ImageAccess,
{
#[inline]
fn inner(&self) -> ImageInner {
(**self).inner()
}
#[inline]
fn initial_layout_requirement(&self) -> ImageLayout {
(**self).initial_layout_requirement()
}
#[inline]
fn final_layout_requirement(&self) -> ImageLayout {
(**self).final_layout_requirement()
}
#[inline]
fn descriptor_layouts(&self) -> Option<ImageDescriptorLayouts> {
(**self).descriptor_layouts()
}
#[inline]
fn conflict_key(&self) -> u64 {
(**self).conflict_key()
}
#[inline]
unsafe fn layout_initialized(&self) {
(**self).layout_initialized();
}
#[inline]
fn is_layout_initialized(&self) -> bool {
(**self).is_layout_initialized()
}
fn current_mip_levels_access(&self) -> std::ops::Range<u32> {
(**self).current_mip_levels_access()
}
fn current_array_layers_access(&self) -> std::ops::Range<u32> {
(**self).current_array_layers_access()
}
}
| 31.821429 | 99 | 0.661769 |
fb6ce546221f57d6f79afa12495bbb0c7b6c3ec0
| 12,416 |
use solana_sdk::{clock::Slot, commitment_config::CommitmentLevel};
use solana_vote_program::vote_state::MAX_LOCKOUT_HISTORY;
use std::collections::HashMap;
pub const VOTE_THRESHOLD_SIZE: f64 = 1f64 / 40f64;
pub type BlockCommitmentArray = [u64; MAX_LOCKOUT_HISTORY + 1];
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct BlockCommitment {
pub commitment: BlockCommitmentArray,
}
impl BlockCommitment {
pub fn increase_confirmation_stake(&mut self, confirmation_count: usize, stake: u64) {
assert!(confirmation_count > 0 && confirmation_count <= MAX_LOCKOUT_HISTORY);
self.commitment[confirmation_count - 1] += stake;
}
pub fn get_confirmation_stake(&mut self, confirmation_count: usize) -> u64 {
assert!(confirmation_count > 0 && confirmation_count <= MAX_LOCKOUT_HISTORY);
self.commitment[confirmation_count - 1]
}
pub fn increase_rooted_stake(&mut self, stake: u64) {
self.commitment[MAX_LOCKOUT_HISTORY] += stake;
}
pub fn get_rooted_stake(&self) -> u64 {
self.commitment[MAX_LOCKOUT_HISTORY]
}
pub fn new(commitment: BlockCommitmentArray) -> Self {
Self { commitment }
}
}
/// A node's view of cluster commitment as per a particular bank
#[derive(Default)]
pub struct BlockCommitmentCache {
/// Map of all commitment levels of current ancestor slots, aggregated from the vote account
/// data in the bank
block_commitment: HashMap<Slot, BlockCommitment>,
/// Cache slot details. Cluster data is calculated from the block_commitment map, and cached in
/// the struct to avoid the expense of recalculating on every call.
commitment_slots: CommitmentSlots,
/// Total stake active during the bank's epoch
total_stake: u64,
}
impl std::fmt::Debug for BlockCommitmentCache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BlockCommitmentCache")
.field("block_commitment", &self.block_commitment)
.field("total_stake", &self.total_stake)
.field(
"bank",
&format_args!("Bank({{current_slot: {:?}}})", self.commitment_slots.slot),
)
.field("root", &self.commitment_slots.root)
.finish()
}
}
impl BlockCommitmentCache {
pub fn new(
block_commitment: HashMap<Slot, BlockCommitment>,
total_stake: u64,
commitment_slots: CommitmentSlots,
) -> Self {
Self {
block_commitment,
total_stake,
commitment_slots,
}
}
pub fn get_block_commitment(&self, slot: Slot) -> Option<&BlockCommitment> {
self.block_commitment.get(&slot)
}
pub fn total_stake(&self) -> u64 {
self.total_stake
}
pub fn slot(&self) -> Slot {
self.commitment_slots.slot
}
pub fn root(&self) -> Slot {
self.commitment_slots.root
}
pub fn highest_confirmed_slot(&self) -> Slot {
self.commitment_slots.highest_confirmed_slot
}
pub fn highest_confirmed_root(&self) -> Slot {
self.commitment_slots.highest_confirmed_root
}
pub fn commitment_slots(&self) -> CommitmentSlots {
self.commitment_slots
}
pub fn highest_gossip_confirmed_slot(&self) -> Slot {
// TODO: combine bank caches
// Currently, this information is provided by OptimisticallyConfirmedBank::bank.slot()
self.highest_confirmed_slot()
}
pub fn slot_with_commitment(&self, commitment_level: CommitmentLevel) -> Slot {
match commitment_level {
CommitmentLevel::Recent => self.slot(),
CommitmentLevel::Root => self.root(),
CommitmentLevel::Single => self.highest_confirmed_slot(),
CommitmentLevel::SingleGossip => self.highest_gossip_confirmed_slot(),
CommitmentLevel::Max => self.highest_confirmed_root(),
}
}
fn highest_slot_with_confirmation_count(&self, confirmation_count: usize) -> Slot {
assert!(confirmation_count > 0 && confirmation_count <= MAX_LOCKOUT_HISTORY);
for slot in (self.root()..self.slot()).rev() {
if let Some(count) = self.get_confirmation_count(slot) {
if count >= confirmation_count {
return slot;
}
}
}
self.commitment_slots.root
}
pub fn calculate_highest_confirmed_slot(&self) -> Slot {
self.highest_slot_with_confirmation_count(1)
}
pub fn get_confirmation_count(&self, slot: Slot) -> Option<usize> {
self.get_lockout_count(slot, VOTE_THRESHOLD_SIZE)
}
// Returns the lowest level at which at least `minimum_stake_percentage` of the total epoch
// stake is locked out
fn get_lockout_count(&self, slot: Slot, minimum_stake_percentage: f64) -> Option<usize> {
self.get_block_commitment(slot).map(|block_commitment| {
let iterator = block_commitment.commitment.iter().enumerate().rev();
let mut sum = 0;
for (i, stake) in iterator {
sum += stake;
if (sum as f64 / self.total_stake as f64) > minimum_stake_percentage {
return i + 1;
}
}
0
})
}
pub fn new_for_tests() -> Self {
let mut block_commitment: HashMap<Slot, BlockCommitment> = HashMap::new();
block_commitment.insert(0, BlockCommitment::default());
Self {
block_commitment,
total_stake: 42,
..Self::default()
}
}
pub fn new_for_tests_with_slots(slot: Slot, root: Slot) -> Self {
let mut block_commitment: HashMap<Slot, BlockCommitment> = HashMap::new();
block_commitment.insert(0, BlockCommitment::default());
Self {
block_commitment,
total_stake: 42,
commitment_slots: CommitmentSlots {
slot,
root,
highest_confirmed_slot: root,
highest_confirmed_root: root,
},
}
}
pub fn set_highest_confirmed_slot(&mut self, slot: Slot) {
self.commitment_slots.highest_confirmed_slot = slot;
}
pub fn set_highest_confirmed_root(&mut self, root: Slot) {
self.commitment_slots.highest_confirmed_root = root;
}
pub fn initialize_slots(&mut self, slot: Slot) {
self.commitment_slots.slot = slot;
self.commitment_slots.root = slot;
}
}
#[derive(Default, Clone, Copy)]
pub struct CommitmentSlots {
/// The slot of the bank from which all other slots were calculated.
pub slot: Slot,
/// The current node root
pub root: Slot,
/// Highest cluster-confirmed slot
pub highest_confirmed_slot: Slot,
/// Highest cluster-confirmed root
pub highest_confirmed_root: Slot,
}
impl CommitmentSlots {
pub fn new_from_slot(slot: Slot) -> Self {
Self {
slot,
..Self::default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_block_commitment() {
let mut cache = BlockCommitment::default();
assert_eq!(cache.get_confirmation_stake(1), 0);
cache.increase_confirmation_stake(1, 10);
assert_eq!(cache.get_confirmation_stake(1), 10);
cache.increase_confirmation_stake(1, 20);
assert_eq!(cache.get_confirmation_stake(1), 30);
}
#[test]
fn test_get_confirmations() {
// Build BlockCommitmentCache with votes at depths 0 and 1 for 2 slots
let mut cache0 = BlockCommitment::default();
cache0.increase_confirmation_stake(1, 5);
cache0.increase_confirmation_stake(2, 40);
let mut cache1 = BlockCommitment::default();
cache1.increase_confirmation_stake(1, 40);
cache1.increase_confirmation_stake(2, 5);
let mut cache2 = BlockCommitment::default();
cache2.increase_confirmation_stake(1, 20);
cache2.increase_confirmation_stake(2, 5);
let mut block_commitment = HashMap::new();
block_commitment.entry(0).or_insert(cache0);
block_commitment.entry(1).or_insert(cache1);
block_commitment.entry(2).or_insert(cache2);
let block_commitment_cache = BlockCommitmentCache {
block_commitment,
total_stake: 50,
..BlockCommitmentCache::default()
};
assert_eq!(block_commitment_cache.get_confirmation_count(0), Some(2));
assert_eq!(block_commitment_cache.get_confirmation_count(1), Some(1));
assert_eq!(block_commitment_cache.get_confirmation_count(2), Some(0),);
assert_eq!(block_commitment_cache.get_confirmation_count(3), None,);
}
#[test]
fn test_highest_confirmed_slot() {
let bank_slot_5 = 5;
let total_stake = 50;
// Build cache with confirmation_count 2 given total_stake
let mut cache0 = BlockCommitment::default();
cache0.increase_confirmation_stake(1, 5);
cache0.increase_confirmation_stake(2, 40);
// Build cache with confirmation_count 1 given total_stake
let mut cache1 = BlockCommitment::default();
cache1.increase_confirmation_stake(1, 40);
cache1.increase_confirmation_stake(2, 5);
// Build cache with confirmation_count 0 given total_stake
let mut cache2 = BlockCommitment::default();
cache2.increase_confirmation_stake(1, 20);
cache2.increase_confirmation_stake(2, 5);
let mut block_commitment = HashMap::new();
block_commitment.entry(1).or_insert_with(|| cache0.clone()); // Slot 1, conf 2
block_commitment.entry(2).or_insert_with(|| cache1.clone()); // Slot 2, conf 1
block_commitment.entry(3).or_insert_with(|| cache2.clone()); // Slot 3, conf 0
let commitment_slots = CommitmentSlots::new_from_slot(bank_slot_5);
let block_commitment_cache =
BlockCommitmentCache::new(block_commitment, total_stake, commitment_slots);
assert_eq!(block_commitment_cache.calculate_highest_confirmed_slot(), 2);
// Build map with multiple slots at conf 1
let mut block_commitment = HashMap::new();
block_commitment.entry(1).or_insert_with(|| cache1.clone()); // Slot 1, conf 1
block_commitment.entry(2).or_insert_with(|| cache1.clone()); // Slot 2, conf 1
block_commitment.entry(3).or_insert_with(|| cache2.clone()); // Slot 3, conf 0
let block_commitment_cache =
BlockCommitmentCache::new(block_commitment, total_stake, commitment_slots);
assert_eq!(block_commitment_cache.calculate_highest_confirmed_slot(), 2);
// Build map with slot gaps
let mut block_commitment = HashMap::new();
block_commitment.entry(1).or_insert_with(|| cache1.clone()); // Slot 1, conf 1
block_commitment.entry(3).or_insert(cache1); // Slot 3, conf 1
block_commitment.entry(5).or_insert_with(|| cache2.clone()); // Slot 5, conf 0
let block_commitment_cache =
BlockCommitmentCache::new(block_commitment, total_stake, commitment_slots);
assert_eq!(block_commitment_cache.calculate_highest_confirmed_slot(), 3);
// Build map with no conf 1 slots, but one higher
let mut block_commitment = HashMap::new();
block_commitment.entry(1).or_insert(cache0); // Slot 1, conf 2
block_commitment.entry(2).or_insert_with(|| cache2.clone()); // Slot 2, conf 0
block_commitment.entry(3).or_insert_with(|| cache2.clone()); // Slot 3, conf 0
let block_commitment_cache =
BlockCommitmentCache::new(block_commitment, total_stake, commitment_slots);
assert_eq!(block_commitment_cache.calculate_highest_confirmed_slot(), 1);
// Build map with no conf 1 or higher slots
let mut block_commitment = HashMap::new();
block_commitment.entry(1).or_insert_with(|| cache2.clone()); // Slot 1, conf 0
block_commitment.entry(2).or_insert_with(|| cache2.clone()); // Slot 2, conf 0
block_commitment.entry(3).or_insert(cache2); // Slot 3, conf 0
let block_commitment_cache =
BlockCommitmentCache::new(block_commitment, total_stake, commitment_slots);
assert_eq!(block_commitment_cache.calculate_highest_confirmed_slot(), 0);
}
}
| 37.173653 | 99 | 0.650129 |
26362dc3c44e30d473013e4852c3c659a3add340
| 73 |
/// General use 2D spatial dimensions.
pub type Dimensions = [f64; 2];
| 14.6 | 38 | 0.684932 |
e47670bcfc41aa21582d8bca00c853669e995119
| 1,277 |
use crate::modes::get_delay;
use kafcat::configs::AppConfig;
use kafcat::error::KafcatError;
use kafcat::interface::KafkaConsumer;
use kafcat::interface::KafkaInterface;
use kafcat::interface::KafkaProducer;
use tokio::time::timeout_at;
use tokio::time::Instant;
pub async fn run_async_copy_topic<Interface: KafkaInterface>(
_interface: Interface,
config: AppConfig,
) -> Result<(), KafcatError> {
let input_config = config
.consumer_kafka
.as_ref()
.expect("Must specify input kafka config");
let consumer: Interface::Consumer =
Interface::Consumer::from_config(input_config.clone()).await;
consumer
.set_offset_and_subscribe(input_config.offset)
.await?;
let producer: Interface::Producer = Interface::Producer::from_config(
config
.producer_kafka
.clone()
.expect("Must specify output kafka config"),
)
.await;
let timeout = get_delay(input_config.exit_on_done);
loop {
match timeout_at(Instant::now() + timeout, consumer.recv()).await {
Ok(Ok(msg)) => {
producer.write_one(msg).await?;
}
Ok(Err(err)) => return Err(err),
Err(_) => break,
}
}
Ok(())
}
| 29.697674 | 75 | 0.624119 |
9cb7c916090bad47e6822b4d6fde91c5d3922134
| 753 |
type PatternId = usize;
struct Pattern {
left: u64,
right: u64,
up: u64,
down: u64,
bit: u64,
}
struct Model {
patterns: Vec<Pattern>,
}
struct Wave {
cells: Vec<u64>,
width: usize,
height: usize,
}
const SKY_BIT: u64 = 1 << 0;
const GROUND_BIT: u64 = 2 << 0;
const GROUND_SKYP_UP: u64 = 2 << 0;
fn main() {
let model = Model {
patterns: vec![
Pattern {
bit: SKY_BIT,
left: 0,
right: 0,
up: 0,
down: 0,
},
Pattern {
bit: GROUND_BIT,
left: 0,
right: 0,
up: 0,
down: 0,
},
],
};
}
| 16.369565 | 35 | 0.399734 |
5b9b58f0288945e9f532e0801a4b762a4811624b
| 888 |
// Copyright 2016 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.
// compile-flags: -C debug_assertions=yes
use std::panic;
fn main() {
let r = panic::catch_unwind(|| {
let mut it = u8::max_value()..;
it.next().unwrap(); // 255
it.next().unwrap();
});
assert!(r.is_err());
let r = panic::catch_unwind(|| {
let mut it = i8::max_value()..;
it.next().unwrap(); // 127
it.next().unwrap();
});
assert!(r.is_err());
}
| 29.6 | 68 | 0.627252 |
11b2cabbb424fe2f26d9b20e41d27b1a41cf1ab9
| 982 |
// iterators1.rs
//
// Make me compile by filling in the `???`s
//
// When performing operations on elements within a collection, iterators are essential.
// This module helps you get familiar with the structure of using an iterator and
// how to go through elements within an iterable collection.
//
// Execute `rustlings hint iterators1` for hints :D
/*
https://doc.rust-lang.org/book/ch13-02-iterators.html
*/
fn main () {
let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"];
let mut my_iterable_fav_fruits = my_fav_fruits.iter();
assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana"));
assert_eq!(my_iterable_fav_fruits.next(), Some(&"custard apple"));
assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado"));
assert_eq!(my_iterable_fav_fruits.next(), Some(&"peach"));
assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry"));
assert_eq!(my_iterable_fav_fruits.next(), None);
}
| 36.37037 | 89 | 0.700611 |
22ea80b935bd9023a57dc47e02c13881389a9316
| 1,792 |
use tss_esapi_sys::TPM2B_ECC_POINT;
// Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use crate::{structures::EccParameter, tss2_esys::TPMS_ECC_POINT, Error, Result};
use std::convert::{TryFrom, TryInto};
/// Structure holding ecc point information
///
/// # Details
/// This corresponds to TPMS_ECC_POINT
#[derive(Debug, Clone)]
pub struct EccPoint {
x: EccParameter,
y: EccParameter,
}
impl EccPoint {
/// Creates a new ecc point
pub const fn new(x: EccParameter, y: EccParameter) -> Self {
EccPoint { x, y }
}
/// Returns x value as an [EccParameter] reference.
pub const fn x(&self) -> &EccParameter {
&self.x
}
/// Returns y value as an [EccParameter] reference.
pub const fn y(&self) -> &EccParameter {
&self.y
}
}
impl Default for EccPoint {
fn default() -> Self {
EccPoint::new(EccParameter::default(), EccParameter::default())
}
}
impl From<EccPoint> for TPMS_ECC_POINT {
fn from(ecc_point: EccPoint) -> Self {
TPMS_ECC_POINT {
x: ecc_point.x.into(),
y: ecc_point.y.into(),
}
}
}
impl From<EccPoint> for TPM2B_ECC_POINT {
fn from(ecc_point: EccPoint) -> Self {
let size = std::mem::size_of::<u16>()
+ ecc_point.x().len()
+ std::mem::size_of::<u16>()
+ ecc_point.y().len();
TPM2B_ECC_POINT {
size: size as u16,
point: ecc_point.into(),
}
}
}
impl TryFrom<TPMS_ECC_POINT> for EccPoint {
type Error = Error;
fn try_from(tpms_ecc_point: TPMS_ECC_POINT) -> Result<Self> {
Ok(EccPoint {
x: tpms_ecc_point.x.try_into()?,
y: tpms_ecc_point.y.try_into()?,
})
}
}
| 24.547945 | 80 | 0.594866 |
71767fcfd49339ad5256d7c9b8a0e45209fe21d7
| 107,361 |
// ignore-tidy-linelength
#![allow(non_snake_case)]
register_long_diagnostics! {
E0023: r##"
A pattern used to match against an enum variant must provide a sub-pattern for
each field of the enum variant. This error indicates that a pattern attempted to
extract an incorrect number of fields from a variant.
```
enum Fruit {
Apple(String, String),
Pear(u32),
}
```
Here the `Apple` variant has two fields, and should be matched against like so:
```
enum Fruit {
Apple(String, String),
Pear(u32),
}
let x = Fruit::Apple(String::new(), String::new());
// Correct.
match x {
Fruit::Apple(a, b) => {},
_ => {}
}
```
Matching with the wrong number of fields has no sensible interpretation:
```compile_fail,E0023
enum Fruit {
Apple(String, String),
Pear(u32),
}
let x = Fruit::Apple(String::new(), String::new());
// Incorrect.
match x {
Fruit::Apple(a) => {},
Fruit::Apple(a, b, c) => {},
}
```
Check how many fields the enum was declared with and ensure that your pattern
uses the same number.
"##,
E0025: r##"
Each field of a struct can only be bound once in a pattern. Erroneous code
example:
```compile_fail,E0025
struct Foo {
a: u8,
b: u8,
}
fn main(){
let x = Foo { a:1, b:2 };
let Foo { a: x, a: y } = x;
// error: field `a` bound multiple times in the pattern
}
```
Each occurrence of a field name binds the value of that field, so to fix this
error you will have to remove or alter the duplicate uses of the field name.
Perhaps you misspelled another field name? Example:
```
struct Foo {
a: u8,
b: u8,
}
fn main(){
let x = Foo { a:1, b:2 };
let Foo { a: x, b: y } = x; // ok!
}
```
"##,
E0026: r##"
This error indicates that a struct pattern attempted to extract a non-existent
field from a struct. Struct fields are identified by the name used before the
colon `:` so struct patterns should resemble the declaration of the struct type
being matched.
```
// Correct matching.
struct Thing {
x: u32,
y: u32
}
let thing = Thing { x: 1, y: 2 };
match thing {
Thing { x: xfield, y: yfield } => {}
}
```
If you are using shorthand field patterns but want to refer to the struct field
by a different name, you should rename it explicitly.
Change this:
```compile_fail,E0026
struct Thing {
x: u32,
y: u32
}
let thing = Thing { x: 0, y: 0 };
match thing {
Thing { x, z } => {}
}
```
To this:
```
struct Thing {
x: u32,
y: u32
}
let thing = Thing { x: 0, y: 0 };
match thing {
Thing { x, y: z } => {}
}
```
"##,
E0027: r##"
This error indicates that a pattern for a struct fails to specify a sub-pattern
for every one of the struct's fields. Ensure that each field from the struct's
definition is mentioned in the pattern, or use `..` to ignore unwanted fields.
For example:
```compile_fail,E0027
struct Dog {
name: String,
age: u32,
}
let d = Dog { name: "Rusty".to_string(), age: 8 };
// This is incorrect.
match d {
Dog { age: x } => {}
}
```
This is correct (explicit):
```
struct Dog {
name: String,
age: u32,
}
let d = Dog { name: "Rusty".to_string(), age: 8 };
match d {
Dog { name: ref n, age: x } => {}
}
// This is also correct (ignore unused fields).
match d {
Dog { age: x, .. } => {}
}
```
"##,
E0029: r##"
In a match expression, only numbers and characters can be matched against a
range. This is because the compiler checks that the range is non-empty at
compile-time, and is unable to evaluate arbitrary comparison functions. If you
want to capture values of an orderable type between two end-points, you can use
a guard.
```compile_fail,E0029
let string = "salutations !";
// The ordering relation for strings can't be evaluated at compile time,
// so this doesn't work:
match string {
"hello" ..= "world" => {}
_ => {}
}
// This is a more general version, using a guard:
match string {
s if s >= "hello" && s <= "world" => {}
_ => {}
}
```
"##,
E0033: r##"
This error indicates that a pointer to a trait type cannot be implicitly
dereferenced by a pattern. Every trait defines a type, but because the
size of trait implementors isn't fixed, this type has no compile-time size.
Therefore, all accesses to trait types must be through pointers. If you
encounter this error you should try to avoid dereferencing the pointer.
```compile_fail,E0033
# trait SomeTrait { fn method_one(&self){} fn method_two(&self){} }
# impl<T> SomeTrait for T {}
let trait_obj: &SomeTrait = &"some_value";
// This tries to implicitly dereference to create an unsized local variable.
let &invalid = trait_obj;
// You can call methods without binding to the value being pointed at.
trait_obj.method_one();
trait_obj.method_two();
```
You can read more about trait objects in the [Trait Objects] section of the
Reference.
[Trait Objects]: https://doc.rust-lang.org/reference/types.html#trait-objects
"##,
E0034: r##"
The compiler doesn't know what method to call because more than one method
has the same prototype. Erroneous code example:
```compile_fail,E0034
struct Test;
trait Trait1 {
fn foo();
}
trait Trait2 {
fn foo();
}
impl Trait1 for Test { fn foo() {} }
impl Trait2 for Test { fn foo() {} }
fn main() {
Test::foo() // error, which foo() to call?
}
```
To avoid this error, you have to keep only one of them and remove the others.
So let's take our example and fix it:
```
struct Test;
trait Trait1 {
fn foo();
}
impl Trait1 for Test { fn foo() {} }
fn main() {
Test::foo() // and now that's good!
}
```
However, a better solution would be using fully explicit naming of type and
trait:
```
struct Test;
trait Trait1 {
fn foo();
}
trait Trait2 {
fn foo();
}
impl Trait1 for Test { fn foo() {} }
impl Trait2 for Test { fn foo() {} }
fn main() {
<Test as Trait1>::foo()
}
```
One last example:
```
trait F {
fn m(&self);
}
trait G {
fn m(&self);
}
struct X;
impl F for X { fn m(&self) { println!("I am F"); } }
impl G for X { fn m(&self) { println!("I am G"); } }
fn main() {
let f = X;
F::m(&f); // it displays "I am F"
G::m(&f); // it displays "I am G"
}
```
"##,
E0040: r##"
It is not allowed to manually call destructors in Rust. It is also not
necessary to do this since `drop` is called automatically whenever a value goes
out of scope.
Here's an example of this error:
```compile_fail,E0040
struct Foo {
x: i32,
}
impl Drop for Foo {
fn drop(&mut self) {
println!("kaboom");
}
}
fn main() {
let mut x = Foo { x: -7 };
x.drop(); // error: explicit use of destructor method
}
```
"##,
E0044: r##"
You can't use type or const parameters on foreign items.
Example of erroneous code:
```compile_fail,E0044
extern { fn some_func<T>(x: T); }
```
To fix this, replace the generic parameter with the specializations that you
need:
```
extern { fn some_func_i32(x: i32); }
extern { fn some_func_i64(x: i64); }
```
"##,
E0045: r##"
Rust only supports variadic parameters for interoperability with C code in its
FFI. As such, variadic parameters can only be used with functions which are
using the C ABI. Examples of erroneous code:
```compile_fail
#![feature(unboxed_closures)]
extern "rust-call" { fn foo(x: u8, ...); }
// or
fn foo(x: u8, ...) {}
```
To fix such code, put them in an extern "C" block:
```
extern "C" {
fn foo (x: u8, ...);
}
```
"##,
E0046: r##"
Items are missing in a trait implementation. Erroneous code example:
```compile_fail,E0046
trait Foo {
fn foo();
}
struct Bar;
impl Foo for Bar {}
// error: not all trait items implemented, missing: `foo`
```
When trying to make some type implement a trait `Foo`, you must, at minimum,
provide implementations for all of `Foo`'s required methods (meaning the
methods that do not have default implementations), as well as any required
trait items like associated types or constants. Example:
```
trait Foo {
fn foo();
}
struct Bar;
impl Foo for Bar {
fn foo() {} // ok!
}
```
"##,
E0049: r##"
This error indicates that an attempted implementation of a trait method
has the wrong number of type parameters.
For example, the trait below has a method `foo` with a type parameter `T`,
but the implementation of `foo` for the type `Bar` is missing this parameter:
```compile_fail,E0049
trait Foo {
fn foo<T: Default>(x: T) -> Self;
}
struct Bar;
// error: method `foo` has 0 type parameters but its trait declaration has 1
// type parameter
impl Foo for Bar {
fn foo(x: bool) -> Self { Bar }
}
```
"##,
E0050: r##"
This error indicates that an attempted implementation of a trait method
has the wrong number of function parameters.
For example, the trait below has a method `foo` with two function parameters
(`&self` and `u8`), but the implementation of `foo` for the type `Bar` omits
the `u8` parameter:
```compile_fail,E0050
trait Foo {
fn foo(&self, x: u8) -> bool;
}
struct Bar;
// error: method `foo` has 1 parameter but the declaration in trait `Foo::foo`
// has 2
impl Foo for Bar {
fn foo(&self) -> bool { true }
}
```
"##,
E0053: r##"
The parameters of any trait method must match between a trait implementation
and the trait definition.
Here are a couple examples of this error:
```compile_fail,E0053
trait Foo {
fn foo(x: u16);
fn bar(&self);
}
struct Bar;
impl Foo for Bar {
// error, expected u16, found i16
fn foo(x: i16) { }
// error, types differ in mutability
fn bar(&mut self) { }
}
```
"##,
E0054: r##"
It is not allowed to cast to a bool. If you are trying to cast a numeric type
to a bool, you can compare it with zero instead:
```compile_fail,E0054
let x = 5;
// Not allowed, won't compile
let x_is_nonzero = x as bool;
```
```
let x = 5;
// Ok
let x_is_nonzero = x != 0;
```
"##,
E0055: r##"
During a method call, a value is automatically dereferenced as many times as
needed to make the value's type match the method's receiver. The catch is that
the compiler will only attempt to dereference a number of times up to the
recursion limit (which can be set via the `recursion_limit` attribute).
For a somewhat artificial example:
```compile_fail,E0055
#![recursion_limit="5"]
struct Foo;
impl Foo {
fn foo(&self) {}
}
fn main() {
let foo = Foo;
let ref_foo = &&&&&Foo;
// error, reached the recursion limit while auto-dereferencing `&&&&&Foo`
ref_foo.foo();
}
```
One fix may be to increase the recursion limit. Note that it is possible to
create an infinite recursion of dereferencing, in which case the only fix is to
somehow break the recursion.
"##,
E0057: r##"
When invoking closures or other implementations of the function traits `Fn`,
`FnMut` or `FnOnce` using call notation, the number of parameters passed to the
function must match its definition.
An example using a closure:
```compile_fail,E0057
let f = |x| x * 3;
let a = f(); // invalid, too few parameters
let b = f(4); // this works!
let c = f(2, 3); // invalid, too many parameters
```
A generic function must be treated similarly:
```
fn foo<F: Fn()>(f: F) {
f(); // this is valid, but f(3) would not work
}
```
"##,
E0059: r##"
The built-in function traits are generic over a tuple of the function arguments.
If one uses angle-bracket notation (`Fn<(T,), Output=U>`) instead of parentheses
(`Fn(T) -> U`) to denote the function trait, the type parameter should be a
tuple. Otherwise function call notation cannot be used and the trait will not be
implemented by closures.
The most likely source of this error is using angle-bracket notation without
wrapping the function argument type into a tuple, for example:
```compile_fail,E0059
#![feature(unboxed_closures)]
fn foo<F: Fn<i32>>(f: F) -> F::Output { f(3) }
```
It can be fixed by adjusting the trait bound like this:
```
#![feature(unboxed_closures)]
fn foo<F: Fn<(i32,)>>(f: F) -> F::Output { f(3) }
```
Note that `(T,)` always denotes the type of a 1-tuple containing an element of
type `T`. The comma is necessary for syntactic disambiguation.
"##,
E0060: r##"
External C functions are allowed to be variadic. However, a variadic function
takes a minimum number of arguments. For example, consider C's variadic `printf`
function:
```
use std::os::raw::{c_char, c_int};
extern "C" {
fn printf(_: *const c_char, ...) -> c_int;
}
```
Using this declaration, it must be called with at least one argument, so
simply calling `printf()` is invalid. But the following uses are allowed:
```
# #![feature(static_nobundle)]
# use std::os::raw::{c_char, c_int};
# #[cfg_attr(all(windows, target_env = "msvc"),
# link(name = "legacy_stdio_definitions", kind = "static-nobundle"))]
# extern "C" { fn printf(_: *const c_char, ...) -> c_int; }
# fn main() {
unsafe {
use std::ffi::CString;
let fmt = CString::new("test\n").unwrap();
printf(fmt.as_ptr());
let fmt = CString::new("number = %d\n").unwrap();
printf(fmt.as_ptr(), 3);
let fmt = CString::new("%d, %d\n").unwrap();
printf(fmt.as_ptr(), 10, 5);
}
# }
```
"##,
// ^ Note: On MSVC 2015, the `printf` function is "inlined" in the C code, and
// the C runtime does not contain the `printf` definition. This leads to linker
// error from the doc test (issue #42830).
// This can be fixed by linking to the static library
// `legacy_stdio_definitions.lib` (see https://stackoverflow.com/a/36504365/).
// If this compatibility library is removed in the future, consider changing
// `printf` in this example to another well-known variadic function.
E0061: r##"
The number of arguments passed to a function must match the number of arguments
specified in the function signature.
For example, a function like:
```
fn f(a: u16, b: &str) {}
```
Must always be called with exactly two arguments, e.g., `f(2, "test")`.
Note that Rust does not have a notion of optional function arguments or
variadic functions (except for its C-FFI).
"##,
E0062: r##"
This error indicates that during an attempt to build a struct or struct-like
enum variant, one of the fields was specified more than once. Erroneous code
example:
```compile_fail,E0062
struct Foo {
x: i32,
}
fn main() {
let x = Foo {
x: 0,
x: 0, // error: field `x` specified more than once
};
}
```
Each field should be specified exactly one time. Example:
```
struct Foo {
x: i32,
}
fn main() {
let x = Foo { x: 0 }; // ok!
}
```
"##,
E0063: r##"
This error indicates that during an attempt to build a struct or struct-like
enum variant, one of the fields was not provided. Erroneous code example:
```compile_fail,E0063
struct Foo {
x: i32,
y: i32,
}
fn main() {
let x = Foo { x: 0 }; // error: missing field: `y`
}
```
Each field should be specified exactly once. Example:
```
struct Foo {
x: i32,
y: i32,
}
fn main() {
let x = Foo { x: 0, y: 0 }; // ok!
}
```
"##,
E0067: r##"
The left-hand side of a compound assignment expression must be a place
expression. A place expression represents a memory location and includes
item paths (ie, namespaced variables), dereferences, indexing expressions,
and field references.
Let's start with some erroneous code examples:
```compile_fail,E0067
use std::collections::LinkedList;
// Bad: assignment to non-place expression
LinkedList::new() += 1;
// ...
fn some_func(i: &mut i32) {
i += 12; // Error : '+=' operation cannot be applied on a reference !
}
```
And now some working examples:
```
let mut i : i32 = 0;
i += 12; // Good !
// ...
fn some_func(i: &mut i32) {
*i += 12; // Good !
}
```
"##,
E0069: r##"
The compiler found a function whose body contains a `return;` statement but
whose return type is not `()`. An example of this is:
```compile_fail,E0069
// error
fn foo() -> u8 {
return;
}
```
Since `return;` is just like `return ();`, there is a mismatch between the
function's return type and the value being returned.
"##,
E0070: r##"
The left-hand side of an assignment operator must be a place expression. A
place expression represents a memory location and can be a variable (with
optional namespacing), a dereference, an indexing expression or a field
reference.
More details can be found in the [Expressions] section of the Reference.
[Expressions]: https://doc.rust-lang.org/reference/expressions.html#places-rvalues-and-temporaries
Now, we can go further. Here are some erroneous code examples:
```compile_fail,E0070
struct SomeStruct {
x: i32,
y: i32
}
const SOME_CONST : i32 = 12;
fn some_other_func() {}
fn some_function() {
SOME_CONST = 14; // error : a constant value cannot be changed!
1 = 3; // error : 1 isn't a valid place!
some_other_func() = 4; // error : we can't assign value to a function!
SomeStruct.x = 12; // error : SomeStruct a structure name but it is used
// like a variable!
}
```
And now let's give working examples:
```
struct SomeStruct {
x: i32,
y: i32
}
let mut s = SomeStruct {x: 0, y: 0};
s.x = 3; // that's good !
// ...
fn some_func(x: &mut i32) {
*x = 12; // that's good !
}
```
"##,
E0071: r##"
You tried to use structure-literal syntax to create an item that is
not a structure or enum variant.
Example of erroneous code:
```compile_fail,E0071
type U32 = u32;
let t = U32 { value: 4 }; // error: expected struct, variant or union type,
// found builtin type `u32`
```
To fix this, ensure that the name was correctly spelled, and that
the correct form of initializer was used.
For example, the code above can be fixed to:
```
enum Foo {
FirstValue(i32)
}
fn main() {
let u = Foo::FirstValue(0i32);
let t = 4;
}
```
"##,
E0073: r##"
#### Note: this error code is no longer emitted by the compiler.
You cannot define a struct (or enum) `Foo` that requires an instance of `Foo`
in order to make a new `Foo` value. This is because there would be no way a
first instance of `Foo` could be made to initialize another instance!
Here's an example of a struct that has this problem:
```
struct Foo { x: Box<Foo> } // error
```
One fix is to use `Option`, like so:
```
struct Foo { x: Option<Box<Foo>> }
```
Now it's possible to create at least one instance of `Foo`: `Foo { x: None }`.
"##,
E0074: r##"
#### Note: this error code is no longer emitted by the compiler.
When using the `#[simd]` attribute on a tuple struct, the components of the
tuple struct must all be of a concrete, nongeneric type so the compiler can
reason about how to use SIMD with them. This error will occur if the types
are generic.
This will cause an error:
```
#![feature(repr_simd)]
#[repr(simd)]
struct Bad<T>(T, T, T);
```
This will not:
```
#![feature(repr_simd)]
#[repr(simd)]
struct Good(u32, u32, u32);
```
"##,
E0075: r##"
The `#[simd]` attribute can only be applied to non empty tuple structs, because
it doesn't make sense to try to use SIMD operations when there are no values to
operate on.
This will cause an error:
```compile_fail,E0075
#![feature(repr_simd)]
#[repr(simd)]
struct Bad;
```
This will not:
```
#![feature(repr_simd)]
#[repr(simd)]
struct Good(u32);
```
"##,
E0076: r##"
When using the `#[simd]` attribute to automatically use SIMD operations in tuple
struct, the types in the struct must all be of the same type, or the compiler
will trigger this error.
This will cause an error:
```compile_fail,E0076
#![feature(repr_simd)]
#[repr(simd)]
struct Bad(u16, u32, u32);
```
This will not:
```
#![feature(repr_simd)]
#[repr(simd)]
struct Good(u32, u32, u32);
```
"##,
E0077: r##"
When using the `#[simd]` attribute on a tuple struct, the elements in the tuple
must be machine types so SIMD operations can be applied to them.
This will cause an error:
```compile_fail,E0077
#![feature(repr_simd)]
#[repr(simd)]
struct Bad(String);
```
This will not:
```
#![feature(repr_simd)]
#[repr(simd)]
struct Good(u32, u32, u32);
```
"##,
E0081: r##"
Enum discriminants are used to differentiate enum variants stored in memory.
This error indicates that the same value was used for two or more variants,
making them impossible to tell apart.
```compile_fail,E0081
// Bad.
enum Enum {
P = 3,
X = 3,
Y = 5,
}
```
```
// Good.
enum Enum {
P,
X = 3,
Y = 5,
}
```
Note that variants without a manually specified discriminant are numbered from
top to bottom starting from 0, so clashes can occur with seemingly unrelated
variants.
```compile_fail,E0081
enum Bad {
X,
Y = 0
}
```
Here `X` will have already been specified the discriminant 0 by the time `Y` is
encountered, so a conflict occurs.
"##,
E0084: r##"
An unsupported representation was attempted on a zero-variant enum.
Erroneous code example:
```compile_fail,E0084
#[repr(i32)]
enum NightsWatch {} // error: unsupported representation for zero-variant enum
```
It is impossible to define an integer type to be used to represent zero-variant
enum values because there are no zero-variant enum values. There is no way to
construct an instance of the following type using only safe code. So you have
two solutions. Either you add variants in your enum:
```
#[repr(i32)]
enum NightsWatch {
JonSnow,
Commander,
}
```
or you remove the integer represention of your enum:
```
enum NightsWatch {}
```
"##,
E0087: r##"
#### Note: this error code is no longer emitted by the compiler.
Too many type arguments were supplied for a function. For example:
```compile_fail,E0107
fn foo<T>() {}
fn main() {
foo::<f64, bool>(); // error: wrong number of type arguments:
// expected 1, found 2
}
```
The number of supplied arguments must exactly match the number of defined type
parameters.
"##,
E0088: r##"
#### Note: this error code is no longer emitted by the compiler.
You gave too many lifetime arguments. Erroneous code example:
```compile_fail,E0107
fn f() {}
fn main() {
f::<'static>() // error: wrong number of lifetime arguments:
// expected 0, found 1
}
```
Please check you give the right number of lifetime arguments. Example:
```
fn f() {}
fn main() {
f() // ok!
}
```
It's also important to note that the Rust compiler can generally
determine the lifetime by itself. Example:
```
struct Foo {
value: String
}
impl Foo {
// it can be written like this
fn get_value<'a>(&'a self) -> &'a str { &self.value }
// but the compiler works fine with this too:
fn without_lifetime(&self) -> &str { &self.value }
}
fn main() {
let f = Foo { value: "hello".to_owned() };
println!("{}", f.get_value());
println!("{}", f.without_lifetime());
}
```
"##,
E0089: r##"
#### Note: this error code is no longer emitted by the compiler.
Too few type arguments were supplied for a function. For example:
```compile_fail,E0107
fn foo<T, U>() {}
fn main() {
foo::<f64>(); // error: wrong number of type arguments: expected 2, found 1
}
```
Note that if a function takes multiple type arguments but you want the compiler
to infer some of them, you can use type placeholders:
```compile_fail,E0107
fn foo<T, U>(x: T) {}
fn main() {
let x: bool = true;
foo::<f64>(x); // error: wrong number of type arguments:
// expected 2, found 1
foo::<_, f64>(x); // same as `foo::<bool, f64>(x)`
}
```
"##,
E0090: r##"
#### Note: this error code is no longer emitted by the compiler.
You gave too few lifetime arguments. Example:
```compile_fail,E0107
fn foo<'a: 'b, 'b: 'a>() {}
fn main() {
foo::<'static>(); // error: wrong number of lifetime arguments:
// expected 2, found 1
}
```
Please check you give the right number of lifetime arguments. Example:
```
fn foo<'a: 'b, 'b: 'a>() {}
fn main() {
foo::<'static, 'static>();
}
```
"##,
E0091: r##"
You gave an unnecessary type parameter in a type alias. Erroneous code
example:
```compile_fail,E0091
type Foo<T> = u32; // error: type parameter `T` is unused
// or:
type Foo<A,B> = Box<A>; // error: type parameter `B` is unused
```
Please check you didn't write too many type parameters. Example:
```
type Foo = u32; // ok!
type Foo2<A> = Box<A>; // ok!
```
"##,
E0092: r##"
You tried to declare an undefined atomic operation function.
Erroneous code example:
```compile_fail,E0092
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn atomic_foo(); // error: unrecognized atomic operation
// function
}
```
Please check you didn't make a mistake in the function's name. All intrinsic
functions are defined in librustc_codegen_llvm/intrinsic.rs and in
libcore/intrinsics.rs in the Rust source code. Example:
```
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn atomic_fence(); // ok!
}
```
"##,
E0093: r##"
You declared an unknown intrinsic function. Erroneous code example:
```compile_fail,E0093
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn foo(); // error: unrecognized intrinsic function: `foo`
}
fn main() {
unsafe {
foo();
}
}
```
Please check you didn't make a mistake in the function's name. All intrinsic
functions are defined in librustc_codegen_llvm/intrinsic.rs and in
libcore/intrinsics.rs in the Rust source code. Example:
```
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn atomic_fence(); // ok!
}
fn main() {
unsafe {
atomic_fence();
}
}
```
"##,
E0094: r##"
You gave an invalid number of type parameters to an intrinsic function.
Erroneous code example:
```compile_fail,E0094
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn size_of<T, U>() -> usize; // error: intrinsic has wrong number
// of type parameters
}
```
Please check that you provided the right number of type parameters
and verify with the function declaration in the Rust source code.
Example:
```
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn size_of<T>() -> usize; // ok!
}
```
"##,
E0107: r##"
This error means that an incorrect number of generic arguments were provided:
```compile_fail,E0107
struct Foo<T> { x: T }
struct Bar { x: Foo } // error: wrong number of type arguments:
// expected 1, found 0
struct Baz<S, T> { x: Foo<S, T> } // error: wrong number of type arguments:
// expected 1, found 2
fn foo<T, U>(x: T, y: U) {}
fn main() {
let x: bool = true;
foo::<bool>(x); // error: wrong number of type arguments:
// expected 2, found 1
foo::<bool, i32, i32>(x, 2, 4); // error: wrong number of type arguments:
// expected 2, found 3
}
fn f() {}
fn main() {
f::<'static>(); // error: wrong number of lifetime arguments:
// expected 0, found 1
}
```
"##,
E0109: r##"
You tried to give a type parameter to a type which doesn't need it. Erroneous
code example:
```compile_fail,E0109
type X = u32<i32>; // error: type arguments are not allowed on this entity
```
Please check that you used the correct type and recheck its definition. Perhaps
it doesn't need the type parameter.
Example:
```
type X = u32; // this compiles
```
Note that type parameters for enum-variant constructors go after the variant,
not after the enum (`Option::None::<u32>`, not `Option::<u32>::None`).
"##,
E0110: r##"
You tried to give a lifetime parameter to a type which doesn't need it.
Erroneous code example:
```compile_fail,E0110
type X = u32<'static>; // error: lifetime parameters are not allowed on
// this type
```
Please check that the correct type was used and recheck its definition; perhaps
it doesn't need the lifetime parameter. Example:
```
type X = u32; // ok!
```
"##,
E0116: r##"
You can only define an inherent implementation for a type in the same crate
where the type was defined. For example, an `impl` block as below is not allowed
since `Vec` is defined in the standard library:
```compile_fail,E0116
impl Vec<u8> { } // error
```
To fix this problem, you can do either of these things:
- define a trait that has the desired associated functions/types/constants and
implement the trait for the type in question
- define a new type wrapping the type and define an implementation on the new
type
Note that using the `type` keyword does not work here because `type` only
introduces a type alias:
```compile_fail,E0116
type Bytes = Vec<u8>;
impl Bytes { } // error, same as above
```
"##,
E0117: r##"
This error indicates a violation of one of Rust's orphan rules for trait
implementations. The rule prohibits any implementation of a foreign trait (a
trait defined in another crate) where
- the type that is implementing the trait is foreign
- all of the parameters being passed to the trait (if there are any) are also
foreign.
Here's one example of this error:
```compile_fail,E0117
impl Drop for u32 {}
```
To avoid this kind of error, ensure that at least one local type is referenced
by the `impl`:
```
pub struct Foo; // you define your type in your crate
impl Drop for Foo { // and you can implement the trait on it!
// code of trait implementation here
# fn drop(&mut self) { }
}
impl From<Foo> for i32 { // or you use a type from your crate as
// a type parameter
fn from(i: Foo) -> i32 {
0
}
}
```
Alternatively, define a trait locally and implement that instead:
```
trait Bar {
fn get(&self) -> usize;
}
impl Bar for u32 {
fn get(&self) -> usize { 0 }
}
```
For information on the design of the orphan rules, see [RFC 1023].
[RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
"##,
E0118: r##"
You're trying to write an inherent implementation for something which isn't a
struct nor an enum. Erroneous code example:
```compile_fail,E0118
impl (u8, u8) { // error: no base type found for inherent implementation
fn get_state(&self) -> String {
// ...
}
}
```
To fix this error, please implement a trait on the type or wrap it in a struct.
Example:
```
// we create a trait here
trait LiveLongAndProsper {
fn get_state(&self) -> String;
}
// and now you can implement it on (u8, u8)
impl LiveLongAndProsper for (u8, u8) {
fn get_state(&self) -> String {
"He's dead, Jim!".to_owned()
}
}
```
Alternatively, you can create a newtype. A newtype is a wrapping tuple-struct.
For example, `NewType` is a newtype over `Foo` in `struct NewType(Foo)`.
Example:
```
struct TypeWrapper((u8, u8));
impl TypeWrapper {
fn get_state(&self) -> String {
"Fascinating!".to_owned()
}
}
```
"##,
E0120: r##"
An attempt was made to implement Drop on a trait, which is not allowed: only
structs and enums can implement Drop. An example causing this error:
```compile_fail,E0120
trait MyTrait {}
impl Drop for MyTrait {
fn drop(&mut self) {}
}
```
A workaround for this problem is to wrap the trait up in a struct, and implement
Drop on that. An example is shown below:
```
trait MyTrait {}
struct MyWrapper<T: MyTrait> { foo: T }
impl <T: MyTrait> Drop for MyWrapper<T> {
fn drop(&mut self) {}
}
```
Alternatively, wrapping trait objects requires something like the following:
```
trait MyTrait {}
//or Box<MyTrait>, if you wanted an owned trait object
struct MyWrapper<'a> { foo: &'a MyTrait }
impl <'a> Drop for MyWrapper<'a> {
fn drop(&mut self) {}
}
```
"##,
E0121: r##"
In order to be consistent with Rust's lack of global type inference, type
placeholders are disallowed by design in item signatures.
Examples of this error include:
```compile_fail,E0121
fn foo() -> _ { 5 } // error, explicitly write out the return type instead
static BAR: _ = "test"; // error, explicitly write out the type instead
```
"##,
E0124: r##"
You declared two fields of a struct with the same name. Erroneous code
example:
```compile_fail,E0124
struct Foo {
field1: i32,
field1: i32, // error: field is already declared
}
```
Please verify that the field names have been correctly spelled. Example:
```
struct Foo {
field1: i32,
field2: i32, // ok!
}
```
"##,
E0131: r##"
It is not possible to define `main` with generic parameters.
When `main` is present, it must take no arguments and return `()`.
Erroneous code example:
```compile_fail,E0131
fn main<T>() { // error: main function is not allowed to have generic parameters
}
```
"##,
E0132: r##"
A function with the `start` attribute was declared with type parameters.
Erroneous code example:
```compile_fail,E0132
#![feature(start)]
#[start]
fn f<T>() {}
```
It is not possible to declare type parameters on a function that has the `start`
attribute. Such a function must have the following type signature (for more
information, view [the unstable book][1]):
[1]: https://doc.rust-lang.org/unstable-book/language-features/lang-items.html#writing-an-executable-without-stdlib
```
# let _:
fn(isize, *const *const u8) -> isize;
```
Example:
```
#![feature(start)]
#[start]
fn my_start(argc: isize, argv: *const *const u8) -> isize {
0
}
```
"##,
E0164: r##"
This error means that an attempt was made to match a struct type enum
variant as a non-struct type:
```compile_fail,E0164
enum Foo { B { i: u32 } }
fn bar(foo: Foo) -> u32 {
match foo {
Foo::B(i) => i, // error E0164
}
}
```
Try using `{}` instead:
```
enum Foo { B { i: u32 } }
fn bar(foo: Foo) -> u32 {
match foo {
Foo::B{i} => i,
}
}
```
"##,
E0184: r##"
Explicitly implementing both Drop and Copy for a type is currently disallowed.
This feature can make some sense in theory, but the current implementation is
incorrect and can lead to memory unsafety (see [issue #20126][iss20126]), so
it has been disabled for now.
[iss20126]: https://github.com/rust-lang/rust/issues/20126
"##,
E0185: r##"
An associated function for a trait was defined to be static, but an
implementation of the trait declared the same function to be a method (i.e., to
take a `self` parameter).
Here's an example of this error:
```compile_fail,E0185
trait Foo {
fn foo();
}
struct Bar;
impl Foo for Bar {
// error, method `foo` has a `&self` declaration in the impl, but not in
// the trait
fn foo(&self) {}
}
```
"##,
E0186: r##"
An associated function for a trait was defined to be a method (i.e., to take a
`self` parameter), but an implementation of the trait declared the same function
to be static.
Here's an example of this error:
```compile_fail,E0186
trait Foo {
fn foo(&self);
}
struct Bar;
impl Foo for Bar {
// error, method `foo` has a `&self` declaration in the trait, but not in
// the impl
fn foo() {}
}
```
"##,
E0191: r##"
Trait objects need to have all associated types specified. Erroneous code
example:
```compile_fail,E0191
trait Trait {
type Bar;
}
type Foo = Trait; // error: the value of the associated type `Bar` (from
// the trait `Trait`) must be specified
```
Please verify you specified all associated types of the trait and that you
used the right trait. Example:
```
trait Trait {
type Bar;
}
type Foo = Trait<Bar=i32>; // ok!
```
"##,
E0192: r##"
Negative impls are only allowed for auto traits. For more
information see the [opt-in builtin traits RFC][RFC 19].
[RFC 19]: https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md
"##,
E0193: r##"
#### Note: this error code is no longer emitted by the compiler.
`where` clauses must use generic type parameters: it does not make sense to use
them otherwise. An example causing this error:
```
trait Foo {
fn bar(&self);
}
#[derive(Copy,Clone)]
struct Wrapper<T> {
Wrapped: T
}
impl Foo for Wrapper<u32> where Wrapper<u32>: Clone {
fn bar(&self) { }
}
```
This use of a `where` clause is strange - a more common usage would look
something like the following:
```
trait Foo {
fn bar(&self);
}
#[derive(Copy,Clone)]
struct Wrapper<T> {
Wrapped: T
}
impl <T> Foo for Wrapper<T> where Wrapper<T>: Clone {
fn bar(&self) { }
}
```
Here, we're saying that the implementation exists on Wrapper only when the
wrapped type `T` implements `Clone`. The `where` clause is important because
some types will not implement `Clone`, and thus will not get this method.
In our erroneous example, however, we're referencing a single concrete type.
Since we know for certain that `Wrapper<u32>` implements `Clone`, there's no
reason to also specify it in a `where` clause.
"##,
E0194: r##"
A type parameter was declared which shadows an existing one. An example of this
error:
```compile_fail,E0194
trait Foo<T> {
fn do_something(&self) -> T;
fn do_something_else<T: Clone>(&self, bar: T);
}
```
In this example, the trait `Foo` and the trait method `do_something_else` both
define a type parameter `T`. This is not allowed: if the method wishes to
define a type parameter, it must use a different name for it.
"##,
E0195: r##"
Your method's lifetime parameters do not match the trait declaration.
Erroneous code example:
```compile_fail,E0195
trait Trait {
fn bar<'a,'b:'a>(x: &'a str, y: &'b str);
}
struct Foo;
impl Trait for Foo {
fn bar<'a,'b>(x: &'a str, y: &'b str) {
// error: lifetime parameters or bounds on method `bar`
// do not match the trait declaration
}
}
```
The lifetime constraint `'b` for bar() implementation does not match the
trait declaration. Ensure lifetime declarations match exactly in both trait
declaration and implementation. Example:
```
trait Trait {
fn t<'a,'b:'a>(x: &'a str, y: &'b str);
}
struct Foo;
impl Trait for Foo {
fn t<'a,'b:'a>(x: &'a str, y: &'b str) { // ok!
}
}
```
"##,
E0199: r##"
Safe traits should not have unsafe implementations, therefore marking an
implementation for a safe trait unsafe will cause a compiler error. Removing
the unsafe marker on the trait noted in the error will resolve this problem.
```compile_fail,E0199
struct Foo;
trait Bar { }
// this won't compile because Bar is safe
unsafe impl Bar for Foo { }
// this will compile
impl Bar for Foo { }
```
"##,
E0200: r##"
Unsafe traits must have unsafe implementations. This error occurs when an
implementation for an unsafe trait isn't marked as unsafe. This may be resolved
by marking the unsafe implementation as unsafe.
```compile_fail,E0200
struct Foo;
unsafe trait Bar { }
// this won't compile because Bar is unsafe and impl isn't unsafe
impl Bar for Foo { }
// this will compile
unsafe impl Bar for Foo { }
```
"##,
E0201: r##"
It is an error to define two associated items (like methods, associated types,
associated functions, etc.) with the same identifier.
For example:
```compile_fail,E0201
struct Foo(u8);
impl Foo {
fn bar(&self) -> bool { self.0 > 5 }
fn bar() {} // error: duplicate associated function
}
trait Baz {
type Quux;
fn baz(&self) -> bool;
}
impl Baz for Foo {
type Quux = u32;
fn baz(&self) -> bool { true }
// error: duplicate method
fn baz(&self) -> bool { self.0 > 5 }
// error: duplicate associated type
type Quux = u32;
}
```
Note, however, that items with the same name are allowed for inherent `impl`
blocks that don't overlap:
```
struct Foo<T>(T);
impl Foo<u8> {
fn bar(&self) -> bool { self.0 > 5 }
}
impl Foo<bool> {
fn bar(&self) -> bool { self.0 }
}
```
"##,
E0202: r##"
Inherent associated types were part of [RFC 195] but are not yet implemented.
See [the tracking issue][iss8995] for the status of this implementation.
[RFC 195]: https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md
[iss8995]: https://github.com/rust-lang/rust/issues/8995
"##,
E0204: r##"
An attempt to implement the `Copy` trait for a struct failed because one of the
fields does not implement `Copy`. To fix this, you must implement `Copy` for the
mentioned field. Note that this may not be possible, as in the example of
```compile_fail,E0204
struct Foo {
foo : Vec<u32>,
}
impl Copy for Foo { }
```
This fails because `Vec<T>` does not implement `Copy` for any `T`.
Here's another example that will fail:
```compile_fail,E0204
#[derive(Copy)]
struct Foo<'a> {
ty: &'a mut bool,
}
```
This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
differs from the behavior for `&T`, which is always `Copy`).
"##,
/*
E0205: r##"
An attempt to implement the `Copy` trait for an enum failed because one of the
variants does not implement `Copy`. To fix this, you must implement `Copy` for
the mentioned variant. Note that this may not be possible, as in the example of
```compile_fail,E0205
enum Foo {
Bar(Vec<u32>),
Baz,
}
impl Copy for Foo { }
```
This fails because `Vec<T>` does not implement `Copy` for any `T`.
Here's another example that will fail:
```compile_fail,E0205
#[derive(Copy)]
enum Foo<'a> {
Bar(&'a mut bool),
Baz,
}
```
This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
differs from the behavior for `&T`, which is always `Copy`).
"##,
*/
E0206: r##"
You can only implement `Copy` for a struct or enum. Both of the following
examples will fail, because neither `[u8; 256]` nor `&'static mut Bar`
(mutable reference to `Bar`) is a struct or enum:
```compile_fail,E0206
type Foo = [u8; 256];
impl Copy for Foo { } // error
#[derive(Copy, Clone)]
struct Bar;
impl Copy for &'static mut Bar { } // error
```
"##,
E0207: r##"
Any type parameter or lifetime parameter of an `impl` must meet at least one of
the following criteria:
- it appears in the self type of the impl
- for a trait impl, it appears in the trait reference
- it is bound as an associated type
### Error example 1
Suppose we have a struct `Foo` and we would like to define some methods for it.
The following definition leads to a compiler error:
```compile_fail,E0207
struct Foo;
impl<T: Default> Foo {
// error: the type parameter `T` is not constrained by the impl trait, self
// type, or predicates [E0207]
fn get(&self) -> T {
<T as Default>::default()
}
}
```
The problem is that the parameter `T` does not appear in the self type (`Foo`)
of the impl. In this case, we can fix the error by moving the type parameter
from the `impl` to the method `get`:
```
struct Foo;
// Move the type parameter from the impl to the method
impl Foo {
fn get<T: Default>(&self) -> T {
<T as Default>::default()
}
}
```
### Error example 2
As another example, suppose we have a `Maker` trait and want to establish a
type `FooMaker` that makes `Foo`s:
```compile_fail,E0207
trait Maker {
type Item;
fn make(&mut self) -> Self::Item;
}
struct Foo<T> {
foo: T
}
struct FooMaker;
impl<T: Default> Maker for FooMaker {
// error: the type parameter `T` is not constrained by the impl trait, self
// type, or predicates [E0207]
type Item = Foo<T>;
fn make(&mut self) -> Foo<T> {
Foo { foo: <T as Default>::default() }
}
}
```
This fails to compile because `T` does not appear in the trait or in the
implementing type.
One way to work around this is to introduce a phantom type parameter into
`FooMaker`, like so:
```
use std::marker::PhantomData;
trait Maker {
type Item;
fn make(&mut self) -> Self::Item;
}
struct Foo<T> {
foo: T
}
// Add a type parameter to `FooMaker`
struct FooMaker<T> {
phantom: PhantomData<T>,
}
impl<T: Default> Maker for FooMaker<T> {
type Item = Foo<T>;
fn make(&mut self) -> Foo<T> {
Foo {
foo: <T as Default>::default(),
}
}
}
```
Another way is to do away with the associated type in `Maker` and use an input
type parameter instead:
```
// Use a type parameter instead of an associated type here
trait Maker<Item> {
fn make(&mut self) -> Item;
}
struct Foo<T> {
foo: T
}
struct FooMaker;
impl<T: Default> Maker<Foo<T>> for FooMaker {
fn make(&mut self) -> Foo<T> {
Foo { foo: <T as Default>::default() }
}
}
```
### Additional information
For more information, please see [RFC 447].
[RFC 447]: https://github.com/rust-lang/rfcs/blob/master/text/0447-no-unused-impl-parameters.md
"##,
E0210: r##"
This error indicates a violation of one of Rust's orphan rules for trait
implementations. The rule concerns the use of type parameters in an
implementation of a foreign trait (a trait defined in another crate), and
states that type parameters must be "covered" by a local type. To understand
what this means, it is perhaps easiest to consider a few examples.
If `ForeignTrait` is a trait defined in some external crate `foo`, then the
following trait `impl` is an error:
```compile_fail,E0210
# #[cfg(for_demonstration_only)]
extern crate foo;
# #[cfg(for_demonstration_only)]
use foo::ForeignTrait;
# use std::panic::UnwindSafe as ForeignTrait;
impl<T> ForeignTrait for T { } // error
# fn main() {}
```
To work around this, it can be covered with a local type, `MyType`:
```
# use std::panic::UnwindSafe as ForeignTrait;
struct MyType<T>(T);
impl<T> ForeignTrait for MyType<T> { } // Ok
```
Please note that a type alias is not sufficient.
For another example of an error, suppose there's another trait defined in `foo`
named `ForeignTrait2` that takes two type parameters. Then this `impl` results
in the same rule violation:
```ignore (cannot-doctest-multicrate-project)
struct MyType2;
impl<T> ForeignTrait2<T, MyType<T>> for MyType2 { } // error
```
The reason for this is that there are two appearances of type parameter `T` in
the `impl` header, both as parameters for `ForeignTrait2`. The first appearance
is uncovered, and so runs afoul of the orphan rule.
Consider one more example:
```ignore (cannot-doctest-multicrate-project)
impl<T> ForeignTrait2<MyType<T>, T> for MyType2 { } // Ok
```
This only differs from the previous `impl` in that the parameters `T` and
`MyType<T>` for `ForeignTrait2` have been swapped. This example does *not*
violate the orphan rule; it is permitted.
To see why that last example was allowed, you need to understand the general
rule. Unfortunately this rule is a bit tricky to state. Consider an `impl`:
```ignore (only-for-syntax-highlight)
impl<P1, ..., Pm> ForeignTrait<T1, ..., Tn> for T0 { ... }
```
where `P1, ..., Pm` are the type parameters of the `impl` and `T0, ..., Tn`
are types. One of the types `T0, ..., Tn` must be a local type (this is another
orphan rule, see the explanation for E0117). Let `i` be the smallest integer
such that `Ti` is a local type. Then no type parameter can appear in any of the
`Tj` for `j < i`.
For information on the design of the orphan rules, see [RFC 1023].
[RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
"##,
/*
E0211: r##"
You used a function or type which doesn't fit the requirements for where it was
used. Erroneous code examples:
```compile_fail
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn size_of<T>(); // error: intrinsic has wrong type
}
// or:
fn main() -> i32 { 0 }
// error: main function expects type: `fn() {main}`: expected (), found i32
// or:
let x = 1u8;
match x {
0u8..=3i8 => (),
// error: mismatched types in range: expected u8, found i8
_ => ()
}
// or:
use std::rc::Rc;
struct Foo;
impl Foo {
fn x(self: Rc<Foo>) {}
// error: mismatched self type: expected `Foo`: expected struct
// `Foo`, found struct `alloc::rc::Rc`
}
```
For the first code example, please check the function definition. Example:
```
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn size_of<T>() -> usize; // ok!
}
```
The second case example is a bit particular : the main function must always
have this definition:
```compile_fail
fn main();
```
They never take parameters and never return types.
For the third example, when you match, all patterns must have the same type
as the type you're matching on. Example:
```
let x = 1u8;
match x {
0u8..=3u8 => (), // ok!
_ => ()
}
```
And finally, for the last example, only `Box<Self>`, `&Self`, `Self`,
or `&mut Self` work as explicit self parameters. Example:
```
struct Foo;
impl Foo {
fn x(self: Box<Foo>) {} // ok!
}
```
"##,
*/
E0220: r##"
You used an associated type which isn't defined in the trait.
Erroneous code example:
```compile_fail,E0220
trait T1 {
type Bar;
}
type Foo = T1<F=i32>; // error: associated type `F` not found for `T1`
// or:
trait T2 {
type Bar;
// error: Baz is used but not declared
fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
}
```
Make sure that you have defined the associated type in the trait body.
Also, verify that you used the right trait or you didn't misspell the
associated type name. Example:
```
trait T1 {
type Bar;
}
type Foo = T1<Bar=i32>; // ok!
// or:
trait T2 {
type Bar;
type Baz; // we declare `Baz` in our trait.
// and now we can use it here:
fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
}
```
"##,
E0221: r##"
An attempt was made to retrieve an associated type, but the type was ambiguous.
For example:
```compile_fail,E0221
trait T1 {}
trait T2 {}
trait Foo {
type A: T1;
}
trait Bar : Foo {
type A: T2;
fn do_something() {
let _: Self::A;
}
}
```
In this example, `Foo` defines an associated type `A`. `Bar` inherits that type
from `Foo`, and defines another associated type of the same name. As a result,
when we attempt to use `Self::A`, it's ambiguous whether we mean the `A` defined
by `Foo` or the one defined by `Bar`.
There are two options to work around this issue. The first is simply to rename
one of the types. Alternatively, one can specify the intended type using the
following syntax:
```
trait T1 {}
trait T2 {}
trait Foo {
type A: T1;
}
trait Bar : Foo {
type A: T2;
fn do_something() {
let _: <Self as Bar>::A;
}
}
```
"##,
E0223: r##"
An attempt was made to retrieve an associated type, but the type was ambiguous.
For example:
```compile_fail,E0223
trait MyTrait {type X; }
fn main() {
let foo: MyTrait::X;
}
```
The problem here is that we're attempting to take the type of X from MyTrait.
Unfortunately, the type of X is not defined, because it's only made concrete in
implementations of the trait. A working version of this code might look like:
```
trait MyTrait {type X; }
struct MyStruct;
impl MyTrait for MyStruct {
type X = u32;
}
fn main() {
let foo: <MyStruct as MyTrait>::X;
}
```
This syntax specifies that we want the X type from MyTrait, as made concrete in
MyStruct. The reason that we cannot simply use `MyStruct::X` is that MyStruct
might implement two different traits with identically-named associated types.
This syntax allows disambiguation between the two.
"##,
E0225: r##"
You attempted to use multiple types as bounds for a closure or trait object.
Rust does not currently support this. A simple example that causes this error:
```compile_fail,E0225
fn main() {
let _: Box<dyn std::io::Read + std::io::Write>;
}
```
Auto traits such as Send and Sync are an exception to this rule:
It's possible to have bounds of one non-builtin trait, plus any number of
auto traits. For example, the following compiles correctly:
```
fn main() {
let _: Box<dyn std::io::Read + Send + Sync>;
}
```
"##,
E0229: r##"
An associated type binding was done outside of the type parameter declaration
and `where` clause. Erroneous code example:
```compile_fail,E0229
pub trait Foo {
type A;
fn boo(&self) -> <Self as Foo>::A;
}
struct Bar;
impl Foo for isize {
type A = usize;
fn boo(&self) -> usize { 42 }
}
fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
// error: associated type bindings are not allowed here
```
To solve this error, please move the type bindings in the type parameter
declaration:
```
# struct Bar;
# trait Foo { type A; }
fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
```
Or in the `where` clause:
```
# struct Bar;
# trait Foo { type A; }
fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
```
"##,
E0243: r##"
#### Note: this error code is no longer emitted by the compiler.
This error indicates that not enough type parameters were found in a type or
trait.
For example, the `Foo` struct below is defined to be generic in `T`, but the
type parameter is missing in the definition of `Bar`:
```compile_fail,E0107
struct Foo<T> { x: T }
struct Bar { x: Foo }
```
"##,
E0244: r##"
#### Note: this error code is no longer emitted by the compiler.
This error indicates that too many type parameters were found in a type or
trait.
For example, the `Foo` struct below has no type parameters, but is supplied
with two in the definition of `Bar`:
```compile_fail,E0107
struct Foo { x: bool }
struct Bar<S, T> { x: Foo<S, T> }
```
"##,
E0321: r##"
A cross-crate opt-out trait was implemented on something which wasn't a struct
or enum type. Erroneous code example:
```compile_fail,E0321
#![feature(optin_builtin_traits)]
struct Foo;
impl !Sync for Foo {}
unsafe impl Send for &'static Foo {}
// error: cross-crate traits with a default impl, like `core::marker::Send`,
// can only be implemented for a struct/enum type, not
// `&'static Foo`
```
Only structs and enums are permitted to impl Send, Sync, and other opt-out
trait, and the struct or enum must be local to the current crate. So, for
example, `unsafe impl Send for Rc<Foo>` is not allowed.
"##,
E0322: r##"
The `Sized` trait is a special trait built-in to the compiler for types with a
constant size known at compile-time. This trait is automatically implemented
for types as needed by the compiler, and it is currently disallowed to
explicitly implement it for a type.
"##,
E0323: r##"
An associated const was implemented when another trait item was expected.
Erroneous code example:
```compile_fail,E0323
trait Foo {
type N;
}
struct Bar;
impl Foo for Bar {
const N : u32 = 0;
// error: item `N` is an associated const, which doesn't match its
// trait `<Bar as Foo>`
}
```
Please verify that the associated const wasn't misspelled and the correct trait
was implemented. Example:
```
struct Bar;
trait Foo {
type N;
}
impl Foo for Bar {
type N = u32; // ok!
}
```
Or:
```
struct Bar;
trait Foo {
const N : u32;
}
impl Foo for Bar {
const N : u32 = 0; // ok!
}
```
"##,
E0324: r##"
A method was implemented when another trait item was expected. Erroneous
code example:
```compile_fail,E0324
struct Bar;
trait Foo {
const N : u32;
fn M();
}
impl Foo for Bar {
fn N() {}
// error: item `N` is an associated method, which doesn't match its
// trait `<Bar as Foo>`
}
```
To fix this error, please verify that the method name wasn't misspelled and
verify that you are indeed implementing the correct trait items. Example:
```
struct Bar;
trait Foo {
const N : u32;
fn M();
}
impl Foo for Bar {
const N : u32 = 0;
fn M() {} // ok!
}
```
"##,
E0325: r##"
An associated type was implemented when another trait item was expected.
Erroneous code example:
```compile_fail,E0325
struct Bar;
trait Foo {
const N : u32;
}
impl Foo for Bar {
type N = u32;
// error: item `N` is an associated type, which doesn't match its
// trait `<Bar as Foo>`
}
```
Please verify that the associated type name wasn't misspelled and your
implementation corresponds to the trait definition. Example:
```
struct Bar;
trait Foo {
type N;
}
impl Foo for Bar {
type N = u32; // ok!
}
```
Or:
```
struct Bar;
trait Foo {
const N : u32;
}
impl Foo for Bar {
const N : u32 = 0; // ok!
}
```
"##,
E0326: r##"
The types of any associated constants in a trait implementation must match the
types in the trait definition. This error indicates that there was a mismatch.
Here's an example of this error:
```compile_fail,E0326
trait Foo {
const BAR: bool;
}
struct Bar;
impl Foo for Bar {
const BAR: u32 = 5; // error, expected bool, found u32
}
```
"##,
E0328: r##"
The Unsize trait should not be implemented directly. All implementations of
Unsize are provided automatically by the compiler.
Erroneous code example:
```compile_fail,E0328
#![feature(unsize)]
use std::marker::Unsize;
pub struct MyType;
impl<T> Unsize<T> for MyType {}
```
If you are defining your own smart pointer type and would like to enable
conversion from a sized to an unsized type with the
[DST coercion system][RFC 982], use [`CoerceUnsized`] instead.
```
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
pub struct MyType<T: ?Sized> {
field_with_unsized_type: T,
}
impl<T, U> CoerceUnsized<MyType<U>> for MyType<T>
where T: CoerceUnsized<U> {}
```
[RFC 982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
[`CoerceUnsized`]: https://doc.rust-lang.org/std/ops/trait.CoerceUnsized.html
"##,
/*
// Associated consts can now be accessed through generic type parameters, and
// this error is no longer emitted.
//
// FIXME: consider whether to leave it in the error index, or remove it entirely
// as associated consts is not stabilized yet.
E0329: r##"
An attempt was made to access an associated constant through either a generic
type parameter or `Self`. This is not supported yet. An example causing this
error is shown below:
```
trait Foo {
const BAR: f64;
}
struct MyStruct;
impl Foo for MyStruct {
const BAR: f64 = 0f64;
}
fn get_bar_bad<F: Foo>(t: F) -> f64 {
F::BAR
}
```
Currently, the value of `BAR` for a particular type can only be accessed
through a concrete type, as shown below:
```
trait Foo {
const BAR: f64;
}
struct MyStruct;
fn get_bar_good() -> f64 {
<MyStruct as Foo>::BAR
}
```
"##,
*/
E0366: r##"
An attempt was made to implement `Drop` on a concrete specialization of a
generic type. An example is shown below:
```compile_fail,E0366
struct Foo<T> {
t: T
}
impl Drop for Foo<u32> {
fn drop(&mut self) {}
}
```
This code is not legal: it is not possible to specialize `Drop` to a subset of
implementations of a generic type. One workaround for this is to wrap the
generic type, as shown below:
```
struct Foo<T> {
t: T
}
struct Bar {
t: Foo<u32>
}
impl Drop for Bar {
fn drop(&mut self) {}
}
```
"##,
E0367: r##"
An attempt was made to implement `Drop` on a specialization of a generic type.
An example is shown below:
```compile_fail,E0367
trait Foo{}
struct MyStruct<T> {
t: T
}
impl<T: Foo> Drop for MyStruct<T> {
fn drop(&mut self) {}
}
```
This code is not legal: it is not possible to specialize `Drop` to a subset of
implementations of a generic type. In order for this code to work, `MyStruct`
must also require that `T` implements `Foo`. Alternatively, another option is
to wrap the generic type in another that specializes appropriately:
```
trait Foo{}
struct MyStruct<T> {
t: T
}
struct MyStructWrapper<T: Foo> {
t: MyStruct<T>
}
impl <T: Foo> Drop for MyStructWrapper<T> {
fn drop(&mut self) {}
}
```
"##,
E0368: r##"
This error indicates that a binary assignment operator like `+=` or `^=` was
applied to a type that doesn't support it. For example:
```compile_fail,E0368
let mut x = 12f32; // error: binary operation `<<` cannot be applied to
// type `f32`
x <<= 2;
```
To fix this error, please check that this type implements this binary
operation. Example:
```
let mut x = 12u32; // the `u32` type does implement the `ShlAssign` trait
x <<= 2; // ok!
```
It is also possible to overload most operators for your own type by
implementing the `[OP]Assign` traits from `std::ops`.
Another problem you might be facing is this: suppose you've overloaded the `+`
operator for some type `Foo` by implementing the `std::ops::Add` trait for
`Foo`, but you find that using `+=` does not work, as in this example:
```compile_fail,E0368
use std::ops::Add;
struct Foo(u32);
impl Add for Foo {
type Output = Foo;
fn add(self, rhs: Foo) -> Foo {
Foo(self.0 + rhs.0)
}
}
fn main() {
let mut x: Foo = Foo(5);
x += Foo(7); // error, `+= cannot be applied to the type `Foo`
}
```
This is because `AddAssign` is not automatically implemented, so you need to
manually implement it for your type.
"##,
E0369: r##"
A binary operation was attempted on a type which doesn't support it.
Erroneous code example:
```compile_fail,E0369
let x = 12f32; // error: binary operation `<<` cannot be applied to
// type `f32`
x << 2;
```
To fix this error, please check that this type implements this binary
operation. Example:
```
let x = 12u32; // the `u32` type does implement it:
// https://doc.rust-lang.org/stable/std/ops/trait.Shl.html
x << 2; // ok!
```
It is also possible to overload most operators for your own type by
implementing traits from `std::ops`.
String concatenation appends the string on the right to the string on the
left and may require reallocation. This requires ownership of the string
on the left. If something should be added to a string literal, move the
literal to the heap by allocating it with `to_owned()` like in
`"Your text".to_owned()`.
"##,
E0370: r##"
The maximum value of an enum was reached, so it cannot be automatically
set in the next enum value. Erroneous code example:
```compile_fail
#[deny(overflowing_literals)]
enum Foo {
X = 0x7fffffffffffffff,
Y, // error: enum discriminant overflowed on value after
// 9223372036854775807: i64; set explicitly via
// Y = -9223372036854775808 if that is desired outcome
}
```
To fix this, please set manually the next enum value or put the enum variant
with the maximum value at the end of the enum. Examples:
```
enum Foo {
X = 0x7fffffffffffffff,
Y = 0, // ok!
}
```
Or:
```
enum Foo {
Y = 0, // ok!
X = 0x7fffffffffffffff,
}
```
"##,
E0371: r##"
When `Trait2` is a subtrait of `Trait1` (for example, when `Trait2` has a
definition like `trait Trait2: Trait1 { ... }`), it is not allowed to implement
`Trait1` for `Trait2`. This is because `Trait2` already implements `Trait1` by
definition, so it is not useful to do this.
Example:
```compile_fail,E0371
trait Foo { fn foo(&self) { } }
trait Bar: Foo { }
trait Baz: Bar { }
impl Bar for Baz { } // error, `Baz` implements `Bar` by definition
impl Foo for Baz { } // error, `Baz` implements `Bar` which implements `Foo`
impl Baz for Baz { } // error, `Baz` (trivially) implements `Baz`
impl Baz for Bar { } // Note: This is OK
```
"##,
E0374: r##"
A struct without a field containing an unsized type cannot implement
`CoerceUnsized`. An [unsized type][1] is any type that the compiler
doesn't know the length or alignment of at compile time. Any struct
containing an unsized type is also unsized.
[1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
Example of erroneous code:
```compile_fail,E0374
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
struct Foo<T: ?Sized> {
a: i32,
}
// error: Struct `Foo` has no unsized fields that need `CoerceUnsized`.
impl<T, U> CoerceUnsized<Foo<U>> for Foo<T>
where T: CoerceUnsized<U> {}
```
`CoerceUnsized` is used to coerce one struct containing an unsized type
into another struct containing a different unsized type. If the struct
doesn't have any fields of unsized types then you don't need explicit
coercion to get the types you want. To fix this you can either
not try to implement `CoerceUnsized` or you can add a field that is
unsized to the struct.
Example:
```
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
// We don't need to impl `CoerceUnsized` here.
struct Foo {
a: i32,
}
// We add the unsized type field to the struct.
struct Bar<T: ?Sized> {
a: i32,
b: T,
}
// The struct has an unsized field so we can implement
// `CoerceUnsized` for it.
impl<T, U> CoerceUnsized<Bar<U>> for Bar<T>
where T: CoerceUnsized<U> {}
```
Note that `CoerceUnsized` is mainly used by smart pointers like `Box`, `Rc`
and `Arc` to be able to mark that they can coerce unsized types that they
are pointing at.
"##,
E0375: r##"
A struct with more than one field containing an unsized type cannot implement
`CoerceUnsized`. This only occurs when you are trying to coerce one of the
types in your struct to another type in the struct. In this case we try to
impl `CoerceUnsized` from `T` to `U` which are both types that the struct
takes. An [unsized type][1] is any type that the compiler doesn't know the
length or alignment of at compile time. Any struct containing an unsized type
is also unsized.
Example of erroneous code:
```compile_fail,E0375
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
struct Foo<T: ?Sized, U: ?Sized> {
a: i32,
b: T,
c: U,
}
// error: Struct `Foo` has more than one unsized field.
impl<T, U> CoerceUnsized<Foo<U, T>> for Foo<T, U> {}
```
`CoerceUnsized` only allows for coercion from a structure with a single
unsized type field to another struct with a single unsized type field.
In fact Rust only allows for a struct to have one unsized type in a struct
and that unsized type must be the last field in the struct. So having two
unsized types in a single struct is not allowed by the compiler. To fix this
use only one field containing an unsized type in the struct and then use
multiple structs to manage each unsized type field you need.
Example:
```
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
struct Foo<T: ?Sized> {
a: i32,
b: T,
}
impl <T, U> CoerceUnsized<Foo<U>> for Foo<T>
where T: CoerceUnsized<U> {}
fn coerce_foo<T: CoerceUnsized<U>, U>(t: T) -> Foo<U> {
Foo { a: 12i32, b: t } // we use coercion to get the `Foo<U>` type we need
}
```
[1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
"##,
E0376: r##"
The type you are trying to impl `CoerceUnsized` for is not a struct.
`CoerceUnsized` can only be implemented for a struct. Unsized types are
already able to be coerced without an implementation of `CoerceUnsized`
whereas a struct containing an unsized type needs to know the unsized type
field it's containing is able to be coerced. An [unsized type][1]
is any type that the compiler doesn't know the length or alignment of at
compile time. Any struct containing an unsized type is also unsized.
[1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
Example of erroneous code:
```compile_fail,E0376
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
struct Foo<T: ?Sized> {
a: T,
}
// error: The type `U` is not a struct
impl<T, U> CoerceUnsized<U> for Foo<T> {}
```
The `CoerceUnsized` trait takes a struct type. Make sure the type you are
providing to `CoerceUnsized` is a struct with only the last field containing an
unsized type.
Example:
```
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
struct Foo<T> {
a: T,
}
// The `Foo<U>` is a struct so `CoerceUnsized` can be implemented
impl<T, U> CoerceUnsized<Foo<U>> for Foo<T> where T: CoerceUnsized<U> {}
```
Note that in Rust, structs can only contain an unsized type if the field
containing the unsized type is the last and only unsized type field in the
struct.
"##,
E0378: r##"
The `DispatchFromDyn` trait currently can only be implemented for
builtin pointer types and structs that are newtype wrappers around them
— that is, the struct must have only one field (except for`PhantomData`),
and that field must itself implement `DispatchFromDyn`.
Examples:
```
#![feature(dispatch_from_dyn, unsize)]
use std::{
marker::Unsize,
ops::DispatchFromDyn,
};
struct Ptr<T: ?Sized>(*const T);
impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Ptr<U>> for Ptr<T>
where
T: Unsize<U>,
{}
```
```
#![feature(dispatch_from_dyn)]
use std::{
ops::DispatchFromDyn,
marker::PhantomData,
};
struct Wrapper<T> {
ptr: T,
_phantom: PhantomData<()>,
}
impl<T, U> DispatchFromDyn<Wrapper<U>> for Wrapper<T>
where
T: DispatchFromDyn<U>,
{}
```
Example of illegal `DispatchFromDyn` implementation
(illegal because of extra field)
```compile-fail,E0378
#![feature(dispatch_from_dyn)]
use std::ops::DispatchFromDyn;
struct WrapperExtraField<T> {
ptr: T,
extra_stuff: i32,
}
impl<T, U> DispatchFromDyn<WrapperExtraField<U>> for WrapperExtraField<T>
where
T: DispatchFromDyn<U>,
{}
```
"##,
E0390: r##"
You tried to implement methods for a primitive type. Erroneous code example:
```compile_fail,E0390
struct Foo {
x: i32
}
impl *mut Foo {}
// error: only a single inherent implementation marked with
// `#[lang = "mut_ptr"]` is allowed for the `*mut T` primitive
```
This isn't allowed, but using a trait to implement a method is a good solution.
Example:
```
struct Foo {
x: i32
}
trait Bar {
fn bar();
}
impl Bar for *mut Foo {
fn bar() {} // ok!
}
```
"##,
E0392: r##"
This error indicates that a type or lifetime parameter has been declared
but not actually used. Here is an example that demonstrates the error:
```compile_fail,E0392
enum Foo<T> {
Bar,
}
```
If the type parameter was included by mistake, this error can be fixed
by simply removing the type parameter, as shown below:
```
enum Foo {
Bar,
}
```
Alternatively, if the type parameter was intentionally inserted, it must be
used. A simple fix is shown below:
```
enum Foo<T> {
Bar(T),
}
```
This error may also commonly be found when working with unsafe code. For
example, when using raw pointers one may wish to specify the lifetime for
which the pointed-at data is valid. An initial attempt (below) causes this
error:
```compile_fail,E0392
struct Foo<'a, T> {
x: *const T,
}
```
We want to express the constraint that Foo should not outlive `'a`, because
the data pointed to by `T` is only valid for that lifetime. The problem is
that there are no actual uses of `'a`. It's possible to work around this
by adding a PhantomData type to the struct, using it to tell the compiler
to act as if the struct contained a borrowed reference `&'a T`:
```
use std::marker::PhantomData;
struct Foo<'a, T: 'a> {
x: *const T,
phantom: PhantomData<&'a T>
}
```
[PhantomData] can also be used to express information about unused type
parameters.
[PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html
"##,
E0393: r##"
A type parameter which references `Self` in its default value was not specified.
Example of erroneous code:
```compile_fail,E0393
trait A<T=Self> {}
fn together_we_will_rule_the_galaxy(son: &A) {}
// error: the type parameter `T` must be explicitly specified in an
// object type because its default value `Self` references the
// type `Self`
```
A trait object is defined over a single, fully-defined trait. With a regular
default parameter, this parameter can just be substituted in. However, if the
default parameter is `Self`, the trait changes for each concrete type; i.e.
`i32` will be expected to implement `A<i32>`, `bool` will be expected to
implement `A<bool>`, etc... These types will not share an implementation of a
fully-defined trait; instead they share implementations of a trait with
different parameters substituted in for each implementation. This is
irreconcilable with what we need to make a trait object work, and is thus
disallowed. Making the trait concrete by explicitly specifying the value of the
defaulted parameter will fix this issue. Fixed example:
```
trait A<T=Self> {}
fn together_we_will_rule_the_galaxy(son: &A<i32>) {} // Ok!
```
"##,
E0399: r##"
You implemented a trait, overriding one or more of its associated types but did
not reimplement its default methods.
Example of erroneous code:
```compile_fail,E0399
#![feature(associated_type_defaults)]
pub trait Foo {
type Assoc = u8;
fn bar(&self) {}
}
impl Foo for i32 {
// error - the following trait items need to be reimplemented as
// `Assoc` was overridden: `bar`
type Assoc = i32;
}
```
To fix this, add an implementation for each default method from the trait:
```
#![feature(associated_type_defaults)]
pub trait Foo {
type Assoc = u8;
fn bar(&self) {}
}
impl Foo for i32 {
type Assoc = i32;
fn bar(&self) {} // ok!
}
```
"##,
E0436: r##"
The functional record update syntax is only allowed for structs. (Struct-like
enum variants don't qualify, for example.)
Erroneous code example:
```compile_fail,E0436
enum PublicationFrequency {
Weekly,
SemiMonthly { days: (u8, u8), annual_special: bool },
}
fn one_up_competitor(competitor_frequency: PublicationFrequency)
-> PublicationFrequency {
match competitor_frequency {
PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
days: (1, 15), annual_special: false
},
c @ PublicationFrequency::SemiMonthly{ .. } =>
PublicationFrequency::SemiMonthly {
annual_special: true, ..c // error: functional record update
// syntax requires a struct
}
}
}
```
Rewrite the expression without functional record update syntax:
```
enum PublicationFrequency {
Weekly,
SemiMonthly { days: (u8, u8), annual_special: bool },
}
fn one_up_competitor(competitor_frequency: PublicationFrequency)
-> PublicationFrequency {
match competitor_frequency {
PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
days: (1, 15), annual_special: false
},
PublicationFrequency::SemiMonthly{ days, .. } =>
PublicationFrequency::SemiMonthly {
days, annual_special: true // ok!
}
}
}
```
"##,
E0439: r##"
The length of the platform-intrinsic function `simd_shuffle`
wasn't specified. Erroneous code example:
```compile_fail,E0439
#![feature(platform_intrinsics)]
extern "platform-intrinsic" {
fn simd_shuffle<A,B>(a: A, b: A, c: [u32; 8]) -> B;
// error: invalid `simd_shuffle`, needs length: `simd_shuffle`
}
```
The `simd_shuffle` function needs the length of the array passed as
last parameter in its name. Example:
```
#![feature(platform_intrinsics)]
extern "platform-intrinsic" {
fn simd_shuffle8<A,B>(a: A, b: A, c: [u32; 8]) -> B;
}
```
"##,
E0516: r##"
The `typeof` keyword is currently reserved but unimplemented.
Erroneous code example:
```compile_fail,E0516
fn main() {
let x: typeof(92) = 92;
}
```
Try using type inference instead. Example:
```
fn main() {
let x = 92;
}
```
"##,
E0520: r##"
A non-default implementation was already made on this type so it cannot be
specialized further. Erroneous code example:
```compile_fail,E0520
#![feature(specialization)]
trait SpaceLlama {
fn fly(&self);
}
// applies to all T
impl<T> SpaceLlama for T {
default fn fly(&self) {}
}
// non-default impl
// applies to all `Clone` T and overrides the previous impl
impl<T: Clone> SpaceLlama for T {
fn fly(&self) {}
}
// since `i32` is clone, this conflicts with the previous implementation
impl SpaceLlama for i32 {
default fn fly(&self) {}
// error: item `fly` is provided by an `impl` that specializes
// another, but the item in the parent `impl` is not marked
// `default` and so it cannot be specialized.
}
```
Specialization only allows you to override `default` functions in
implementations.
To fix this error, you need to mark all the parent implementations as default.
Example:
```
#![feature(specialization)]
trait SpaceLlama {
fn fly(&self);
}
// applies to all T
impl<T> SpaceLlama for T {
default fn fly(&self) {} // This is a parent implementation.
}
// applies to all `Clone` T; overrides the previous impl
impl<T: Clone> SpaceLlama for T {
default fn fly(&self) {} // This is a parent implementation but was
// previously not a default one, causing the error
}
// applies to i32, overrides the previous two impls
impl SpaceLlama for i32 {
fn fly(&self) {} // And now that's ok!
}
```
"##,
E0527: r##"
The number of elements in an array or slice pattern differed from the number of
elements in the array being matched.
Example of erroneous code:
```compile_fail,E0527
let r = &[1, 2, 3, 4];
match r {
&[a, b] => { // error: pattern requires 2 elements but array
// has 4
println!("a={}, b={}", a, b);
}
}
```
Ensure that the pattern is consistent with the size of the matched
array. Additional elements can be matched with `..`:
```
#![feature(slice_patterns)]
let r = &[1, 2, 3, 4];
match r {
&[a, b, ..] => { // ok!
println!("a={}, b={}", a, b);
}
}
```
"##,
E0528: r##"
An array or slice pattern required more elements than were present in the
matched array.
Example of erroneous code:
```compile_fail,E0528
#![feature(slice_patterns)]
let r = &[1, 2];
match r {
&[a, b, c, rest..] => { // error: pattern requires at least 3
// elements but array has 2
println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
}
}
```
Ensure that the matched array has at least as many elements as the pattern
requires. You can match an arbitrary number of remaining elements with `..`:
```
#![feature(slice_patterns)]
let r = &[1, 2, 3, 4, 5];
match r {
&[a, b, c, rest..] => { // ok!
// prints `a=1, b=2, c=3 rest=[4, 5]`
println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
}
}
```
"##,
E0529: r##"
An array or slice pattern was matched against some other type.
Example of erroneous code:
```compile_fail,E0529
let r: f32 = 1.0;
match r {
[a, b] => { // error: expected an array or slice, found `f32`
println!("a={}, b={}", a, b);
}
}
```
Ensure that the pattern and the expression being matched on are of consistent
types:
```
let r = [1.0, 2.0];
match r {
[a, b] => { // ok!
println!("a={}, b={}", a, b);
}
}
```
"##,
E0534: r##"
The `inline` attribute was malformed.
Erroneous code example:
```ignore (compile_fail not working here; see Issue #43707)
#[inline()] // error: expected one argument
pub fn something() {}
fn main() {}
```
The parenthesized `inline` attribute requires the parameter to be specified:
```
#[inline(always)]
fn something() {}
```
or:
```
#[inline(never)]
fn something() {}
```
Alternatively, a paren-less version of the attribute may be used to hint the
compiler about inlining opportunity:
```
#[inline]
fn something() {}
```
For more information about the inline attribute, read:
https://doc.rust-lang.org/reference.html#inline-attributes
"##,
E0535: r##"
An unknown argument was given to the `inline` attribute.
Erroneous code example:
```ignore (compile_fail not working here; see Issue #43707)
#[inline(unknown)] // error: invalid argument
pub fn something() {}
fn main() {}
```
The `inline` attribute only supports two arguments:
* always
* never
All other arguments given to the `inline` attribute will return this error.
Example:
```
#[inline(never)] // ok!
pub fn something() {}
fn main() {}
```
For more information about the inline attribute, https:
read://doc.rust-lang.org/reference.html#inline-attributes
"##,
E0559: r##"
An unknown field was specified into an enum's structure variant.
Erroneous code example:
```compile_fail,E0559
enum Field {
Fool { x: u32 },
}
let s = Field::Fool { joke: 0 };
// error: struct variant `Field::Fool` has no field named `joke`
```
Verify you didn't misspell the field's name or that the field exists. Example:
```
enum Field {
Fool { joke: u32 },
}
let s = Field::Fool { joke: 0 }; // ok!
```
"##,
E0560: r##"
An unknown field was specified into a structure.
Erroneous code example:
```compile_fail,E0560
struct Simba {
mother: u32,
}
let s = Simba { mother: 1, father: 0 };
// error: structure `Simba` has no field named `father`
```
Verify you didn't misspell the field's name or that the field exists. Example:
```
struct Simba {
mother: u32,
father: u32,
}
let s = Simba { mother: 1, father: 0 }; // ok!
```
"##,
E0569: r##"
If an impl has a generic parameter with the `#[may_dangle]` attribute, then
that impl must be declared as an `unsafe impl.
Erroneous code example:
```compile_fail,E0569
#![feature(dropck_eyepatch)]
struct Foo<X>(X);
impl<#[may_dangle] X> Drop for Foo<X> {
fn drop(&mut self) { }
}
```
In this example, we are asserting that the destructor for `Foo` will not
access any data of type `X`, and require this assertion to be true for
overall safety in our program. The compiler does not currently attempt to
verify this assertion; therefore we must tag this `impl` as unsafe.
"##,
E0570: r##"
The requested ABI is unsupported by the current target.
The rust compiler maintains for each target a blacklist of ABIs unsupported on
that target. If an ABI is present in such a list this usually means that the
target / ABI combination is currently unsupported by llvm.
If necessary, you can circumvent this check using custom target specifications.
"##,
E0572: r##"
A return statement was found outside of a function body.
Erroneous code example:
```compile_fail,E0572
const FOO: u32 = return 0; // error: return statement outside of function body
fn main() {}
```
To fix this issue, just remove the return keyword or move the expression into a
function. Example:
```
const FOO: u32 = 0;
fn some_fn() -> u32 {
return FOO;
}
fn main() {
some_fn();
}
```
"##,
E0581: r##"
In a `fn` type, a lifetime appears only in the return type,
and not in the arguments types.
Erroneous code example:
```compile_fail,E0581
fn main() {
// Here, `'a` appears only in the return type:
let x: for<'a> fn() -> &'a i32;
}
```
To fix this issue, either use the lifetime in the arguments, or use
`'static`. Example:
```
fn main() {
// Here, `'a` appears only in the return type:
let x: for<'a> fn(&'a i32) -> &'a i32;
let y: fn() -> &'static i32;
}
```
Note: The examples above used to be (erroneously) accepted by the
compiler, but this was since corrected. See [issue #33685] for more
details.
[issue #33685]: https://github.com/rust-lang/rust/issues/33685
"##,
E0582: r##"
A lifetime appears only in an associated-type binding,
and not in the input types to the trait.
Erroneous code example:
```compile_fail,E0582
fn bar<F>(t: F)
// No type can satisfy this requirement, since `'a` does not
// appear in any of the input types (here, `i32`):
where F: for<'a> Fn(i32) -> Option<&'a i32>
{
}
fn main() { }
```
To fix this issue, either use the lifetime in the inputs, or use
`'static`. Example:
```
fn bar<F, G>(t: F, u: G)
where F: for<'a> Fn(&'a i32) -> Option<&'a i32>,
G: Fn(i32) -> Option<&'static i32>,
{
}
fn main() { }
```
Note: The examples above used to be (erroneously) accepted by the
compiler, but this was since corrected. See [issue #33685] for more
details.
[issue #33685]: https://github.com/rust-lang/rust/issues/33685
"##,
E0599: r##"
This error occurs when a method is used on a type which doesn't implement it:
Erroneous code example:
```compile_fail,E0599
struct Mouth;
let x = Mouth;
x.chocolate(); // error: no method named `chocolate` found for type `Mouth`
// in the current scope
```
"##,
E0600: r##"
An unary operator was used on a type which doesn't implement it.
Example of erroneous code:
```compile_fail,E0600
enum Question {
Yes,
No,
}
!Question::Yes; // error: cannot apply unary operator `!` to type `Question`
```
In this case, `Question` would need to implement the `std::ops::Not` trait in
order to be able to use `!` on it. Let's implement it:
```
use std::ops::Not;
enum Question {
Yes,
No,
}
// We implement the `Not` trait on the enum.
impl Not for Question {
type Output = bool;
fn not(self) -> bool {
match self {
Question::Yes => false, // If the `Answer` is `Yes`, then it
// returns false.
Question::No => true, // And here we do the opposite.
}
}
}
assert_eq!(!Question::Yes, false);
assert_eq!(!Question::No, true);
```
"##,
E0608: r##"
An attempt to index into a type which doesn't implement the `std::ops::Index`
trait was performed.
Erroneous code example:
```compile_fail,E0608
0u8[2]; // error: cannot index into a value of type `u8`
```
To be able to index into a type it needs to implement the `std::ops::Index`
trait. Example:
```
let v: Vec<u8> = vec![0, 1, 2, 3];
// The `Vec` type implements the `Index` trait so you can do:
println!("{}", v[2]);
```
"##,
E0604: r##"
A cast to `char` was attempted on a type other than `u8`.
Erroneous code example:
```compile_fail,E0604
0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
```
As the error message indicates, only `u8` can be cast into `char`. Example:
```
let c = 86u8 as char; // ok!
assert_eq!(c, 'V');
```
For more information about casts, take a look at the Type cast section in
[The Reference Book][1].
[1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
"##,
E0605: r##"
An invalid cast was attempted.
Erroneous code examples:
```compile_fail,E0605
let x = 0u8;
x as Vec<u8>; // error: non-primitive cast: `u8` as `std::vec::Vec<u8>`
// Another example
let v = 0 as *const u8; // So here, `v` is a `*const u8`.
v as &u8; // error: non-primitive cast: `*const u8` as `&u8`
```
Only primitive types can be cast into each other. Examples:
```
let x = 0u8;
x as u32; // ok!
let v = 0 as *const u8;
v as *const i8; // ok!
```
For more information about casts, take a look at the Type cast section in
[The Reference Book][1].
[1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
"##,
E0606: r##"
An incompatible cast was attempted.
Erroneous code example:
```compile_fail,E0606
let x = &0u8; // Here, `x` is a `&u8`.
let y: u32 = x as u32; // error: casting `&u8` as `u32` is invalid
```
When casting, keep in mind that only primitive types can be cast into each
other. Example:
```
let x = &0u8;
let y: u32 = *x as u32; // We dereference it first and then cast it.
```
For more information about casts, take a look at the Type cast section in
[The Reference Book][1].
[1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
"##,
E0607: r##"
A cast between a thin and a fat pointer was attempted.
Erroneous code example:
```compile_fail,E0607
let v = 0 as *const u8;
v as *const [u8];
```
First: what are thin and fat pointers?
Thin pointers are "simple" pointers: they are purely a reference to a memory
address.
Fat pointers are pointers referencing Dynamically Sized Types (also called DST).
DST don't have a statically known size, therefore they can only exist behind
some kind of pointers that contain additional information. Slices and trait
objects are DSTs. In the case of slices, the additional information the fat
pointer holds is their size.
To fix this error, don't try to cast directly between thin and fat pointers.
For more information about casts, take a look at the Type cast section in
[The Reference Book][1].
[1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
"##,
E0609: r##"
Attempted to access a non-existent field in a struct.
Erroneous code example:
```compile_fail,E0609
struct StructWithFields {
x: u32,
}
let s = StructWithFields { x: 0 };
println!("{}", s.foo); // error: no field `foo` on type `StructWithFields`
```
To fix this error, check that you didn't misspell the field's name or that the
field actually exists. Example:
```
struct StructWithFields {
x: u32,
}
let s = StructWithFields { x: 0 };
println!("{}", s.x); // ok!
```
"##,
E0610: r##"
Attempted to access a field on a primitive type.
Erroneous code example:
```compile_fail,E0610
let x: u32 = 0;
println!("{}", x.foo); // error: `{integer}` is a primitive type, therefore
// doesn't have fields
```
Primitive types are the most basic types available in Rust and don't have
fields. To access data via named fields, struct types are used. Example:
```
// We declare struct called `Foo` containing two fields:
struct Foo {
x: u32,
y: i64,
}
// We create an instance of this struct:
let variable = Foo { x: 0, y: -12 };
// And we can now access its fields:
println!("x: {}, y: {}", variable.x, variable.y);
```
For more information about primitives and structs, take a look at The Book:
https://doc.rust-lang.org/book/ch03-02-data-types.html
https://doc.rust-lang.org/book/ch05-00-structs.html
"##,
E0614: r##"
Attempted to dereference a variable which cannot be dereferenced.
Erroneous code example:
```compile_fail,E0614
let y = 0u32;
*y; // error: type `u32` cannot be dereferenced
```
Only types implementing `std::ops::Deref` can be dereferenced (such as `&T`).
Example:
```
let y = 0u32;
let x = &y;
// So here, `x` is a `&u32`, so we can dereference it:
*x; // ok!
```
"##,
E0615: r##"
Attempted to access a method like a field.
Erroneous code example:
```compile_fail,E0615
struct Foo {
x: u32,
}
impl Foo {
fn method(&self) {}
}
let f = Foo { x: 0 };
f.method; // error: attempted to take value of method `method` on type `Foo`
```
If you want to use a method, add `()` after it:
```
# struct Foo { x: u32 }
# impl Foo { fn method(&self) {} }
# let f = Foo { x: 0 };
f.method();
```
However, if you wanted to access a field of a struct check that the field name
is spelled correctly. Example:
```
# struct Foo { x: u32 }
# impl Foo { fn method(&self) {} }
# let f = Foo { x: 0 };
println!("{}", f.x);
```
"##,
E0616: r##"
Attempted to access a private field on a struct.
Erroneous code example:
```compile_fail,E0616
mod some_module {
pub struct Foo {
x: u32, // So `x` is private in here.
}
impl Foo {
pub fn new() -> Foo { Foo { x: 0 } }
}
}
let f = some_module::Foo::new();
println!("{}", f.x); // error: field `x` of struct `some_module::Foo` is private
```
If you want to access this field, you have two options:
1) Set the field public:
```
mod some_module {
pub struct Foo {
pub x: u32, // `x` is now public.
}
impl Foo {
pub fn new() -> Foo { Foo { x: 0 } }
}
}
let f = some_module::Foo::new();
println!("{}", f.x); // ok!
```
2) Add a getter function:
```
mod some_module {
pub struct Foo {
x: u32, // So `x` is still private in here.
}
impl Foo {
pub fn new() -> Foo { Foo { x: 0 } }
// We create the getter function here:
pub fn get_x(&self) -> &u32 { &self.x }
}
}
let f = some_module::Foo::new();
println!("{}", f.get_x()); // ok!
```
"##,
E0617: r##"
Attempted to pass an invalid type of variable into a variadic function.
Erroneous code example:
```compile_fail,E0617
extern {
fn printf(c: *const i8, ...);
}
unsafe {
printf(::std::ptr::null(), 0f32);
// error: can't pass an `f32` to variadic function, cast to `c_double`
}
```
Certain Rust types must be cast before passing them to a variadic function,
because of arcane ABI rules dictated by the C standard. To fix the error,
cast the value to the type specified by the error message (which you may need
to import from `std::os::raw`).
"##,
E0618: r##"
Attempted to call something which isn't a function nor a method.
Erroneous code examples:
```compile_fail,E0618
enum X {
Entry,
}
X::Entry(); // error: expected function, found `X::Entry`
// Or even simpler:
let x = 0i32;
x(); // error: expected function, found `i32`
```
Only functions and methods can be called using `()`. Example:
```
// We declare a function:
fn i_am_a_function() {}
// And we call it:
i_am_a_function();
```
"##,
E0619: r##"
#### Note: this error code is no longer emitted by the compiler.
The type-checker needed to know the type of an expression, but that type had not
yet been inferred.
Erroneous code example:
```compile_fail
let mut x = vec![];
match x.pop() {
Some(v) => {
// Here, the type of `v` is not (yet) known, so we
// cannot resolve this method call:
v.to_uppercase(); // error: the type of this value must be known in
// this context
}
None => {}
}
```
Type inference typically proceeds from the top of the function to the bottom,
figuring out types as it goes. In some cases -- notably method calls and
overloadable operators like `*` -- the type checker may not have enough
information *yet* to make progress. This can be true even if the rest of the
function provides enough context (because the type-checker hasn't looked that
far ahead yet). In this case, type annotations can be used to help it along.
To fix this error, just specify the type of the variable. Example:
```
let mut x: Vec<String> = vec![]; // We precise the type of the vec elements.
match x.pop() {
Some(v) => {
v.to_uppercase(); // Since rustc now knows the type of the vec elements,
// we can use `v`'s methods.
}
None => {}
}
```
"##,
E0620: r##"
A cast to an unsized type was attempted.
Erroneous code example:
```compile_fail,E0620
let x = &[1_usize, 2] as [usize]; // error: cast to unsized type: `&[usize; 2]`
// as `[usize]`
```
In Rust, some types don't have a known size at compile-time. For example, in a
slice type like `[u32]`, the number of elements is not known at compile-time and
hence the overall size cannot be computed. As a result, such types can only be
manipulated through a reference (e.g., `&T` or `&mut T`) or other pointer-type
(e.g., `Box` or `Rc`). Try casting to a reference instead:
```
let x = &[1_usize, 2] as &[usize]; // ok!
```
"##,
E0622: r##"
An intrinsic was declared without being a function.
Erroneous code example:
```compile_fail,E0622
#![feature(intrinsics)]
extern "rust-intrinsic" {
pub static breakpoint : unsafe extern "rust-intrinsic" fn();
// error: intrinsic must be a function
}
fn main() { unsafe { breakpoint(); } }
```
An intrinsic is a function available for use in a given programming language
whose implementation is handled specially by the compiler. In order to fix this
error, just declare a function.
"##,
E0624: r##"
A private item was used outside of its scope.
Erroneous code example:
```compile_fail,E0624
mod inner {
pub struct Foo;
impl Foo {
fn method(&self) {}
}
}
let foo = inner::Foo;
foo.method(); // error: method `method` is private
```
Two possibilities are available to solve this issue:
1. Only use the item in the scope it has been defined:
```
mod inner {
pub struct Foo;
impl Foo {
fn method(&self) {}
}
pub fn call_method(foo: &Foo) { // We create a public function.
foo.method(); // Which calls the item.
}
}
let foo = inner::Foo;
inner::call_method(&foo); // And since the function is public, we can call the
// method through it.
```
2. Make the item public:
```
mod inner {
pub struct Foo;
impl Foo {
pub fn method(&self) {} // It's now public.
}
}
let foo = inner::Foo;
foo.method(); // Ok!
```
"##,
E0638: r##"
This error indicates that the struct or enum must be matched non-exhaustively
as it has been marked as `non_exhaustive`.
When applied within a crate, downstream users of the crate will need to use the
`_` pattern when matching enums and use the `..` pattern when matching structs.
For example, in the below example, since the enum is marked as
`non_exhaustive`, it is required that downstream crates match non-exhaustively
on it.
```rust,ignore (pseudo-Rust)
use std::error::Error as StdError;
#[non_exhaustive] pub enum Error {
Message(String),
Other,
}
impl StdError for Error {
fn description(&self) -> &str {
// This will not error, despite being marked as non_exhaustive, as this
// enum is defined within the current crate, it can be matched
// exhaustively.
match *self {
Message(ref s) => s,
Other => "other or unknown error",
}
}
}
```
An example of matching non-exhaustively on the above enum is provided below:
```rust,ignore (pseudo-Rust)
use mycrate::Error;
// This will not error as the non_exhaustive Error enum has been matched with a
// wildcard.
match error {
Message(ref s) => ...,
Other => ...,
_ => ...,
}
```
Similarly, for structs, match with `..` to avoid this error.
"##,
E0639: r##"
This error indicates that the struct or enum cannot be instantiated from
outside of the defining crate as it has been marked as `non_exhaustive` and as
such more fields/variants may be added in future that could cause adverse side
effects for this code.
It is recommended that you look for a `new` function or equivalent in the
crate's documentation.
"##,
E0643: r##"
This error indicates that there is a mismatch between generic parameters and
impl Trait parameters in a trait declaration versus its impl.
```compile_fail,E0643
trait Foo {
fn foo(&self, _: &impl Iterator);
}
impl Foo for () {
fn foo<U: Iterator>(&self, _: &U) { } // error method `foo` has incompatible
// signature for trait
}
```
"##,
E0646: r##"
It is not possible to define `main` with a where clause.
Erroneous code example:
```compile_fail,E0646
fn main() where i32: Copy { // error: main function is not allowed to have
// a where clause
}
```
"##,
E0647: r##"
It is not possible to define `start` with a where clause.
Erroneous code example:
```compile_fail,E0647
#![feature(start)]
#[start]
fn start(_: isize, _: *const *const u8) -> isize where (): Copy {
//^ error: start function is not allowed to have a where clause
0
}
```
"##,
E0648: r##"
`export_name` attributes may not contain null characters (`\0`).
```compile_fail,E0648
#[export_name="\0foo"] // error: `export_name` may not contain null characters
pub fn bar() {}
```
"##,
E0689: r##"
This error indicates that the numeric value for the method being passed exists
but the type of the numeric value or binding could not be identified.
The error happens on numeric literals:
```compile_fail,E0689
2.0.neg();
```
and on numeric bindings without an identified concrete type:
```compile_fail,E0689
let x = 2.0;
x.neg(); // same error as above
```
Because of this, you must give the numeric literal or binding a type:
```
use std::ops::Neg;
let _ = 2.0_f32.neg();
let x: f32 = 2.0;
let _ = x.neg();
let _ = (2.0 as f32).neg();
```
"##,
E0690: r##"
A struct with the representation hint `repr(transparent)` had zero or more than
on fields that were not guaranteed to be zero-sized.
Erroneous code example:
```compile_fail,E0690
#[repr(transparent)]
struct LengthWithUnit<U> { // error: transparent struct needs exactly one
value: f32, // non-zero-sized field, but has 2
unit: U,
}
```
Because transparent structs are represented exactly like one of their fields at
run time, said field must be uniquely determined. If there is no field, or if
there are multiple fields, it is not clear how the struct should be represented.
Note that fields of zero-typed types (e.g., `PhantomData`) can also exist
alongside the field that contains the actual data, they do not count for this
error. When generic types are involved (as in the above example), an error is
reported because the type parameter could be non-zero-sized.
To combine `repr(transparent)` with type parameters, `PhantomData` may be
useful:
```
use std::marker::PhantomData;
#[repr(transparent)]
struct LengthWithUnit<U> {
value: f32,
unit: PhantomData<U>,
}
```
"##,
E0691: r##"
A struct with the `repr(transparent)` representation hint contains a zero-sized
field that requires non-trivial alignment.
Erroneous code example:
```compile_fail,E0691
#![feature(repr_align)]
#[repr(align(32))]
struct ForceAlign32;
#[repr(transparent)]
struct Wrapper(f32, ForceAlign32); // error: zero-sized field in transparent
// struct has alignment larger than 1
```
A transparent struct is supposed to be represented exactly like the piece of
data it contains. Zero-sized fields with different alignment requirements
potentially conflict with this property. In the example above, `Wrapper` would
have to be aligned to 32 bytes even though `f32` has a smaller alignment
requirement.
Consider removing the over-aligned zero-sized field:
```
#[repr(transparent)]
struct Wrapper(f32);
```
Alternatively, `PhantomData<T>` has alignment 1 for all `T`, so you can use it
if you need to keep the field for some reason:
```
#![feature(repr_align)]
use std::marker::PhantomData;
#[repr(align(32))]
struct ForceAlign32;
#[repr(transparent)]
struct Wrapper(f32, PhantomData<ForceAlign32>);
```
Note that empty arrays `[T; 0]` have the same alignment requirement as the
element type `T`. Also note that the error is conservatively reported even when
the alignment of the zero-sized type is less than or equal to the data field's
alignment.
"##,
E0699: r##"
A method was called on a raw pointer whose inner type wasn't completely known.
For example, you may have done something like:
```compile_fail
# #![deny(warnings)]
let foo = &1;
let bar = foo as *const _;
if bar.is_null() {
// ...
}
```
Here, the type of `bar` isn't known; it could be a pointer to anything. Instead,
specify a type for the pointer (preferably something that makes sense for the
thing you're pointing to):
```
let foo = &1;
let bar = foo as *const i32;
if bar.is_null() {
// ...
}
```
Even though `is_null()` exists as a method on any raw pointer, Rust shows this
error because Rust allows for `self` to have arbitrary types (behind the
arbitrary_self_types feature flag).
This means that someone can specify such a function:
```ignore (cannot-doctest-feature-doesnt-exist-yet)
impl Foo {
fn is_null(self: *const Self) -> bool {
// do something else
}
}
```
and now when you call `.is_null()` on a raw pointer to `Foo`, there's ambiguity.
Given that we don't know what type the pointer is, and there's potential
ambiguity for some types, we disallow calling methods on raw pointers when
the type is unknown.
"##,
E0714: r##"
A `#[marker]` trait contained an associated item.
The items of marker traits cannot be overridden, so there's no need to have them
when they cannot be changed per-type anyway. If you wanted them for ergonomic
reasons, consider making an extension trait instead.
"##,
E0715: r##"
An `impl` for a `#[marker]` trait tried to override an associated item.
Because marker traits are allowed to have multiple implementations for the same
type, it's not allowed to override anything in those implementations, as it
would be ambiguous which override should actually be used.
"##,
E0720: r##"
An `impl Trait` type expands to a recursive type.
An `impl Trait` type must be expandable to a concrete type that contains no
`impl Trait` types. For example the following example tries to create an
`impl Trait` type `T` that is equal to `[T, T]`:
```compile_fail,E0720
fn make_recursive_type() -> impl Sized {
[make_recursive_type(), make_recursive_type()]
}
```
"##,
}
register_diagnostics! {
// E0035, merged into E0087/E0089
// E0036, merged into E0087/E0089
// E0068,
// E0085,
// E0086,
// E0103,
// E0104,
// E0122, // bounds in type aliases are ignored, turned into proper lint
// E0123,
// E0127,
// E0129,
// E0141,
// E0159, // use of trait `{}` as struct constructor
// E0163, // merged into E0071
// E0167,
// E0168,
// E0172, // non-trait found in a type sum, moved to resolve
// E0173, // manual implementations of unboxed closure traits are experimental
// E0174,
// E0182, // merged into E0229
E0183,
// E0187, // can't infer the kind of the closure
// E0188, // can not cast an immutable reference to a mutable pointer
// E0189, // deprecated: can only cast a boxed pointer to a boxed object
// E0190, // deprecated: can only cast a &-pointer to an &-object
// E0196, // cannot determine a type for this closure
E0203, // type parameter has more than one relaxed default bound,
// and only one is supported
E0208,
// E0209, // builtin traits can only be implemented on structs or enums
E0212, // cannot extract an associated type from a higher-ranked trait bound
// E0213, // associated types are not accepted in this context
// E0215, // angle-bracket notation is not stable with `Fn`
// E0216, // parenthetical notation is only stable with `Fn`
// E0217, // ambiguous associated type, defined in multiple supertraits
// E0218, // no associated type defined
// E0219, // associated type defined in higher-ranked supertrait
// E0222, // Error code E0045 (variadic function must have C or cdecl calling
// convention) duplicate
E0224, // at least one non-builtin train is required for an object type
E0227, // ambiguous lifetime bound, explicit lifetime bound required
E0228, // explicit lifetime bound required
// E0233,
// E0234,
// E0235, // structure constructor specifies a structure of type but
// E0236, // no lang item for range syntax
// E0237, // no lang item for range syntax
// E0238, // parenthesized parameters may only be used with a trait
// E0239, // `next` method of `Iterator` trait has unexpected type
// E0240,
// E0241,
// E0242,
// E0245, // not a trait
// E0246, // invalid recursive type
// E0247,
// E0248, // value used as a type, now reported earlier during resolution as E0412
// E0249,
E0307, // invalid method `self` type
// E0319, // trait impls for defaulted traits allowed just for structs/enums
// E0372, // coherence not object safe
E0377, // the trait `CoerceUnsized` may only be implemented for a coercion
// between structures with the same definition
// E0558, // replaced with a generic attribute input check
E0533, // `{}` does not name a unit variant, unit struct or a constant
// E0563, // cannot determine a type for this `impl Trait`: {} // removed in 6383de15
E0564, // only named lifetimes are allowed in `impl Trait`,
// but `{}` was found in the type `{}`
E0587, // type has conflicting packed and align representation hints
E0588, // packed type cannot transitively contain a `[repr(align)]` type
E0592, // duplicate definitions with name `{}`
// E0611, // merged into E0616
// E0612, // merged into E0609
// E0613, // Removed (merged with E0609)
E0627, // yield statement outside of generator literal
E0632, // cannot provide explicit type parameters when `impl Trait` is used in
// argument position.
E0634, // type has conflicting packed representaton hints
E0640, // infer outlives requirements
E0641, // cannot cast to/from a pointer with an unknown kind
E0645, // trait aliases not finished
E0698, // type inside generator must be known in this context
E0719, // duplicate values for associated type binding
E0722, // Malformed #[optimize] attribute
}
| 22.659561 | 115 | 0.669107 |
0e01506ffdbd52d0d9cbd3ca0fcc62f4c4b51c1f
| 3,519 |
use clap::{App, Arg, ArgSettings};
#[test]
fn opt_default_no_delim() {
let m = App::new("no_delim")
.arg(
Arg::new("option")
.long("option")
.setting(ArgSettings::TakesValue),
)
.try_get_matches_from(vec!["", "--option", "val1,val2,val3"]);
assert!(m.is_ok());
let m = m.unwrap();
assert!(m.is_present("option"));
assert_eq!(m.occurrences_of("option"), 1);
assert_eq!(m.value_of("option").unwrap(), "val1,val2,val3");
}
#[test]
fn opt_eq_no_delim() {
let m = App::new("no_delim")
.arg(
Arg::new("option")
.long("option")
.setting(ArgSettings::TakesValue),
)
.try_get_matches_from(vec!["", "--option=val1,val2,val3"]);
assert!(m.is_ok());
let m = m.unwrap();
assert!(m.is_present("option"));
assert_eq!(m.occurrences_of("option"), 1);
assert_eq!(m.value_of("option").unwrap(), "val1,val2,val3");
}
#[test]
fn opt_s_eq_no_delim() {
let m = App::new("no_delim")
.arg(
Arg::new("option")
.short('o')
.setting(ArgSettings::TakesValue),
)
.try_get_matches_from(vec!["", "-o=val1,val2,val3"]);
assert!(m.is_ok(), "{:?}", m.unwrap_err());
let m = m.unwrap();
assert!(m.is_present("option"));
assert_eq!(m.occurrences_of("option"), 1);
assert_eq!(m.value_of("option").unwrap(), "val1,val2,val3");
}
#[test]
fn opt_s_default_no_delim() {
let m = App::new("no_delim")
.arg(
Arg::new("option")
.short('o')
.setting(ArgSettings::TakesValue),
)
.try_get_matches_from(vec!["", "-o", "val1,val2,val3"]);
assert!(m.is_ok(), "{:?}", m.unwrap_err());
let m = m.unwrap();
assert!(m.is_present("option"));
assert_eq!(m.occurrences_of("option"), 1);
assert_eq!(m.value_of("option").unwrap(), "val1,val2,val3");
}
#[test]
fn opt_s_no_space_no_delim() {
let m = App::new("no_delim")
.arg(
Arg::new("option")
.short('o')
.setting(ArgSettings::TakesValue),
)
.try_get_matches_from(vec!["", "-o", "val1,val2,val3"]);
assert!(m.is_ok());
let m = m.unwrap();
assert!(m.is_present("option"));
assert_eq!(m.occurrences_of("option"), 1);
assert_eq!(m.value_of("option").unwrap(), "val1,val2,val3");
}
#[test]
fn opt_s_no_space_mult_no_delim() {
let m = App::new("no_delim")
.arg(
Arg::new("option")
.short('o')
.setting(ArgSettings::MultipleValues),
)
.try_get_matches_from(vec!["", "-o", "val1,val2,val3"]);
assert!(m.is_ok());
let m = m.unwrap();
assert!(m.is_present("option"));
assert_eq!(m.occurrences_of("option"), 1);
assert_eq!(m.value_of("option").unwrap(), "val1,val2,val3");
}
#[test]
fn opt_eq_mult_def_delim() {
let m = App::new("no_delim")
.arg(
Arg::new("option")
.long("opt")
.multiple(true)
.use_delimiter(true)
.setting(ArgSettings::TakesValue),
)
.try_get_matches_from(vec!["", "--opt=val1,val2,val3"]);
assert!(m.is_ok());
let m = m.unwrap();
assert!(m.is_present("option"));
assert_eq!(m.occurrences_of("option"), 1);
assert_eq!(
m.values_of("option").unwrap().collect::<Vec<_>>(),
&["val1", "val2", "val3"]
);
}
| 26.458647 | 70 | 0.526854 |
b91e39758a1f54917d7383b392ce3afa039ffb50
| 1,613 |
use smallvec::SmallVec;
use crate::attribute_info::AttributeInfo;
use crate::{constant_info::Utf8Constant, constant_pool::ConstantPoolIndexRaw};
#[derive(Clone, Debug)]
pub struct FieldInfo {
pub access_flags: FieldAccessFlags,
pub name_index: ConstantPoolIndexRaw<Utf8Constant>,
pub descriptor_index: ConstantPoolIndexRaw<Utf8Constant>,
pub attributes_count: u16,
pub attributes: SmallVec<[AttributeInfo; 2]>,
}
#[derive(Clone, Debug)]
pub struct FieldInfoOpt {
pub access_flags: FieldAccessFlags,
pub name_index: ConstantPoolIndexRaw<Utf8Constant>,
pub descriptor_index: ConstantPoolIndexRaw<Utf8Constant>,
pub attributes_count: u16
}
bitflags! {
pub struct FieldAccessFlags: u16 {
const PUBLIC = 0x0001; // Declared public; may be accessed from outside its package.
const PRIVATE = 0x0002; // Declared private; usable only within the defining class.
const PROTECTED = 0x0004; // Declared protected; may be accessed within subclasses.
const STATIC = 0x0008; // Declared static.
const FINAL = 0x0010; // Declared final; never directly assigned to after object construction.
const VOLATILE = 0x0040; // Declared volatile; cannot be cached.
const TRANSIENT = 0x0080; // Declared transient; not written or read by a persistent object manager.
const SYNTHETIC = 0x1000; // Declared synthetic; not present in the source code.
const ANNOTATION = 0x2000; // Declared as an annotation type.
const ENUM = 0x4000; // Declared as an element of an enum.
}
}
| 42.447368 | 110 | 0.707378 |
d73f93d619b099d304fc94bae41ff6ea916766e4
| 3,383 |
extern crate env_logger;
#[macro_use]
extern crate log;
extern crate rand;
extern crate rusqlite;
#[macro_use]
extern crate lordbornebot_core;
mod data;
use data::*;
use lordbornebot_core::{CommandData, Config, Message, Module, PrivateMessage};
use rand::random;
use rusqlite::Connection;
use std::boxed::Box;
#[no_mangle]
pub extern "C" fn _create_module(config: &Config) -> *mut Module {
Box::into_raw(Box::new(Gamble::new(
Connection::open(&config.database_path).unwrap(),
)))
}
pub struct Gamble {
connection: Connection,
}
impl Gamble {
pub fn new(connection: Connection) -> Gamble {
Gamble { connection }
}
fn gamble_command(&self, privmsg: &PrivateMessage, command: &CommandData) -> Option<Message> {
let args = &command.args;
if args.is_empty() {
return None;
}
let curr_points = match get_points(&self.connection, &privmsg.tags["user-id"]) {
Ok(points) => points,
Err(e) => {
warn!("{}", e);
return None;
}
};
let amount = if let Ok(amount) = args[0].parse::<i32>() {
amount
} else if args[0] == "all" {
curr_points
} else {
return None;
};
if amount <= 0 {
return Some(whisper!(
&privmsg.tags["display-name"],
"{}, please enter a positive amount of points.",
&privmsg.tags["display-name"]
));
}
if amount <= curr_points {
// Have to do it like this until custom message interpolation/templating system.
let (new_points, message) = if random::<f32>() > 0.5 {
let new_points = curr_points - amount;
(
new_points,
privmsg!(
&privmsg.channel,
"{} has lost and now has {} points. FeelsWeirdMan",
&privmsg.tags["display-name"],
new_points
),
)
} else {
let new_points = curr_points + amount;
(
new_points,
privmsg!(
&privmsg.channel,
"{} has won and now has {} points. PagChomp",
&privmsg.tags["display-name"],
new_points
),
)
};
match set_points(&self.connection, &privmsg.tags["user-id"], new_points) {
Ok(_) => Some(message),
Err(e) => {
warn!("{}", e);
None
}
}
} else {
Some(whisper!(
&privmsg.tags["display-name"],
"{}, you don't have enough points for this roulette.",
&privmsg.tags["display-name"]
))
}
}
}
impl Module for Gamble {
fn handle_message(&mut self, message: &Message) -> Option<Message> {
match message {
Message::Command(privmsg, command) => match command.name.as_ref() {
"gamble" | "roulette" => self.gamble_command(&privmsg, &command),
_ => None,
},
_ => None,
}
}
}
| 28.669492 | 98 | 0.468815 |
e8e76d7d54cb73bddf3b2f061b07435eab578628
| 119 |
pub use crate::objects::*;
pub use crate::api::*;
pub use crate::downloader::*;
pub use crate::dependency_resolver::*;
| 23.8 | 38 | 0.697479 |
21819cf817eec0dbd7d31a758657130216580dbd
| 42,304 |
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::convert::TryInto;
use std::ffi::{OsStr, OsString};
use std::fmt::Write;
use std::path::PathBuf;
use std::time::SystemTime;
use eyre::Context;
use os_str_bytes::OsStrBytes;
use tracing::warn;
use crate::core::effects::Effects;
use crate::core::eventlog::EventTransactionId;
use crate::core::formatting::{printable_styled_string, Pluralize};
use crate::git::{
check_out_commit, GitRunInfo, MaybeZeroOid, NonZeroOid, Repo, ResolvedReferenceInfo,
};
use super::plan::RebasePlan;
/// Given a list of rewritten OIDs, move the branches attached to those OIDs
/// from their old commits to their new commits. Invoke the
/// `reference-transaction` hook when done.
pub fn move_branches<'a>(
effects: &Effects,
git_run_info: &GitRunInfo,
repo: &'a Repo,
event_tx_id: EventTransactionId,
rewritten_oids_map: &'a HashMap<NonZeroOid, MaybeZeroOid>,
) -> eyre::Result<()> {
let branch_oid_to_names = repo.get_branch_oid_to_names()?;
// We may experience an error in the case of a branch move. Ideally, we
// would use `git2::Transaction::commit`, which stops the transaction at the
// first error, but we don't know which references we successfully committed
// in that case. Instead, we just do things non-atomically and record which
// ones succeeded. See https://github.com/libgit2/libgit2/issues/5918
let mut branch_moves: Vec<(NonZeroOid, MaybeZeroOid, &OsStr)> = Vec::new();
let mut branch_move_err: Option<eyre::Error> = None;
'outer: for (old_oid, names) in branch_oid_to_names.iter() {
let new_oid = match rewritten_oids_map.get(old_oid) {
Some(new_oid) => new_oid,
None => continue,
};
let mut names: Vec<_> = names.iter().collect();
// Sort for determinism in tests.
names.sort_unstable();
match new_oid {
MaybeZeroOid::NonZero(new_oid) => {
let new_commit = match repo.find_commit_or_fail(*new_oid).wrap_err_with(|| {
format!(
"Could not find newly-rewritten commit with old OID: {:?}, new OID: {:?}",
old_oid, new_oid,
)
}) {
Ok(commit) => commit,
Err(err) => {
branch_move_err = Some(err);
break 'outer;
}
};
for name in names {
if let Err(err) =
repo.create_reference(name, new_commit.get_oid(), true, "move branches")
{
branch_move_err = Some(err);
break 'outer;
}
branch_moves.push((*old_oid, MaybeZeroOid::NonZero(*new_oid), name));
}
}
MaybeZeroOid::Zero => {
for name in names {
match repo.find_reference(name) {
Ok(Some(mut reference)) => {
if let Err(err) = reference.delete() {
branch_move_err = Some(err);
break 'outer;
}
}
Ok(None) => {
warn!(?name, "Reference not found, not deleting")
}
Err(err) => {
branch_move_err = Some(err);
break 'outer;
}
};
branch_moves.push((*old_oid, MaybeZeroOid::Zero, name));
}
}
}
}
let branch_moves_stdin: Vec<u8> = branch_moves
.into_iter()
.flat_map(|(old_oid, new_oid, name)| {
let mut line = Vec::new();
line.extend(old_oid.to_string().as_bytes());
line.push(b' ');
line.extend(new_oid.to_string().as_bytes());
line.push(b' ');
line.extend(name.to_raw_bytes().iter());
line.push(b'\n');
line
})
.collect();
let branch_moves_stdin =
OsStrBytes::from_raw_bytes(branch_moves_stdin).wrap_err("Encoding branch moves stdin")?;
let branch_moves_stdin = OsString::from(branch_moves_stdin);
git_run_info.run_hook(
effects,
repo,
"reference-transaction",
event_tx_id,
&["committed"],
Some(branch_moves_stdin),
)?;
match branch_move_err {
Some(err) => Err(err),
None => Ok(()),
}
}
/// After a rebase, check out the appropriate new `HEAD`. This can be difficult
/// because the commit might have been rewritten, dropped, or have a branch
/// pointing to it which also needs to be checked out.
///
/// `skipped_head_updated_oid` is the caller's belief of what the new OID of
/// `HEAD` should be in the event that the original commit was skipped. If the
/// caller doesn't think that the previous `HEAD` commit was skipped, then they
/// should pass in `None`.
pub fn check_out_updated_head(
effects: &Effects,
git_run_info: &GitRunInfo,
repo: &Repo,
event_tx_id: EventTransactionId,
rewritten_oids: &HashMap<NonZeroOid, MaybeZeroOid>,
previous_head_info: &ResolvedReferenceInfo,
skipped_head_updated_oid: Option<NonZeroOid>,
) -> eyre::Result<isize> {
let checkout_target: ResolvedReferenceInfo = match previous_head_info {
ResolvedReferenceInfo {
oid: None,
reference_name: None,
} => {
// Head was unborn, so no need to check out a new branch.
ResolvedReferenceInfo {
oid: skipped_head_updated_oid,
reference_name: None,
}
}
ResolvedReferenceInfo {
oid: None,
reference_name: Some(reference_name),
} => {
// Head was unborn but a branch was checked out. Not sure if this
// can happen, but if so, just use that branch.
ResolvedReferenceInfo {
oid: None,
reference_name: Some(Cow::Borrowed(reference_name)),
}
}
ResolvedReferenceInfo {
oid: Some(previous_head_oid),
reference_name: None,
} => {
// No branch was checked out.
match rewritten_oids.get(previous_head_oid) {
Some(MaybeZeroOid::NonZero(oid)) => {
// This OID was rewritten, so check out the new version of the commit.
ResolvedReferenceInfo {
oid: Some(*oid),
reference_name: None,
}
}
Some(MaybeZeroOid::Zero) => {
// The commit was skipped. Get the new location for `HEAD`.
ResolvedReferenceInfo {
oid: skipped_head_updated_oid,
reference_name: None,
}
}
None => {
// This OID was not rewritten, so check it out again.
ResolvedReferenceInfo {
oid: Some(*previous_head_oid),
reference_name: None,
}
}
}
}
ResolvedReferenceInfo {
oid: Some(_),
reference_name: Some(reference_name),
} => {
// Find the reference at current time to see if it still exists.
match repo.find_reference(reference_name)? {
Some(reference) => {
// The branch moved, so we need to make sure that we are
// still checked out to it.
//
// * On-disk rebases will end with the branch pointing to
// the last rebase head, which may not be the `HEAD` commit
// before the rebase.
//
// * In-memory rebases will detach `HEAD` before proceeding,
// so we need to reattach it if necessary.
let oid = repo.resolve_reference(&reference)?.oid;
ResolvedReferenceInfo {
oid,
reference_name: Some(Cow::Borrowed(reference_name)),
}
}
None => {
// The branch was deleted because it pointed to a skipped
// commit. Get the new location for `HEAD`.
ResolvedReferenceInfo {
oid: skipped_head_updated_oid,
reference_name: None,
}
}
}
}
};
let head_info = repo.get_head_info()?;
if head_info == checkout_target {
return Ok(0);
}
let checkout_target: Cow<OsStr> = match &checkout_target {
ResolvedReferenceInfo {
oid: None,
reference_name: None,
} => return Ok(0),
ResolvedReferenceInfo {
oid: Some(oid),
reference_name: None,
} => Cow::Owned(OsString::from(oid.to_string())),
ResolvedReferenceInfo {
oid: _,
reference_name: Some(reference_name),
} => {
// FIXME: we could check to see if the OIDs are the same and, if so,
// reattach or detach `HEAD` manually without having to call `git checkout`.
match checkout_target.get_branch_name()? {
Some(branch_name) => Cow::Owned(branch_name),
None => Cow::Borrowed(reference_name),
}
}
};
let result = check_out_commit(
effects,
git_run_info,
Some(event_tx_id),
Some(&checkout_target),
&[] as &[&OsStr],
)?;
Ok(result)
}
/// Information about a merge conflict that occurred while moving commits.
pub struct MergeConflictInfo {
/// The OID of the commit that, when moved, caused a conflict.
pub commit_oid: NonZeroOid,
/// The paths which were in conflict.
pub conflicting_paths: HashSet<PathBuf>,
}
impl MergeConflictInfo {
/// Describe the merge conflict in a user-friendly way and advise to rerun
/// with `--merge`.
pub fn describe(&self, effects: &Effects, repo: &Repo) -> eyre::Result<()> {
writeln!(
effects.get_output_stream(),
"This operation would cause a merge conflict:"
)?;
writeln!(
effects.get_output_stream(),
"{} ({}) {}",
effects.get_glyphs().bullet_point,
Pluralize {
amount: self.conflicting_paths.len().try_into()?,
singular: "conflicting file",
plural: "conflicting files"
}
.to_string(),
printable_styled_string(
effects.get_glyphs(),
repo.friendly_describe_commit_from_oid(self.commit_oid)?
)?
)?;
writeln!(
effects.get_output_stream(),
"To resolve merge conflicts, retry this operation with the --merge option."
)?;
Ok(())
}
}
mod in_memory {
use std::collections::HashMap;
use std::ffi::OsString;
use std::fmt::Write;
use eyre::Context;
use indicatif::{ProgressBar, ProgressStyle};
use tracing::{instrument, warn};
use crate::commands::gc::mark_commit_reachable;
use crate::core::effects::Effects;
use crate::core::formatting::printable_styled_string;
use crate::core::rewrite::execute::check_out_updated_head;
use crate::core::rewrite::move_branches;
use crate::core::rewrite::plan::{OidOrLabel, RebaseCommand, RebasePlan};
use crate::git::{
CherryPickFastError, CherryPickFastOptions, GitRunInfo, MaybeZeroOid, NonZeroOid, Repo,
};
use super::{ExecuteRebasePlanOptions, MergeConflictInfo};
pub enum RebaseInMemoryResult {
Succeeded {
rewritten_oids: Vec<(NonZeroOid, MaybeZeroOid)>,
/// The new OID that `HEAD` should point to, based on the rebase.
///
/// - This is only `None` if `HEAD` was unborn.
/// - This doesn't capture if `HEAD` was pointing to a branch. The
/// caller will need to figure that out.
new_head_oid: Option<NonZeroOid>,
},
CannotRebaseMergeCommit {
commit_oid: NonZeroOid,
},
MergeConflict(MergeConflictInfo),
}
#[instrument]
pub fn rebase_in_memory(
effects: &Effects,
repo: &Repo,
rebase_plan: &RebasePlan,
options: &ExecuteRebasePlanOptions,
) -> eyre::Result<RebaseInMemoryResult> {
if let Some(merge_commit_oid) =
rebase_plan
.commands
.iter()
.find_map(|command| match command {
RebaseCommand::Merge {
commit_oid,
commits_to_merge: _,
} => Some(commit_oid),
RebaseCommand::CreateLabel { .. }
| RebaseCommand::Reset { .. }
| RebaseCommand::Pick { .. }
| RebaseCommand::RegisterExtraPostRewriteHook
| RebaseCommand::DetectEmptyCommit { .. }
| RebaseCommand::SkipUpstreamAppliedCommit { .. } => None,
})
{
return Ok(RebaseInMemoryResult::CannotRebaseMergeCommit {
commit_oid: *merge_commit_oid,
});
}
let ExecuteRebasePlanOptions {
now,
// Transaction ID will be passed to the `post-rewrite` hook via
// environment variable.
event_tx_id: _,
preserve_timestamps,
force_in_memory: _,
force_on_disk: _,
resolve_merge_conflicts: _, // May be needed once we can resolve merge conflicts in memory.
} = options;
let mut current_oid = rebase_plan.first_dest_oid;
let mut labels: HashMap<String, NonZeroOid> = HashMap::new();
let mut rewritten_oids: Vec<(NonZeroOid, MaybeZeroOid)> = Vec::new();
// Normally, we can determine the new `HEAD` OID by looking at the
// rewritten commits. However, if `HEAD` pointed to a commit that was
// skipped, then the rewritten OID is zero. In that case, we need to
// delete the branch (responsibility of the caller) and choose a
// different `HEAD` OID.
let head_oid = repo.get_head_info()?.oid;
let mut skipped_head_new_oid = None;
let mut maybe_set_skipped_head_new_oid = |skipped_head_oid, current_oid| {
if Some(skipped_head_oid) == head_oid {
skipped_head_new_oid.get_or_insert(current_oid);
}
};
let mut i = 0;
let num_picks = rebase_plan
.commands
.iter()
.filter(|command| match command {
RebaseCommand::CreateLabel { .. }
| RebaseCommand::Reset { .. }
| RebaseCommand::RegisterExtraPostRewriteHook
| RebaseCommand::DetectEmptyCommit { .. } => false,
RebaseCommand::Pick { .. }
| RebaseCommand::Merge { .. }
| RebaseCommand::SkipUpstreamAppliedCommit { .. } => true,
})
.count();
for command in rebase_plan.commands.iter() {
match command {
RebaseCommand::CreateLabel { label_name } => {
labels.insert(label_name.clone(), current_oid);
}
RebaseCommand::Reset {
target: OidOrLabel::Label(label_name),
} => {
current_oid = match labels.get(label_name) {
Some(oid) => *oid,
None => eyre::bail!("BUG: no associated OID for label: {}", label_name),
};
}
RebaseCommand::Reset {
target: OidOrLabel::Oid(commit_oid),
} => {
current_oid = *commit_oid;
}
RebaseCommand::Pick { commit_oid } => {
let current_commit = repo
.find_commit_or_fail(current_oid)
.wrap_err("Finding current commit")?;
let commit_to_apply = repo
.find_commit_or_fail(*commit_oid)
.wrap_err("Finding commit to apply")?;
i += 1;
let commit_description = printable_styled_string(
effects.get_glyphs(),
commit_to_apply.friendly_describe()?,
)?;
let commit_num = format!("[{}/{}]", i, num_picks);
let progress_template = format!("{} {{spinner}} {{wide_msg}}", commit_num);
let progress = ProgressBar::new_spinner();
progress.set_style(
ProgressStyle::default_spinner().template(progress_template.trim()),
);
progress.set_message("Starting");
progress.enable_steady_tick(100);
if commit_to_apply.get_parent_count() > 1 {
warn!(
?commit_oid,
"BUG: Merge commit should have been detected during planning phase"
);
return Ok(RebaseInMemoryResult::CannotRebaseMergeCommit {
commit_oid: *commit_oid,
});
};
progress
.set_message(format!("Applying patch for commit: {}", commit_description));
let commit_tree = match repo.cherry_pick_fast(
&commit_to_apply,
¤t_commit,
&CherryPickFastOptions {
reuse_parent_tree_if_possible: true,
},
)? {
Ok(rebased_commit) => rebased_commit,
Err(CherryPickFastError::MergeConflict { conflicting_paths }) => {
return Ok(RebaseInMemoryResult::MergeConflict(MergeConflictInfo {
commit_oid: *commit_oid,
conflicting_paths,
}))
}
};
let commit_message = commit_to_apply.get_message_raw()?;
let commit_message = commit_message.to_str().ok_or_else(|| {
eyre::eyre!(
"Could not decode commit message for commit: {:?}",
commit_oid
)
})?;
progress
.set_message(format!("Committing to repository: {}", commit_description));
let committer_signature = if *preserve_timestamps {
commit_to_apply.get_committer()
} else {
commit_to_apply.get_committer().update_timestamp(*now)?
};
let rebased_commit_oid = repo
.create_commit(
None,
&commit_to_apply.get_author(),
&committer_signature,
commit_message,
&commit_tree,
vec![¤t_commit],
)
.wrap_err("Applying rebased commit")?;
let rebased_commit = repo
.find_commit_or_fail(rebased_commit_oid)
.wrap_err("Looking up just-rebased commit")?;
let commit_description = printable_styled_string(
effects.get_glyphs(),
repo.friendly_describe_commit_from_oid(rebased_commit_oid)?,
)?;
if rebased_commit.is_empty() {
rewritten_oids.push((*commit_oid, MaybeZeroOid::Zero));
maybe_set_skipped_head_new_oid(*commit_oid, current_oid);
progress.finish_and_clear();
writeln!(
effects.get_output_stream(),
"[{}/{}] Skipped now-empty commit: {}",
i,
num_picks,
commit_description
)?;
} else {
rewritten_oids
.push((*commit_oid, MaybeZeroOid::NonZero(rebased_commit_oid)));
current_oid = rebased_commit_oid;
progress.finish_and_clear();
writeln!(
effects.get_output_stream(),
"{} Committed as: {}",
commit_num,
commit_description
)?;
}
}
RebaseCommand::Merge {
commit_oid,
commits_to_merge: _,
} => {
warn!(
?commit_oid,
"BUG: Merge commit should have been detected when starting in-memory rebase"
);
return Ok(RebaseInMemoryResult::CannotRebaseMergeCommit {
commit_oid: *commit_oid,
});
}
RebaseCommand::SkipUpstreamAppliedCommit { commit_oid } => {
let progress = ProgressBar::new_spinner();
i += 1;
let commit_num = format!("[{}/{}]", i, num_picks);
let progress_template = format!("{} {{spinner}} {{wide_msg}}", commit_num);
progress.set_style(
ProgressStyle::default_spinner().template(progress_template.trim()),
);
let commit = repo.find_commit_or_fail(*commit_oid)?;
rewritten_oids.push((*commit_oid, MaybeZeroOid::Zero));
maybe_set_skipped_head_new_oid(*commit_oid, current_oid);
progress.finish_and_clear();
let commit_description = commit.friendly_describe()?;
let commit_description =
printable_styled_string(effects.get_glyphs(), commit_description)?;
writeln!(
effects.get_output_stream(),
"{} Skipped commit (was already applied upstream): {}",
commit_num,
commit_description
)?;
}
RebaseCommand::RegisterExtraPostRewriteHook
| RebaseCommand::DetectEmptyCommit { .. } => {
// Do nothing. We'll carry out post-rebase operations after the
// in-memory rebase completes.
}
}
}
let new_head_oid: Option<NonZeroOid> = match head_oid {
None => {
// `HEAD` is unborn, so keep it that way.
None
}
Some(head_oid) => {
let new_head_oid = rewritten_oids.iter().find_map(|(source_oid, dest_oid)| {
if *source_oid == head_oid {
Some(*dest_oid)
} else {
None
}
});
match new_head_oid {
Some(MaybeZeroOid::NonZero(new_head_oid)) => {
// `HEAD` was rewritten to this OID.
Some(new_head_oid)
}
Some(MaybeZeroOid::Zero) => {
// `HEAD` was rewritten, but its associated commit was
// skipped. Use whatever saved new `HEAD` OID we have.
let new_head_oid = match skipped_head_new_oid {
Some(new_head_oid) => new_head_oid,
None => {
warn!(
?head_oid,
"`HEAD` OID was rewritten to 0, but no skipped `HEAD` OID was set",
);
head_oid
}
};
Some(new_head_oid)
}
None => {
// The `HEAD` OID was not rewritten, so use its current value.
Some(head_oid)
}
}
}
};
Ok(RebaseInMemoryResult::Succeeded {
rewritten_oids,
new_head_oid,
})
}
pub fn post_rebase_in_memory(
effects: &Effects,
git_run_info: &GitRunInfo,
repo: &Repo,
rewritten_oids: &[(NonZeroOid, MaybeZeroOid)],
skipped_head_updated_oid: Option<NonZeroOid>,
options: &ExecuteRebasePlanOptions,
) -> eyre::Result<isize> {
let ExecuteRebasePlanOptions {
now: _,
event_tx_id,
preserve_timestamps: _,
force_in_memory: _,
force_on_disk: _,
resolve_merge_conflicts: _,
} = options;
// Note that if an OID has been mapped to multiple other OIDs, then the last
// mapping wins. (This corresponds to the last applied rebase operation.)
let rewritten_oids_map: HashMap<NonZeroOid, MaybeZeroOid> =
rewritten_oids.iter().copied().collect();
for new_oid in rewritten_oids_map.values() {
if let MaybeZeroOid::NonZero(new_oid) = new_oid {
mark_commit_reachable(repo, *new_oid)?;
}
}
let head_info = repo.get_head_info()?;
if head_info.oid.is_some() {
// Avoid moving the branch which HEAD points to, or else the index will show
// a lot of changes in the working copy.
repo.detach_head(&head_info)?;
}
move_branches(
effects,
git_run_info,
repo,
*event_tx_id,
&rewritten_oids_map,
)?;
// Call the `post-rewrite` hook only after moving branches so that we don't
// produce a spurious abandoned-branch warning.
let post_rewrite_stdin: String = rewritten_oids
.iter()
.map(|(old_oid, new_oid)| format!("{} {}\n", old_oid, new_oid))
.collect();
let post_rewrite_stdin = OsString::from(post_rewrite_stdin);
git_run_info.run_hook(
effects,
repo,
"post-rewrite",
*event_tx_id,
&["rebase"],
Some(post_rewrite_stdin),
)?;
let exit_code = check_out_updated_head(
effects,
git_run_info,
repo,
*event_tx_id,
&rewritten_oids_map,
&head_info,
skipped_head_updated_oid,
)?;
Ok(exit_code)
}
}
mod on_disk {
use std::ffi::OsStr;
use std::fmt::Write;
use eyre::Context;
use os_str_bytes::OsStrBytes;
use tracing::instrument;
use crate::core::effects::{Effects, OperationType};
use crate::core::rewrite::plan::RebasePlan;
use crate::core::rewrite::rewrite_hooks::save_original_head_info;
use crate::git::{GitRunInfo, Repo};
use super::ExecuteRebasePlanOptions;
pub enum Error {
ChangedFilesInRepository,
OperationAlreadyInProgress { operation_type: String },
}
fn write_rebase_state_to_disk(
effects: &Effects,
git_run_info: &GitRunInfo,
repo: &Repo,
rebase_plan: &RebasePlan,
options: &ExecuteRebasePlanOptions,
) -> eyre::Result<Result<(), Error>> {
let ExecuteRebasePlanOptions {
now: _,
event_tx_id: _,
preserve_timestamps,
force_in_memory: _,
force_on_disk: _,
resolve_merge_conflicts: _,
} = options;
let (effects, _progress) = effects.start_operation(OperationType::InitializeRebase);
let head_info = repo.get_head_info()?;
let current_operation_type = repo.get_current_operation_type();
if let Some(current_operation_type) = current_operation_type {
return Ok(Err(Error::OperationAlreadyInProgress {
operation_type: current_operation_type.to_string(),
}));
}
if repo.has_changed_files(&effects, git_run_info)? {
return Ok(Err(Error::ChangedFilesInRepository));
}
let rebase_state_dir = repo.get_rebase_state_dir_path();
std::fs::create_dir_all(&rebase_state_dir).wrap_err_with(|| {
format!(
"Creating rebase state directory at: {:?}",
&rebase_state_dir
)
})?;
// Mark this rebase as an interactive rebase. For whatever reason, if this
// is not marked as an interactive rebase, then some rebase plans fail with
// this error:
//
// ```
// BUG: builtin/rebase.c:1178: Unhandled rebase type 1
// ```
let interactive_file_path = rebase_state_dir.join("interactive");
std::fs::write(&interactive_file_path, "")
.wrap_err_with(|| format!("Writing interactive to: {:?}", &interactive_file_path))?;
if let Some(head_oid) = head_info.oid {
let orig_head_file_path = repo.get_path().join("ORIG_HEAD");
std::fs::write(&orig_head_file_path, head_oid.to_string())
.wrap_err_with(|| format!("Writing `ORIG_HEAD` to: {:?}", &orig_head_file_path))?;
// Confusingly, there is also a file at
// `.git/rebase-merge/orig-head` (different from `.git/ORIG_HEAD`),
// which seems to store the same thing.
let rebase_orig_head_file_path = rebase_state_dir.join("orig-head");
std::fs::write(&rebase_orig_head_file_path, head_oid.to_string()).wrap_err_with(
|| format!("Writing `orig-head` to: {:?}", &rebase_orig_head_file_path),
)?;
// `head-name` contains the name of the branch which will be reset
// to point to the OID contained in `orig-head` when the rebase is
// aborted.
let head_name_file_path = rebase_state_dir.join("head-name");
std::fs::write(
&head_name_file_path,
head_info
.reference_name
.as_deref()
.unwrap_or_else(|| OsStr::new("detached HEAD"))
.to_raw_bytes(),
)
.wrap_err_with(|| format!("Writing head-name to: {:?}", &head_name_file_path))?;
save_original_head_info(repo, &head_info)?;
// Dummy `head` file. We will `reset` to the appropriate commit as soon as
// we start the rebase.
let rebase_merge_head_file_path = rebase_state_dir.join("head");
std::fs::write(
&rebase_merge_head_file_path,
rebase_plan.first_dest_oid.to_string(),
)
.wrap_err_with(|| format!("Writing head to: {:?}", &rebase_merge_head_file_path))?;
}
// Dummy `onto` file. We may be rebasing onto a set of unrelated
// nodes in the same operation, so there may not be a single "onto" node to
// refer to.
let onto_file_path = rebase_state_dir.join("onto");
std::fs::write(&onto_file_path, rebase_plan.first_dest_oid.to_string()).wrap_err_with(
|| {
format!(
"Writing onto {:?} to: {:?}",
&rebase_plan.first_dest_oid, &onto_file_path
)
},
)?;
let todo_file_path = rebase_state_dir.join("git-rebase-todo");
std::fs::write(
&todo_file_path,
rebase_plan
.commands
.iter()
.map(|command| format!("{}\n", command.to_string()))
.collect::<String>(),
)
.wrap_err_with(|| {
format!(
"Writing `git-rebase-todo` to: {:?}",
todo_file_path.as_path()
)
})?;
let end_file_path = rebase_state_dir.join("end");
std::fs::write(
end_file_path.as_path(),
format!("{}\n", rebase_plan.commands.len()),
)
.wrap_err_with(|| format!("Writing `end` to: {:?}", end_file_path.as_path()))?;
// Corresponds to the `--empty=keep` flag. We'll drop the commits later once
// we find out that they're empty.
let keep_redundant_commits_file_path = rebase_state_dir.join("keep_redundant_commits");
std::fs::write(&keep_redundant_commits_file_path, "").wrap_err_with(|| {
format!(
"Writing `keep_redundant_commits` to: {:?}",
&keep_redundant_commits_file_path
)
})?;
if *preserve_timestamps {
let cdate_is_adate_file_path = rebase_state_dir.join("cdate_is_adate");
std::fs::write(&cdate_is_adate_file_path, "").wrap_err_with(|| {
format!(
"Writing `cdate_is_adate` option file to: {:?}",
&cdate_is_adate_file_path
)
})?;
}
// Make sure we don't move around the current branch unintentionally. If it
// actually needs to be moved, then it will be moved as part of the
// post-rebase operations.
if head_info.oid.is_some() {
repo.detach_head(&head_info)?;
}
Ok(Ok(()))
}
/// Rebase on-disk. We don't use `git2`'s `Rebase` machinery because it ends up
/// being too slow.
///
/// Note that this calls `git rebase`, which may fail (e.g. if there are
/// merge conflicts). The exit code is then propagated to the caller.
#[instrument]
pub fn rebase_on_disk(
effects: &Effects,
git_run_info: &GitRunInfo,
repo: &Repo,
rebase_plan: &RebasePlan,
options: &ExecuteRebasePlanOptions,
) -> eyre::Result<Result<isize, Error>> {
let ExecuteRebasePlanOptions {
// `git rebase` will make its own timestamp.
now: _,
event_tx_id,
preserve_timestamps: _,
force_in_memory: _,
force_on_disk: _,
resolve_merge_conflicts: _,
} = options;
match write_rebase_state_to_disk(effects, git_run_info, repo, rebase_plan, options)? {
Ok(()) => {}
Err(err) => return Ok(Err(err)),
};
writeln!(
effects.get_output_stream(),
"Calling Git for on-disk rebase..."
)?;
let exit_code = git_run_info.run(effects, Some(*event_tx_id), &["rebase", "--continue"])?;
Ok(Ok(exit_code))
}
}
/// Options to use when executing a `RebasePlan`.
#[derive(Clone, Debug)]
pub struct ExecuteRebasePlanOptions {
/// The time which should be recorded for this event.
pub now: SystemTime,
/// The transaction ID for this event.
pub event_tx_id: EventTransactionId,
/// If `true`, any rewritten commits will keep the same authored and
/// committed timestamps. If `false`, the committed timestamps will be updated
/// to the current time.
pub preserve_timestamps: bool,
/// Force an in-memory rebase (as opposed to an on-disk rebase).
pub force_in_memory: bool,
/// Force an on-disk rebase (as opposed to an in-memory rebase).
pub force_on_disk: bool,
/// Whether or not an attempt should be made to resolve merge conflicts,
/// rather than failing-fast.
pub resolve_merge_conflicts: bool,
}
/// The result of executing a rebase plan.
#[must_use]
pub enum ExecuteRebasePlanResult {
/// The rebase operation succeeded.
Succeeded,
/// The rebase operation encounter a merge conflict, and it was not
/// requested to try to resolve it.
DeclinedToMerge {
/// Information about the merge conflict that occurred.
merge_conflict: MergeConflictInfo,
},
/// The rebase operation failed.
Failed {
/// The exit code to exit with. (This value may have been obtained from
/// a subcommand invocation.)
exit_code: isize,
},
}
/// Execute the provided rebase plan. Returns the exit status (zero indicates
/// success).
pub fn execute_rebase_plan(
effects: &Effects,
git_run_info: &GitRunInfo,
repo: &Repo,
rebase_plan: &RebasePlan,
options: &ExecuteRebasePlanOptions,
) -> eyre::Result<ExecuteRebasePlanResult> {
let ExecuteRebasePlanOptions {
now: _,
event_tx_id: _,
preserve_timestamps: _,
force_in_memory,
force_on_disk,
resolve_merge_conflicts,
} = options;
if !force_on_disk {
use in_memory::*;
writeln!(
effects.get_output_stream(),
"Attempting rebase in-memory..."
)?;
match rebase_in_memory(effects, repo, rebase_plan, options)? {
RebaseInMemoryResult::Succeeded {
rewritten_oids,
new_head_oid,
} => {
post_rebase_in_memory(
effects,
git_run_info,
repo,
&rewritten_oids,
new_head_oid,
options,
)?;
writeln!(effects.get_output_stream(), "In-memory rebase succeeded.")?;
return Ok(ExecuteRebasePlanResult::Succeeded);
}
RebaseInMemoryResult::CannotRebaseMergeCommit { commit_oid } => {
writeln!(
effects.get_output_stream(),
"Merge commits currently can't be rebased in-memory."
)?;
writeln!(
effects.get_output_stream(),
"The merge commit was: {}",
printable_styled_string(
effects.get_glyphs(),
repo.friendly_describe_commit_from_oid(commit_oid)?
)?,
)?;
}
RebaseInMemoryResult::MergeConflict(merge_conflict) => {
if !resolve_merge_conflicts
// If an in-memory rebase was forced, don't suggest to the user
// that they can re-run with `--merge`, since that still won't
// work.
&& !*force_in_memory
{
return Ok(ExecuteRebasePlanResult::DeclinedToMerge { merge_conflict });
}
let MergeConflictInfo {
commit_oid,
conflicting_paths: _,
} = merge_conflict;
writeln!(
effects.get_output_stream(),
"There was a merge conflict, which currently can't be resolved when rebasing in-memory."
)?;
writeln!(
effects.get_output_stream(),
"The conflicting commit was: {}",
printable_styled_string(
effects.get_glyphs(),
repo.friendly_describe_commit_from_oid(commit_oid)?
)?,
)?;
}
}
// The rebase has failed at this point, decide whether or not to try
// again with an on-disk rebase.
if *force_in_memory {
writeln!(
effects.get_output_stream(),
"Aborting since an in-memory rebase was requested."
)?;
return Ok(ExecuteRebasePlanResult::Failed { exit_code: 1 });
} else {
writeln!(effects.get_output_stream(), "Trying again on-disk...")?;
}
}
if !force_in_memory {
use on_disk::*;
match rebase_on_disk(effects, git_run_info, repo, rebase_plan, options)? {
Ok(0) => return Ok(ExecuteRebasePlanResult::Succeeded),
Ok(exit_code) => return Ok(ExecuteRebasePlanResult::Failed { exit_code }),
Err(Error::ChangedFilesInRepository) => {
write!(
effects.get_output_stream(),
"\
This operation would modify the working copy, but you have uncommitted changes
in your working copy which might be overwritten as a result.
Commit your changes and then try again.
"
)?;
return Ok(ExecuteRebasePlanResult::Failed { exit_code: 1 });
}
Err(Error::OperationAlreadyInProgress { operation_type }) => {
writeln!(
effects.get_output_stream(),
"A {} operation is already in progress.",
operation_type
)?;
writeln!(
effects.get_output_stream(),
"Run git {0} --continue or git {0} --abort to resolve it and proceed.",
operation_type
)?;
return Ok(ExecuteRebasePlanResult::Failed { exit_code: 1 });
}
}
}
eyre::bail!("Both force_in_memory and force_on_disk were requested, but these options conflict")
}
| 38.146078 | 108 | 0.516854 |
eda31ab6d42ae2c03233fcf9640697391d0bcca5
| 656 |
use std::collections::HashSet;
#[derive(PartialEq, Debug, Clone)]
pub struct Redraw {
pub entries: bool,
pub peak_volume: Option<usize>,
pub resize: bool,
pub affected_entries: HashSet<usize>,
pub context_menu: bool,
}
impl Default for Redraw {
fn default() -> Self {
Self {
entries: false,
peak_volume: None,
resize: false,
affected_entries: HashSet::new(),
context_menu: false,
}
}
}
impl Redraw {
pub fn reset(&mut self) {
*self = Redraw::default();
}
pub fn anything(&self) -> bool {
self.entries
|| self.peak_volume.is_some()
|| self.resize
|| self.context_menu
|| !self.affected_entries.is_empty()
}
}
| 18.742857 | 39 | 0.664634 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.