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
|
---|---|---|---|---|---|
dd2d8ed5419683882aefae41e4b410e9f47d07a4 | 2,102 | //! Program state processor
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint::ProgramResult,
pubkey::Pubkey,
rent::Rent,
sysvar::Sysvar,
};
use spl_governance_tools::account::create_and_serialize_account_signed;
/// Processes Approve instruction
pub fn process_approve_kicker_coin(program_id: &Pubkey, accounts: &[AccountInfo],coordinator_input: String,) -> ProgramResult {
unimplemented!();
// this function make coordinator to input some text message to first kicker
// that text make rater and init content holder to create RFT for rating other
// this minting can only when first kicker and coordinator stay in same tanistry
// At this point, we need to create a zero version of CandidateLimitRecord to prepare for the candidate
// The program to create the mpc is in this record
let account_info_iter = &mut accounts.iter();
let kicker_info = next_account_info(account_info_iter)?; // 0
let coordinator_info = next_account_info(account_info_iter)?; // 1
let tanistry_info = next_account_info(account_info_iter)?; // 2
let coordinator_input_info = next_account_info(account_info_iter)?; // 3
let kicker_token_source_info = next_account_info(account_info_iter)?; // 4
let tanistry_authority_info = next_account_info(account_info_iter)?; // 5
let coordinator_receive_token_info = next_account_info(account_info_iter)?; // 6
let kicker_coin_owner_record_info = next_account_info(account_info_iter)?; // 7
let kicker_receive_token_info = next_account_info(account_info_iter)?; // 8
let candidate_token_holding_info = next_account_info(account_info_iter)?; // 8
let system_info = next_account_info(account_info_iter)?; // 10
let rent_sysvar_info = next_account_info(account_info_iter)?; // 11
let rent = &Rent::from_account_info(rent_sysvar_info)?;
let clock_info = next_account_info(account_info_iter)?; // 12
let clock = Clock::from_account_info(clock_info)?;
assert_can_approve_kicker_coin();
assert_valid_coordinator_input_on_kicker_coin();
}
| 46.711111 | 127 | 0.76118 |
1146e139be0ae99e2f699f43a32f3734402e9ada | 5,937 | // lineChart
use super::Grouping;
use super::VaryColors;
use super::AreaChartSeries;
use super::DataLabels;
use super::ShowMarker;
use super::Smooth;
use super::AxisId;
use writer::driver::*;
use quick_xml::Reader;
use quick_xml::events::{Event, BytesStart};
use quick_xml::Writer;
use std::io::Cursor;
#[derive(Default, Debug)]
pub struct LineChart {
grouping: Grouping,
vary_colors: VaryColors,
area_chart_series: Vec<AreaChartSeries>,
data_labels: DataLabels,
show_marker: ShowMarker,
smooth: Smooth,
axis_id: Vec<AxisId>,
}
impl LineChart {
pub fn get_grouping(&self)-> &Grouping {
&self.grouping
}
pub fn get_grouping_mut(&mut self)-> &mut Grouping {
&mut self.grouping
}
pub fn set_grouping(&mut self, value:Grouping)-> &mut LineChart {
self.grouping = value;
self
}
pub fn get_vary_colors(&self)-> &VaryColors {
&self.vary_colors
}
pub fn get_vary_colors_mut(&mut self)-> &mut VaryColors {
&mut self.vary_colors
}
pub fn set_vary_colors(&mut self, value:VaryColors)-> &mut LineChart {
self.vary_colors = value;
self
}
pub fn get_area_chart_series(&self)-> &Vec<AreaChartSeries> {
&self.area_chart_series
}
pub fn get_area_chart_series_mut(&mut self)-> &mut Vec<AreaChartSeries> {
&mut self.area_chart_series
}
pub fn set_area_chart_series(&mut self, value:Vec<AreaChartSeries>)-> &mut LineChart {
self.area_chart_series = value;
self
}
pub fn add_area_chart_series(&mut self, value:AreaChartSeries)-> &mut LineChart {
self.area_chart_series.push(value);
self
}
pub fn get_data_labels(&self)-> &DataLabels {
&self.data_labels
}
pub fn get_data_labels_mut(&mut self)-> &mut DataLabels {
&mut self.data_labels
}
pub fn set_data_labels(&mut self, value:DataLabels)-> &mut LineChart {
self.data_labels = value;
self
}
pub fn get_show_marker(&self)-> &ShowMarker {
&self.show_marker
}
pub fn get_show_marker_mut(&mut self)-> &mut ShowMarker {
&mut self.show_marker
}
pub fn set_show_marker(&mut self, value:ShowMarker)-> &mut LineChart {
self.show_marker = value;
self
}
pub fn get_smooth(&self)-> &Smooth {
&self.smooth
}
pub fn get_smooth_mut(&mut self)-> &mut Smooth {
&mut self.smooth
}
pub fn set_smooth(&mut self, value:Smooth)-> &mut LineChart {
self.smooth = value;
self
}
pub fn get_axis_id(&self)-> &Vec<AxisId> {
&self.axis_id
}
pub fn get_axis_id_mut(&mut self)-> &mut Vec<AxisId> {
&mut self.axis_id
}
pub fn set_axis_id(&mut self, value:Vec<AxisId>)-> &mut LineChart {
self.axis_id = value;
self
}
pub fn add_axis_id(&mut self, value:AxisId)-> &mut LineChart {
self.axis_id.push(value);
self
}
pub(crate) fn set_attributes<R: std::io::BufRead>(
&mut self,
reader:&mut Reader<R>,
_e:&BytesStart
) {
let mut buf = Vec::new();
loop {
match reader.read_event(&mut buf) {
Ok(Event::Start(ref e)) => {
match e.name() {
b"c:ser" => {
let mut obj = AreaChartSeries::default();
obj.set_attributes(reader, e);
self.add_area_chart_series(obj);
},
b"c:dLbls" => {
self.data_labels.set_attributes(reader, e);
},
_ => (),
}
},
Ok(Event::Empty(ref e)) => {
match e.name() {
b"c:grouping" => {
self.grouping.set_attributes(reader, e);
},
b"c:varyColors" => {
self.vary_colors.set_attributes(reader, e);
},
b"c:marker" => {
self.show_marker.set_attributes(reader, e);
},
b"c:smooth" => {
self.smooth.set_attributes(reader, e);
},
b"c:axId" => {
let mut obj = AxisId::default();
obj.set_attributes(reader, e);
self.add_axis_id(obj);
},
_ => (),
}
},
Ok(Event::End(ref e)) => {
match e.name() {
b"c:lineChart" => return,
_ => (),
}
},
Ok(Event::Eof) => panic!("Error not find {} end element", "c:lineChart"),
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (),
}
buf.clear();
}
}
pub(crate) fn write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>) {
// c:lineChart
write_start_tag(writer, "c:lineChart", vec![], false);
// c:grouping
&self.grouping.write_to(writer);
// c:varyColors
&self.vary_colors.write_to(writer);
// c:ser
for v in &self.area_chart_series {
v.write_to(writer);
}
// c:dLbls
&self.data_labels.write_to(writer);
// c:marker
&self.show_marker.write_to(writer);
// c:smooth
&self.smooth.write_to(writer);
// c:axId
for v in &self.axis_id {
v.write_to(writer);
}
write_end_tag(writer, "c:lineChart");
}
}
| 27.486111 | 92 | 0.497726 |
90581e0084a769dd79e73201410f565ff33625e2 | 12,284 | use expression::{Expression, AsExpression};
use super::operators::*;
use types::{Array, Text};
pub trait PgExpressionMethods: Expression + Sized {
/// Creates a PostgreSQL `IS NOT DISTINCT FROM` expression. This behaves
/// identically to the `=` operator, except that `NULL` is treated as a
/// normal value.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// # users {
/// # id -> Integer,
/// # name -> VarChar,
/// # }
/// # }
/// #
/// # fn main() {
/// # use self::users::dsl::*;
/// # let connection = establish_connection();
/// let distinct = users.select(id).filter(name.is_distinct_from("Sean"));
/// let not_distinct = users.select(id).filter(name.is_not_distinct_from("Sean"));
/// assert_eq!(Ok(2), distinct.first(&connection));
/// assert_eq!(Ok(1), not_distinct.first(&connection));
/// # }
/// ```
fn is_not_distinct_from<T>(self, other: T)
-> IsNotDistinctFrom<Self, T::Expression> where
T: AsExpression<Self::SqlType>,
{
IsNotDistinctFrom::new(self, other.as_expression())
}
/// Creates a PostgreSQL `IS DISTINCT FROM` expression. This behaves
/// identically to the `!=` operator, except that `NULL` is treated as a
/// normal value.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// # users {
/// # id -> Integer,
/// # name -> VarChar,
/// # }
/// # }
/// #
/// # fn main() {
/// # use self::users::dsl::*;
/// # let connection = establish_connection();
/// let distinct = users.select(id).filter(name.is_distinct_from("Sean"));
/// let not_distinct = users.select(id).filter(name.is_not_distinct_from("Sean"));
/// assert_eq!(Ok(2), distinct.first(&connection));
/// assert_eq!(Ok(1), not_distinct.first(&connection));
/// # }
/// ```
fn is_distinct_from<T>(self, other: T)
-> IsDistinctFrom<Self, T::Expression> where
T: AsExpression<Self::SqlType>,
{
IsDistinctFrom::new(self, other.as_expression())
}
}
impl<T: Expression> PgExpressionMethods for T {}
use super::date_and_time::{AtTimeZone, DateTimeLike};
use types::VarChar;
#[doc(hidden)]
pub trait PgTimestampExpressionMethods: Expression + Sized {
/// Returns a PostgreSQL "AT TIME ZONE" expression
fn at_time_zone<T>(self, timezone: T) -> AtTimeZone<Self, T::Expression> where
T: AsExpression<VarChar>,
{
AtTimeZone::new(self, timezone.as_expression())
}
}
impl<T: Expression> PgTimestampExpressionMethods for T where
T::SqlType: DateTimeLike,
{}
pub trait ArrayExpressionMethods<ST>: Expression<SqlType=Array<ST>> + Sized {
/// Compares two arrays for common elements, using the `&&` operator in
/// the final SQL
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # #[macro_use] extern crate diesel_codegen;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// # posts {
/// # id -> Integer,
/// # tags -> Array<VarChar>,
/// # }
/// # }
/// #
/// # // FIXME: We shouldn't need to define a users table here
/// # table! {
/// # users {
/// # id -> Integer,
/// # name -> VarChar,
/// # }
/// # }
/// #
/// # #[derive(Insertable)]
/// # #[table_name="posts"]
/// # struct NewPost<'a> { tags: Vec<&'a str> }
/// #
/// # fn main() {
/// # use self::posts::dsl::*;
/// # let conn = establish_connection();
/// # conn.execute("DROP TABLE IF EXISTS posts").unwrap();
/// # conn.execute("CREATE TABLE posts (id SERIAL PRIMARY KEY, tags TEXT[] NOT NULL)").unwrap();
/// #
/// diesel::insert(&vec![
/// NewPost { tags: vec!["cool", "awesome"] },
/// NewPost { tags: vec!["awesome", "great"] },
/// NewPost { tags: vec!["cool", "great"] },
/// ]).into(posts).execute(&conn).unwrap();
///
/// let query = posts.select(id).filter(tags.overlaps_with(vec!["horrid", "cool"]));
/// assert_eq!(Ok(vec![1, 3]), query.load(&conn));
///
/// let query = posts.select(id).filter(tags.overlaps_with(vec!["cool", "great"]));
/// assert_eq!(Ok(vec![1, 2, 3]), query.load(&conn));
///
/// let query = posts.select(id).filter(tags.overlaps_with(vec!["horrid"]));
/// assert_eq!(Ok(Vec::new()), query.load::<i32>(&conn));
/// # }
/// ```
fn overlaps_with<T>(self, other: T) -> OverlapsWith<Self, T::Expression> where
T: AsExpression<Self::SqlType>,
{
OverlapsWith::new(self, other.as_expression())
}
/// Compares whether an array contains another array, using the `@>` operator.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # #[macro_use] extern crate diesel_codegen;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// # posts {
/// # id -> Integer,
/// # tags -> Array<VarChar>,
/// # }
/// # }
/// #
/// # // FIXME: We shouldn't need to define a users table here
/// # table! {
/// # users {
/// # id -> Integer,
/// # name -> VarChar,
/// # }
/// # }
/// #
/// # #[derive(Insertable)]
/// # #[table_name="posts"]
/// # struct NewPost<'a> { tags: Vec<&'a str> }
/// #
/// # fn main() {
/// # use self::posts::dsl::*;
/// # let conn = establish_connection();
/// # conn.execute("DROP TABLE IF EXISTS posts").unwrap();
/// # conn.execute("CREATE TABLE posts (id SERIAL PRIMARY KEY, tags TEXT[] NOT NULL)").unwrap();
/// #
/// diesel::insert(&vec![
/// NewPost { tags: vec!["cool", "awesome"] },
/// ]).into(posts).execute(&conn).unwrap();
///
/// let query = posts.select(id).filter(tags.contains(vec!["cool"]));
/// assert_eq!(Ok(vec![1]), query.load(&conn));
///
/// let query = posts.select(id).filter(tags.contains(vec!["cool", "amazing"]));
/// assert_eq!(Ok(Vec::new()), query.load::<i32>(&conn));
/// # }
/// ```
fn contains<T>(self, other: T) -> Contains<Self, T::Expression> where
T: AsExpression<Self::SqlType>,
{
Contains::new(self, other.as_expression())
}
/// Compares whether an array is contained by another array, using the `<@` operator.
/// This is the opposite of `contains`
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # #[macro_use] extern crate diesel_codegen;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// # posts {
/// # id -> Integer,
/// # tags -> Array<VarChar>,
/// # }
/// # }
/// #
/// # // FIXME: We shouldn't need to define a users table here
/// # table! {
/// # users {
/// # id -> Integer,
/// # name -> VarChar,
/// # }
/// # }
/// #
/// # #[derive(Insertable)]
/// # #[table_name="posts"]
/// # struct NewPost<'a> { tags: Vec<&'a str> }
/// #
/// # fn main() {
/// # use self::posts::dsl::*;
/// # let conn = establish_connection();
/// # conn.execute("DROP TABLE IF EXISTS posts").unwrap();
/// # conn.execute("CREATE TABLE posts (id SERIAL PRIMARY KEY, tags TEXT[] NOT NULL)").unwrap();
/// #
/// diesel::insert(&vec![
/// NewPost { tags: vec!["cool", "awesome"] },
/// ]).into(posts).execute(&conn).unwrap();
///
/// let query = posts.select(id).filter(tags.is_contained_by(vec!["cool", "awesome", "amazing"]));
/// assert_eq!(Ok(vec![1]), query.load(&conn));
///
/// let query = posts.select(id).filter(tags.is_contained_by(vec!["cool"]));
/// assert_eq!(Ok(Vec::new()), query.load::<i32>(&conn));
/// # }
/// ```
fn is_contained_by<T>(self, other: T) -> IsContainedBy<Self, T::Expression> where
T: AsExpression<Self::SqlType>,
{
IsContainedBy::new(self, other.as_expression())
}
}
impl<T, ST> ArrayExpressionMethods<ST> for T where
T: Expression<SqlType=Array<ST>>,
{
}
use expression::operators::{Asc, Desc};
pub trait SortExpressionMethods : Sized {
/// Specify that nulls should come before other values in this ordering.
/// Normally, nulls come last when sorting in ascending order and first
/// when sorting in descending order.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # #[macro_use] extern crate diesel_codegen;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// # users {
/// # id -> Integer,
/// # name -> VarChar,
/// # }
/// # }
/// #
/// # table! {
/// # foos {
/// # id -> Integer,
/// # foo -> Nullable<Integer>,
/// # }
/// # }
/// #
/// # fn main() {
/// # let connection = connection_no_data();
/// # connection.execute("DROP TABLE IF EXISTS foos").unwrap();
/// connection.execute("CREATE TABLE foos (id SERIAL PRIMARY KEY, foo INTEGER)").unwrap();
/// connection.execute("INSERT INTO foos (foo) VALUES (NULL), (1), (2)").unwrap();
///
/// # use self::foos::dsl::*;
/// assert_eq!(Ok(vec![Some(1), Some(2), None]),
/// foos.select(foo).order(foo.asc()).load(&connection));
/// assert_eq!(Ok(vec![None, Some(1), Some(2)]),
/// foos.select(foo).order(foo.asc().nulls_first()).load(&connection));
/// # connection.execute("DROP TABLE foos").unwrap();
/// # }
/// ```
fn nulls_first(self) -> NullsFirst<Self> {
NullsFirst::new(self)
}
/// Specify that nulls should come after other values in this ordering.
/// Normally, nulls come last when sorting in ascending order and first
/// when sorting in descending order.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # #[macro_use] extern crate diesel_codegen;
/// # include!("src/doctest_setup.rs");
/// #
/// # table! {
/// # users {
/// # id -> Integer,
/// # name -> VarChar,
/// # }
/// # }
/// #
/// # table! {
/// # foos {
/// # id -> Integer,
/// # foo -> Nullable<Integer>,
/// # }
/// # }
/// #
/// # fn main() {
/// # let connection = connection_no_data();
/// # connection.execute("DROP TABLE IF EXISTS foos").unwrap();
/// connection.execute("CREATE TABLE foos (id SERIAL PRIMARY KEY, foo INTEGER)").unwrap();
/// connection.execute("INSERT INTO foos (foo) VALUES (NULL), (1), (2)").unwrap();
///
/// # use self::foos::dsl::*;
/// assert_eq!(Ok(vec![None, Some(2), Some(1)]),
/// foos.select(foo).order(foo.desc()).load(&connection));
/// assert_eq!(Ok(vec![Some(2), Some(1), None]),
/// foos.select(foo).order(foo.desc().nulls_last()).load(&connection));
/// # connection.execute("DROP TABLE foos").unwrap();
/// # }
/// ```
fn nulls_last(self) -> NullsLast<Self> {
NullsLast::new(self)
}
}
impl<T> SortExpressionMethods for Asc<T> {}
impl<T> SortExpressionMethods for Desc<T> {}
pub trait PgTextExpressionMethods: Expression<SqlType=Text> + Sized {
/// Returns a SQL `ILIKE` expression
fn ilike<T: AsExpression<Text>>(self, other: T) -> ILike<Self, T::Expression> {
ILike::new(self.as_expression(), other.as_expression())
}
/// Returns a SQL `NOT ILIKE` expression
fn not_ilike<T: AsExpression<Text>>(self, other: T) -> NotILike<Self, T::Expression> {
NotILike::new(self.as_expression(), other.as_expression())
}
}
impl<T: Expression<SqlType=Text>> PgTextExpressionMethods for T {}
| 33.562842 | 104 | 0.521573 |
89bc9ebc8962268c828a47febcad2d37e1130946 | 1,197 | //! Types that map to concepts in HTTP.
//!
//! This module exports types that map to HTTP concepts or to the underlying
//! HTTP library when needed. Because the underlying HTTP library is likely to
//! change (see <a
//! href="https://github.com/SergioBenitez/Rocket/issues/17">#17</a>), types in
//! [hyper](hyper/index.html) should be considered unstable.
pub mod hyper;
pub mod uri;
#[macro_use]
mod known_media_types;
mod cookies;
mod method;
mod media_type;
mod content_type;
mod status;
mod header;
mod accept;
mod raw_str;
pub(crate) mod parse;
// We need to export these for codegen, but otherwise it's unnecessary.
// TODO: Expose a `const fn` from ContentType when possible. (see RFC#1817)
pub mod uncased;
#[doc(hidden)] pub use self::parse::IndexedStr;
#[doc(hidden)] pub use self::media_type::{MediaParams, Source};
pub use self::method::Method;
pub use self::content_type::ContentType;
pub use self::accept::{Accept, QMediaType};
pub use self::status::{Status, StatusClass};
pub use self::header::{Header, HeaderMap};
pub use self::raw_str::RawStr;
pub use self::media_type::MediaType;
pub use self::cookies::{Cookie, Cookies};
pub(crate) use self::cookies::{Key, CookieJar};
| 29.925 | 79 | 0.734336 |
3ae2e20f0b5da82536f59f3be1465445c61f2de5 | 40 | pub mod cc_overlap;
pub mod gpu_memory;
| 13.333333 | 19 | 0.8 |
4b9203aefc39a660633cbbcd96e3755b2166ae7c | 938 | use algebra::{BigInteger, PrimeField};
#[derive(Hash, Eq, PartialEq, Debug, Clone, Copy)]
pub struct EndoScalar<A: PrimeField>(pub A);
impl<F: PrimeField> EndoScalar<F> {
pub fn to_field(&self, endo_coeff: &F) -> F {
let length_in_bits: usize = 256;
let EndoScalar(x) = self;
let mut bits = x.into_repr().to_bits();
bits.reverse();
assert_eq!(length_in_bits, bits.len());
let mut a: F = (2 as u64).into();
let mut b: F = (2 as u64).into();
let one = F::one();
let neg_one = -one;
for i in (0..(length_in_bits / 2)).rev() {
a.double_in_place();
b.double_in_place();
let r_2i = bits[2 * i];
let s = if !r_2i { &neg_one } else { &one };
if !bits[2 * i + 1] {
b += s;
} else {
a += s;
}
}
a * endo_coeff + &b
}
}
| 24.684211 | 56 | 0.476546 |
2f76654fa61cf287bc0c7b9efbe168fc3acf6027 | 3,330 | use std::marker::PhantomData;
use derivative::Derivative;
use amethyst_core::{
ecs::prelude::{Component, Read, ReadStorage, System, SystemData, World, Write},
shrev::{Event, EventChannel, ReaderId},
SystemDesc,
};
use crate::event::TargetedEvent;
#[cfg(feature = "profiler")]
use thread_profiler::profile_scope;
/// Describes anything that can receive events one by one or in batches. This
/// lets whoever wants to receive triggered events decide on how they
/// want to receive them, instead of forcing them to construct certain
/// data structures such as a `Vec`.
pub trait EventReceiver<T> {
/// Receive a single event
fn receive_one(&mut self, value: &T);
/// Receive an iterator over several events
fn receive(&mut self, values: &[T]);
}
impl<T> EventReceiver<T> for EventChannel<T>
where
T: Clone + Event,
{
fn receive_one(&mut self, value: &T) {
self.single_write(value.clone());
}
fn receive(&mut self, values: &[T]) {
self.iter_write(values.iter().cloned());
}
}
pub trait EventRetrigger: Component {
type In: Clone + Send + Sync + TargetedEvent;
type Out: Clone + Send + Sync;
fn apply<R>(&self, event: &Self::In, out: &mut R)
where
R: EventReceiver<Self::Out>;
}
// Unable to derive `SystemDesc` on `EventRetriggerSystem` because the proc macro doesn't yet
// support creating a `PhantomData` for computed fields.
/// Builds an `EventRetriggerSystem`.
#[derive(Derivative, Debug)]
#[derivative(Default(bound = ""))]
pub struct EventRetriggerSystemDesc<T> {
marker: PhantomData<T>,
}
impl<'a, 'b, T> SystemDesc<'a, 'b, EventRetriggerSystem<T>> for EventRetriggerSystemDesc<T>
where
T: EventRetrigger,
{
fn build(self, world: &mut World) -> EventRetriggerSystem<T> {
<EventRetriggerSystem<T> as System<'_>>::SystemData::setup(world);
let event_reader = world.fetch_mut::<EventChannel<T::In>>().register_reader();
EventRetriggerSystem::new(event_reader)
}
}
/// Links up the given in- and output types' `EventChannel`s listening
/// to incoming events and calling `apply` on the respective `Retrigger`
/// components.
#[derive(Debug)]
pub struct EventRetriggerSystem<T: EventRetrigger> {
event_reader: ReaderId<T::In>,
}
impl<T> EventRetriggerSystem<T>
where
T: EventRetrigger,
{
/// Constructs a default `EventRetriggerSystem`. Since the `event_reader`
/// will automatically be fetched when the system is set up, this should
/// always be used to construct `EventRetriggerSystem`s.
pub fn new(event_reader: ReaderId<T::In>) -> Self {
Self { event_reader }
}
}
impl<'s, T> System<'s> for EventRetriggerSystem<T>
where
T: EventRetrigger,
{
type SystemData = (
Read<'s, EventChannel<T::In>>,
Write<'s, EventChannel<T::Out>>,
ReadStorage<'s, T>,
);
fn run(&mut self, (in_channel, mut out_channel, retrigger): Self::SystemData) {
#[cfg(feature = "profiler")]
profile_scope!("event_retrigger_system");
let event_reader = &mut self.event_reader;
for event in in_channel.read(event_reader) {
if let Some(entity_retrigger) = retrigger.get(event.get_target()) {
entity_retrigger.apply(&event, &mut *out_channel);
}
}
}
}
| 29.210526 | 93 | 0.666366 |
8faa269a015b579a969cc3466370d118b801fc1c | 4,042 | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use std::sync::Arc;
use std::time::Instant;
use fail;
use test_raftstore::*;
use tikv_util::config::*;
#[test]
fn test_pending_peers() {
let _guard = crate::setup();
let mut cluster = new_node_cluster(0, 3);
cluster.cfg.raft_store.pd_heartbeat_tick_interval = ReadableDuration::millis(100);
let region_worker_fp = "region_apply_snap";
let pd_client = Arc::clone(&cluster.pd_client);
// Disable default max peer count check.
pd_client.disable_default_operator();
let region_id = cluster.run_conf_change();
pd_client.must_add_peer(region_id, new_peer(2, 2));
cluster.must_put(b"k1", b"v1");
fail::cfg(region_worker_fp, "sleep(2000)").unwrap();
pd_client.must_add_peer(region_id, new_peer(3, 3));
sleep_ms(1000);
let pending_peers = pd_client.get_pending_peers();
// Region worker is not started, snapshot should not be applied yet.
assert_eq!(pending_peers[&3], new_peer(3, 3));
// But it will be applied finally.
must_get_equal(&cluster.get_engine(3), b"k1", b"v1");
sleep_ms(100);
let pending_peers = pd_client.get_pending_peers();
assert!(pending_peers.is_empty());
}
// Tests if raftstore and apply worker write truncated_state concurrently could lead to
// dirty write.
#[test]
fn test_pending_snapshot() {
let _guard = crate::setup();
let mut cluster = new_node_cluster(0, 3);
configure_for_snapshot(&mut cluster);
let election_timeout = configure_for_lease_read(&mut cluster, None, Some(15));
let gc_limit = cluster.cfg.raft_store.raft_log_gc_count_limit;
cluster.cfg.raft_store.pd_heartbeat_tick_interval = ReadableDuration::millis(100);
let handle_snapshot_fp = "apply_on_handle_snapshot_1_1";
let handle_snapshot_finish_fp = "apply_on_handle_snapshot_finish_1_1";
fail::cfg("apply_on_handle_snapshot_sync", "return").unwrap();
let pd_client = Arc::clone(&cluster.pd_client);
// Disable default max peer count check.
pd_client.disable_default_operator();
let region_id = cluster.run_conf_change();
pd_client.must_add_peer(region_id, new_peer(2, 2));
cluster.must_transfer_leader(region_id, new_peer(1, 1));
cluster.must_put(b"k1", b"v1");
fail::cfg(handle_snapshot_fp, "pause").unwrap();
pd_client.must_add_peer(region_id, new_peer(3, 3));
// Give some time for peer 3 to request snapshot.
sleep_ms(100);
// Isolate peer 1 from rest of the cluster.
cluster.add_send_filter(IsolationFilterFactory::new(1));
sleep_ms((election_timeout.as_millis() * 2) as _);
cluster.reset_leader_of_region(region_id);
// Compact logs to force requesting snapshot after clearing send filters.
let state2 = cluster.truncated_state(1, 2);
for i in 1..gc_limit * 10 {
let k = i.to_string().into_bytes();
cluster.must_put(&k, &k.clone());
}
for _ in 0..100 {
if cluster
.get_raft_engine(2)
.get(&keys::raft_log_key(1, state2.get_index() + 5 * gc_limit))
.unwrap()
.is_none()
{
break;
}
sleep_ms(50);
}
// Make sure peer 1 has applied snapshot.
cluster.clear_send_filters();
let start = Instant::now();
loop {
if cluster.pd_client.get_pending_peers().get(&1).is_none()
|| start.elapsed() > election_timeout * 10
{
break;
}
sleep_ms(50);
}
let state1 = cluster.truncated_state(1, 1);
// Peer 2 continues to handle snapshot.
fail::cfg(handle_snapshot_finish_fp, "pause").unwrap();
fail::remove(handle_snapshot_fp);
sleep_ms(200);
let state2 = cluster.truncated_state(1, 1);
fail::remove(handle_snapshot_finish_fp);
assert!(
state1.get_term() <= state2.get_term(),
"{:?} {:?}",
state1,
state2
);
assert!(
state1.get_index() <= state2.get_index(),
"{:?} {:?}",
state1,
state2
);
}
| 32.079365 | 87 | 0.65908 |
2996b80c9cbad5f584e2965dd71654290d12e000 | 17,831 | use crate::artos::client::channel::{ClientResponseHandler, Event, EventType};
use crate::artos::client::query::{NullQueryProtocol, QueryProtocol};
use crate::artos::client::{ClientStore, CompletionHandler};
use crate::artos::common::Error;
use crate::artos::common::{FlowController, FlowType};
use crate::artos::common::{GroupConfiguration, MessageSender, MessageSenderFactory, ServerConfiguration};
use crate::artos::message::client::{
ConfigurationRequest, LogEntry, PublishRequest, PublishResponse, RestartSessionRequest,
};
use crate::compartment::{Sender, Timer};
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
use std::time::{Duration, Instant};
use uuid::Uuid;
use log::debug;
use log::info;
use log::trace;
use log::warn;
use crate::artos::message::{Request, Response};
use rand::Rng;
//////////////////////////////////////////////////////////
// PublishProtocol API
//////////////////////////////////////////////////////////
pub trait PublishProtocol {
fn is_connected(&self) -> bool {
unimplemented!()
}
fn group_configuration(&self) -> GroupConfiguration {
unimplemented!()
}
fn next_message_id(&self) -> u64 {
unimplemented!()
}
fn on_disconnected(&self) {
unimplemented!()
}
}
pub struct NullPublishProtocol {}
impl NullPublishProtocol {
pub fn new() -> Rc<dyn PublishProtocol> {
Rc::new(NullPublishProtocol {})
}
}
impl PublishProtocol for NullPublishProtocol {}
//////////////////////////////////////////////////////////
// PublishProtocolImpl
//////////////////////////////////////////////////////////
pub struct PublishProtocolImpl {
endpoint: String,
client_id: Uuid,
group_id: Uuid,
lock_queue_capacity: usize,
unlock_queue_capacity: usize,
max_batch_size: usize,
flow_controller: Rc<dyn FlowController>,
handler: Rc<dyn CompletionHandler>,
message_sender_factory: Box<dyn MessageSenderFactory>,
initial_configuration: GroupConfiguration,
sender: Sender<Event>,
state: RefCell<State>,
}
struct State {
client_store: Box<dyn ClientStore>,
leader_timeout_timer: Timer,
heartbeat_timer: Timer,
update_configuration_timer: Timer,
leader_id: Option<Uuid>,
leader_endpoint: Option<String>,
message_sender: Option<Rc<dyn MessageSender>>,
configuration: GroupConfiguration,
in_progress: bool,
query_protocol: Rc<dyn QueryProtocol>,
queue: VecDeque<EntryInfo>,
next_message_id: u64,
last_sent_message_id: u64,
last_committed_message_id: u64,
flow_locked: bool,
}
struct EntryInfo {
log_entry: LogEntry,
user_data: usize,
}
impl PublishProtocolImpl {
pub fn new(
endpoint: String,
client_id: Uuid,
group_id: Uuid,
message_sender_factory: Box<dyn MessageSenderFactory>,
client_store: Box<dyn ClientStore>,
initial_configuration: GroupConfiguration,
sender: Sender<Event>,
acknowledge_request_period: Duration,
update_configuration_period: Duration,
leader_timeout: Duration,
lock_queue_capacity: usize,
unlock_queue_capacity: usize,
max_batch_size: usize,
flow_controller: Rc<dyn FlowController>,
handler: Rc<dyn CompletionHandler>,
) -> PublishProtocolImpl {
PublishProtocolImpl {
endpoint,
client_id,
group_id,
lock_queue_capacity,
unlock_queue_capacity,
max_batch_size,
flow_controller,
handler,
message_sender_factory,
initial_configuration: initial_configuration.clone(),
sender,
state: RefCell::new(State {
client_store,
leader_timeout_timer: Timer::new(false, leader_timeout),
heartbeat_timer: Timer::new(false, acknowledge_request_period),
update_configuration_timer: Timer::new(false, update_configuration_period),
leader_id: None,
leader_endpoint: None,
message_sender: None,
configuration: initial_configuration,
in_progress: false,
query_protocol: NullQueryProtocol::new(),
queue: VecDeque::new(),
next_message_id: 1,
last_sent_message_id: 0,
last_committed_message_id: 0,
flow_locked: false,
}),
}
}
pub fn set_query_protocol(&self, value: Rc<dyn QueryProtocol>) {
let state = &mut self.state.borrow_mut();
state.query_protocol = value;
}
pub fn start(&self) {
let state = &mut self.state.borrow_mut();
if let Some(configuration) = state
.client_store
.load_group_configuration(self.initial_configuration.id())
{
state.configuration = configuration;
} else {
let configuration = state.configuration.clone();
state.client_store.save_group_configuration(configuration);
}
state.query_protocol.update_configuration(state.configuration.clone());
state.heartbeat_timer.start();
}
pub fn stop(&self) {
let state = &mut self.state.borrow_mut();
self.on_leader_disconnected(true, state);
state.heartbeat_timer.stop();
}
pub fn process(&self) {
let state = &mut self.state.borrow_mut();
if state.message_sender.is_some() && !state.in_progress {
if let Some(request) = self.create_request(state) {
self.send_request(request, state);
}
}
}
pub fn on_timer(&self, current_time: Instant) {
let state = &mut self.state.borrow_mut();
if state.leader_timeout_timer.is_fired(current_time) {
self.handle_leader_timeout(state);
}
if state.update_configuration_timer.is_fired(current_time) {
self.request_configuration_update(state);
}
if state.heartbeat_timer.is_fired(current_time) {
self.request_heartbeat(state);
}
}
pub fn publish(&self, value: Vec<u8>, user_data: usize) {
let state = &mut self.state.borrow_mut();
let log_entry = LogEntry::new(state.next_message_id, value);
state.next_message_id += 1;
state.queue.push_back(EntryInfo { log_entry, user_data });
self.check_flow(state);
}
pub fn handle_succeeded_response(&self, serialized_response: Vec<u8>) {
let state = &mut self.state.borrow_mut();
state.in_progress = false;
if let bincode::Result::Ok(response) = bincode::deserialize::<Response>(&serialized_response) {
if let Response::Publish(response) = response {
match state.leader_id {
Some(leader_id) => {
if response.server_id() != leader_id {
return;
}
}
None => return,
}
trace!("[{}] Response received: {:?}.", self.endpoint, response);
if response.is_accepted() {
if let Some(configuration) = response.configuration() {
self.update_configuration(configuration.clone(), state);
}
self.handle_accepted_publish_response(response, state);
state.leader_timeout_timer.restart();
} else if response.leader_id().is_none() || response.leader_id() != state.leader_id {
debug!(
"[{}] Group endpoint is not a leader: {:?}:{:?}.",
self.endpoint, state.leader_endpoint, state.leader_id
);
self.on_leader_disconnected(true, state);
if response.leader_id().is_some() {
state.leader_id = response.leader_id();
}
}
}
}
}
pub fn handle_failed_response(&self, server_configuration: ServerConfiguration, error: Error) {
let state = &mut self.state.borrow_mut();
state.in_progress = false;
warn!(
"[{}] Response error received from server {}: {:?}.",
self.endpoint,
server_configuration.endpoint(),
error
);
self.on_leader_disconnected(true, state);
}
}
impl PublishProtocol for PublishProtocolImpl {
fn is_connected(&self) -> bool {
self.state.borrow().message_sender.is_some()
}
fn group_configuration(&self) -> GroupConfiguration {
self.state.borrow().configuration.clone()
}
fn next_message_id(&self) -> u64 {
self.state.borrow().next_message_id
}
fn on_disconnected(&self) {
let state = &mut self.state.borrow_mut();
self.on_leader_disconnected(false, state);
}
}
//////////////////////////////////////////////////////////
// Publish Protocol implementation
//////////////////////////////////////////////////////////
impl PublishProtocolImpl {
fn handle_accepted_publish_response(&self, response: PublishResponse, state: &mut State) {
if response.is_out_of_order_received() {
let last_received_message_id = response.last_received_message_id();
if last_received_message_id == 0 && state.last_committed_message_id > 0 {
self.request_restart_session(state);
} else {
assert!(last_received_message_id >= state.last_committed_message_id);
state.last_sent_message_id = last_received_message_id;
}
}
let last_committed_message_id = response.last_committed_message_id();
if last_committed_message_id != 0 {
self.remove_committed_entries(last_committed_message_id, state);
}
}
fn handle_leader_timeout(&self, state: &mut State) {
warn!(
"[{}] Timeout has occurred, when waiting response from leader ''{:?}''.",
self.endpoint, state.leader_id
);
self.on_leader_disconnected(true, state);
}
fn create_request(&self, state: &State) -> Option<Request> {
let mut entries = Vec::new();
let mut batch_size = 0;
assert!(state.last_sent_message_id >= state.last_committed_message_id);
let start = (state.last_sent_message_id - state.last_committed_message_id) as usize;
for i in start..state.queue.len() {
let log_entry = state.queue.get(i).unwrap().log_entry.clone();
let value_length = log_entry.value().len();
if value_length + batch_size > self.max_batch_size {
break;
}
entries.push(log_entry);
batch_size += value_length;
}
if !entries.is_empty() {
Some(Request::Publish(PublishRequest::new(
self.client_id,
self.group_id,
entries,
)))
} else {
None
}
}
fn send_request(&self, request: Request, state: &mut State) {
self.ensure_message_sender(state);
if state.message_sender.is_some() {
trace!("[{}] Request sent: {:?}.", self.endpoint, request);
state.heartbeat_timer.restart();
state.in_progress = true;
let serialized_request = bincode::serialize(&request).unwrap();
state.message_sender.as_ref().unwrap().send(serialized_request);
}
}
fn ensure_message_sender(&self, state: &mut State) {
if state.message_sender.is_none() {
let (leader_id, leader_endpoint) = self.leader_configuration(state.leader_id, state);
state.leader_id = Some(leader_id);
state.leader_endpoint = Some(leader_endpoint.clone());
match self.message_sender_factory.create_sender(
leader_endpoint.clone(),
Box::new(ClientResponseHandler::new(
EventType::Publish,
self.sender.clone(),
ServerConfiguration::new(leader_id, leader_endpoint),
)),
) {
Ok(message_sender) => {
state.message_sender = Some(Rc::from(message_sender));
self.on_leader_connected(state);
}
Err(error) => {
warn!("[{}] Could not create message sender: {:?}.", self.endpoint, error);
self.on_leader_disconnected(true, state);
}
}
}
}
fn on_leader_connected(&self, state: &mut State) {
state.in_progress = false;
state.leader_timeout_timer.start();
if !state.configuration.is_single_server() {
state.update_configuration_timer.start();
}
state.query_protocol.on_leader_connected(
state.message_sender.as_ref().unwrap().clone(),
ServerConfiguration::new(
state.leader_id.unwrap(),
state.leader_endpoint.as_ref().unwrap().to_string(),
),
);
info!(
"[{}] Group endpoint has been connected: {:?}:{:?}.",
self.endpoint, state.leader_endpoint, state.leader_id
);
}
fn on_leader_disconnected(&self, notify_query_protocol: bool, state: &mut State) {
if state.leader_id.is_some() {
info!(
"[{}] Group endpoint has been disconnected: {:?}:{:?}.",
self.endpoint, state.leader_endpoint, state.leader_id
);
state.leader_id = None;
state.leader_endpoint = None;
state.in_progress = false;
state.message_sender = None;
state.last_sent_message_id = state.last_committed_message_id;
if notify_query_protocol {
state.query_protocol.on_leader_disconnected();
}
state.leader_timeout_timer.stop();
state.update_configuration_timer.stop();
}
}
fn leader_configuration(&self, leader_id: Option<Uuid>, state: &State) -> (Uuid, String) {
if let Some(leader_id) = leader_id {
let server_configuration = state.configuration.servers().iter().find(|v| v.id() == leader_id);
if let Some(server_configuration) = server_configuration {
return (server_configuration.id(), server_configuration.endpoint().clone());
}
}
let mut random = rand::thread_rng();
let index = random.gen_range(0, state.configuration.servers().len());
let server_configuration = state.configuration.servers()[index].clone();
debug!(
"[{}] Random server has been selected as primary group endpoint: {:?}.",
self.endpoint, server_configuration
);
(server_configuration.id(), server_configuration.endpoint().clone())
}
fn request_heartbeat(&self, state: &mut State) {
if state.in_progress {
return;
}
self.send_request(
Request::Publish(PublishRequest::new(self.client_id, self.group_id, vec![])),
state,
);
}
fn request_restart_session(&self, state: &mut State) {
let request = Request::RestartSession(RestartSessionRequest::new(
self.client_id,
self.group_id,
state.last_sent_message_id,
));
self.send_request(request, state);
}
fn request_configuration_update(&self, state: &mut State) {
if state.in_progress {
state.update_configuration_timer.delayed_fire();
return;
}
self.send_request(
Request::Configuration(ConfigurationRequest::new(self.client_id, self.group_id)),
state,
);
}
fn remove_committed_entries(&self, last_committed_message_id: u64, state: &mut State) {
loop {
if let Some(info) = state.queue.front() {
if info.log_entry.message_id() <= last_committed_message_id {
let user_data = info.user_data;
state.last_committed_message_id = info.log_entry.message_id();
if state.last_sent_message_id < state.last_committed_message_id {
state.last_sent_message_id = state.last_committed_message_id;
}
state.queue.pop_front();
self.handler.on_commit(user_data);
self.check_flow(state);
} else {
break;
}
} else {
break;
}
}
}
fn check_flow(&self, state: &mut State) {
if !state.flow_locked && state.queue.len() >= self.lock_queue_capacity {
state.flow_locked = true;
self.flow_controller.lock_flow(FlowType::Publish);
}
if state.flow_locked && state.queue.len() <= self.unlock_queue_capacity {
state.flow_locked = false;
self.flow_controller.unlock_flow(FlowType::Publish);
}
}
fn update_configuration(&self, configuration: GroupConfiguration, state: &mut State) {
if state.configuration != configuration {
debug!(
"[{}] Group configuration has been updated: {:?}.",
self.endpoint, configuration
);
state.configuration = configuration.clone();
state.client_store.save_group_configuration(configuration.clone());
state.query_protocol.update_configuration(configuration);
}
}
}
| 33.204842 | 106 | 0.578487 |
dd35abbd72f387e625673614363271d5ff189ff1 | 25,244 | use super::prelude::*;
use std::hash::{Hash, Hasher};
use super::Categorical;
use crate::graph::number::{RandomF32, RandomI32, RandomU32};
use serde::{
de::{Deserialize, Deserializer},
ser::Serializer,
Serialize,
};
#[derive(Clone, Copy)]
pub enum NumberContentKind {
U64,
I64,
F64,
}
impl NumberContentKind {
pub fn upcast(self) -> Self {
match self {
Self::U64 => Self::I64,
Self::I64 | Self::F64 => Self::F64,
}
}
}
pub trait NumberKindExt {
fn kind(&self) -> NumberContentKind;
}
impl NumberKindExt for Number {
fn kind(&self) -> NumberContentKind {
if self.is_u64() {
NumberContentKind::U64
} else if self.is_i64() {
NumberContentKind::I64
} else if self.is_f64() {
NumberContentKind::F64
} else {
unreachable!()
}
}
}
// Generate a snake case version of NumberContent variant
// name via `serde`. We use this hack because `serde` case
// conversion functions are internal
macro_rules! serde_convert_case {
($identifier:ident,$case:expr) => {{
#[derive(Serialize)]
#[serde(rename_all = $case)]
enum SnakeCaseHelper {
$identifier,
}
// Safety: since we derive `Serialize`, unwrap() shouldn't panic
// for any identifier that doesn't brake `enum` compilation
serde_json::to_value(&SnakeCaseHelper::$identifier).unwrap()
}};
}
macro_rules! number_content {
{
$(
$(#[$default:meta])?
$ty:ty[$is:ident, $def:ident] as $as:ident {
$(
$variant:ident($variant_ty:path),
)*
},
)*
} => {
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum NumberContent {
$($as(number_content::$as),)*
}
impl NumberContent {
pub fn kind(&self) -> String {
match self {
$($(Self::$as(number_content::$as::$variant(_)) => {
concat!(stringify!($as), "::", stringify!($variant)).to_string()
},)*)*
}
}
$(
pub fn $def() -> Self {
Self::$as(number_content::$as::Range(RangeStep::default()))
}
pub fn $is(&self) -> bool {
match self {
Self::$as(_) => true,
_ => false
}
}
)*
}
impl Serialize for NumberContent {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match &self {
$(
NumberContent::$as(value) => {
let mut obj = serde_json::to_value(value).map_err(S::Error::custom)?;
let obj_map = obj.as_object_mut().ok_or(S::Error::custom("Object value expected"))?;
obj_map.insert("subtype".to_string(), serde_convert_case!($as, "snake_case"));
obj_map.serialize(serializer)
}
)*
}
}
}
impl<'de> Deserialize<'de> for NumberContent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let mut v: serde_json::Value = Value::deserialize(deserializer)?;
let as_object = v.as_object_mut().ok_or(D::Error::custom("Object value expected"))?;
match as_object.remove("subtype") {
Some(subtype) => {
$(
if subtype == stringify!($ty) {
if as_object.is_empty() {
Ok(Self::$def())
} else {
let inner = number_content::$as::deserialize(v).map_err(D::Error::custom)?;
Ok(NumberContent::$as(inner))
}
} else
)*
{
Err(D::Error::unknown_variant(format!("{:?}", subtype).as_str(), &[""]))
}
}
None => {
$( if let Ok(inner) = number_content::$as::deserialize(&v) {
Ok(NumberContent::$as(inner))
} else )* {
Err(D::Error::custom("Failed to infer numeric type from its value: try specifying the 'subtype' parameter"))
}
}
}
}
}
pub mod number_content {
use super::{RangeStep, Categorical, NumberContent};
use serde::{Serialize, Deserialize};
$(
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
$(#[$default])?
pub enum $as {
$($variant($variant_ty),)*
}
$(
impl From<$variant_ty> for $as {
fn from(value: $variant_ty) -> Self {
Self::$variant(value)
}
}
)*
impl From<$as> for NumberContent {
fn from(value: $as) -> Self {
Self::$as(value)
}
}
)*
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, Hash)]
#[serde(deny_unknown_fields)]
pub struct Id<N> {
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub start_at: Option<N>,
}
impl NumberContent {
pub fn accepts(&self, number: &Number) -> Result<()> {
if self.is_u64() && number.is_u64()
|| self.is_i64() && number.is_i64()
|| self.is_f64() && number.is_f64()
{
Ok(())
} else {
// TODO: better error
Err(failed!(target: Release, "numerical type mismatch"))
}
}
pub fn try_transmute_to_id(self) -> Result<Self> {
match self {
NumberContent::U32(_) => Ok(Self::u32_default_id()),
NumberContent::U64(_) => Ok(Self::u64_default_id()),
NumberContent::I32(_) => Ok(Self::i32_default_id()),
NumberContent::I64(_) => Ok(Self::i64_default_id()),
NumberContent::F64(_) => bail!("could not transmute f64 into id"),
NumberContent::F32(_) => bail!("could not transmute f32 into id"),
}
}
pub fn u32_default_id() -> Self {
NumberContent::U32(number_content::U32::Id(Id::default()))
}
pub fn u64_default_id() -> Self {
NumberContent::U64(number_content::U64::Id(Id::default()))
}
pub fn i32_default_id() -> Self {
NumberContent::I32(number_content::I32::Id(Id::default()))
}
pub fn i64_default_id() -> Self {
NumberContent::I64(number_content::I64::Id(Id::default()))
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub struct RangeStep<N> {
#[serde(skip_serializing_if = "Option::is_none")]
pub low: Option<N>,
#[serde(skip_serializing_if = "Option::is_none")]
pub high: Option<N>,
#[serde(skip_serializing_if = "Option::is_none")]
pub step: Option<N>,
#[serde(skip_serializing_if = "std::clone::Clone::clone")]
pub include_low: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub include_high: bool,
}
impl<N> Default for RangeStep<N> {
fn default() -> Self {
Self {
low: None,
high: None,
step: None,
include_low: true,
include_high: false,
}
}
}
impl<N> RangeStep<N> {
pub fn new(low: N, high: N, step: N) -> Self {
Self {
low: Some(low),
high: Some(high),
step: Some(step),
..Default::default()
}
}
fn bound(value: Option<&N>, inclusive: bool) -> std::ops::Bound<&N> {
match value {
Some(n) if inclusive => std::ops::Bound::Included(n),
Some(n) => std::ops::Bound::Excluded(n),
None => std::ops::Bound::Unbounded,
}
}
fn cast<F, M>(self, f: F) -> RangeStep<M>
where
F: Fn(N) -> M,
{
self.try_cast::<_, _, std::convert::Infallible>(|value| Ok(f(value)))
.unwrap()
}
fn try_cast<F, M, E>(self, f: F) -> Result<RangeStep<M>, E>
where
F: Fn(N) -> Result<M, E>,
{
Ok(RangeStep::<M> {
low: self.low.map(&f).transpose()?,
high: self.high.map(&f).transpose()?,
step: self.step.map(&f).transpose()?,
include_low: self.include_low,
include_high: self.include_high,
})
}
}
impl<N: Copy> RangeStep<N> {
pub fn step(&self) -> Option<N> {
self.step.as_ref().cloned()
}
}
impl<N> std::ops::RangeBounds<N> for RangeStep<N> {
fn start_bound(&self) -> std::ops::Bound<&N> {
RangeStep::bound(self.low.as_ref(), self.include_low)
}
fn end_bound(&self) -> std::ops::Bound<&N> {
RangeStep::bound(self.high.as_ref(), self.include_high)
}
}
macro_rules! derive_hash {
(f32) => {
impl Hash for RangeStep<f32> {
derive_hash!(float);
}
};
(f64) => {
impl Hash for RangeStep<f64> {
derive_hash!(float);
}
};
(float) => {
fn hash<H: Hasher>(&self, state: &mut H) {
if let Some(low) = self.low {
low.to_bits().hash(state);
}
if let Some(high) = self.high {
high.to_bits().hash(state);
}
if let Some(step) = self.step {
step.to_bits().hash(state);
}
self.include_low.hash(state);
self.include_high.hash(state);
}
};
{$t:ty} => {
impl Hash for RangeStep<$t> {
fn hash<H: Hasher>(&self, state: &mut H) {
if let Some(low) = self.low {
low.hash(state);
}
if let Some(high) = self.high {
high.hash(state);
}
if let Some(step) = self.step {
step.hash(state);
}
self.include_low.hash(state);
self.include_high.hash(state);
}
}
};
{$($t:ident),*} => {
$(derive_hash!{$t})*
};
}
derive_hash!(i32, u32, i64, u64, f32, f64);
number_content!(
#[derive(PartialEq, Hash)]
u32[is_u32, default_u32_range] as U32 {
Range(RangeStep<u32>),
Categorical(Categorical<u32>),
Constant(u32),
Id(crate::schema::Id<u32>),
},
#[derive(PartialEq, Hash)]
u64[is_u64, default_u64_range] as U64 {
Range(RangeStep<u64>),
Categorical(Categorical<u64>),
Constant(u64),
Id(crate::schema::Id<u64>),
},
#[derive(PartialEq, Hash)]
i32[is_i32, default_i32_range] as I32 {
Range(RangeStep<i32>),
Categorical(Categorical<i32>),
Constant(i32),
Id(crate::schema::Id<i32>),
},
#[derive(PartialEq, Hash)]
i64[is_i64, default_i64_range] as I64 {
Range(RangeStep<i64>),
Categorical(Categorical<i64>),
Constant(i64),
Id(crate::schema::Id<i64>),
},
f64[is_f64, default_f64_range] as F64 {
Range(RangeStep<f64>),
Constant(f64),
},
f32[is_f32, default_f32_range] as F32 {
Range(RangeStep<f32>),
Constant(f32),
},
);
impl Compile for NumberContent {
fn compile<'a, C: Compiler<'a>>(&'a self, _compiler: C) -> Result<Graph> {
let number_node = match self {
Self::U64(u64_content) => {
let random_u64 = match u64_content {
number_content::U64::Range(range) => RandomU64::range(*range)?,
number_content::U64::Categorical(categorical_content) => {
RandomU64::categorical(categorical_content.clone())
}
number_content::U64::Constant(val) => RandomU64::constant(*val),
number_content::U64::Id(id) => {
let gen = Incrementing::new_at(id.start_at.unwrap_or(1));
RandomU64::incrementing(gen)
}
};
random_u64.into()
}
Self::I64(i64_content) => {
let random_i64 = match i64_content {
number_content::I64::Range(range) => RandomI64::range(*range)?,
number_content::I64::Categorical(categorical_content) => {
RandomI64::categorical(categorical_content.clone())
}
number_content::I64::Constant(val) => RandomI64::constant(*val),
number_content::I64::Id(id) => {
RandomI64::incrementing(Incrementing::new_at(id.start_at.unwrap_or(1)))
}
};
random_i64.into()
}
Self::F64(f64_content) => {
let random_f64 = match f64_content {
number_content::F64::Range(range) => RandomF64::range(*range)?,
number_content::F64::Constant(val) => RandomF64::constant(*val),
};
random_f64.into()
}
Self::U32(u32_content) => {
let random_u32 = match u32_content {
number_content::U32::Range(range) => RandomU32::range(*range)?,
number_content::U32::Categorical(categorical_content) => {
RandomU32::categorical(categorical_content.clone())
}
number_content::U32::Constant(val) => RandomU32::constant(*val),
number_content::U32::Id(id) => {
RandomU32::incrementing(Incrementing::new_at(id.start_at.unwrap_or(1)))
}
};
random_u32.into()
}
Self::I32(i32_content) => {
let random_i32 = match i32_content {
number_content::I32::Range(range) => RandomI32::range(*range)?,
number_content::I32::Categorical(categorical_content) => {
RandomI32::categorical(categorical_content.clone())
}
number_content::I32::Constant(val) => RandomI32::constant(*val),
number_content::I32::Id(id) => {
RandomI32::incrementing(Incrementing::new_at(id.start_at.unwrap_or(1)))
}
};
random_i32.into()
}
Self::F32(f32_content) => {
let random_f32 = match f32_content {
number_content::F32::Range(range) => RandomF32::range(*range)?,
number_content::F32::Constant(val) => RandomF32::constant(*val),
};
random_f32.into()
}
};
Ok(Graph::Number(number_node))
}
}
impl RangeStep<u64> {
pub fn upcast(self, to: NumberContentKind) -> Result<NumberContent> {
match to {
NumberContentKind::U64 => Ok(number_content::U64::Range(self).into()),
NumberContentKind::I64 => {
let cast = self.try_cast(i64::try_from)?;
Ok(number_content::I64::Range(cast).into())
}
NumberContentKind::F64 => {
let cast = self.cast(|value| value as f64);
Ok(number_content::F64::Range(cast).into())
}
}
}
}
impl Categorical<u64> {
pub fn upcast(self, to: NumberContentKind) -> Result<NumberContent> {
match to {
NumberContentKind::U64 => {
Ok(number_content::U64::Categorical(self).into())
}
NumberContentKind::I64 => {
let cast = Categorical {
seen: self
.seen
.into_iter()
.map(|(k, v)| {
i64::try_from(k)
.map(|k_cast| (k_cast, v))
.map_err(|err| err.into())
}).collect::<Result<_>>()?,
total: self.total,
};
Ok(number_content::I64::Categorical(cast).into())
}
NumberContentKind::F64 => Err(failed!(target: Release, "cannot upcast categorical subtypes to accept floats; try changing this another numerical subtype manually"))
}
}
}
impl Id<i64> {
pub fn upcast(self, to: NumberContentKind) -> Result<NumberContent> {
match to {
NumberContentKind::U64 => {
let start_at = self.start_at.unwrap_or(1);
return if start_at < 0 {
Err(failed!(
target: Release,
"cannot cast id with negative start_at to u64"
))
} else {
Ok(number_content::U64::Id(Id {
start_at: Some(start_at as u64),
})
.into())
};
}
NumberContentKind::I64 => Ok(number_content::I64::Id(self).into()),
NumberContentKind::F64 => Err(failed!(target: Release, "cannot cast id f64")),
}
}
}
impl RangeStep<i64> {
pub fn upcast(self, to: NumberContentKind) -> Result<NumberContent> {
match to {
NumberContentKind::U64 => Err(failed!(
target: Release,
"cannot downcast numerical subtypes"
)),
NumberContentKind::I64 => Ok(number_content::I64::Range(self).into()),
NumberContentKind::F64 => {
let cast = self.cast(|value| value as f64);
Ok(number_content::F64::Range(cast).into())
}
}
}
}
impl RangeStep<f64> {
pub fn upcast(self, to: NumberContentKind) -> Result<NumberContent> {
match to {
NumberContentKind::U64 | NumberContentKind::I64 => Err(failed!(
target: Release,
"cannot downcast numerical subtypes"
)),
NumberContentKind::F64 => Ok(number_content::F64::Range(self).into()),
}
}
}
impl Categorical<i64> {
pub fn upcast(self, to: NumberContentKind) -> Result<NumberContent> {
match to {
NumberContentKind::U64 => {
Err(failed!(target: Release, "cannot downcast numerical subtypes"))
}
NumberContentKind::I64 => Ok(number_content::I64::Categorical(self).into()),
NumberContentKind::F64 => Err(failed!(target: Release, "cannot upcast categorical subtypes to accept floats; try changing this another numerical subtype manually")),
}
}
}
impl number_content::U64 {
pub fn upcast(self, to: NumberContentKind) -> Result<NumberContent> {
match self {
Self::Range(range) => range.upcast(to),
Self::Categorical(cat) => cat.upcast(to),
Self::Constant(val) => match to {
NumberContentKind::U64 => Ok(self.into()),
NumberContentKind::I64 => {
let cast = i64::try_from(val)?;
Ok(number_content::I64::Constant(cast).into())
}
NumberContentKind::F64 => {
let cast = val as f64;
Ok(number_content::F64::Constant(cast).into())
}
},
Self::Id(_id) => Err(failed!(
target: Release,
"cannot upcast an id number subtype: only unsigned integers are supported"
)),
}
}
}
impl number_content::I64 {
pub fn upcast(self, to: NumberContentKind) -> Result<NumberContent> {
match self {
Self::Range(range) => range.upcast(to),
Self::Categorical(cat) => cat.upcast(to),
Self::Constant(val) => match to {
NumberContentKind::U64 => Err(failed!(
target: Release,
"cannot downcast numerical subtypes"
)),
NumberContentKind::I64 => Ok(self.into()),
NumberContentKind::F64 => {
let cast = val as f64;
Ok(number_content::F64::Constant(cast).into())
}
},
Self::Id(id) => id.upcast(to),
}
}
}
impl number_content::F64 {
pub fn upcast(self, to: NumberContentKind) -> Result<NumberContent> {
match self {
Self::Range(range) => range.upcast(to),
Self::Constant(_) => match to {
NumberContentKind::U64 => Err(failed!(
target: Release,
"cannot downcast numerical subtypes"
)),
NumberContentKind::I64 => Err(failed!(
target: Release,
"cannot downcast numerical subtypes"
)),
NumberContentKind::F64 => Ok(self.into()),
},
}
}
}
impl Hash for number_content::F32 {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
Self::Range(range) => range.hash(state),
Self::Constant(constant) => constant.to_bits().hash(state),
}
}
}
impl PartialEq for number_content::F32 {
fn eq(&self, other: &number_content::F32) -> bool {
match self {
Self::Range(range) => match other {
Self::Range(o_range) => range == o_range,
_ => false,
},
Self::Constant(constant) => match other {
Self::Constant(o_constant) => constant == o_constant,
_ => false,
},
}
}
}
impl Hash for number_content::F64 {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
Self::Range(range) => range.hash(state),
Self::Constant(constant) => constant.to_bits().hash(state),
}
}
}
impl PartialEq for number_content::F64 {
fn eq(&self, other: &number_content::F64) -> bool {
match self {
Self::Range(range) => match other {
Self::Range(o_range) => range == o_range,
_ => false,
},
Self::Constant(constant) => match other {
Self::Constant(o_constant) => constant == o_constant,
_ => false,
},
}
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use num::One;
// TODO: f32 deserializes successfully to `inf` when OOR
macro_rules! test_number_variants {
($($test:ident -> $name:literal $as:ident: $ty:ty $(,)?)+) => {
$(
#[test]
fn $test() {
// Inferred
let number_content_as_json = json!({
"range": {
"low": <$ty>::MIN,
"high": <$ty>::MAX
}
});
let number_content: NumberContent = serde_json::from_value(number_content_as_json).unwrap();
assert_eq!(
number_content,
NumberContent::$as(number_content::$as::Range(RangeStep {
low: Some(<$ty>::MIN),
high: Some(<$ty>::MAX),
step: None,
..Default::default()
}))
);
// Specified
let number_content_as_json = json!({
"subtype": $name,
"constant": <$ty>::one()
});
let number_content: NumberContent = serde_json::from_value(number_content_as_json).unwrap();
assert_eq!(
number_content,
NumberContent::$as(number_content::$as::Constant(<$ty>::one()))
);
}
)+
}
}
test_number_variants!(
test_u32 -> "u32" U32: u32,
test_u64 -> "u64" U64: u64,
test_i32 -> "i32" I32: i32,
test_i64 -> "i64" I64: i64,
);
}
| 33.391534 | 177 | 0.471756 |
893038efdd3db55d814e439b6f57065eb3505032 | 14,693 | use core::marker::PhantomData;
use core::ops::Deref;
use core::ptr;
use crate::dma::traits::PeriAddress;
use crate::gpio::{Const, NoPin, PinA, PushPull, SetAlternate};
use crate::pac;
/// Clock polarity
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Polarity {
/// Clock signal low when idle
IdleLow,
/// Clock signal high when idle
IdleHigh,
}
/// Clock phase
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Phase {
/// Data in "captured" on the first clock transition
CaptureOnFirstTransition,
/// Data in "captured" on the second clock transition
CaptureOnSecondTransition,
}
/// SPI mode
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Mode {
/// Clock polarity
pub polarity: Polarity,
/// Clock phase
pub phase: Phase,
}
mod hal_02;
mod hal_1;
use crate::pac::{spi1, RCC};
use crate::rcc;
use crate::rcc::Clocks;
use fugit::HertzU32 as Hertz;
/// SPI error
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[non_exhaustive]
pub enum Error {
/// Overrun occurred
Overrun,
/// Mode fault occurred
ModeFault,
/// CRC error
Crc,
}
pub struct Sck;
impl crate::Sealed for Sck {}
pub struct Miso;
impl crate::Sealed for Miso {}
pub struct Mosi;
impl crate::Sealed for Mosi {}
pub struct Nss;
impl crate::Sealed for Nss {}
pub trait Pins<SPI> {
fn set_alt_mode(&mut self);
fn restore_mode(&mut self);
}
impl<SPI, SCK, MISO, MOSI, const SCKA: u8, const MISOA: u8, const MOSIA: u8> Pins<SPI>
for (SCK, MISO, MOSI)
where
SCK: PinA<Sck, SPI, A = Const<SCKA>> + SetAlternate<SCKA, PushPull>,
MISO: PinA<Miso, SPI, A = Const<MISOA>> + SetAlternate<MISOA, PushPull>,
MOSI: PinA<Mosi, SPI, A = Const<MOSIA>> + SetAlternate<MOSIA, PushPull>,
{
fn set_alt_mode(&mut self) {
self.0.set_alt_mode();
self.1.set_alt_mode();
self.2.set_alt_mode();
}
fn restore_mode(&mut self) {
self.0.restore_mode();
self.1.restore_mode();
self.2.restore_mode();
}
}
/// A filler type for when the SCK pin is unnecessary
pub type NoSck = NoPin;
/// A filler type for when the Miso pin is unnecessary
pub type NoMiso = NoPin;
/// A filler type for when the Mosi pin is unnecessary
pub type NoMosi = NoPin;
/// Interrupt events
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum Event {
/// New data has been received
Rxne,
/// Data can be sent
Txe,
/// An error occurred
Error,
}
/// Normal mode - RX and TX pins are independent
pub struct TransferModeNormal;
/// BIDI mode - use TX pin as RX then spi receive data
pub struct TransferModeBidi;
#[derive(Debug)]
pub struct Spi<SPI, PINS, TRANSFER_MODE = TransferModeNormal> {
spi: SPI,
pins: PINS,
_transfer_mode: PhantomData<TRANSFER_MODE>,
}
// Implemented by all SPI instances
pub trait Instance:
crate::Sealed + Deref<Target = spi1::RegisterBlock> + rcc::Enable + rcc::Reset + rcc::BusClock
{
#[doc(hidden)]
fn ptr() -> *const spi1::RegisterBlock;
}
// Implemented by all SPI instances
macro_rules! spi {
($SPI:ty: $Spi:ident) => {
pub type $Spi<PINS, TRANSFER_MODE = TransferModeNormal> = Spi<$SPI, PINS, TRANSFER_MODE>;
impl Instance for $SPI {
fn ptr() -> *const spi1::RegisterBlock {
<$SPI>::ptr() as *const _
}
}
};
}
spi! { pac::SPI1: Spi1 }
spi! { pac::SPI2: Spi2 }
#[cfg(feature = "spi3")]
spi! { pac::SPI3: Spi3 }
#[cfg(feature = "spi4")]
spi! { pac::SPI4: Spi4 }
#[cfg(feature = "spi5")]
spi! { pac::SPI5: Spi5 }
#[cfg(feature = "spi6")]
spi! { pac::SPI6: Spi6 }
pub trait SpiExt: Sized + Instance {
fn spi<SCK, MISO, MOSI>(
self,
pins: (SCK, MISO, MOSI),
mode: impl Into<Mode>,
freq: Hertz,
clocks: &Clocks,
) -> Spi<Self, (SCK, MISO, MOSI), TransferModeNormal>
where
(SCK, MISO, MOSI): Pins<Self>;
fn spi_bidi<SCK, MISO, MOSI>(
self,
pins: (SCK, MISO, MOSI),
mode: impl Into<Mode>,
freq: Hertz,
clocks: &Clocks,
) -> Spi<Self, (SCK, MISO, MOSI), TransferModeBidi>
where
(SCK, MISO, MOSI): Pins<Self>;
}
impl<SPI: Instance> SpiExt for SPI {
fn spi<SCK, MISO, MOSI>(
self,
pins: (SCK, MISO, MOSI),
mode: impl Into<Mode>,
freq: Hertz,
clocks: &Clocks,
) -> Spi<Self, (SCK, MISO, MOSI), TransferModeNormal>
where
(SCK, MISO, MOSI): Pins<Self>,
{
Spi::new(self, pins, mode, freq, clocks)
}
fn spi_bidi<SCK, MISO, MOSI>(
self,
pins: (SCK, MISO, MOSI),
mode: impl Into<Mode>,
freq: Hertz,
clocks: &Clocks,
) -> Spi<Self, (SCK, MISO, MOSI), TransferModeBidi>
where
(SCK, MISO, MOSI): Pins<Self>,
{
Spi::new_bidi(self, pins, mode, freq, clocks)
}
}
impl<SPI: Instance, SCK, MISO, MOSI> Spi<SPI, (SCK, MISO, MOSI), TransferModeNormal> {
pub fn new(
spi: SPI,
mut pins: (SCK, MISO, MOSI),
mode: impl Into<Mode>,
freq: Hertz,
clocks: &Clocks,
) -> Self
where
(SCK, MISO, MOSI): Pins<SPI>,
{
unsafe {
// NOTE(unsafe) this reference will only be used for atomic writes with no side effects.
let rcc = &(*RCC::ptr());
SPI::enable(rcc);
SPI::reset(rcc);
}
pins.set_alt_mode();
Self::_new(spi, pins)
.pre_init(mode.into(), freq, SPI::clock(clocks))
.init()
}
}
impl<SPI: Instance, PINS> Spi<SPI, PINS, TransferModeNormal> {
pub fn init(self) -> Self {
self.spi.cr1.modify(|_, w| {
// bidimode: 2-line unidirectional
w.bidimode()
.clear_bit()
.bidioe()
.clear_bit()
// spe: enable the SPI bus
.spe()
.set_bit()
});
self
}
pub fn to_bidi_transfer_mode(self) -> Spi<SPI, PINS, TransferModeBidi> {
let mut dev_w_new_t_mode = self.into_mode::<TransferModeBidi>();
dev_w_new_t_mode.enable(false);
dev_w_new_t_mode.init()
}
}
impl<SPI: Instance, SCK, MISO, MOSI> Spi<SPI, (SCK, MISO, MOSI), TransferModeBidi> {
pub fn new_bidi(
spi: SPI,
mut pins: (SCK, MISO, MOSI),
mode: impl Into<Mode>,
freq: Hertz,
clocks: &Clocks,
) -> Self
where
(SCK, MISO, MOSI): Pins<SPI>,
{
unsafe {
// NOTE(unsafe) this reference will only be used for atomic writes with no side effects.
let rcc = &(*RCC::ptr());
SPI::enable(rcc);
SPI::reset(rcc);
}
pins.set_alt_mode();
Self::_new(spi, pins)
.pre_init(mode.into(), freq, SPI::clock(clocks))
.init()
}
}
impl<SPI: Instance, PINS> Spi<SPI, PINS, TransferModeBidi> {
pub fn init(self) -> Self {
self.spi.cr1.modify(|_, w| {
// bidimode: 1-line unidirectional
w.bidimode()
.set_bit()
.bidioe()
.set_bit()
// spe: enable the SPI bus
.spe()
.set_bit()
});
self
}
pub fn to_normal_transfer_mode(self) -> Spi<SPI, PINS, TransferModeNormal> {
let mut dev_w_new_t_mode = self.into_mode::<TransferModeNormal>();
dev_w_new_t_mode.enable(false);
dev_w_new_t_mode.init()
}
}
impl<SPI, SCK, MISO, MOSI, TRANSFER_MODE> Spi<SPI, (SCK, MISO, MOSI), TRANSFER_MODE>
where
SPI: Instance,
(SCK, MISO, MOSI): Pins<SPI>,
{
pub fn release(mut self) -> (SPI, (SCK, MISO, MOSI)) {
self.pins.restore_mode();
(self.spi, (self.pins.0, self.pins.1, self.pins.2))
}
}
impl<SPI: Instance, PINS, TRANSFER_MODE> Spi<SPI, PINS, TRANSFER_MODE> {
fn _new(spi: SPI, pins: PINS) -> Self {
Self {
spi,
pins,
_transfer_mode: PhantomData,
}
}
/// Convert the spi to another transfer mode.
fn into_mode<TRANSFER_MODE2>(self) -> Spi<SPI, PINS, TRANSFER_MODE2> {
Spi::_new(self.spi, self.pins)
}
/// Enable/disable spi
pub fn enable(&mut self, enable: bool) {
self.spi.cr1.modify(|_, w| {
// spe: enable the SPI bus
w.spe().bit(enable)
});
}
/// Pre initializing the SPI bus.
fn pre_init(self, mode: Mode, freq: Hertz, clock: Hertz) -> Self {
// disable SS output
self.spi.cr2.write(|w| w.ssoe().clear_bit());
let br = match clock.raw() / freq.raw() {
0 => unreachable!(),
1..=2 => 0b000,
3..=5 => 0b001,
6..=11 => 0b010,
12..=23 => 0b011,
24..=47 => 0b100,
48..=95 => 0b101,
96..=191 => 0b110,
_ => 0b111,
};
self.spi.cr1.write(|w| {
w.cpha()
.bit(mode.phase == Phase::CaptureOnSecondTransition)
.cpol()
.bit(mode.polarity == Polarity::IdleHigh)
// mstr: master configuration
.mstr()
.set_bit()
.br()
.bits(br)
// lsbfirst: MSB first
.lsbfirst()
.clear_bit()
// ssm: enable software slave management (NSS pin free for other uses)
.ssm()
.set_bit()
// ssi: set nss high = master mode
.ssi()
.set_bit()
.rxonly()
.clear_bit()
// dff: 8 bit frames
.dff()
.clear_bit()
});
self
}
/// Enable interrupts for the given `event`:
/// - Received data ready to be read (RXNE)
/// - Transmit data register empty (TXE)
/// - Transfer error
pub fn listen(&mut self, event: Event) {
match event {
Event::Rxne => self.spi.cr2.modify(|_, w| w.rxneie().set_bit()),
Event::Txe => self.spi.cr2.modify(|_, w| w.txeie().set_bit()),
Event::Error => self.spi.cr2.modify(|_, w| w.errie().set_bit()),
}
}
/// Disable interrupts for the given `event`:
/// - Received data ready to be read (RXNE)
/// - Transmit data register empty (TXE)
/// - Transfer error
pub fn unlisten(&mut self, event: Event) {
match event {
Event::Rxne => self.spi.cr2.modify(|_, w| w.rxneie().clear_bit()),
Event::Txe => self.spi.cr2.modify(|_, w| w.txeie().clear_bit()),
Event::Error => self.spi.cr2.modify(|_, w| w.errie().clear_bit()),
}
}
/// Return `true` if the TXE flag is set, i.e. new data to transmit
/// can be written to the SPI.
pub fn is_txe(&self) -> bool {
self.spi.sr.read().txe().bit_is_set()
}
/// Return `true` if the RXNE flag is set, i.e. new data has been received
/// and can be read from the SPI.
pub fn is_rxne(&self) -> bool {
self.spi.sr.read().rxne().bit_is_set()
}
/// Return `true` if the MODF flag is set, i.e. the SPI has experienced a
/// Master Mode Fault. (see chapter 28.3.10 of the STM32F4 Reference Manual)
pub fn is_modf(&self) -> bool {
self.spi.sr.read().modf().bit_is_set()
}
/// Return `true` if the OVR flag is set, i.e. new data has been received
/// while the receive data register was already filled.
pub fn is_ovr(&self) -> bool {
self.spi.sr.read().ovr().bit_is_set()
}
pub fn use_dma(self) -> DmaBuilder<SPI> {
DmaBuilder { spi: self.spi }
}
#[inline(always)]
fn check_read(&mut self) -> nb::Result<u8, Error> {
let sr = self.spi.sr.read();
Err(if sr.ovr().bit_is_set() {
Error::Overrun.into()
} else if sr.modf().bit_is_set() {
Error::ModeFault.into()
} else if sr.crcerr().bit_is_set() {
Error::Crc.into()
} else if sr.rxne().bit_is_set() {
return Ok(self.read_u8());
} else {
nb::Error::WouldBlock
})
}
#[inline(always)]
fn check_send(&mut self, byte: u8) -> nb::Result<(), Error> {
let sr = self.spi.sr.read();
Err(if sr.ovr().bit_is_set() {
// Read from the DR to clear the OVR bit
let _ = self.spi.dr.read();
Error::Overrun.into()
} else if sr.modf().bit_is_set() {
// Write to CR1 to clear MODF
self.spi.cr1.modify(|_r, w| w);
Error::ModeFault.into()
} else if sr.crcerr().bit_is_set() {
// Clear the CRCERR bit
self.spi.sr.modify(|_r, w| {
w.crcerr().clear_bit();
w
});
Error::Crc.into()
} else if sr.txe().bit_is_set() {
self.send_u8(byte);
return Ok(());
} else {
nb::Error::WouldBlock
})
}
#[inline(always)]
fn read_u8(&mut self) -> u8 {
// NOTE(read_volatile) read only 1 byte (the svd2rust API only allows reading a half-word)
unsafe { ptr::read_volatile(&self.spi.dr as *const _ as *const u8) }
}
#[inline(always)]
fn send_u8(&mut self, byte: u8) {
// NOTE(write_volatile) see note above
unsafe { ptr::write_volatile(&self.spi.dr as *const _ as *mut u8, byte) }
}
}
pub struct DmaBuilder<SPI> {
spi: SPI,
}
pub struct Tx<SPI> {
spi: PhantomData<SPI>,
}
pub struct Rx<SPI> {
spi: PhantomData<SPI>,
}
impl<SPI: Instance> DmaBuilder<SPI> {
pub fn tx(self) -> Tx<SPI> {
self.new_tx()
}
pub fn rx(self) -> Rx<SPI> {
self.new_rx()
}
pub fn txrx(self) -> (Tx<SPI>, Rx<SPI>) {
(self.new_tx(), self.new_rx())
}
fn new_tx(&self) -> Tx<SPI> {
self.spi.cr2.modify(|_, w| w.txdmaen().enabled());
Tx { spi: PhantomData }
}
fn new_rx(self) -> Rx<SPI> {
self.spi.cr2.modify(|_, w| w.rxdmaen().enabled());
Rx { spi: PhantomData }
}
}
unsafe impl<SPI: Instance> PeriAddress for Rx<SPI> {
#[inline(always)]
fn address(&self) -> u32 {
unsafe { &(*SPI::ptr()).dr as *const _ as u32 }
}
type MemSize = u8;
}
unsafe impl<SPI: Instance> PeriAddress for Tx<SPI> {
#[inline(always)]
fn address(&self) -> u32 {
unsafe { &(*SPI::ptr()).dr as *const _ as u32 }
}
type MemSize = u8;
}
| 26.910256 | 100 | 0.54121 |
23724689f5204fe19036a52552f7e8a96e160caf | 9,749 | use super::{Location, NodeTypeFlags};
use bp7::canonical::{new_canonical_block, CanonicalBlockType, CanonicalData};
use bp7::{CanonicalBlock, EndpointID};
use derive_try_from_primitive::TryFromPrimitive;
use serde::de::{SeqAccess, Visitor};
use serde::ser::{SerializeSeq, Serializer};
use serde::{de, Deserialize, Deserializer, Serialize};
use std::convert::TryFrom;
use std::fmt;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum LocationError {
#[error("serde cbor error: {0}")]
Cbor(#[from] serde_cbor::Error),
#[error("failed to create endpoint: {0}")]
EndpointIdInvalid(#[from] bp7::eid::EndpointIdError),
#[error("invalid endpoint supplied")]
InvalidEndpoint,
#[error("payload missing")]
PayloadMissing,
#[error("invalid location block")]
InvalidLocationBlock,
}
#[derive(Debug, Clone, PartialEq, TryFromPrimitive, Serialize, Deserialize)]
#[repr(u8)]
pub enum LocationBlockType {
Position = 1,
FenceEllipse = 2,
FenceRect = 3,
Trace = 4,
}
// HOP_COUNT_BLOCK is a BlockType for a Hop Count block as defined in
// section 4.3.3.
pub const LOCATION_BLOCK: CanonicalBlockType = 223;
#[derive(Debug, Clone, PartialEq)]
pub enum LocationBlockData {
Position(NodeTypeFlags, Location),
FenceEllipse(Location, u64, u64),
FenceRect(Location, Location),
Trace(NodeTypeFlags, EndpointID, Location),
}
impl Serialize for LocationBlockData {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
LocationBlockData::Position(info, coords) => {
let mut seq = serializer.serialize_seq(Some(3))?;
seq.serialize_element(&(LocationBlockType::Position as u8))?;
seq.serialize_element(&info.bits())?;
seq.serialize_element(&coords)?;
seq.end()
}
LocationBlockData::FenceEllipse(coords, r1, r2) => {
let mut seq = serializer.serialize_seq(Some(4))?;
seq.serialize_element(&(LocationBlockType::FenceEllipse as u8))?;
seq.serialize_element(&coords)?;
seq.serialize_element(r1)?;
seq.serialize_element(r2)?;
seq.end()
}
LocationBlockData::FenceRect(topleft, bottomright) => {
let mut seq = serializer.serialize_seq(Some(3))?;
seq.serialize_element(&(LocationBlockType::FenceRect as u8))?;
seq.serialize_element(&topleft)?;
seq.serialize_element(&bottomright)?;
seq.end()
}
LocationBlockData::Trace(info, node, coords) => {
let mut seq = serializer.serialize_seq(Some(4))?;
seq.serialize_element(&(LocationBlockType::Trace as u8))?;
seq.serialize_element(&info.bits())?;
seq.serialize_element(&node)?;
seq.serialize_element(&coords)?;
seq.end()
}
}
}
}
impl<'de> Deserialize<'de> for LocationBlockData {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct LocationBlockDataVisitor;
impl<'de> Visitor<'de> for LocationBlockDataVisitor {
type Value = LocationBlockData;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("LocationBlockData")
}
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
let loc_type: u8 = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(0, &self))?;
let loc = LocationBlockType::try_from(loc_type).map_err(|_err| {
de::Error::invalid_value(
serde::de::Unexpected::Unsigned(loc_type.into()),
&self,
)
})?;
match loc {
LocationBlockType::Position => {
let info: NodeTypeFlags = NodeTypeFlags::from_bits(
seq.next_element()?
.ok_or_else(|| de::Error::invalid_length(1, &self))?,
)
.unwrap_or_default();
let coords: Location = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(2, &self))?;
Ok(LocationBlockData::Position(info, coords))
}
LocationBlockType::FenceEllipse => {
let coords: Location = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(1, &self))?;
let r1: u64 = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(2, &self))?;
let r2: u64 = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(3, &self))?;
Ok(LocationBlockData::FenceEllipse(coords, r1, r2))
}
LocationBlockType::FenceRect => {
let topleft: Location = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(1, &self))?;
let bottomright: Location = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(2, &self))?;
Ok(LocationBlockData::FenceRect(topleft, bottomright))
}
LocationBlockType::Trace => {
let info: NodeTypeFlags = NodeTypeFlags::from_bits(
seq.next_element()?
.ok_or_else(|| de::Error::invalid_length(1, &self))?,
)
.unwrap_or_default();
let node: EndpointID = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(2, &self))?;
let coords: Location = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(3, &self))?;
Ok(LocationBlockData::Trace(info, node, coords))
}
}
}
}
deserializer.deserialize_any(LocationBlockDataVisitor)
}
}
pub fn new_location_block(block_number: u64, data: LocationBlockData) -> CanonicalBlock {
new_canonical_block(
LOCATION_BLOCK,
block_number,
0,
CanonicalData::Unknown(serde_cbor::to_vec(&data).unwrap_or_default()),
)
}
pub fn get_location_data(cblock: &CanonicalBlock) -> Result<LocationBlockData, LocationError> {
if cblock.block_type == LOCATION_BLOCK {
if let CanonicalData::Unknown(data) = cblock.data() {
let loc_data =
serde_cbor::from_slice(data).map_err(|_err| LocationError::InvalidLocationBlock);
loc_data
} else {
Err(LocationError::InvalidLocationBlock)
}
} else {
Err(LocationError::InvalidLocationBlock)
}
}
#[cfg(test)]
mod tests {
use crate::location::{
get_location_data, new_location_block, Location, LocationBlockData, NodeTypeFlags,
};
use bp7::bundle::Block;
use bp7::EndpointID;
use std::convert::TryFrom;
#[test]
fn test_locblock_data_position_roundtrip() {
let loc = Location::LatLon((23.0, 42.0));
let data = LocationBlockData::Position(NodeTypeFlags::MOBILE, loc);
let buf = serde_cbor::to_vec(&data).unwrap();
let data2 = serde_cbor::from_slice(&buf).unwrap();
assert_eq!(data, data2);
}
#[test]
fn test_locblock_data_fence_ellipse_roundtrip() {
let loc = Location::LatLon((23.0, 42.0));
let data = LocationBlockData::FenceEllipse(loc, 10, 5);
let buf = serde_cbor::to_vec(&data).unwrap();
let data2 = serde_cbor::from_slice(&buf).unwrap();
assert_eq!(data, data2);
}
#[test]
fn test_locblock_data_fence_rect_roundtrip() {
let loc = Location::LatLon((23.0, 42.0));
let loc2 = Location::LatLon((42.0, 66.0));
let data = LocationBlockData::FenceRect(loc, loc2);
let buf = serde_cbor::to_vec(&data).unwrap();
let data2 = serde_cbor::from_slice(&buf).unwrap();
assert_eq!(data, data2);
}
#[test]
fn test_locblock_data_trace_roundtrip() {
let loc = Location::LatLon((23.0, 42.0));
let data = LocationBlockData::Trace(
NodeTypeFlags::MOBILE,
EndpointID::try_from("dtn://node1").unwrap(),
loc,
);
let buf = serde_cbor::to_vec(&data).unwrap();
let data2 = serde_cbor::from_slice(&buf).unwrap();
assert_eq!(data, data2);
}
#[test]
fn test_cblock_location_roundtrip() {
let loc = Location::LatLon((23.0, 42.0));
let data = LocationBlockData::Position(NodeTypeFlags::MOBILE, loc);
let cblock = new_location_block(1, data.clone());
let buf = cblock.to_cbor();
let cblock2 = serde_cbor::from_slice(&buf).unwrap();
assert_eq!(cblock, cblock2);
let data2 = get_location_data(&cblock2).unwrap();
assert_eq!(data, data2);
}
}
| 38.38189 | 97 | 0.541286 |
722681c4064698c33bd56e0768078ed37f7171b6 | 3,526 | #![allow(clippy::module_inception)]
#![allow(clippy::upper_case_acronyms)]
#![allow(clippy::large_enum_variant)]
#![allow(clippy::wrong_self_convention)]
#![allow(clippy::should_implement_trait)]
#![allow(clippy::blacklisted_name)]
#![allow(clippy::vec_init_then_push)]
#![allow(clippy::type_complexity)]
#![allow(rustdoc::bare_urls)]
#![warn(missing_docs)]
//! <p>Amazon CloudWatch monitors your Amazon Web Services (Amazon Web Services) resources and the
//! applications you run on Amazon Web Services in real time. You can use CloudWatch to collect and track
//! metrics, which are the variables you want to measure for your resources and
//! applications.</p>
//!
//! <p>CloudWatch alarms send notifications or automatically change the resources you are monitoring based on rules
//! that you define. For example, you can monitor the CPU usage and disk reads and writes of your Amazon EC2
//! instances. Then, use this data to determine whether you should launch
//! additional instances to handle increased load. You can also use this data to stop
//! under-used instances to save
//! money.</p>
//!
//! <p>In addition to monitoring the built-in metrics that come with Amazon Web Services, you can monitor
//! your own custom metrics. With CloudWatch, you gain system-wide visibility into resource
//! utilization, application performance, and operational health.</p>
//!
//! # Crate Organization
//!
//! The entry point for most customers will be [`Client`]. [`Client`] exposes one method for each API offered
//! by the service.
//!
//! Some APIs require complex or nested arguments. These exist in [`model`](crate::model).
//!
//! Lastly, errors that can be returned by the service are contained within [`error`]. [`Error`] defines a meta
//! error encompassing all possible errors that can be returned by the service.
//!
//! The other modules within this crate are not required for normal usage.
//!
//! # Examples
//! Examples can be found [here](https://github.com/awslabs/aws-sdk-rust/tree/main/examples/cloudwatch).
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub use error_meta::Error;
#[doc(inline)]
pub use config::Config;
mod aws_endpoint;
/// Client and fluent builders for calling the service.
pub mod client;
/// Configuration for the service.
pub mod config;
/// Errors that can occur when calling the service.
pub mod error;
mod error_meta;
/// Input structures for operations.
pub mod input;
/// Generated accessors for nested fields
pub mod lens;
pub mod middleware;
/// Data structures used by operation inputs/outputs.
pub mod model;
mod no_credentials;
/// All operations that this crate can perform.
pub mod operation;
mod operation_deser;
mod operation_ser;
/// Output structures for operations.
pub mod output;
/// Paginators for the service
pub mod paginator;
mod query_ser;
mod rest_xml_wrapped_errors;
mod xml_deser;
/// Crate version number.
pub static PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
/// Re-exported types from supporting crates.
pub mod types {
pub use aws_smithy_http::result::SdkError;
pub use aws_smithy_types::Blob;
pub use aws_smithy_types::DateTime;
}
static API_METADATA: aws_http::user_agent::ApiMetadata =
aws_http::user_agent::ApiMetadata::new("cloudwatch", PKG_VERSION);
pub use aws_smithy_http::endpoint::Endpoint;
pub use aws_smithy_types::retry::RetryConfig;
pub use aws_types::app_name::AppName;
pub use aws_types::region::Region;
pub use aws_types::Credentials;
#[doc(inline)]
pub use client::Client;
| 38.326087 | 115 | 0.753829 |
8a487c374f9d31dc9a28b4a77256b366f141825c | 3,782 | use super::{helpers, helpers::render as tools, workflow::store::Store};
use std::{
fs,
path::{Path, PathBuf},
};
mod templates {
pub const MODULE: &str = r#"#![allow(dead_code)]
pub mod identification;
use super::{producer, protocol};
use log::error;
use thiserror::Error;
use tokio::sync::mpsc::{error::SendError, UnboundedSender};
use uuid::Uuid;
#[derive(Error, Debug)]
pub enum ConsumerError {
#[error("fail to read buffer: `{0:?}`")]
Reading(protocol::ReadError),
}
pub type ConsumerMessages = Vec<(protocol::AvailableMessages, protocol::PackageHeader)>;
pub struct Consumer {
uuid: Uuid,
buffer: protocol::Buffer<protocol::AvailableMessages>,
identification: identification::Identification,
hash_accepted: bool,
confirmed: bool,
}
impl Consumer {
pub fn new(
uuid: Uuid,
options: &producer::Options,
tx_ident_change: UnboundedSender<identification::IdentificationChannel>,
) -> Self {
Self {
uuid,
buffer: protocol::Buffer::new(),
identification: identification::Identification::new(uuid, options, tx_ident_change),
hash_accepted: false,
confirmed: false,
}
}
pub fn accept_hash(&mut self) {
self.hash_accepted = true;
}
pub fn is_hash_accepted(&self) -> bool {
self.hash_accepted
}
pub fn is_confirmed(&self) -> bool {
self.confirmed
}
pub fn confirm(&mut self) {
self.confirmed = true;
}
pub fn get_uuid(&self) -> Uuid {
self.uuid
}
pub fn get_identification(&self) -> &identification::Identification {
&self.identification
}
pub fn get_mut_identification(&mut self) -> &mut identification::Identification {
&mut self.identification
}
pub fn key(&mut self, key: &protocol::[[self_key]], overwrite: bool) -> String {
self.identification.key(key.clone(), overwrite);
self.uuid.to_string()
}
pub fn assign(&mut self, key: protocol::[[assign_key]], overwrite: bool) {
self.identification.assign(key, overwrite);
}
#[allow(clippy::ptr_arg)]
pub fn chunk(&mut self, buffer: &Vec<u8>) -> Result<(), ConsumerError> {
self.buffer
.chunk(buffer, Some(self.uuid.to_string()))
.map_err(ConsumerError::Reading)
}
pub fn get_messages(&mut self) -> ConsumerMessages {
let mut msgs: ConsumerMessages = vec![];
while let Some(msg) = self.buffer.next() {
msgs.push((msg.msg, msg.header));
}
msgs
}
}"#;
}
pub struct Render {}
impl Default for Render {
fn default() -> Self {
Self::new()
}
}
impl Render {
pub fn new() -> Self {
Self {}
}
pub fn render(&self, base: &Path, store: &Store) -> Result<(), String> {
let dest: PathBuf = self.get_dest_file(base)?;
let mut output = templates::MODULE.to_owned();
output = output.replace(
"[[assign_key]]",
&tools::into_rust_path(&store.get_config()?.get_assigned()?),
);
output = output.replace(
"[[self_key]]",
&tools::into_rust_path(&store.get_config()?.get_self()?),
);
helpers::fs::write(dest, output, true)
}
fn get_dest_file(&self, base: &Path) -> Result<PathBuf, String> {
let dest = base.join("implementation").join("consumer");
if !dest.exists() {
if let Err(e) = fs::create_dir_all(&dest) {
return Err(format!(
"Fail to create dest folder {}. Error: {}",
dest.to_string_lossy(),
e
));
}
}
Ok(dest.join("mod.rs"))
}
}
| 26.263889 | 96 | 0.575621 |
f8837d3b43052f0d4b28b371a70a9b657531607e | 5,122 | //! The `packet` module defines data structures and methods to pull data from the network.
use crate::recvmmsg::{recv_mmsg, NUM_RCVMMSGS};
pub use solana_perf::packet::{
limited_deserialize, to_packets_chunked, Packets, PacketsRecycler, NUM_PACKETS,
PACKETS_PER_BATCH,
};
use solana_metrics::inc_new_counter_debug;
pub use solana_sdk::packet::{Meta, Packet, PACKET_DATA_SIZE};
use std::{io::Result, net::UdpSocket, time::Instant};
pub fn recv_from(obj: &mut Packets, socket: &UdpSocket, max_wait_ms: u64) -> Result<usize> {
let mut i = 0;
//DOCUMENTED SIDE-EFFECT
//Performance out of the IO without poll
// * block on the socket until it's readable
// * set the socket to non blocking
// * read until it fails
// * set it back to blocking before returning
socket.set_nonblocking(false)?;
trace!("receiving on {}", socket.local_addr().unwrap());
let start = Instant::now();
loop {
obj.packets.resize(
std::cmp::min(i + NUM_RCVMMSGS, PACKETS_PER_BATCH),
Packet::default(),
);
match recv_mmsg(socket, &mut obj.packets[i..]) {
Err(_) if i > 0 => {
if start.elapsed().as_millis() as u64 > max_wait_ms {
break;
}
}
Err(e) => {
trace!("recv_from err {:?}", e);
return Err(e);
}
Ok((_, npkts)) => {
if i == 0 {
socket.set_nonblocking(true)?;
}
trace!("got {} packets", npkts);
i += npkts;
// Try to batch into big enough buffers
// will cause less re-shuffling later on.
if start.elapsed().as_millis() as u64 > max_wait_ms || i >= PACKETS_PER_BATCH {
break;
}
}
}
}
obj.packets.truncate(i);
inc_new_counter_debug!("packets-recv_count", i);
Ok(i)
}
pub fn send_to(obj: &Packets, socket: &UdpSocket) -> Result<()> {
for p in &obj.packets {
let a = p.meta.addr();
socket.send_to(&p.data[..p.meta.size], &a)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::io;
use std::io::Write;
use std::net::{SocketAddr, UdpSocket};
#[test]
fn test_packets_set_addr() {
// test that the address is actually being updated
let send_addr: SocketAddr = "127.0.0.1:123".parse().unwrap();
let packets = vec![Packet::default()];
let mut msgs = Packets::new(packets);
msgs.set_addr(&send_addr);
assert_eq!(msgs.packets[0].meta.addr(), send_addr);
}
#[test]
pub fn packet_send_recv() {
solana_logger::setup();
let recv_socket = UdpSocket::bind("127.0.0.1:0").expect("bind");
let addr = recv_socket.local_addr().unwrap();
let send_socket = UdpSocket::bind("127.0.0.1:0").expect("bind");
let saddr = send_socket.local_addr().unwrap();
let mut p = Packets::default();
p.packets.resize(10, Packet::default());
for m in p.packets.iter_mut() {
m.meta.set_addr(&addr);
m.meta.size = PACKET_DATA_SIZE;
}
send_to(&p, &send_socket).unwrap();
let recvd = recv_from(&mut p, &recv_socket, 1).unwrap();
assert_eq!(recvd, p.packets.len());
for m in &p.packets {
assert_eq!(m.meta.size, PACKET_DATA_SIZE);
assert_eq!(m.meta.addr(), saddr);
}
}
#[test]
pub fn debug_trait() {
write!(io::sink(), "{:?}", Packet::default()).unwrap();
write!(io::sink(), "{:?}", Packets::default()).unwrap();
}
#[test]
fn test_packet_partial_eq() {
let mut p1 = Packet::default();
let mut p2 = Packet::default();
p1.meta.size = 1;
p1.data[0] = 0;
p2.meta.size = 1;
p2.data[0] = 0;
assert!(p1 == p2);
p2.data[0] = 4;
assert!(p1 != p2);
}
#[test]
fn test_packet_resize() {
solana_logger::setup();
let recv_socket = UdpSocket::bind("127.0.0.1:0").expect("bind");
let addr = recv_socket.local_addr().unwrap();
let send_socket = UdpSocket::bind("127.0.0.1:0").expect("bind");
let mut p = Packets::default();
p.packets.resize(PACKETS_PER_BATCH, Packet::default());
// Should only get PACKETS_PER_BATCH packets per iteration even
// if a lot more were sent, and regardless of packet size
for _ in 0..2 * PACKETS_PER_BATCH {
let mut p = Packets::default();
p.packets.resize(1, Packet::default());
for m in p.packets.iter_mut() {
m.meta.set_addr(&addr);
m.meta.size = 1;
}
send_to(&p, &send_socket).unwrap();
}
let recvd = recv_from(&mut p, &recv_socket, 100).unwrap();
// Check we only got PACKETS_PER_BATCH packets
assert_eq!(recvd, PACKETS_PER_BATCH);
assert_eq!(p.packets.capacity(), PACKETS_PER_BATCH);
}
}
| 32.0125 | 95 | 0.547442 |
ed473da19176b3c1378eff1301c705b7f5335ad4 | 24,982 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Reduced graph building
//!
//! Here we build the "reduced graph": the graph of the module tree without
//! any imports resolved.
use resolve_imports::ImportDirectiveSubclass::{self, GlobImport};
use Module;
use Namespace::{self, TypeNS, ValueNS};
use {NameBinding, NameBindingKind};
use ParentLink::{ModuleParentLink, BlockParentLink};
use Resolver;
use {resolve_error, resolve_struct_error, ResolutionError};
use rustc::middle::cstore::{CrateStore, ChildItem, DlDef};
use rustc::lint;
use rustc::hir::def::*;
use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
use rustc::ty::{self, VariantKind};
use syntax::ast::{Name, NodeId};
use syntax::attr::AttrMetaMethods;
use syntax::parse::token::keywords;
use syntax::codemap::{Span, DUMMY_SP};
use rustc::hir;
use rustc::hir::{Block, DeclItem};
use rustc::hir::{ForeignItem, ForeignItemFn, ForeignItemStatic};
use rustc::hir::{Item, ItemConst, ItemEnum, ItemExternCrate, ItemFn};
use rustc::hir::{ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
use rustc::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
use rustc::hir::{PathListIdent, PathListMod, StmtDecl};
use rustc::hir::{Variant, ViewPathGlob, ViewPathList, ViewPathSimple};
use rustc::hir::intravisit::{self, Visitor};
trait ToNameBinding<'a> {
fn to_name_binding(self) -> NameBinding<'a>;
}
impl<'a> ToNameBinding<'a> for (Module<'a>, Span) {
fn to_name_binding(self) -> NameBinding<'a> {
NameBinding::create_from_module(self.0, Some(self.1))
}
}
impl<'a> ToNameBinding<'a> for (Def, Span, ty::Visibility) {
fn to_name_binding(self) -> NameBinding<'a> {
NameBinding { kind: NameBindingKind::Def(self.0), span: Some(self.1), vis: self.2 }
}
}
impl<'b, 'tcx:'b> Resolver<'b, 'tcx> {
/// Constructs the reduced graph for the entire crate.
pub fn build_reduced_graph(&mut self, krate: &hir::Crate) {
let mut visitor = BuildReducedGraphVisitor {
parent: self.graph_root,
resolver: self,
};
intravisit::walk_crate(&mut visitor, krate);
}
/// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined.
fn try_define<T>(&self, parent: Module<'b>, name: Name, ns: Namespace, def: T)
where T: ToNameBinding<'b>
{
let _ = parent.try_define_child(name, ns, def.to_name_binding());
}
/// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
/// otherwise, reports an error.
fn define<T: ToNameBinding<'b>>(&self, parent: Module<'b>, name: Name, ns: Namespace, def: T) {
let binding = def.to_name_binding();
if let Err(old_binding) = parent.try_define_child(name, ns, binding.clone()) {
self.report_conflict(parent, name, ns, old_binding, &binding);
}
}
fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
fn is_item(statement: &hir::Stmt) -> bool {
if let StmtDecl(ref declaration, _) = statement.node {
if let DeclItem(_) = declaration.node {
return true;
}
}
false
}
// If any statements are items, we need to create an anonymous module
block.stmts.iter().any(is_item)
}
fn sanity_check_import(&self, view_path: &hir::ViewPath, id: NodeId) {
let path = match view_path.node {
ViewPathSimple(_, ref path) |
ViewPathGlob (ref path) |
ViewPathList(ref path, _) => path
};
// Check for type parameters
let found_param = path.segments.iter().any(|segment| {
!segment.parameters.types().is_empty() ||
!segment.parameters.lifetimes().is_empty() ||
!segment.parameters.bindings().is_empty()
});
if found_param {
self.session.span_err(path.span, "type or lifetime parameters in import path");
}
// Checking for special identifiers in path
// prevent `self` or `super` at beginning of global path
if path.global && path.segments.len() > 0 {
let first = path.segments[0].identifier.name;
if first == keywords::Super.name() || first == keywords::SelfValue.name() {
self.session.add_lint(
lint::builtin::SUPER_OR_SELF_IN_GLOBAL_PATH, id, path.span,
format!("expected identifier, found keyword `{}`", first)
);
}
}
}
/// Constructs the reduced graph for one item.
fn build_reduced_graph_for_item(&mut self, item: &Item, parent_ref: &mut Module<'b>) {
let parent = *parent_ref;
let name = item.name;
let sp = item.span;
self.current_module = parent;
let vis = self.resolve_visibility(&item.vis);
match item.node {
ItemUse(ref view_path) => {
// Extract and intern the module part of the path. For
// globs and lists, the path is found directly in the AST;
// for simple paths we have to munge the path a little.
let module_path: Vec<Name> = match view_path.node {
ViewPathSimple(_, ref full_path) => {
full_path.segments
.split_last()
.unwrap()
.1
.iter()
.map(|seg| seg.identifier.name)
.collect()
}
ViewPathGlob(ref module_ident_path) |
ViewPathList(ref module_ident_path, _) => {
module_ident_path.segments
.iter()
.map(|seg| seg.identifier.name)
.collect()
}
};
self.sanity_check_import(view_path, item.id);
// Build up the import directives.
let is_prelude = item.attrs.iter().any(|attr| attr.name() == "prelude_import");
match view_path.node {
ViewPathSimple(binding, ref full_path) => {
let source_name = full_path.segments.last().unwrap().identifier.name;
if source_name.as_str() == "mod" || source_name.as_str() == "self" {
resolve_error(self,
view_path.span,
ResolutionError::SelfImportsOnlyAllowedWithin);
}
let subclass = ImportDirectiveSubclass::single(binding, source_name);
let span = view_path.span;
parent.add_import_directive(module_path, subclass, span, item.id, vis);
self.unresolved_imports += 1;
}
ViewPathList(_, ref source_items) => {
// Make sure there's at most one `mod` import in the list.
let mod_spans = source_items.iter()
.filter_map(|item| {
match item.node {
PathListMod { .. } => Some(item.span),
_ => None,
}
})
.collect::<Vec<Span>>();
if mod_spans.len() > 1 {
let mut e = resolve_struct_error(self,
mod_spans[0],
ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
for other_span in mod_spans.iter().skip(1) {
e.span_note(*other_span, "another `self` import appears here");
}
e.emit();
}
for source_item in source_items {
let (module_path, name, rename) = match source_item.node {
PathListIdent { name, rename, .. } =>
(module_path.clone(), name, rename.unwrap_or(name)),
PathListMod { rename, .. } => {
let name = match module_path.last() {
Some(name) => *name,
None => {
resolve_error(
self,
source_item.span,
ResolutionError::
SelfImportOnlyInImportListWithNonEmptyPrefix
);
continue;
}
};
let module_path = module_path.split_last().unwrap().1;
let rename = rename.unwrap_or(name);
(module_path.to_vec(), name, rename)
}
};
let subclass = ImportDirectiveSubclass::single(rename, name);
let (span, id) = (source_item.span, source_item.node.id());
parent.add_import_directive(module_path, subclass, span, id, vis);
self.unresolved_imports += 1;
}
}
ViewPathGlob(_) => {
let subclass = GlobImport { is_prelude: is_prelude };
let span = view_path.span;
parent.add_import_directive(module_path, subclass, span, item.id, vis);
self.unresolved_imports += 1;
}
}
}
ItemExternCrate(_) => {
// n.b. we don't need to look at the path option here, because cstore already
// did
if let Some(crate_id) = self.session.cstore.extern_mod_stmt_cnum(item.id) {
let def_id = DefId {
krate: crate_id,
index: CRATE_DEF_INDEX,
};
let parent_link = ModuleParentLink(parent, name);
let def = Def::Mod(def_id);
let module = self.new_extern_crate_module(parent_link, def, vis, item.id);
self.define(parent, name, TypeNS, (module, sp));
self.build_reduced_graph_for_external_crate(module);
}
}
ItemMod(..) => {
let parent_link = ModuleParentLink(parent, name);
let def = Def::Mod(self.ast_map.local_def_id(item.id));
let module = self.new_module(parent_link, Some(def), false, vis);
self.define(parent, name, TypeNS, (module, sp));
self.module_map.insert(item.id, module);
*parent_ref = module;
}
ItemForeignMod(..) => {}
// These items live in the value namespace.
ItemStatic(_, m, _) => {
let mutbl = m == hir::MutMutable;
let def = Def::Static(self.ast_map.local_def_id(item.id), mutbl);
self.define(parent, name, ValueNS, (def, sp, vis));
}
ItemConst(_, _) => {
let def = Def::Const(self.ast_map.local_def_id(item.id));
self.define(parent, name, ValueNS, (def, sp, vis));
}
ItemFn(_, _, _, _, _, _) => {
let def = Def::Fn(self.ast_map.local_def_id(item.id));
self.define(parent, name, ValueNS, (def, sp, vis));
}
// These items live in the type namespace.
ItemTy(..) => {
let def = Def::TyAlias(self.ast_map.local_def_id(item.id));
self.define(parent, name, TypeNS, (def, sp, vis));
}
ItemEnum(ref enum_definition, _) => {
let parent_link = ModuleParentLink(parent, name);
let def = Def::Enum(self.ast_map.local_def_id(item.id));
let module = self.new_module(parent_link, Some(def), false, vis);
self.define(parent, name, TypeNS, (module, sp));
for variant in &(*enum_definition).variants {
let item_def_id = self.ast_map.local_def_id(item.id);
self.build_reduced_graph_for_variant(variant, item_def_id, module);
}
}
// These items live in both the type and value namespaces.
ItemStruct(ref struct_def, _) => {
// Define a name in the type namespace.
let def = Def::Struct(self.ast_map.local_def_id(item.id));
self.define(parent, name, TypeNS, (def, sp, vis));
// If this is a newtype or unit-like struct, define a name
// in the value namespace as well
if !struct_def.is_struct() {
let def = Def::Struct(self.ast_map.local_def_id(struct_def.id()));
self.define(parent, name, ValueNS, (def, sp, vis));
}
// Record the def ID and fields of this struct.
let field_names = struct_def.fields().iter().map(|field| {
self.resolve_visibility(&field.vis);
field.name
}).collect();
let item_def_id = self.ast_map.local_def_id(item.id);
self.structs.insert(item_def_id, field_names);
}
ItemDefaultImpl(_, _) | ItemImpl(..) => {}
ItemTrait(_, _, _, ref items) => {
let def_id = self.ast_map.local_def_id(item.id);
// Add all the items within to a new module.
let parent_link = ModuleParentLink(parent, name);
let def = Def::Trait(def_id);
let module_parent = self.new_module(parent_link, Some(def), false, vis);
self.define(parent, name, TypeNS, (module_parent, sp));
// Add the names of all the items to the trait info.
for item in items {
let item_def_id = self.ast_map.local_def_id(item.id);
let (def, ns) = match item.node {
hir::ConstTraitItem(..) => (Def::AssociatedConst(item_def_id), ValueNS),
hir::MethodTraitItem(..) => (Def::Method(item_def_id), ValueNS),
hir::TypeTraitItem(..) => (Def::AssociatedTy(def_id, item_def_id), TypeNS),
};
self.define(module_parent, item.name, ns, (def, item.span, vis));
self.trait_item_map.insert((item.name, def_id), item_def_id);
}
}
}
}
// Constructs the reduced graph for one variant. Variants exist in the
// type and value namespaces.
fn build_reduced_graph_for_variant(&mut self,
variant: &Variant,
item_id: DefId,
parent: Module<'b>) {
let name = variant.node.name;
if variant.node.data.is_struct() {
// Not adding fields for variants as they are not accessed with a self receiver
let variant_def_id = self.ast_map.local_def_id(variant.node.data.id());
self.structs.insert(variant_def_id, Vec::new());
}
// Variants are always treated as importable to allow them to be glob used.
// All variants are defined in both type and value namespaces as future-proofing.
let def = Def::Variant(item_id, self.ast_map.local_def_id(variant.node.data.id()));
self.define(parent, name, ValueNS, (def, variant.span, parent.vis));
self.define(parent, name, TypeNS, (def, variant.span, parent.vis));
}
/// Constructs the reduced graph for one foreign item.
fn build_reduced_graph_for_foreign_item(&mut self,
foreign_item: &ForeignItem,
parent: Module<'b>) {
let name = foreign_item.name;
let def = match foreign_item.node {
ForeignItemFn(..) => {
Def::Fn(self.ast_map.local_def_id(foreign_item.id))
}
ForeignItemStatic(_, m) => {
Def::Static(self.ast_map.local_def_id(foreign_item.id), m)
}
};
self.current_module = parent;
let vis = self.resolve_visibility(&foreign_item.vis);
self.define(parent, name, ValueNS, (def, foreign_item.span, vis));
}
fn build_reduced_graph_for_block(&mut self, block: &Block, parent: &mut Module<'b>) {
if self.block_needs_anonymous_module(block) {
let block_id = block.id;
debug!("(building reduced graph for block) creating a new anonymous module for block \
{}",
block_id);
let parent_link = BlockParentLink(parent, block_id);
let new_module = self.new_module(parent_link, None, false, parent.vis);
self.module_map.insert(block_id, new_module);
*parent = new_module;
}
}
/// Builds the reduced graph for a single item in an external crate.
fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'b>, xcdef: ChildItem) {
let def = match xcdef.def {
DlDef(def) => def,
_ => return,
};
if let Def::ForeignMod(def_id) = def {
// Foreign modules have no names. Recur and populate eagerly.
for child in self.session.cstore.item_children(def_id) {
self.build_reduced_graph_for_external_crate_def(parent, child);
}
return;
}
let name = xcdef.name;
let vis = if parent.is_trait() { ty::Visibility::Public } else { xcdef.vis };
match def {
Def::Mod(_) | Def::ForeignMod(_) | Def::Enum(..) => {
debug!("(building reduced graph for external crate) building module {} {:?}",
name, vis);
let parent_link = ModuleParentLink(parent, name);
let module = self.new_module(parent_link, Some(def), true, vis);
self.try_define(parent, name, TypeNS, (module, DUMMY_SP));
}
Def::Variant(_, variant_id) => {
debug!("(building reduced graph for external crate) building variant {}", name);
// Variants are always treated as importable to allow them to be glob used.
// All variants are defined in both type and value namespaces as future-proofing.
self.try_define(parent, name, TypeNS, (def, DUMMY_SP, vis));
self.try_define(parent, name, ValueNS, (def, DUMMY_SP, vis));
if self.session.cstore.variant_kind(variant_id) == Some(VariantKind::Struct) {
// Not adding fields for variants as they are not accessed with a self receiver
self.structs.insert(variant_id, Vec::new());
}
}
Def::Fn(..) |
Def::Static(..) |
Def::Const(..) |
Def::AssociatedConst(..) |
Def::Method(..) => {
debug!("(building reduced graph for external crate) building value (fn/static) {}",
name);
self.try_define(parent, name, ValueNS, (def, DUMMY_SP, vis));
}
Def::Trait(def_id) => {
debug!("(building reduced graph for external crate) building type {}", name);
// If this is a trait, add all the trait item names to the trait
// info.
let trait_item_def_ids = self.session.cstore.trait_item_def_ids(def_id);
for trait_item_def in &trait_item_def_ids {
let trait_item_name =
self.session.cstore.item_name(trait_item_def.def_id());
debug!("(building reduced graph for external crate) ... adding trait item \
'{}'",
trait_item_name);
self.trait_item_map.insert((trait_item_name, def_id), trait_item_def.def_id());
}
let parent_link = ModuleParentLink(parent, name);
let module = self.new_module(parent_link, Some(def), true, vis);
self.try_define(parent, name, TypeNS, (module, DUMMY_SP));
}
Def::TyAlias(..) | Def::AssociatedTy(..) => {
debug!("(building reduced graph for external crate) building type {}", name);
self.try_define(parent, name, TypeNS, (def, DUMMY_SP, vis));
}
Def::Struct(def_id)
if self.session.cstore.tuple_struct_definition_if_ctor(def_id).is_none() => {
debug!("(building reduced graph for external crate) building type and value for {}",
name);
self.try_define(parent, name, TypeNS, (def, DUMMY_SP, vis));
if let Some(ctor_def_id) = self.session.cstore.struct_ctor_def_id(def_id) {
let def = Def::Struct(ctor_def_id);
self.try_define(parent, name, ValueNS, (def, DUMMY_SP, vis));
}
// Record the def ID and fields of this struct.
let fields = self.session.cstore.struct_field_names(def_id);
self.structs.insert(def_id, fields);
}
Def::Struct(..) => {}
Def::Local(..) |
Def::PrimTy(..) |
Def::TyParam(..) |
Def::Upvar(..) |
Def::Label(..) |
Def::SelfTy(..) |
Def::Err => {
bug!("didn't expect `{:?}`", def);
}
}
}
/// Builds the reduced graph rooted at the 'use' directive for an external
/// crate.
fn build_reduced_graph_for_external_crate(&mut self, root: Module<'b>) {
let root_cnum = root.def_id().unwrap().krate;
for child in self.session.cstore.crate_top_level_items(root_cnum) {
self.build_reduced_graph_for_external_crate_def(root, child);
}
}
/// Ensures that the reduced graph rooted at the given external module
/// is built, building it if it is not.
pub fn populate_module_if_necessary(&mut self, module: Module<'b>) {
if module.populated.get() { return }
for child in self.session.cstore.item_children(module.def_id().unwrap()) {
self.build_reduced_graph_for_external_crate_def(module, child);
}
module.populated.set(true)
}
}
struct BuildReducedGraphVisitor<'a, 'b: 'a, 'tcx: 'b> {
resolver: &'a mut Resolver<'b, 'tcx>,
parent: Module<'b>,
}
impl<'a, 'b, 'v, 'tcx> Visitor<'v> for BuildReducedGraphVisitor<'a, 'b, 'tcx> {
fn visit_nested_item(&mut self, item: hir::ItemId) {
self.visit_item(self.resolver.ast_map.expect_item(item.id))
}
fn visit_item(&mut self, item: &Item) {
let old_parent = self.parent;
self.resolver.build_reduced_graph_for_item(item, &mut self.parent);
intravisit::walk_item(self, item);
self.parent = old_parent;
}
fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
self.resolver.build_reduced_graph_for_foreign_item(foreign_item, &self.parent);
}
fn visit_block(&mut self, block: &Block) {
let old_parent = self.parent;
self.resolver.build_reduced_graph_for_block(block, &mut self.parent);
intravisit::walk_block(self, block);
self.parent = old_parent;
}
}
| 45.257246 | 100 | 0.521936 |
e9517504dcea57b60e22785e087405df9f97bc35 | 2,179 | #[allow(unused)]
use vizia::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
use vizia_core::resource::ImageRetentionPolicy;
#[allow(unused)]
const STYLE: &'static str = r#"
element {
background-image: "sample.png";
width: 1s;
height: 1s;
}
"#;
#[cfg(target_arch = "wasm32")]
fn main() {
panic!("This example is not supported on wasm - threads are experimental");
}
#[cfg(not(target_arch = "wasm32"))]
fn main() {
Application::new(|cx| {
cx.add_theme(STYLE);
cx.set_image_loader(|cx, path| {
if path.starts_with("https://") {
let path = path.to_string();
cx.spawn(move |cx| {
let data = reqwest::blocking::get(&path).unwrap().bytes().unwrap();
cx.load_image(
path.clone(),
image::load_from_memory_with_format(
&data,
image::guess_format(&data).unwrap(),
)
.unwrap(),
ImageRetentionPolicy::DropWhenUnusedForOneFrame,
)
.unwrap();
});
} else if path == "sample.png" {
cx.load_image(
path.to_owned(),
image::load_from_memory_with_format(
include_bytes!("../resources/sample-hut-400x300.png"),
image::ImageFormat::Png,
)
.unwrap(),
ImageRetentionPolicy::DropWhenUnusedForOneFrame,
);
} else {
panic!();
}
});
Label::new(cx, "Any view can be styled with a background image. An Image view can be used to present a non-tiling background image.")
.width(Stretch(1.0))
.position_type(PositionType::SelfDirected)
.space(Pixels(10.0));
Element::new(cx);
Image::new(cx, "https://download.samplelib.com/png/sample-bumblebee-400x300.png");
Label::new(cx, "Wait for the image to load :)");
})
.title("Image")
.run()
}
| 32.522388 | 141 | 0.486921 |
ac2d7ede12eef15700c94052dca622c552ac4979 | 73,195 | #![doc = "generated by AutoRust"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::de::{value, Deserializer, IntoDeserializer};
use serde::{Deserialize, Serialize, Serializer};
use std::str::FromStr;
#[doc = "Represents a recommendation action advisor."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Advisor {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "The properties of a recommendation action advisor."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AdvisorProperties>,
}
impl Advisor {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The properties of a recommendation action advisor."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct AdvisorProperties {}
impl AdvisorProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of query statistics."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct AdvisorsResultList {
#[doc = "The list of recommendation action advisors."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Advisor>,
#[doc = "Link to retrieve next page of results."]
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl azure_core::Continuable for AdvisorsResultList {
fn continuation(&self) -> Option<String> {
self.next_link.clone()
}
}
impl AdvisorsResultList {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "An error response from the Batch service."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct CloudError {
#[doc = "An error response from the Batch service."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<CloudErrorBody>,
}
impl azure_core::Continuable for CloudError {
fn continuation(&self) -> Option<String> {
None
}
}
impl CloudError {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "An error response from the Batch service."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct CloudErrorBody {
#[doc = "An identifier for the error. Codes are invariant and are intended to be consumed programmatically."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[doc = "A message describing the error, intended to be suitable for display in a user interface."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[doc = "The target of the particular error. For example, the name of the property in error."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[doc = "A list of additional details about the error."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<CloudErrorBody>,
}
impl CloudErrorBody {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Represents a Configuration."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Configuration {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "The properties of a configuration."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ConfigurationProperties>,
}
impl Configuration {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of server configurations."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ConfigurationListResult {
#[doc = "The list of server configurations."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Configuration>,
}
impl azure_core::Continuable for ConfigurationListResult {
fn continuation(&self) -> Option<String> {
None
}
}
impl ConfigurationListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The properties of a configuration."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ConfigurationProperties {
#[doc = "Value of the configuration."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[doc = "Description of the configuration."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[doc = "Default value of the configuration."]
#[serde(rename = "defaultValue", default, skip_serializing_if = "Option::is_none")]
pub default_value: Option<String>,
#[doc = "Data type of the configuration."]
#[serde(rename = "dataType", default, skip_serializing_if = "Option::is_none")]
pub data_type: Option<String>,
#[doc = "Allowed values of the configuration."]
#[serde(rename = "allowedValues", default, skip_serializing_if = "Option::is_none")]
pub allowed_values: Option<String>,
#[doc = "Source of the configuration."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
}
impl ConfigurationProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Represents a Database."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Database {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "The properties of a database."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DatabaseProperties>,
}
impl Database {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A List of databases."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct DatabaseListResult {
#[doc = "The list of databases housed in a server"]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Database>,
}
impl azure_core::Continuable for DatabaseListResult {
fn continuation(&self) -> Option<String> {
None
}
}
impl DatabaseListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The properties of a database."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct DatabaseProperties {
#[doc = "The charset of the database."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub charset: Option<String>,
#[doc = "The collation of the database."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub collation: Option<String>,
}
impl DatabaseProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Represents a server firewall rule."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FirewallRule {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "The properties of a server firewall rule."]
pub properties: FirewallRuleProperties,
}
impl FirewallRule {
pub fn new(properties: FirewallRuleProperties) -> Self {
Self {
proxy_resource: ProxyResource::default(),
properties,
}
}
}
#[doc = "A list of firewall rules."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct FirewallRuleListResult {
#[doc = "The list of firewall rules in a server."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<FirewallRule>,
}
impl azure_core::Continuable for FirewallRuleListResult {
fn continuation(&self) -> Option<String> {
None
}
}
impl FirewallRuleListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The properties of a server firewall rule."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FirewallRuleProperties {
#[doc = "The start IP address of the server firewall rule. Must be IPv4 format."]
#[serde(rename = "startIpAddress")]
pub start_ip_address: String,
#[doc = "The end IP address of the server firewall rule. Must be IPv4 format."]
#[serde(rename = "endIpAddress")]
pub end_ip_address: String,
}
impl FirewallRuleProperties {
pub fn new(start_ip_address: String, end_ip_address: String) -> Self {
Self {
start_ip_address,
end_ip_address,
}
}
}
#[doc = "Represents a log file."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct LogFile {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "The name of the log file."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "The properties of a log file."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<LogFileProperties>,
}
impl LogFile {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of log files."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct LogFileListResult {
#[doc = "The list of log files."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<LogFile>,
}
impl azure_core::Continuable for LogFileListResult {
fn continuation(&self) -> Option<String> {
None
}
}
impl LogFileListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The properties of a log file."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct LogFileProperties {
#[doc = "Size of the log file."]
#[serde(rename = "sizeInKB", default, skip_serializing_if = "Option::is_none")]
pub size_in_kb: Option<i64>,
#[doc = "Creation timestamp of the log file."]
#[serde(rename = "createdTime", default, skip_serializing_if = "Option::is_none")]
pub created_time: Option<String>,
#[doc = "Last modified timestamp of the log file."]
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[doc = "Type of the log file."]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[doc = "The url to download the log file from."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
}
impl LogFileProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Enforce a minimal Tls version for the server."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "MinimalTlsVersion")]
pub enum MinimalTlsVersion {
#[serde(rename = "TLS1_0")]
Tls10,
#[serde(rename = "TLS1_1")]
Tls11,
#[serde(rename = "TLS1_2")]
Tls12,
#[serde(rename = "TLSEnforcementDisabled")]
TlsEnforcementDisabled,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for MinimalTlsVersion {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for MinimalTlsVersion {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for MinimalTlsVersion {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Tls10 => serializer.serialize_unit_variant("MinimalTlsVersion", 0u32, "TLS1_0"),
Self::Tls11 => serializer.serialize_unit_variant("MinimalTlsVersion", 1u32, "TLS1_1"),
Self::Tls12 => serializer.serialize_unit_variant("MinimalTlsVersion", 2u32, "TLS1_2"),
Self::TlsEnforcementDisabled => serializer.serialize_unit_variant("MinimalTlsVersion", 3u32, "TLSEnforcementDisabled"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
#[doc = "Represents a resource name availability."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct NameAvailability {
#[doc = "Error Message."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[doc = "Indicates whether the resource name is available."]
#[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")]
pub name_available: Option<bool>,
#[doc = "Reason for name being unavailable."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
impl NameAvailability {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Request from client to check resource name availability."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NameAvailabilityRequest {
#[doc = "Resource name to verify."]
pub name: String,
#[doc = "Resource type used for verification."]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
impl NameAvailabilityRequest {
pub fn new(name: String) -> Self {
Self { name, type_: None }
}
}
#[doc = "REST API operation definition."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Operation {
#[doc = "The name of the operation being performed on this particular object."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "Display metadata associated with the operation."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<OperationDisplay>,
#[doc = "The intended executor of the operation."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<operation::Origin>,
#[doc = "Additional descriptions for the operation."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
}
impl Operation {
pub fn new() -> Self {
Self::default()
}
}
pub mod operation {
use super::*;
#[doc = "The intended executor of the operation."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Origin")]
pub enum Origin {
NotSpecified,
#[serde(rename = "user")]
User,
#[serde(rename = "system")]
System,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for Origin {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for Origin {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for Origin {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::NotSpecified => serializer.serialize_unit_variant("Origin", 0u32, "NotSpecified"),
Self::User => serializer.serialize_unit_variant("Origin", 1u32, "user"),
Self::System => serializer.serialize_unit_variant("Origin", 2u32, "system"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
}
#[doc = "Display metadata associated with the operation."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct OperationDisplay {
#[doc = "Operation resource provider name."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[doc = "Resource on which the operation is performed."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[doc = "Localized friendly name for the operation."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[doc = "Operation description."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
impl OperationDisplay {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of resource provider operations."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct OperationListResult {
#[doc = "The list of resource provider operations."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
}
impl OperationListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of performance tiers."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PerformanceTierListResult {
#[doc = "The list of performance tiers"]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PerformanceTierProperties>,
}
impl azure_core::Continuable for PerformanceTierListResult {
fn continuation(&self) -> Option<String> {
None
}
}
impl PerformanceTierListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Performance tier properties"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PerformanceTierProperties {
#[doc = "ID of the performance tier."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[doc = "Service level objectives associated with the performance tier"]
#[serde(rename = "serviceLevelObjectives", default, skip_serializing_if = "Vec::is_empty")]
pub service_level_objectives: Vec<PerformanceTierServiceLevelObjectives>,
}
impl PerformanceTierProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Service level objectives for performance tier."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PerformanceTierServiceLevelObjectives {
#[doc = "ID for the service level objective."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[doc = "Edition of the performance tier."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub edition: Option<String>,
#[doc = "vCore associated with the service level objective"]
#[serde(rename = "vCore", default, skip_serializing_if = "Option::is_none")]
pub v_core: Option<i64>,
#[doc = "Hardware generation associated with the service level objective"]
#[serde(rename = "hardwareGeneration", default, skip_serializing_if = "Option::is_none")]
pub hardware_generation: Option<String>,
#[doc = "Maximum Backup retention in days for the performance tier edition"]
#[serde(rename = "maxBackupRetentionDays", default, skip_serializing_if = "Option::is_none")]
pub max_backup_retention_days: Option<i64>,
#[doc = "Minimum Backup retention in days for the performance tier edition"]
#[serde(rename = "minBackupRetentionDays", default, skip_serializing_if = "Option::is_none")]
pub min_backup_retention_days: Option<i64>,
#[doc = "Max storage allowed for a server."]
#[serde(rename = "maxStorageMB", default, skip_serializing_if = "Option::is_none")]
pub max_storage_mb: Option<i32>,
#[doc = "Max storage allowed for a server."]
#[serde(rename = "minStorageMB", default, skip_serializing_if = "Option::is_none")]
pub min_storage_mb: Option<i32>,
}
impl PerformanceTierServiceLevelObjectives {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A private endpoint connection"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateEndpointConnection {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "Properties of a private endpoint connection."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PrivateEndpointConnectionProperties>,
}
impl PrivateEndpointConnection {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of private endpoint connections."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateEndpointConnectionListResult {
#[doc = "Array of results."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PrivateEndpointConnection>,
#[doc = "Link to retrieve next page of results."]
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl azure_core::Continuable for PrivateEndpointConnectionListResult {
fn continuation(&self) -> Option<String> {
self.next_link.clone()
}
}
impl PrivateEndpointConnectionListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Properties of a private endpoint connection."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateEndpointConnectionProperties {
#[serde(rename = "privateEndpoint", default, skip_serializing_if = "Option::is_none")]
pub private_endpoint: Option<PrivateEndpointProperty>,
#[serde(rename = "privateLinkServiceConnectionState", default, skip_serializing_if = "Option::is_none")]
pub private_link_service_connection_state: Option<PrivateLinkServiceConnectionStateProperty>,
#[doc = "State of the private endpoint connection."]
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
}
impl PrivateEndpointConnectionProperties {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateEndpointProperty {
#[doc = "Resource id of the private endpoint."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
impl PrivateEndpointProperty {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A private link resource"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateLinkResource {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "Properties of a private link resource."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PrivateLinkResourceProperties>,
}
impl PrivateLinkResource {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of private link resources"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateLinkResourceListResult {
#[doc = "Array of results."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PrivateLinkResource>,
#[doc = "Link to retrieve next page of results."]
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl azure_core::Continuable for PrivateLinkResourceListResult {
fn continuation(&self) -> Option<String> {
self.next_link.clone()
}
}
impl PrivateLinkResourceListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Properties of a private link resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateLinkResourceProperties {
#[doc = "The private link resource group id."]
#[serde(rename = "groupId", default, skip_serializing_if = "Option::is_none")]
pub group_id: Option<String>,
#[doc = "The private link resource required member names."]
#[serde(rename = "requiredMembers", default, skip_serializing_if = "Vec::is_empty")]
pub required_members: Vec<String>,
}
impl PrivateLinkResourceProperties {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateLinkServiceConnectionStateProperty {
#[doc = "The private link service connection status."]
pub status: String,
#[doc = "The private link service connection description."]
pub description: String,
#[doc = "The actions required for private link service connection."]
#[serde(rename = "actionsRequired", default, skip_serializing_if = "Option::is_none")]
pub actions_required: Option<String>,
}
impl PrivateLinkServiceConnectionStateProperty {
pub fn new(status: String, description: String) -> Self {
Self {
status,
description,
actions_required: None,
}
}
}
#[doc = "The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ProxyResource {
#[serde(flatten)]
pub resource: Resource,
}
impl ProxyResource {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Represents a Query Statistic."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct QueryStatistic {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "The properties of a query statistic."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<QueryStatisticProperties>,
}
impl QueryStatistic {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The properties of a query statistic."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct QueryStatisticProperties {
#[doc = "Database query identifier."]
#[serde(rename = "queryId", default, skip_serializing_if = "Option::is_none")]
pub query_id: Option<String>,
#[doc = "Observation start time."]
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[doc = "Observation end time."]
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[doc = "Aggregation function name."]
#[serde(rename = "aggregationFunction", default, skip_serializing_if = "Option::is_none")]
pub aggregation_function: Option<String>,
#[doc = "The list of database names."]
#[serde(rename = "databaseNames", default, skip_serializing_if = "Vec::is_empty")]
pub database_names: Vec<String>,
#[doc = "Number of query executions in this time interval."]
#[serde(rename = "queryExecutionCount", default, skip_serializing_if = "Option::is_none")]
pub query_execution_count: Option<i64>,
#[doc = "Metric name."]
#[serde(rename = "metricName", default, skip_serializing_if = "Option::is_none")]
pub metric_name: Option<String>,
#[doc = "Metric display name."]
#[serde(rename = "metricDisplayName", default, skip_serializing_if = "Option::is_none")]
pub metric_display_name: Option<String>,
#[doc = "Metric value."]
#[serde(rename = "metricValue", default, skip_serializing_if = "Option::is_none")]
pub metric_value: Option<f64>,
#[doc = "Metric value unit."]
#[serde(rename = "metricValueUnit", default, skip_serializing_if = "Option::is_none")]
pub metric_value_unit: Option<String>,
}
impl QueryStatisticProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Represents a Query Text."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct QueryText {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "The properties of a query text."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<QueryTextProperties>,
}
impl QueryText {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The properties of a query text."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct QueryTextProperties {
#[doc = "Query identifier unique to the server."]
#[serde(rename = "queryId", default, skip_serializing_if = "Option::is_none")]
pub query_id: Option<String>,
#[doc = "Query text."]
#[serde(rename = "queryText", default, skip_serializing_if = "Option::is_none")]
pub query_text: Option<String>,
}
impl QueryTextProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of query texts."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct QueryTextsResultList {
#[doc = "The list of query texts."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<QueryText>,
#[doc = "Link to retrieve next page of results."]
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl azure_core::Continuable for QueryTextsResultList {
fn continuation(&self) -> Option<String> {
self.next_link.clone()
}
}
impl QueryTextsResultList {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Represents a Recommendation Action."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct RecommendationAction {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "The properties of a recommendation action."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<RecommendationActionProperties>,
}
impl RecommendationAction {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The properties of a recommendation action."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct RecommendationActionProperties {
#[doc = "Advisor name."]
#[serde(rename = "advisorName", default, skip_serializing_if = "Option::is_none")]
pub advisor_name: Option<String>,
#[doc = "Recommendation action session identifier."]
#[serde(rename = "sessionId", default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
#[doc = "Recommendation action identifier."]
#[serde(rename = "actionId", default, skip_serializing_if = "Option::is_none")]
pub action_id: Option<i32>,
#[doc = "Recommendation action creation time."]
#[serde(rename = "createdTime", default, skip_serializing_if = "Option::is_none")]
pub created_time: Option<String>,
#[doc = "Recommendation action expiration time."]
#[serde(rename = "expirationTime", default, skip_serializing_if = "Option::is_none")]
pub expiration_time: Option<String>,
#[doc = "Recommendation action reason."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[doc = "Recommendation action type."]
#[serde(rename = "recommendationType", default, skip_serializing_if = "Option::is_none")]
pub recommendation_type: Option<String>,
#[doc = "Recommendation action details."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<serde_json::Value>,
}
impl RecommendationActionProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of recommendation actions."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct RecommendationActionsResultList {
#[doc = "The list of recommendation action advisors."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<RecommendationAction>,
#[doc = "Link to retrieve next page of results."]
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl azure_core::Continuable for RecommendationActionsResultList {
fn continuation(&self) -> Option<String> {
self.next_link.clone()
}
}
impl RecommendationActionsResultList {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Recommendation action session operation status."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct RecommendedActionSessionsOperationStatus {
#[doc = "Operation identifier."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "Operation start time."]
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[doc = "Operation status."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
}
impl RecommendedActionSessionsOperationStatus {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Common fields that are returned in the response for all Azure Resource Manager resources"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Resource {
#[doc = "Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[doc = "The name of the resource"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "The type of the resource. E.g. \"Microsoft.Compute/virtualMachines\" or \"Microsoft.Storage/storageAccounts\""]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
impl Resource {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Azure Active Directory identity configuration for a resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ResourceIdentity {
#[doc = "The Azure Active Directory principal id."]
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
#[doc = "The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory principal for the resource."]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<resource_identity::Type>,
#[doc = "The Azure Active Directory tenant id."]
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
}
impl ResourceIdentity {
pub fn new() -> Self {
Self::default()
}
}
pub mod resource_identity {
use super::*;
#[doc = "The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory principal for the resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Type")]
pub enum Type {
SystemAssigned,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for Type {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for Type {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for Type {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::SystemAssigned => serializer.serialize_unit_variant("Type", 0u32, "SystemAssigned"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
}
#[doc = "Properties of a security alert policy."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SecurityAlertPolicyProperties {
#[doc = "Specifies the state of the policy, whether it is enabled or disabled."]
pub state: security_alert_policy_properties::State,
#[doc = "Specifies an array of alerts that are disabled. Allowed values are: Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly"]
#[serde(rename = "disabledAlerts", default, skip_serializing_if = "Vec::is_empty")]
pub disabled_alerts: Vec<String>,
#[doc = "Specifies an array of e-mail addresses to which the alert is sent."]
#[serde(rename = "emailAddresses", default, skip_serializing_if = "Vec::is_empty")]
pub email_addresses: Vec<String>,
#[doc = "Specifies that the alert is sent to the account administrators."]
#[serde(rename = "emailAccountAdmins", default, skip_serializing_if = "Option::is_none")]
pub email_account_admins: Option<bool>,
#[doc = "Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). This blob storage will hold all Threat Detection audit logs."]
#[serde(rename = "storageEndpoint", default, skip_serializing_if = "Option::is_none")]
pub storage_endpoint: Option<String>,
#[doc = "Specifies the identifier key of the Threat Detection audit storage account."]
#[serde(rename = "storageAccountAccessKey", default, skip_serializing_if = "Option::is_none")]
pub storage_account_access_key: Option<String>,
#[doc = "Specifies the number of days to keep in the Threat Detection audit logs."]
#[serde(rename = "retentionDays", default, skip_serializing_if = "Option::is_none")]
pub retention_days: Option<i32>,
}
impl SecurityAlertPolicyProperties {
pub fn new(state: security_alert_policy_properties::State) -> Self {
Self {
state,
disabled_alerts: Vec::new(),
email_addresses: Vec::new(),
email_account_admins: None,
storage_endpoint: None,
storage_account_access_key: None,
retention_days: None,
}
}
}
pub mod security_alert_policy_properties {
use super::*;
#[doc = "Specifies the state of the policy, whether it is enabled or disabled."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum State {
Enabled,
Disabled,
}
}
#[doc = "Represents a server."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Server {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[doc = "Azure Active Directory identity configuration for a resource."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<ResourceIdentity>,
#[doc = "Billing information related properties of a server."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[doc = "The properties of a server."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ServerProperties>,
}
impl Server {
pub fn new(tracked_resource: TrackedResource) -> Self {
Self {
tracked_resource,
identity: None,
sku: None,
properties: None,
}
}
}
#[doc = "Represents a server to be created."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerForCreate {
#[doc = "Billing information related properties of a server."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[doc = "The properties used to create a new server."]
pub properties: ServerPropertiesForCreate,
#[doc = "The location the resource resides in."]
pub location: String,
#[doc = "Application-specific metadata in the form of key-value pairs."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
impl ServerForCreate {
pub fn new(properties: ServerPropertiesForCreate, location: String) -> Self {
Self {
sku: None,
properties,
location,
tags: None,
}
}
}
#[doc = "A list of servers."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ServerListResult {
#[doc = "The list of servers"]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Server>,
}
impl azure_core::Continuable for ServerListResult {
fn continuation(&self) -> Option<String> {
None
}
}
impl ServerListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The properties of a server."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ServerProperties {
#[doc = "The administrator's login name of a server. Can only be specified when the server is being created (and is required for creation)."]
#[serde(rename = "administratorLogin", default, skip_serializing_if = "Option::is_none")]
pub administrator_login: Option<String>,
#[doc = "The version of a server."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<ServerVersion>,
#[doc = "Enable ssl enforcement or not when connect to server."]
#[serde(rename = "sslEnforcement", default, skip_serializing_if = "Option::is_none")]
pub ssl_enforcement: Option<SslEnforcement>,
#[doc = "Enforce a minimal Tls version for the server."]
#[serde(rename = "minimalTlsVersion", default, skip_serializing_if = "Option::is_none")]
pub minimal_tls_version: Option<MinimalTlsVersion>,
#[doc = "A state of a server that is visible to user."]
#[serde(rename = "userVisibleState", default, skip_serializing_if = "Option::is_none")]
pub user_visible_state: Option<server_properties::UserVisibleState>,
#[doc = "The fully qualified domain name of a server."]
#[serde(rename = "fullyQualifiedDomainName", default, skip_serializing_if = "Option::is_none")]
pub fully_qualified_domain_name: Option<String>,
#[doc = "Earliest restore point creation time (ISO8601 format)"]
#[serde(rename = "earliestRestoreDate", default, skip_serializing_if = "Option::is_none")]
pub earliest_restore_date: Option<String>,
#[doc = "Storage Profile properties of a server"]
#[serde(rename = "storageProfile", default, skip_serializing_if = "Option::is_none")]
pub storage_profile: Option<StorageProfile>,
#[doc = "The replication role of the server."]
#[serde(rename = "replicationRole", default, skip_serializing_if = "Option::is_none")]
pub replication_role: Option<String>,
#[doc = "The master server id of a replica server."]
#[serde(rename = "masterServerId", default, skip_serializing_if = "Option::is_none")]
pub master_server_id: Option<String>,
#[doc = "The maximum number of replicas that a master server can have."]
#[serde(rename = "replicaCapacity", default, skip_serializing_if = "Option::is_none")]
pub replica_capacity: Option<i32>,
}
impl ServerProperties {
pub fn new() -> Self {
Self::default()
}
}
pub mod server_properties {
use super::*;
#[doc = "A state of a server that is visible to user."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "UserVisibleState")]
pub enum UserVisibleState {
Ready,
Dropping,
Disabled,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for UserVisibleState {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for UserVisibleState {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for UserVisibleState {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Ready => serializer.serialize_unit_variant("UserVisibleState", 0u32, "Ready"),
Self::Dropping => serializer.serialize_unit_variant("UserVisibleState", 1u32, "Dropping"),
Self::Disabled => serializer.serialize_unit_variant("UserVisibleState", 2u32, "Disabled"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
}
#[doc = "The properties used to create a new server."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerPropertiesForCreate {
#[doc = "The version of a server."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<ServerVersion>,
#[doc = "Enable ssl enforcement or not when connect to server."]
#[serde(rename = "sslEnforcement", default, skip_serializing_if = "Option::is_none")]
pub ssl_enforcement: Option<SslEnforcement>,
#[doc = "Enforce a minimal Tls version for the server."]
#[serde(rename = "minimalTlsVersion", default, skip_serializing_if = "Option::is_none")]
pub minimal_tls_version: Option<MinimalTlsVersion>,
#[doc = "Storage Profile properties of a server"]
#[serde(rename = "storageProfile", default, skip_serializing_if = "Option::is_none")]
pub storage_profile: Option<StorageProfile>,
#[doc = "The mode to create a new server."]
#[serde(rename = "createMode")]
pub create_mode: server_properties_for_create::CreateMode,
}
impl ServerPropertiesForCreate {
pub fn new(create_mode: server_properties_for_create::CreateMode) -> Self {
Self {
version: None,
ssl_enforcement: None,
minimal_tls_version: None,
storage_profile: None,
create_mode,
}
}
}
pub mod server_properties_for_create {
use super::*;
#[doc = "The mode to create a new server."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "CreateMode")]
pub enum CreateMode {
Default,
PointInTimeRestore,
GeoRestore,
Replica,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for CreateMode {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for CreateMode {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for CreateMode {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Default => serializer.serialize_unit_variant("CreateMode", 0u32, "Default"),
Self::PointInTimeRestore => serializer.serialize_unit_variant("CreateMode", 1u32, "PointInTimeRestore"),
Self::GeoRestore => serializer.serialize_unit_variant("CreateMode", 2u32, "GeoRestore"),
Self::Replica => serializer.serialize_unit_variant("CreateMode", 3u32, "Replica"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
}
#[doc = "The properties used to create a new server."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerPropertiesForDefaultCreate {
#[serde(flatten)]
pub server_properties_for_create: ServerPropertiesForCreate,
#[doc = "The administrator's login name of a server. Can only be specified when the server is being created (and is required for creation)."]
#[serde(rename = "administratorLogin")]
pub administrator_login: String,
#[doc = "The password of the administrator login."]
#[serde(rename = "administratorLoginPassword")]
pub administrator_login_password: String,
}
impl ServerPropertiesForDefaultCreate {
pub fn new(
server_properties_for_create: ServerPropertiesForCreate,
administrator_login: String,
administrator_login_password: String,
) -> Self {
Self {
server_properties_for_create,
administrator_login,
administrator_login_password,
}
}
}
#[doc = "The properties used to create a new server by restoring to a different region from a geo replicated backup."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerPropertiesForGeoRestore {
#[serde(flatten)]
pub server_properties_for_create: ServerPropertiesForCreate,
#[doc = "The source server id to restore from."]
#[serde(rename = "sourceServerId")]
pub source_server_id: String,
}
impl ServerPropertiesForGeoRestore {
pub fn new(server_properties_for_create: ServerPropertiesForCreate, source_server_id: String) -> Self {
Self {
server_properties_for_create,
source_server_id,
}
}
}
#[doc = "The properties to create a new replica."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerPropertiesForReplica {
#[serde(flatten)]
pub server_properties_for_create: ServerPropertiesForCreate,
#[doc = "The master server id to create replica from."]
#[serde(rename = "sourceServerId")]
pub source_server_id: String,
}
impl ServerPropertiesForReplica {
pub fn new(server_properties_for_create: ServerPropertiesForCreate, source_server_id: String) -> Self {
Self {
server_properties_for_create,
source_server_id,
}
}
}
#[doc = "The properties used to create a new server by restoring from a backup."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerPropertiesForRestore {
#[serde(flatten)]
pub server_properties_for_create: ServerPropertiesForCreate,
#[doc = "The source server id to restore from."]
#[serde(rename = "sourceServerId")]
pub source_server_id: String,
#[doc = "Restore point creation time (ISO8601 format), specifying the time to restore from."]
#[serde(rename = "restorePointInTime")]
pub restore_point_in_time: String,
}
impl ServerPropertiesForRestore {
pub fn new(server_properties_for_create: ServerPropertiesForCreate, source_server_id: String, restore_point_in_time: String) -> Self {
Self {
server_properties_for_create,
source_server_id,
restore_point_in_time,
}
}
}
#[doc = "A server security alert policy."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ServerSecurityAlertPolicy {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "Properties of a security alert policy."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<SecurityAlertPolicyProperties>,
}
impl ServerSecurityAlertPolicy {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Parameters allowed to update for a server."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ServerUpdateParameters {
#[doc = "Billing information related properties of a server."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[doc = "The properties that can be updated for a server."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<server_update_parameters::Properties>,
#[doc = "Application-specific metadata in the form of key-value pairs."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
impl ServerUpdateParameters {
pub fn new() -> Self {
Self::default()
}
}
pub mod server_update_parameters {
use super::*;
#[doc = "The properties that can be updated for a server."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Properties {
#[doc = "Storage Profile properties of a server"]
#[serde(rename = "storageProfile", default, skip_serializing_if = "Option::is_none")]
pub storage_profile: Option<StorageProfile>,
#[doc = "The password of the administrator login."]
#[serde(rename = "administratorLoginPassword", default, skip_serializing_if = "Option::is_none")]
pub administrator_login_password: Option<String>,
#[doc = "The version of a server."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<ServerVersion>,
#[doc = "Enable ssl enforcement or not when connect to server."]
#[serde(rename = "sslEnforcement", default, skip_serializing_if = "Option::is_none")]
pub ssl_enforcement: Option<SslEnforcement>,
#[doc = "Enforce a minimal Tls version for the server."]
#[serde(rename = "minimalTlsVersion", default, skip_serializing_if = "Option::is_none")]
pub minimal_tls_version: Option<MinimalTlsVersion>,
#[doc = "The replication role of the server."]
#[serde(rename = "replicationRole", default, skip_serializing_if = "Option::is_none")]
pub replication_role: Option<String>,
}
impl Properties {
pub fn new() -> Self {
Self::default()
}
}
}
#[doc = "The version of a server."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "ServerVersion")]
pub enum ServerVersion {
#[serde(rename = "10.2")]
N10_2,
#[serde(rename = "10.3")]
N10_3,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for ServerVersion {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for ServerVersion {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for ServerVersion {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::N10_2 => serializer.serialize_unit_variant("ServerVersion", 0u32, "10.2"),
Self::N10_3 => serializer.serialize_unit_variant("ServerVersion", 1u32, "10.3"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
#[doc = "Billing information related properties of a server."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sku {
#[doc = "The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8."]
pub name: String,
#[doc = "The tier of the particular SKU, e.g. Basic."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tier: Option<sku::Tier>,
#[doc = "The scale up/out capacity, representing server's compute units."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capacity: Option<i32>,
#[doc = "The size code, to be interpreted by resource as appropriate."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<String>,
#[doc = "The family of hardware."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub family: Option<String>,
}
impl Sku {
pub fn new(name: String) -> Self {
Self {
name,
tier: None,
capacity: None,
size: None,
family: None,
}
}
}
pub mod sku {
use super::*;
#[doc = "The tier of the particular SKU, e.g. Basic."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Tier")]
pub enum Tier {
Basic,
GeneralPurpose,
MemoryOptimized,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for Tier {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for Tier {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for Tier {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Basic => serializer.serialize_unit_variant("Tier", 0u32, "Basic"),
Self::GeneralPurpose => serializer.serialize_unit_variant("Tier", 1u32, "GeneralPurpose"),
Self::MemoryOptimized => serializer.serialize_unit_variant("Tier", 2u32, "MemoryOptimized"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
}
#[doc = "Enable ssl enforcement or not when connect to server."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SslEnforcement {
Enabled,
Disabled,
}
#[doc = "Storage Profile properties of a server"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct StorageProfile {
#[doc = "Backup retention days for the server."]
#[serde(rename = "backupRetentionDays", default, skip_serializing_if = "Option::is_none")]
pub backup_retention_days: Option<i64>,
#[doc = "Enable Geo-redundant or not for server backup."]
#[serde(rename = "geoRedundantBackup", default, skip_serializing_if = "Option::is_none")]
pub geo_redundant_backup: Option<storage_profile::GeoRedundantBackup>,
#[doc = "Max storage allowed for a server."]
#[serde(rename = "storageMB", default, skip_serializing_if = "Option::is_none")]
pub storage_mb: Option<i32>,
#[doc = "Enable Storage Auto Grow."]
#[serde(rename = "storageAutogrow", default, skip_serializing_if = "Option::is_none")]
pub storage_autogrow: Option<storage_profile::StorageAutogrow>,
}
impl StorageProfile {
pub fn new() -> Self {
Self::default()
}
}
pub mod storage_profile {
use super::*;
#[doc = "Enable Geo-redundant or not for server backup."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "GeoRedundantBackup")]
pub enum GeoRedundantBackup {
Enabled,
Disabled,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for GeoRedundantBackup {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for GeoRedundantBackup {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for GeoRedundantBackup {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Enabled => serializer.serialize_unit_variant("GeoRedundantBackup", 0u32, "Enabled"),
Self::Disabled => serializer.serialize_unit_variant("GeoRedundantBackup", 1u32, "Disabled"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
#[doc = "Enable Storage Auto Grow."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "StorageAutogrow")]
pub enum StorageAutogrow {
Enabled,
Disabled,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for StorageAutogrow {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for StorageAutogrow {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for StorageAutogrow {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Enabled => serializer.serialize_unit_variant("StorageAutogrow", 0u32, "Enabled"),
Self::Disabled => serializer.serialize_unit_variant("StorageAutogrow", 1u32, "Disabled"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
}
#[doc = "Tags object for patch operations."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct TagsObject {
#[doc = "Resource tags."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
impl TagsObject {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Input to get top query statistics"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TopQueryStatisticsInput {
#[doc = "The properties for input to get top query statistics"]
pub properties: TopQueryStatisticsInputProperties,
}
impl TopQueryStatisticsInput {
pub fn new(properties: TopQueryStatisticsInputProperties) -> Self {
Self { properties }
}
}
#[doc = "The properties for input to get top query statistics"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TopQueryStatisticsInputProperties {
#[doc = "Max number of top queries to return."]
#[serde(rename = "numberOfTopQueries")]
pub number_of_top_queries: i32,
#[doc = "Aggregation function name."]
#[serde(rename = "aggregationFunction")]
pub aggregation_function: String,
#[doc = "Observed metric name."]
#[serde(rename = "observedMetric")]
pub observed_metric: String,
#[doc = "Observation start time."]
#[serde(rename = "observationStartTime")]
pub observation_start_time: String,
#[doc = "Observation end time."]
#[serde(rename = "observationEndTime")]
pub observation_end_time: String,
#[doc = "Aggregation interval type in ISO 8601 format."]
#[serde(rename = "aggregationWindow")]
pub aggregation_window: String,
}
impl TopQueryStatisticsInputProperties {
pub fn new(
number_of_top_queries: i32,
aggregation_function: String,
observed_metric: String,
observation_start_time: String,
observation_end_time: String,
aggregation_window: String,
) -> Self {
Self {
number_of_top_queries,
aggregation_function,
observed_metric,
observation_start_time,
observation_end_time,
aggregation_window,
}
}
}
#[doc = "A list of query statistics."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct TopQueryStatisticsResultList {
#[doc = "The list of top query statistics."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<QueryStatistic>,
#[doc = "Link to retrieve next page of results."]
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl azure_core::Continuable for TopQueryStatisticsResultList {
fn continuation(&self) -> Option<String> {
self.next_link.clone()
}
}
impl TopQueryStatisticsResultList {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrackedResource {
#[serde(flatten)]
pub resource: Resource,
#[doc = "Resource tags."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[doc = "The geo-location where the resource lives"]
pub location: String,
}
impl TrackedResource {
pub fn new(location: String) -> Self {
Self {
resource: Resource::default(),
tags: None,
location,
}
}
}
#[doc = "A virtual network rule."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct VirtualNetworkRule {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "Properties of a virtual network rule."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<VirtualNetworkRuleProperties>,
}
impl VirtualNetworkRule {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of virtual network rules."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct VirtualNetworkRuleListResult {
#[doc = "Array of results."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<VirtualNetworkRule>,
#[doc = "Link to retrieve next page of results."]
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl azure_core::Continuable for VirtualNetworkRuleListResult {
fn continuation(&self) -> Option<String> {
self.next_link.clone()
}
}
impl VirtualNetworkRuleListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Properties of a virtual network rule."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetworkRuleProperties {
#[doc = "The ARM resource id of the virtual network subnet."]
#[serde(rename = "virtualNetworkSubnetId")]
pub virtual_network_subnet_id: String,
#[doc = "Create firewall rule before the virtual network has vnet service endpoint enabled."]
#[serde(rename = "ignoreMissingVnetServiceEndpoint", default, skip_serializing_if = "Option::is_none")]
pub ignore_missing_vnet_service_endpoint: Option<bool>,
#[doc = "Virtual Network Rule State"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<virtual_network_rule_properties::State>,
}
impl VirtualNetworkRuleProperties {
pub fn new(virtual_network_subnet_id: String) -> Self {
Self {
virtual_network_subnet_id,
ignore_missing_vnet_service_endpoint: None,
state: None,
}
}
}
pub mod virtual_network_rule_properties {
use super::*;
#[doc = "Virtual Network Rule State"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "State")]
pub enum State {
Initializing,
InProgress,
Ready,
Deleting,
Unknown,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for State {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for State {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for State {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Initializing => serializer.serialize_unit_variant("State", 0u32, "Initializing"),
Self::InProgress => serializer.serialize_unit_variant("State", 1u32, "InProgress"),
Self::Ready => serializer.serialize_unit_variant("State", 2u32, "Ready"),
Self::Deleting => serializer.serialize_unit_variant("State", 3u32, "Deleting"),
Self::Unknown => serializer.serialize_unit_variant("State", 4u32, "Unknown"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
}
#[doc = "Represents a Wait Statistic."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct WaitStatistic {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[doc = "The properties of a wait statistic."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<WaitStatisticProperties>,
}
impl WaitStatistic {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The properties of a wait statistic."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct WaitStatisticProperties {
#[doc = "Observation start time."]
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[doc = "Observation end time."]
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[doc = "Wait event name."]
#[serde(rename = "eventName", default, skip_serializing_if = "Option::is_none")]
pub event_name: Option<String>,
#[doc = "Wait event type name."]
#[serde(rename = "eventTypeName", default, skip_serializing_if = "Option::is_none")]
pub event_type_name: Option<String>,
#[doc = "Database query identifier."]
#[serde(rename = "queryId", default, skip_serializing_if = "Option::is_none")]
pub query_id: Option<i64>,
#[doc = "Database Name."]
#[serde(rename = "databaseName", default, skip_serializing_if = "Option::is_none")]
pub database_name: Option<String>,
#[doc = "Database user identifier."]
#[serde(rename = "userId", default, skip_serializing_if = "Option::is_none")]
pub user_id: Option<i64>,
#[doc = "Wait event count observed in this time interval."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i64>,
#[doc = "Total time of wait in milliseconds in this time interval."]
#[serde(rename = "totalTimeInMs", default, skip_serializing_if = "Option::is_none")]
pub total_time_in_ms: Option<f64>,
}
impl WaitStatisticProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Input to get wait statistics"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WaitStatisticsInput {
#[doc = "The properties for input to get wait statistics"]
pub properties: WaitStatisticsInputProperties,
}
impl WaitStatisticsInput {
pub fn new(properties: WaitStatisticsInputProperties) -> Self {
Self { properties }
}
}
#[doc = "The properties for input to get wait statistics"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WaitStatisticsInputProperties {
#[doc = "Observation start time."]
#[serde(rename = "observationStartTime")]
pub observation_start_time: String,
#[doc = "Observation end time."]
#[serde(rename = "observationEndTime")]
pub observation_end_time: String,
#[doc = "Aggregation interval type in ISO 8601 format."]
#[serde(rename = "aggregationWindow")]
pub aggregation_window: String,
}
impl WaitStatisticsInputProperties {
pub fn new(observation_start_time: String, observation_end_time: String, aggregation_window: String) -> Self {
Self {
observation_start_time,
observation_end_time,
aggregation_window,
}
}
}
#[doc = "A list of wait statistics."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct WaitStatisticsResultList {
#[doc = "The list of wait statistics."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<WaitStatistic>,
#[doc = "Link to retrieve next page of results."]
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl azure_core::Continuable for WaitStatisticsResultList {
fn continuation(&self) -> Option<String> {
self.next_link.clone()
}
}
impl WaitStatisticsResultList {
pub fn new() -> Self {
Self::default()
}
}
| 39.016525 | 200 | 0.661671 |
d64df23ca77e337183092577a57e201eb021c831 | 1,722 | use std::{rc::Rc, fmt};
use crate::common::Source;
#[derive(PartialEq, Hash)]
pub struct Span {
pub source: Rc<Source>,
pub start: usize,
pub length: usize,
}
impl Span {
pub fn new(start: usize, length: usize, source: &Rc<Source>) -> Self {
Span {
start,
length,
source: source.clone(),
}
}
pub fn empty() -> Self {
Span {
start: 0,
length: 0,
source: Source::contents(""),
}
}
pub fn end(&self) -> usize {
self.start + self.length
}
pub fn combine(a: &Span, b: &Span) -> Span {
let start = a.start.min(b.start);
let end = a.end().max(b.end());
let length = end - start;
Span::new(start, length, &a.source)
}
pub fn lines(string: &str) -> Vec<String> {
string.split('\n').map(|line| line.to_string()).collect()
}
pub fn line_index(source: &str, offset: usize) -> (usize, usize) {
let lines = Span::lines(&source[..offset]);
let line = lines.len() - 1;
let col = lines.last().unwrap().chars().count();
(line, col)
}
}
impl fmt::Debug for Span {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("{}", self.source.path.to_str().unwrap()))
}
}
impl Clone for Span {
fn clone(&self) -> Self {
Self {
source: self.source.clone(),
start: self.start,
length: self.length,
}
}
}
pub struct Spanned<T> {
pub node: T,
pub source: Span,
}
impl<T> Spanned<T> {
pub fn new(node: T, source: Span) -> Spanned<T> {
Spanned { node, source }
}
}
| 21.259259 | 75 | 0.506388 |
61c2b5b633f5eeef95cf0651725732ea8a7b9dd5 | 74,955 | /**
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree. An additional
* directory.
*
**
*
* THIS FILE IS @generated; DO NOT EDIT IT
* To regenerate this file, run
*
* buck run //hphp/hack/src:generate_full_fidelity
*
**
*
*/
use super::{
has_arena::HasArena,
syntax::*, syntax_variant_generated::*,
};
use crate::{
lexable_token::LexableToken,
syntax::{SyntaxType, SyntaxValueType},
};
impl<'a, C, T, V> SyntaxType<C> for Syntax<'a, T, V>
where
T: LexableToken + Copy,
V: SyntaxValueType<T>,
C: HasArena<'a>,
{
fn make_end_of_file(ctx: &C, token: Self) -> Self {
let syntax = SyntaxVariant::EndOfFile(ctx.get_arena().alloc(EndOfFileChildren {
token,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_script(ctx: &C, declarations: Self) -> Self {
let syntax = SyntaxVariant::Script(ctx.get_arena().alloc(ScriptChildren {
declarations,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_qualified_name(ctx: &C, parts: Self) -> Self {
let syntax = SyntaxVariant::QualifiedName(ctx.get_arena().alloc(QualifiedNameChildren {
parts,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_simple_type_specifier(ctx: &C, specifier: Self) -> Self {
let syntax = SyntaxVariant::SimpleTypeSpecifier(ctx.get_arena().alloc(SimpleTypeSpecifierChildren {
specifier,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_literal_expression(ctx: &C, expression: Self) -> Self {
let syntax = SyntaxVariant::LiteralExpression(ctx.get_arena().alloc(LiteralExpressionChildren {
expression,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_prefixed_string_expression(ctx: &C, name: Self, str: Self) -> Self {
let syntax = SyntaxVariant::PrefixedStringExpression(ctx.get_arena().alloc(PrefixedStringExpressionChildren {
name,
str,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_prefixed_code_expression(ctx: &C, prefix: Self, left_backtick: Self, expression: Self, right_backtick: Self) -> Self {
let syntax = SyntaxVariant::PrefixedCodeExpression(ctx.get_arena().alloc(PrefixedCodeExpressionChildren {
prefix,
left_backtick,
expression,
right_backtick,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_variable_expression(ctx: &C, expression: Self) -> Self {
let syntax = SyntaxVariant::VariableExpression(ctx.get_arena().alloc(VariableExpressionChildren {
expression,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_pipe_variable_expression(ctx: &C, expression: Self) -> Self {
let syntax = SyntaxVariant::PipeVariableExpression(ctx.get_arena().alloc(PipeVariableExpressionChildren {
expression,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_file_attribute_specification(ctx: &C, left_double_angle: Self, keyword: Self, colon: Self, attributes: Self, right_double_angle: Self) -> Self {
let syntax = SyntaxVariant::FileAttributeSpecification(ctx.get_arena().alloc(FileAttributeSpecificationChildren {
left_double_angle,
keyword,
colon,
attributes,
right_double_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_enum_declaration(ctx: &C, attribute_spec: Self, keyword: Self, name: Self, colon: Self, base: Self, type_: Self, includes_keyword: Self, includes_list: Self, left_brace: Self, enumerators: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::EnumDeclaration(ctx.get_arena().alloc(EnumDeclarationChildren {
attribute_spec,
keyword,
name,
colon,
base,
type_,
includes_keyword,
includes_list,
left_brace,
enumerators,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_enumerator(ctx: &C, name: Self, equal: Self, value: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::Enumerator(ctx.get_arena().alloc(EnumeratorChildren {
name,
equal,
value,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_enum_class_declaration(ctx: &C, attribute_spec: Self, enum_keyword: Self, class_keyword: Self, name: Self, colon: Self, base: Self, extends: Self, extends_list: Self, left_brace: Self, elements: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::EnumClassDeclaration(ctx.get_arena().alloc(EnumClassDeclarationChildren {
attribute_spec,
enum_keyword,
class_keyword,
name,
colon,
base,
extends,
extends_list,
left_brace,
elements,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_enum_class_enumerator(ctx: &C, name: Self, left_angle: Self, type_: Self, right_angle: Self, left_paren: Self, initial_value: Self, right_paren: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::EnumClassEnumerator(ctx.get_arena().alloc(EnumClassEnumeratorChildren {
name,
left_angle,
type_,
right_angle,
left_paren,
initial_value,
right_paren,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_record_declaration(ctx: &C, attribute_spec: Self, modifier: Self, keyword: Self, name: Self, extends_keyword: Self, extends_opt: Self, left_brace: Self, fields: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::RecordDeclaration(ctx.get_arena().alloc(RecordDeclarationChildren {
attribute_spec,
modifier,
keyword,
name,
extends_keyword,
extends_opt,
left_brace,
fields,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_record_field(ctx: &C, type_: Self, name: Self, init: Self, semi: Self) -> Self {
let syntax = SyntaxVariant::RecordField(ctx.get_arena().alloc(RecordFieldChildren {
type_,
name,
init,
semi,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_alias_declaration(ctx: &C, attribute_spec: Self, keyword: Self, name: Self, generic_parameter: Self, constraint: Self, equal: Self, type_: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::AliasDeclaration(ctx.get_arena().alloc(AliasDeclarationChildren {
attribute_spec,
keyword,
name,
generic_parameter,
constraint,
equal,
type_,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_property_declaration(ctx: &C, attribute_spec: Self, modifiers: Self, type_: Self, declarators: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::PropertyDeclaration(ctx.get_arena().alloc(PropertyDeclarationChildren {
attribute_spec,
modifiers,
type_,
declarators,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_property_declarator(ctx: &C, name: Self, initializer: Self) -> Self {
let syntax = SyntaxVariant::PropertyDeclarator(ctx.get_arena().alloc(PropertyDeclaratorChildren {
name,
initializer,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_declaration(ctx: &C, header: Self, body: Self) -> Self {
let syntax = SyntaxVariant::NamespaceDeclaration(ctx.get_arena().alloc(NamespaceDeclarationChildren {
header,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_declaration_header(ctx: &C, keyword: Self, name: Self) -> Self {
let syntax = SyntaxVariant::NamespaceDeclarationHeader(ctx.get_arena().alloc(NamespaceDeclarationHeaderChildren {
keyword,
name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_body(ctx: &C, left_brace: Self, declarations: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::NamespaceBody(ctx.get_arena().alloc(NamespaceBodyChildren {
left_brace,
declarations,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_empty_body(ctx: &C, semicolon: Self) -> Self {
let syntax = SyntaxVariant::NamespaceEmptyBody(ctx.get_arena().alloc(NamespaceEmptyBodyChildren {
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_use_declaration(ctx: &C, keyword: Self, kind: Self, clauses: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::NamespaceUseDeclaration(ctx.get_arena().alloc(NamespaceUseDeclarationChildren {
keyword,
kind,
clauses,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_group_use_declaration(ctx: &C, keyword: Self, kind: Self, prefix: Self, left_brace: Self, clauses: Self, right_brace: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::NamespaceGroupUseDeclaration(ctx.get_arena().alloc(NamespaceGroupUseDeclarationChildren {
keyword,
kind,
prefix,
left_brace,
clauses,
right_brace,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_use_clause(ctx: &C, clause_kind: Self, name: Self, as_: Self, alias: Self) -> Self {
let syntax = SyntaxVariant::NamespaceUseClause(ctx.get_arena().alloc(NamespaceUseClauseChildren {
clause_kind,
name,
as_,
alias,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_function_declaration(ctx: &C, attribute_spec: Self, declaration_header: Self, body: Self) -> Self {
let syntax = SyntaxVariant::FunctionDeclaration(ctx.get_arena().alloc(FunctionDeclarationChildren {
attribute_spec,
declaration_header,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_function_declaration_header(ctx: &C, modifiers: Self, keyword: Self, name: Self, type_parameter_list: Self, left_paren: Self, parameter_list: Self, right_paren: Self, capability: Self, colon: Self, type_: Self, where_clause: Self) -> Self {
let syntax = SyntaxVariant::FunctionDeclarationHeader(ctx.get_arena().alloc(FunctionDeclarationHeaderChildren {
modifiers,
keyword,
name,
type_parameter_list,
left_paren,
parameter_list,
right_paren,
capability,
colon,
type_,
where_clause,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_capability(ctx: &C, left_bracket: Self, types: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::Capability(ctx.get_arena().alloc(CapabilityChildren {
left_bracket,
types,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_where_clause(ctx: &C, keyword: Self, constraints: Self) -> Self {
let syntax = SyntaxVariant::WhereClause(ctx.get_arena().alloc(WhereClauseChildren {
keyword,
constraints,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_where_constraint(ctx: &C, left_type: Self, operator: Self, right_type: Self) -> Self {
let syntax = SyntaxVariant::WhereConstraint(ctx.get_arena().alloc(WhereConstraintChildren {
left_type,
operator,
right_type,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_methodish_declaration(ctx: &C, attribute: Self, function_decl_header: Self, function_body: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::MethodishDeclaration(ctx.get_arena().alloc(MethodishDeclarationChildren {
attribute,
function_decl_header,
function_body,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_methodish_trait_resolution(ctx: &C, attribute: Self, function_decl_header: Self, equal: Self, name: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::MethodishTraitResolution(ctx.get_arena().alloc(MethodishTraitResolutionChildren {
attribute,
function_decl_header,
equal,
name,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_classish_declaration(ctx: &C, attribute: Self, modifiers: Self, xhp: Self, keyword: Self, name: Self, type_parameters: Self, extends_keyword: Self, extends_list: Self, implements_keyword: Self, implements_list: Self, where_clause: Self, body: Self) -> Self {
let syntax = SyntaxVariant::ClassishDeclaration(ctx.get_arena().alloc(ClassishDeclarationChildren {
attribute,
modifiers,
xhp,
keyword,
name,
type_parameters,
extends_keyword,
extends_list,
implements_keyword,
implements_list,
where_clause,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_classish_body(ctx: &C, left_brace: Self, elements: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::ClassishBody(ctx.get_arena().alloc(ClassishBodyChildren {
left_brace,
elements,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_trait_use_precedence_item(ctx: &C, name: Self, keyword: Self, removed_names: Self) -> Self {
let syntax = SyntaxVariant::TraitUsePrecedenceItem(ctx.get_arena().alloc(TraitUsePrecedenceItemChildren {
name,
keyword,
removed_names,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_trait_use_alias_item(ctx: &C, aliasing_name: Self, keyword: Self, modifiers: Self, aliased_name: Self) -> Self {
let syntax = SyntaxVariant::TraitUseAliasItem(ctx.get_arena().alloc(TraitUseAliasItemChildren {
aliasing_name,
keyword,
modifiers,
aliased_name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_trait_use_conflict_resolution(ctx: &C, keyword: Self, names: Self, left_brace: Self, clauses: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::TraitUseConflictResolution(ctx.get_arena().alloc(TraitUseConflictResolutionChildren {
keyword,
names,
left_brace,
clauses,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_trait_use(ctx: &C, keyword: Self, names: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::TraitUse(ctx.get_arena().alloc(TraitUseChildren {
keyword,
names,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_require_clause(ctx: &C, keyword: Self, kind: Self, name: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::RequireClause(ctx.get_arena().alloc(RequireClauseChildren {
keyword,
kind,
name,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_const_declaration(ctx: &C, modifiers: Self, keyword: Self, type_specifier: Self, declarators: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::ConstDeclaration(ctx.get_arena().alloc(ConstDeclarationChildren {
modifiers,
keyword,
type_specifier,
declarators,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_constant_declarator(ctx: &C, name: Self, initializer: Self) -> Self {
let syntax = SyntaxVariant::ConstantDeclarator(ctx.get_arena().alloc(ConstantDeclaratorChildren {
name,
initializer,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_type_const_declaration(ctx: &C, attribute_spec: Self, modifiers: Self, keyword: Self, type_keyword: Self, name: Self, type_parameters: Self, type_constraint: Self, equal: Self, type_specifier: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::TypeConstDeclaration(ctx.get_arena().alloc(TypeConstDeclarationChildren {
attribute_spec,
modifiers,
keyword,
type_keyword,
name,
type_parameters,
type_constraint,
equal,
type_specifier,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_decorated_expression(ctx: &C, decorator: Self, expression: Self) -> Self {
let syntax = SyntaxVariant::DecoratedExpression(ctx.get_arena().alloc(DecoratedExpressionChildren {
decorator,
expression,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_parameter_declaration(ctx: &C, attribute: Self, visibility: Self, call_convention: Self, type_: Self, name: Self, default_value: Self) -> Self {
let syntax = SyntaxVariant::ParameterDeclaration(ctx.get_arena().alloc(ParameterDeclarationChildren {
attribute,
visibility,
call_convention,
type_,
name,
default_value,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_variadic_parameter(ctx: &C, call_convention: Self, type_: Self, ellipsis: Self) -> Self {
let syntax = SyntaxVariant::VariadicParameter(ctx.get_arena().alloc(VariadicParameterChildren {
call_convention,
type_,
ellipsis,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_old_attribute_specification(ctx: &C, left_double_angle: Self, attributes: Self, right_double_angle: Self) -> Self {
let syntax = SyntaxVariant::OldAttributeSpecification(ctx.get_arena().alloc(OldAttributeSpecificationChildren {
left_double_angle,
attributes,
right_double_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_attribute_specification(ctx: &C, attributes: Self) -> Self {
let syntax = SyntaxVariant::AttributeSpecification(ctx.get_arena().alloc(AttributeSpecificationChildren {
attributes,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_attribute(ctx: &C, at: Self, attribute_name: Self) -> Self {
let syntax = SyntaxVariant::Attribute(ctx.get_arena().alloc(AttributeChildren {
at,
attribute_name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_inclusion_expression(ctx: &C, require: Self, filename: Self) -> Self {
let syntax = SyntaxVariant::InclusionExpression(ctx.get_arena().alloc(InclusionExpressionChildren {
require,
filename,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_inclusion_directive(ctx: &C, expression: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::InclusionDirective(ctx.get_arena().alloc(InclusionDirectiveChildren {
expression,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_compound_statement(ctx: &C, left_brace: Self, statements: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::CompoundStatement(ctx.get_arena().alloc(CompoundStatementChildren {
left_brace,
statements,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_expression_statement(ctx: &C, expression: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::ExpressionStatement(ctx.get_arena().alloc(ExpressionStatementChildren {
expression,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_markup_section(ctx: &C, hashbang: Self, suffix: Self) -> Self {
let syntax = SyntaxVariant::MarkupSection(ctx.get_arena().alloc(MarkupSectionChildren {
hashbang,
suffix,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_markup_suffix(ctx: &C, less_than_question: Self, name: Self) -> Self {
let syntax = SyntaxVariant::MarkupSuffix(ctx.get_arena().alloc(MarkupSuffixChildren {
less_than_question,
name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_unset_statement(ctx: &C, keyword: Self, left_paren: Self, variables: Self, right_paren: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::UnsetStatement(ctx.get_arena().alloc(UnsetStatementChildren {
keyword,
left_paren,
variables,
right_paren,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_using_statement_block_scoped(ctx: &C, await_keyword: Self, using_keyword: Self, left_paren: Self, expressions: Self, right_paren: Self, body: Self) -> Self {
let syntax = SyntaxVariant::UsingStatementBlockScoped(ctx.get_arena().alloc(UsingStatementBlockScopedChildren {
await_keyword,
using_keyword,
left_paren,
expressions,
right_paren,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_using_statement_function_scoped(ctx: &C, await_keyword: Self, using_keyword: Self, expression: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::UsingStatementFunctionScoped(ctx.get_arena().alloc(UsingStatementFunctionScopedChildren {
await_keyword,
using_keyword,
expression,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_while_statement(ctx: &C, keyword: Self, left_paren: Self, condition: Self, right_paren: Self, body: Self) -> Self {
let syntax = SyntaxVariant::WhileStatement(ctx.get_arena().alloc(WhileStatementChildren {
keyword,
left_paren,
condition,
right_paren,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_if_statement(ctx: &C, keyword: Self, left_paren: Self, condition: Self, right_paren: Self, statement: Self, elseif_clauses: Self, else_clause: Self) -> Self {
let syntax = SyntaxVariant::IfStatement(ctx.get_arena().alloc(IfStatementChildren {
keyword,
left_paren,
condition,
right_paren,
statement,
elseif_clauses,
else_clause,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_elseif_clause(ctx: &C, keyword: Self, left_paren: Self, condition: Self, right_paren: Self, statement: Self) -> Self {
let syntax = SyntaxVariant::ElseifClause(ctx.get_arena().alloc(ElseifClauseChildren {
keyword,
left_paren,
condition,
right_paren,
statement,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_else_clause(ctx: &C, keyword: Self, statement: Self) -> Self {
let syntax = SyntaxVariant::ElseClause(ctx.get_arena().alloc(ElseClauseChildren {
keyword,
statement,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_try_statement(ctx: &C, keyword: Self, compound_statement: Self, catch_clauses: Self, finally_clause: Self) -> Self {
let syntax = SyntaxVariant::TryStatement(ctx.get_arena().alloc(TryStatementChildren {
keyword,
compound_statement,
catch_clauses,
finally_clause,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_catch_clause(ctx: &C, keyword: Self, left_paren: Self, type_: Self, variable: Self, right_paren: Self, body: Self) -> Self {
let syntax = SyntaxVariant::CatchClause(ctx.get_arena().alloc(CatchClauseChildren {
keyword,
left_paren,
type_,
variable,
right_paren,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_finally_clause(ctx: &C, keyword: Self, body: Self) -> Self {
let syntax = SyntaxVariant::FinallyClause(ctx.get_arena().alloc(FinallyClauseChildren {
keyword,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_do_statement(ctx: &C, keyword: Self, body: Self, while_keyword: Self, left_paren: Self, condition: Self, right_paren: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::DoStatement(ctx.get_arena().alloc(DoStatementChildren {
keyword,
body,
while_keyword,
left_paren,
condition,
right_paren,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_for_statement(ctx: &C, keyword: Self, left_paren: Self, initializer: Self, first_semicolon: Self, control: Self, second_semicolon: Self, end_of_loop: Self, right_paren: Self, body: Self) -> Self {
let syntax = SyntaxVariant::ForStatement(ctx.get_arena().alloc(ForStatementChildren {
keyword,
left_paren,
initializer,
first_semicolon,
control,
second_semicolon,
end_of_loop,
right_paren,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_foreach_statement(ctx: &C, keyword: Self, left_paren: Self, collection: Self, await_keyword: Self, as_: Self, key: Self, arrow: Self, value: Self, right_paren: Self, body: Self) -> Self {
let syntax = SyntaxVariant::ForeachStatement(ctx.get_arena().alloc(ForeachStatementChildren {
keyword,
left_paren,
collection,
await_keyword,
as_,
key,
arrow,
value,
right_paren,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_switch_statement(ctx: &C, keyword: Self, left_paren: Self, expression: Self, right_paren: Self, left_brace: Self, sections: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::SwitchStatement(ctx.get_arena().alloc(SwitchStatementChildren {
keyword,
left_paren,
expression,
right_paren,
left_brace,
sections,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_switch_section(ctx: &C, labels: Self, statements: Self, fallthrough: Self) -> Self {
let syntax = SyntaxVariant::SwitchSection(ctx.get_arena().alloc(SwitchSectionChildren {
labels,
statements,
fallthrough,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_switch_fallthrough(ctx: &C, keyword: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::SwitchFallthrough(ctx.get_arena().alloc(SwitchFallthroughChildren {
keyword,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_case_label(ctx: &C, keyword: Self, expression: Self, colon: Self) -> Self {
let syntax = SyntaxVariant::CaseLabel(ctx.get_arena().alloc(CaseLabelChildren {
keyword,
expression,
colon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_default_label(ctx: &C, keyword: Self, colon: Self) -> Self {
let syntax = SyntaxVariant::DefaultLabel(ctx.get_arena().alloc(DefaultLabelChildren {
keyword,
colon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_return_statement(ctx: &C, keyword: Self, expression: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::ReturnStatement(ctx.get_arena().alloc(ReturnStatementChildren {
keyword,
expression,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_throw_statement(ctx: &C, keyword: Self, expression: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::ThrowStatement(ctx.get_arena().alloc(ThrowStatementChildren {
keyword,
expression,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_break_statement(ctx: &C, keyword: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::BreakStatement(ctx.get_arena().alloc(BreakStatementChildren {
keyword,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_continue_statement(ctx: &C, keyword: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::ContinueStatement(ctx.get_arena().alloc(ContinueStatementChildren {
keyword,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_echo_statement(ctx: &C, keyword: Self, expressions: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::EchoStatement(ctx.get_arena().alloc(EchoStatementChildren {
keyword,
expressions,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_concurrent_statement(ctx: &C, keyword: Self, statement: Self) -> Self {
let syntax = SyntaxVariant::ConcurrentStatement(ctx.get_arena().alloc(ConcurrentStatementChildren {
keyword,
statement,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_simple_initializer(ctx: &C, equal: Self, value: Self) -> Self {
let syntax = SyntaxVariant::SimpleInitializer(ctx.get_arena().alloc(SimpleInitializerChildren {
equal,
value,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_anonymous_class(ctx: &C, class_keyword: Self, left_paren: Self, argument_list: Self, right_paren: Self, extends_keyword: Self, extends_list: Self, implements_keyword: Self, implements_list: Self, body: Self) -> Self {
let syntax = SyntaxVariant::AnonymousClass(ctx.get_arena().alloc(AnonymousClassChildren {
class_keyword,
left_paren,
argument_list,
right_paren,
extends_keyword,
extends_list,
implements_keyword,
implements_list,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_anonymous_function(ctx: &C, attribute_spec: Self, static_keyword: Self, async_keyword: Self, function_keyword: Self, left_paren: Self, parameters: Self, right_paren: Self, colon: Self, type_: Self, use_: Self, body: Self) -> Self {
let syntax = SyntaxVariant::AnonymousFunction(ctx.get_arena().alloc(AnonymousFunctionChildren {
attribute_spec,
static_keyword,
async_keyword,
function_keyword,
left_paren,
parameters,
right_paren,
colon,
type_,
use_,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_anonymous_function_use_clause(ctx: &C, keyword: Self, left_paren: Self, variables: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::AnonymousFunctionUseClause(ctx.get_arena().alloc(AnonymousFunctionUseClauseChildren {
keyword,
left_paren,
variables,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_lambda_expression(ctx: &C, attribute_spec: Self, async_: Self, signature: Self, arrow: Self, body: Self) -> Self {
let syntax = SyntaxVariant::LambdaExpression(ctx.get_arena().alloc(LambdaExpressionChildren {
attribute_spec,
async_,
signature,
arrow,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_lambda_signature(ctx: &C, left_paren: Self, parameters: Self, right_paren: Self, capability: Self, colon: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::LambdaSignature(ctx.get_arena().alloc(LambdaSignatureChildren {
left_paren,
parameters,
right_paren,
capability,
colon,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_cast_expression(ctx: &C, left_paren: Self, type_: Self, right_paren: Self, operand: Self) -> Self {
let syntax = SyntaxVariant::CastExpression(ctx.get_arena().alloc(CastExpressionChildren {
left_paren,
type_,
right_paren,
operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_scope_resolution_expression(ctx: &C, qualifier: Self, operator: Self, name: Self) -> Self {
let syntax = SyntaxVariant::ScopeResolutionExpression(ctx.get_arena().alloc(ScopeResolutionExpressionChildren {
qualifier,
operator,
name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_member_selection_expression(ctx: &C, object: Self, operator: Self, name: Self) -> Self {
let syntax = SyntaxVariant::MemberSelectionExpression(ctx.get_arena().alloc(MemberSelectionExpressionChildren {
object,
operator,
name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_safe_member_selection_expression(ctx: &C, object: Self, operator: Self, name: Self) -> Self {
let syntax = SyntaxVariant::SafeMemberSelectionExpression(ctx.get_arena().alloc(SafeMemberSelectionExpressionChildren {
object,
operator,
name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_embedded_member_selection_expression(ctx: &C, object: Self, operator: Self, name: Self) -> Self {
let syntax = SyntaxVariant::EmbeddedMemberSelectionExpression(ctx.get_arena().alloc(EmbeddedMemberSelectionExpressionChildren {
object,
operator,
name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_yield_expression(ctx: &C, keyword: Self, operand: Self) -> Self {
let syntax = SyntaxVariant::YieldExpression(ctx.get_arena().alloc(YieldExpressionChildren {
keyword,
operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_prefix_unary_expression(ctx: &C, operator: Self, operand: Self) -> Self {
let syntax = SyntaxVariant::PrefixUnaryExpression(ctx.get_arena().alloc(PrefixUnaryExpressionChildren {
operator,
operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_postfix_unary_expression(ctx: &C, operand: Self, operator: Self) -> Self {
let syntax = SyntaxVariant::PostfixUnaryExpression(ctx.get_arena().alloc(PostfixUnaryExpressionChildren {
operand,
operator,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_binary_expression(ctx: &C, left_operand: Self, operator: Self, right_operand: Self) -> Self {
let syntax = SyntaxVariant::BinaryExpression(ctx.get_arena().alloc(BinaryExpressionChildren {
left_operand,
operator,
right_operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_is_expression(ctx: &C, left_operand: Self, operator: Self, right_operand: Self) -> Self {
let syntax = SyntaxVariant::IsExpression(ctx.get_arena().alloc(IsExpressionChildren {
left_operand,
operator,
right_operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_as_expression(ctx: &C, left_operand: Self, operator: Self, right_operand: Self) -> Self {
let syntax = SyntaxVariant::AsExpression(ctx.get_arena().alloc(AsExpressionChildren {
left_operand,
operator,
right_operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_nullable_as_expression(ctx: &C, left_operand: Self, operator: Self, right_operand: Self) -> Self {
let syntax = SyntaxVariant::NullableAsExpression(ctx.get_arena().alloc(NullableAsExpressionChildren {
left_operand,
operator,
right_operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_conditional_expression(ctx: &C, test: Self, question: Self, consequence: Self, colon: Self, alternative: Self) -> Self {
let syntax = SyntaxVariant::ConditionalExpression(ctx.get_arena().alloc(ConditionalExpressionChildren {
test,
question,
consequence,
colon,
alternative,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_eval_expression(ctx: &C, keyword: Self, left_paren: Self, argument: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::EvalExpression(ctx.get_arena().alloc(EvalExpressionChildren {
keyword,
left_paren,
argument,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_define_expression(ctx: &C, keyword: Self, left_paren: Self, argument_list: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::DefineExpression(ctx.get_arena().alloc(DefineExpressionChildren {
keyword,
left_paren,
argument_list,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_isset_expression(ctx: &C, keyword: Self, left_paren: Self, argument_list: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::IssetExpression(ctx.get_arena().alloc(IssetExpressionChildren {
keyword,
left_paren,
argument_list,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_function_call_expression(ctx: &C, receiver: Self, type_args: Self, left_paren: Self, argument_list: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::FunctionCallExpression(ctx.get_arena().alloc(FunctionCallExpressionChildren {
receiver,
type_args,
left_paren,
argument_list,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_function_pointer_expression(ctx: &C, receiver: Self, type_args: Self) -> Self {
let syntax = SyntaxVariant::FunctionPointerExpression(ctx.get_arena().alloc(FunctionPointerExpressionChildren {
receiver,
type_args,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_parenthesized_expression(ctx: &C, left_paren: Self, expression: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::ParenthesizedExpression(ctx.get_arena().alloc(ParenthesizedExpressionChildren {
left_paren,
expression,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_braced_expression(ctx: &C, left_brace: Self, expression: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::BracedExpression(ctx.get_arena().alloc(BracedExpressionChildren {
left_brace,
expression,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_embedded_braced_expression(ctx: &C, left_brace: Self, expression: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::EmbeddedBracedExpression(ctx.get_arena().alloc(EmbeddedBracedExpressionChildren {
left_brace,
expression,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_list_expression(ctx: &C, keyword: Self, left_paren: Self, members: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::ListExpression(ctx.get_arena().alloc(ListExpressionChildren {
keyword,
left_paren,
members,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_collection_literal_expression(ctx: &C, name: Self, left_brace: Self, initializers: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::CollectionLiteralExpression(ctx.get_arena().alloc(CollectionLiteralExpressionChildren {
name,
left_brace,
initializers,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_object_creation_expression(ctx: &C, new_keyword: Self, object: Self) -> Self {
let syntax = SyntaxVariant::ObjectCreationExpression(ctx.get_arena().alloc(ObjectCreationExpressionChildren {
new_keyword,
object,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_constructor_call(ctx: &C, type_: Self, left_paren: Self, argument_list: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::ConstructorCall(ctx.get_arena().alloc(ConstructorCallChildren {
type_,
left_paren,
argument_list,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_record_creation_expression(ctx: &C, type_: Self, left_bracket: Self, members: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::RecordCreationExpression(ctx.get_arena().alloc(RecordCreationExpressionChildren {
type_,
left_bracket,
members,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_darray_intrinsic_expression(ctx: &C, keyword: Self, explicit_type: Self, left_bracket: Self, members: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::DarrayIntrinsicExpression(ctx.get_arena().alloc(DarrayIntrinsicExpressionChildren {
keyword,
explicit_type,
left_bracket,
members,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_dictionary_intrinsic_expression(ctx: &C, keyword: Self, explicit_type: Self, left_bracket: Self, members: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::DictionaryIntrinsicExpression(ctx.get_arena().alloc(DictionaryIntrinsicExpressionChildren {
keyword,
explicit_type,
left_bracket,
members,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_keyset_intrinsic_expression(ctx: &C, keyword: Self, explicit_type: Self, left_bracket: Self, members: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::KeysetIntrinsicExpression(ctx.get_arena().alloc(KeysetIntrinsicExpressionChildren {
keyword,
explicit_type,
left_bracket,
members,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_varray_intrinsic_expression(ctx: &C, keyword: Self, explicit_type: Self, left_bracket: Self, members: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::VarrayIntrinsicExpression(ctx.get_arena().alloc(VarrayIntrinsicExpressionChildren {
keyword,
explicit_type,
left_bracket,
members,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_vector_intrinsic_expression(ctx: &C, keyword: Self, explicit_type: Self, left_bracket: Self, members: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::VectorIntrinsicExpression(ctx.get_arena().alloc(VectorIntrinsicExpressionChildren {
keyword,
explicit_type,
left_bracket,
members,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_element_initializer(ctx: &C, key: Self, arrow: Self, value: Self) -> Self {
let syntax = SyntaxVariant::ElementInitializer(ctx.get_arena().alloc(ElementInitializerChildren {
key,
arrow,
value,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_subscript_expression(ctx: &C, receiver: Self, left_bracket: Self, index: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::SubscriptExpression(ctx.get_arena().alloc(SubscriptExpressionChildren {
receiver,
left_bracket,
index,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_embedded_subscript_expression(ctx: &C, receiver: Self, left_bracket: Self, index: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::EmbeddedSubscriptExpression(ctx.get_arena().alloc(EmbeddedSubscriptExpressionChildren {
receiver,
left_bracket,
index,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_awaitable_creation_expression(ctx: &C, attribute_spec: Self, async_: Self, compound_statement: Self) -> Self {
let syntax = SyntaxVariant::AwaitableCreationExpression(ctx.get_arena().alloc(AwaitableCreationExpressionChildren {
attribute_spec,
async_,
compound_statement,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_children_declaration(ctx: &C, keyword: Self, expression: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::XHPChildrenDeclaration(ctx.get_arena().alloc(XHPChildrenDeclarationChildren {
keyword,
expression,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_children_parenthesized_list(ctx: &C, left_paren: Self, xhp_children: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::XHPChildrenParenthesizedList(ctx.get_arena().alloc(XHPChildrenParenthesizedListChildren {
left_paren,
xhp_children,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_category_declaration(ctx: &C, keyword: Self, categories: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::XHPCategoryDeclaration(ctx.get_arena().alloc(XHPCategoryDeclarationChildren {
keyword,
categories,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_enum_type(ctx: &C, keyword: Self, left_brace: Self, values: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::XHPEnumType(ctx.get_arena().alloc(XHPEnumTypeChildren {
keyword,
left_brace,
values,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_lateinit(ctx: &C, at: Self, keyword: Self) -> Self {
let syntax = SyntaxVariant::XHPLateinit(ctx.get_arena().alloc(XHPLateinitChildren {
at,
keyword,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_required(ctx: &C, at: Self, keyword: Self) -> Self {
let syntax = SyntaxVariant::XHPRequired(ctx.get_arena().alloc(XHPRequiredChildren {
at,
keyword,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_class_attribute_declaration(ctx: &C, keyword: Self, attributes: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::XHPClassAttributeDeclaration(ctx.get_arena().alloc(XHPClassAttributeDeclarationChildren {
keyword,
attributes,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_class_attribute(ctx: &C, type_: Self, name: Self, initializer: Self, required: Self) -> Self {
let syntax = SyntaxVariant::XHPClassAttribute(ctx.get_arena().alloc(XHPClassAttributeChildren {
type_,
name,
initializer,
required,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_simple_class_attribute(ctx: &C, type_: Self) -> Self {
let syntax = SyntaxVariant::XHPSimpleClassAttribute(ctx.get_arena().alloc(XHPSimpleClassAttributeChildren {
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_simple_attribute(ctx: &C, name: Self, equal: Self, expression: Self) -> Self {
let syntax = SyntaxVariant::XHPSimpleAttribute(ctx.get_arena().alloc(XHPSimpleAttributeChildren {
name,
equal,
expression,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_spread_attribute(ctx: &C, left_brace: Self, spread_operator: Self, expression: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::XHPSpreadAttribute(ctx.get_arena().alloc(XHPSpreadAttributeChildren {
left_brace,
spread_operator,
expression,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_open(ctx: &C, left_angle: Self, name: Self, attributes: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::XHPOpen(ctx.get_arena().alloc(XHPOpenChildren {
left_angle,
name,
attributes,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_expression(ctx: &C, open: Self, body: Self, close: Self) -> Self {
let syntax = SyntaxVariant::XHPExpression(ctx.get_arena().alloc(XHPExpressionChildren {
open,
body,
close,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_close(ctx: &C, left_angle: Self, name: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::XHPClose(ctx.get_arena().alloc(XHPCloseChildren {
left_angle,
name,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_type_constant(ctx: &C, left_type: Self, separator: Self, right_type: Self) -> Self {
let syntax = SyntaxVariant::TypeConstant(ctx.get_arena().alloc(TypeConstantChildren {
left_type,
separator,
right_type,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_vector_type_specifier(ctx: &C, keyword: Self, left_angle: Self, type_: Self, trailing_comma: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::VectorTypeSpecifier(ctx.get_arena().alloc(VectorTypeSpecifierChildren {
keyword,
left_angle,
type_,
trailing_comma,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_keyset_type_specifier(ctx: &C, keyword: Self, left_angle: Self, type_: Self, trailing_comma: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::KeysetTypeSpecifier(ctx.get_arena().alloc(KeysetTypeSpecifierChildren {
keyword,
left_angle,
type_,
trailing_comma,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_tuple_type_explicit_specifier(ctx: &C, keyword: Self, left_angle: Self, types: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::TupleTypeExplicitSpecifier(ctx.get_arena().alloc(TupleTypeExplicitSpecifierChildren {
keyword,
left_angle,
types,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_varray_type_specifier(ctx: &C, keyword: Self, left_angle: Self, type_: Self, trailing_comma: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::VarrayTypeSpecifier(ctx.get_arena().alloc(VarrayTypeSpecifierChildren {
keyword,
left_angle,
type_,
trailing_comma,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_type_parameter(ctx: &C, attribute_spec: Self, reified: Self, variance: Self, name: Self, param_params: Self, constraints: Self) -> Self {
let syntax = SyntaxVariant::TypeParameter(ctx.get_arena().alloc(TypeParameterChildren {
attribute_spec,
reified,
variance,
name,
param_params,
constraints,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_type_constraint(ctx: &C, keyword: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::TypeConstraint(ctx.get_arena().alloc(TypeConstraintChildren {
keyword,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_darray_type_specifier(ctx: &C, keyword: Self, left_angle: Self, key: Self, comma: Self, value: Self, trailing_comma: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::DarrayTypeSpecifier(ctx.get_arena().alloc(DarrayTypeSpecifierChildren {
keyword,
left_angle,
key,
comma,
value,
trailing_comma,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_dictionary_type_specifier(ctx: &C, keyword: Self, left_angle: Self, members: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::DictionaryTypeSpecifier(ctx.get_arena().alloc(DictionaryTypeSpecifierChildren {
keyword,
left_angle,
members,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_closure_type_specifier(ctx: &C, outer_left_paren: Self, function_keyword: Self, inner_left_paren: Self, parameter_list: Self, inner_right_paren: Self, capability: Self, colon: Self, return_type: Self, outer_right_paren: Self) -> Self {
let syntax = SyntaxVariant::ClosureTypeSpecifier(ctx.get_arena().alloc(ClosureTypeSpecifierChildren {
outer_left_paren,
function_keyword,
inner_left_paren,
parameter_list,
inner_right_paren,
capability,
colon,
return_type,
outer_right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_closure_parameter_type_specifier(ctx: &C, call_convention: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::ClosureParameterTypeSpecifier(ctx.get_arena().alloc(ClosureParameterTypeSpecifierChildren {
call_convention,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_classname_type_specifier(ctx: &C, keyword: Self, left_angle: Self, type_: Self, trailing_comma: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::ClassnameTypeSpecifier(ctx.get_arena().alloc(ClassnameTypeSpecifierChildren {
keyword,
left_angle,
type_,
trailing_comma,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_field_specifier(ctx: &C, question: Self, name: Self, arrow: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::FieldSpecifier(ctx.get_arena().alloc(FieldSpecifierChildren {
question,
name,
arrow,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_field_initializer(ctx: &C, name: Self, arrow: Self, value: Self) -> Self {
let syntax = SyntaxVariant::FieldInitializer(ctx.get_arena().alloc(FieldInitializerChildren {
name,
arrow,
value,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_shape_type_specifier(ctx: &C, keyword: Self, left_paren: Self, fields: Self, ellipsis: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::ShapeTypeSpecifier(ctx.get_arena().alloc(ShapeTypeSpecifierChildren {
keyword,
left_paren,
fields,
ellipsis,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_shape_expression(ctx: &C, keyword: Self, left_paren: Self, fields: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::ShapeExpression(ctx.get_arena().alloc(ShapeExpressionChildren {
keyword,
left_paren,
fields,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_tuple_expression(ctx: &C, keyword: Self, left_paren: Self, items: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::TupleExpression(ctx.get_arena().alloc(TupleExpressionChildren {
keyword,
left_paren,
items,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_generic_type_specifier(ctx: &C, class_type: Self, argument_list: Self) -> Self {
let syntax = SyntaxVariant::GenericTypeSpecifier(ctx.get_arena().alloc(GenericTypeSpecifierChildren {
class_type,
argument_list,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_nullable_type_specifier(ctx: &C, question: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::NullableTypeSpecifier(ctx.get_arena().alloc(NullableTypeSpecifierChildren {
question,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_like_type_specifier(ctx: &C, tilde: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::LikeTypeSpecifier(ctx.get_arena().alloc(LikeTypeSpecifierChildren {
tilde,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_soft_type_specifier(ctx: &C, at: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::SoftTypeSpecifier(ctx.get_arena().alloc(SoftTypeSpecifierChildren {
at,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_attributized_specifier(ctx: &C, attribute_spec: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::AttributizedSpecifier(ctx.get_arena().alloc(AttributizedSpecifierChildren {
attribute_spec,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_reified_type_argument(ctx: &C, reified: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::ReifiedTypeArgument(ctx.get_arena().alloc(ReifiedTypeArgumentChildren {
reified,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_type_arguments(ctx: &C, left_angle: Self, types: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::TypeArguments(ctx.get_arena().alloc(TypeArgumentsChildren {
left_angle,
types,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_type_parameters(ctx: &C, left_angle: Self, parameters: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::TypeParameters(ctx.get_arena().alloc(TypeParametersChildren {
left_angle,
parameters,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_tuple_type_specifier(ctx: &C, left_paren: Self, types: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::TupleTypeSpecifier(ctx.get_arena().alloc(TupleTypeSpecifierChildren {
left_paren,
types,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_union_type_specifier(ctx: &C, left_paren: Self, types: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::UnionTypeSpecifier(ctx.get_arena().alloc(UnionTypeSpecifierChildren {
left_paren,
types,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_intersection_type_specifier(ctx: &C, left_paren: Self, types: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::IntersectionTypeSpecifier(ctx.get_arena().alloc(IntersectionTypeSpecifierChildren {
left_paren,
types,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_error(ctx: &C, error: Self) -> Self {
let syntax = SyntaxVariant::ErrorSyntax(ctx.get_arena().alloc(ErrorSyntaxChildren {
error,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_list_item(ctx: &C, item: Self, separator: Self) -> Self {
let syntax = SyntaxVariant::ListItem(ctx.get_arena().alloc(ListItemChildren {
item,
separator,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_enum_atom_expression(ctx: &C, hash: Self, expression: Self) -> Self {
let syntax = SyntaxVariant::EnumAtomExpression(ctx.get_arena().alloc(EnumAtomExpressionChildren {
hash,
expression,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
}
| 41.16145 | 270 | 0.61625 |
e5af762649d9e7543918f5cae8625447aae4e056 | 1,195 | /*
* Ory APIs
*
* Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers.
*
* The version of the OpenAPI document: v0.0.1-alpha.93
* Contact: [email protected]
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SettingsProfileFormConfig {
/// Action should be used as the form action URL `<form action=\"{{ .Action }}\" method=\"post\">`.
#[serde(rename = "action")]
pub action: String,
#[serde(rename = "messages", skip_serializing_if = "Option::is_none")]
pub messages: Option<Vec<crate::models::UiText>>,
/// Method is the form method (e.g. POST)
#[serde(rename = "method")]
pub method: String,
#[serde(rename = "nodes")]
pub nodes: Vec<crate::models::UiNode>,
}
impl SettingsProfileFormConfig {
pub fn new(action: String, method: String, nodes: Vec<crate::models::UiNode>) -> SettingsProfileFormConfig {
SettingsProfileFormConfig {
action,
messages: None,
method,
nodes,
}
}
}
| 29.875 | 179 | 0.651046 |
14afec603cda41fc3f3de1044290436de9341131 | 15,078 | //! See `CompletionItem` structure.
use std::fmt;
use hir::{Documentation, Mutability};
use ide_db::{
helpers::{
import_assets::LocatedImport,
insert_use::{self, ImportScope, InsertUseConfig},
mod_path_to_ast, SnippetCap,
},
SymbolKind,
};
use stdx::{format_to, impl_from, never};
use syntax::{algo, TextRange};
use text_edit::TextEdit;
/// `CompletionItem` describes a single completion variant in the editor pop-up.
/// It is basically a POD with various properties. To construct a
/// `CompletionItem`, use `new` method and the `Builder` struct.
#[derive(Clone)]
pub struct CompletionItem {
/// Used only internally in tests, to check only specific kind of
/// completion (postfix, keyword, reference, etc).
#[allow(unused)]
pub(crate) completion_kind: CompletionKind,
/// Label in the completion pop up which identifies completion.
label: String,
/// Range of identifier that is being completed.
///
/// It should be used primarily for UI, but we also use this to convert
/// genetic TextEdit into LSP's completion edit (see conv.rs).
///
/// `source_range` must contain the completion offset. `insert_text` should
/// start with what `source_range` points to, or VSCode will filter out the
/// completion silently.
source_range: TextRange,
/// What happens when user selects this item.
///
/// Typically, replaces `source_range` with new identifier.
text_edit: TextEdit,
insert_text_format: InsertTextFormat,
/// What item (struct, function, etc) are we completing.
kind: Option<CompletionItemKind>,
/// Lookup is used to check if completion item indeed can complete current
/// ident.
///
/// That is, in `foo.bar$0` lookup of `abracadabra` will be accepted (it
/// contains `bar` sub sequence), and `quux` will rejected.
lookup: Option<String>,
/// Additional info to show in the UI pop up.
detail: Option<String>,
documentation: Option<Documentation>,
/// Whether this item is marked as deprecated
deprecated: bool,
/// If completing a function call, ask the editor to show parameter popup
/// after completion.
trigger_call_info: bool,
/// We use this to sort completion. Relevance records facts like "do the
/// types align precisely?". We can't sort by relevances directly, they are
/// only partially ordered.
///
/// Note that Relevance ignores fuzzy match score. We compute Relevance for
/// all possible items, and then separately build an ordered completion list
/// based on relevance and fuzzy matching with the already typed identifier.
relevance: Relevance,
/// Indicates that a reference or mutable reference to this variable is a
/// possible match.
ref_match: Option<Mutability>,
/// The import data to add to completion's edits.
import_to_add: Option<ImportEdit>,
}
// We use custom debug for CompletionItem to make snapshot tests more readable.
impl fmt::Debug for CompletionItem {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s = f.debug_struct("CompletionItem");
s.field("label", &self.label()).field("source_range", &self.source_range());
if self.text_edit().len() == 1 {
let atom = &self.text_edit().iter().next().unwrap();
s.field("delete", &atom.delete);
s.field("insert", &atom.insert);
} else {
s.field("text_edit", &self.text_edit);
}
if let Some(kind) = self.kind().as_ref() {
s.field("kind", kind);
}
if self.lookup() != self.label() {
s.field("lookup", &self.lookup());
}
if let Some(detail) = self.detail() {
s.field("detail", &detail);
}
if let Some(documentation) = self.documentation() {
s.field("documentation", &documentation);
}
if self.deprecated {
s.field("deprecated", &true);
}
if self.relevance.is_relevant() {
s.field("relevance", &self.relevance);
}
if let Some(mutability) = &self.ref_match {
s.field("ref_match", &format!("&{}", mutability.as_keyword_for_ref()));
}
if self.trigger_call_info {
s.field("trigger_call_info", &true);
}
s.finish()
}
}
#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq)]
pub enum CompletionScore {
/// If only type match
TypeMatch,
/// If type and name match
TypeAndNameMatch,
}
#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Default)]
pub struct Relevance {
/// This is set in cases like these:
///
/// ```
/// fn f(spam: String) {}
/// fn main {
/// let spam = 92;
/// f($0) // name of local matches the name of param
/// }
/// ```
pub exact_name_match: bool,
/// This is set in cases like these:
///
/// ```
/// fn f(spam: String) {}
/// fn main {
/// let foo = String::new();
/// f($0) // type of local matches the type of param
/// }
/// ```
pub exact_type_match: bool,
}
impl Relevance {
pub fn is_relevant(&self) -> bool {
self != &Relevance::default()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompletionItemKind {
SymbolKind(SymbolKind),
Attribute,
Binding,
BuiltinType,
Keyword,
Method,
Snippet,
UnresolvedReference,
}
impl_from!(SymbolKind for CompletionItemKind);
impl CompletionItemKind {
#[cfg(test)]
pub(crate) fn tag(&self) -> &'static str {
match self {
CompletionItemKind::SymbolKind(kind) => match kind {
SymbolKind::Const => "ct",
SymbolKind::ConstParam => "cp",
SymbolKind::Enum => "en",
SymbolKind::Field => "fd",
SymbolKind::Function => "fn",
SymbolKind::Impl => "im",
SymbolKind::Label => "lb",
SymbolKind::LifetimeParam => "lt",
SymbolKind::Local => "lc",
SymbolKind::Macro => "ma",
SymbolKind::Module => "md",
SymbolKind::SelfParam => "sp",
SymbolKind::Static => "sc",
SymbolKind::Struct => "st",
SymbolKind::Trait => "tt",
SymbolKind::TypeAlias => "ta",
SymbolKind::TypeParam => "tp",
SymbolKind::Union => "un",
SymbolKind::ValueParam => "vp",
SymbolKind::Variant => "ev",
},
CompletionItemKind::Attribute => "at",
CompletionItemKind::Binding => "bn",
CompletionItemKind::BuiltinType => "bt",
CompletionItemKind::Keyword => "kw",
CompletionItemKind::Method => "me",
CompletionItemKind::Snippet => "sn",
CompletionItemKind::UnresolvedReference => "??",
}
}
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub(crate) enum CompletionKind {
/// Parser-based keyword completion.
Keyword,
/// Your usual "complete all valid identifiers".
Reference,
/// "Secret sauce" completions.
Magic,
Snippet,
Postfix,
BuiltinType,
Attribute,
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum InsertTextFormat {
PlainText,
Snippet,
}
impl CompletionItem {
pub(crate) fn new(
completion_kind: CompletionKind,
source_range: TextRange,
label: impl Into<String>,
) -> Builder {
let label = label.into();
Builder {
source_range,
completion_kind,
label,
insert_text: None,
insert_text_format: InsertTextFormat::PlainText,
detail: None,
documentation: None,
lookup: None,
kind: None,
text_edit: None,
deprecated: false,
trigger_call_info: None,
relevance: Relevance::default(),
ref_match: None,
import_to_add: None,
}
}
/// What user sees in pop-up in the UI.
pub fn label(&self) -> &str {
&self.label
}
pub fn source_range(&self) -> TextRange {
self.source_range
}
pub fn insert_text_format(&self) -> InsertTextFormat {
self.insert_text_format
}
pub fn text_edit(&self) -> &TextEdit {
&self.text_edit
}
/// Short one-line additional information, like a type
pub fn detail(&self) -> Option<&str> {
self.detail.as_deref()
}
/// A doc-comment
pub fn documentation(&self) -> Option<Documentation> {
self.documentation.clone()
}
/// What string is used for filtering.
pub fn lookup(&self) -> &str {
self.lookup.as_deref().unwrap_or(&self.label)
}
pub fn kind(&self) -> Option<CompletionItemKind> {
self.kind
}
pub fn deprecated(&self) -> bool {
self.deprecated
}
pub fn relevance(&self) -> Relevance {
self.relevance
}
pub fn trigger_call_info(&self) -> bool {
self.trigger_call_info
}
pub fn ref_match(&self) -> Option<Mutability> {
self.ref_match
}
pub fn import_to_add(&self) -> Option<&ImportEdit> {
self.import_to_add.as_ref()
}
}
/// An extra import to add after the completion is applied.
#[derive(Debug, Clone)]
pub struct ImportEdit {
pub import: LocatedImport,
pub scope: ImportScope,
}
impl ImportEdit {
/// Attempts to insert the import to the given scope, producing a text edit.
/// May return no edit in edge cases, such as scope already containing the import.
pub fn to_text_edit(&self, cfg: InsertUseConfig) -> Option<TextEdit> {
let _p = profile::span("ImportEdit::to_text_edit");
let rewriter =
insert_use::insert_use(&self.scope, mod_path_to_ast(&self.import.import_path), cfg);
let old_ast = rewriter.rewrite_root()?;
let mut import_insert = TextEdit::builder();
algo::diff(&old_ast, &rewriter.rewrite(&old_ast)).into_text_edit(&mut import_insert);
Some(import_insert.finish())
}
}
/// A helper to make `CompletionItem`s.
#[must_use]
#[derive(Clone)]
pub(crate) struct Builder {
source_range: TextRange,
completion_kind: CompletionKind,
import_to_add: Option<ImportEdit>,
label: String,
insert_text: Option<String>,
insert_text_format: InsertTextFormat,
detail: Option<String>,
documentation: Option<Documentation>,
lookup: Option<String>,
kind: Option<CompletionItemKind>,
text_edit: Option<TextEdit>,
deprecated: bool,
trigger_call_info: Option<bool>,
relevance: Relevance,
ref_match: Option<Mutability>,
}
impl Builder {
pub(crate) fn build(self) -> CompletionItem {
let _p = profile::span("item::Builder::build");
let mut label = self.label;
let mut lookup = self.lookup;
let mut insert_text = self.insert_text;
if let Some(original_path) = self
.import_to_add
.as_ref()
.and_then(|import_edit| import_edit.import.original_path.as_ref())
{
lookup = lookup.or_else(|| Some(label.clone()));
insert_text = insert_text.or_else(|| Some(label.clone()));
let original_path_label = original_path.to_string();
if original_path_label.ends_with(&label) {
label = original_path_label;
} else {
format_to!(label, " ({})", original_path)
}
}
let text_edit = match self.text_edit {
Some(it) => it,
None => {
TextEdit::replace(self.source_range, insert_text.unwrap_or_else(|| label.clone()))
}
};
CompletionItem {
source_range: self.source_range,
label,
insert_text_format: self.insert_text_format,
text_edit,
detail: self.detail,
documentation: self.documentation,
lookup,
kind: self.kind,
completion_kind: self.completion_kind,
deprecated: self.deprecated,
trigger_call_info: self.trigger_call_info.unwrap_or(false),
relevance: self.relevance,
ref_match: self.ref_match,
import_to_add: self.import_to_add,
}
}
pub(crate) fn lookup_by(mut self, lookup: impl Into<String>) -> Builder {
self.lookup = Some(lookup.into());
self
}
pub(crate) fn label(mut self, label: impl Into<String>) -> Builder {
self.label = label.into();
self
}
pub(crate) fn insert_text(mut self, insert_text: impl Into<String>) -> Builder {
self.insert_text = Some(insert_text.into());
self
}
pub(crate) fn insert_snippet(
mut self,
_cap: SnippetCap,
snippet: impl Into<String>,
) -> Builder {
self.insert_text_format = InsertTextFormat::Snippet;
self.insert_text(snippet)
}
pub(crate) fn kind(mut self, kind: impl Into<CompletionItemKind>) -> Builder {
self.kind = Some(kind.into());
self
}
pub(crate) fn text_edit(mut self, edit: TextEdit) -> Builder {
self.text_edit = Some(edit);
self
}
pub(crate) fn snippet_edit(mut self, _cap: SnippetCap, edit: TextEdit) -> Builder {
self.insert_text_format = InsertTextFormat::Snippet;
self.text_edit(edit)
}
pub(crate) fn detail(self, detail: impl Into<String>) -> Builder {
self.set_detail(Some(detail))
}
pub(crate) fn set_detail(mut self, detail: Option<impl Into<String>>) -> Builder {
self.detail = detail.map(Into::into);
if let Some(detail) = &self.detail {
if never!(detail.contains('\n'), "multiline detail:\n{}", detail) {
self.detail = Some(detail.splitn(2, '\n').next().unwrap().to_string());
}
}
self
}
#[allow(unused)]
pub(crate) fn documentation(self, docs: Documentation) -> Builder {
self.set_documentation(Some(docs))
}
pub(crate) fn set_documentation(mut self, docs: Option<Documentation>) -> Builder {
self.documentation = docs.map(Into::into);
self
}
pub(crate) fn set_deprecated(mut self, deprecated: bool) -> Builder {
self.deprecated = deprecated;
self
}
pub(crate) fn set_relevance(mut self, relevance: Relevance) -> Builder {
self.relevance = relevance;
self
}
pub(crate) fn trigger_call_info(mut self) -> Builder {
self.trigger_call_info = Some(true);
self
}
pub(crate) fn add_import(mut self, import_to_add: Option<ImportEdit>) -> Builder {
self.import_to_add = import_to_add;
self
}
pub(crate) fn ref_match(mut self, mutability: Mutability) -> Builder {
self.ref_match = Some(mutability);
self
}
}
| 31.610063 | 98 | 0.593713 |
715533cf0a81d94e45b39e2c6fc560eab8e847f1 | 6,447 | use criterion::{Bencher, BenchmarkId, Criterion};
use std::mem;
/// Macro to build a benchmark.
macro_rules! benches {
(
$({
$len:expr, ($($member:ident),*), ($($insert:ident),*), $get:ident
};)*
) => {
fn benches(criterion: &mut Criterion) {
{
let mut group = criterion.benchmark_group("get");
$(
group.bench_with_input(BenchmarkId::new("fixed", $len), &$len, |b: &mut Bencher, _| {
#[allow(unused)]
#[derive(Clone, Copy, fixed_map::Key)]
pub enum Key { $($member,)* }
// Assert that size of Key is identical to array.
assert_eq!(
mem::size_of::<<Key as fixed_map::key::Key<Key, usize>>::Storage>(),
mem::size_of::<[Option<usize>; $len]>(),
);
let mut it = 1u32..;
let mut map = fixed_map::Map::new();
$(map.insert(Key::$insert, it.next().unwrap());)*
b.iter(|| map.get(Key::$get))
});
)*
$(
group.bench_with_input(BenchmarkId::new("hashbrown", $len), &$len, |b: &mut Bencher, _| {
#[allow(unused)]
#[derive(PartialEq, Eq, Hash)]
pub enum Key { $($member,)* }
let mut it = 1u32..;
let mut map = hashbrown::HashMap::with_capacity($len);
$(map.insert(Key::$insert, it.next().unwrap());)*
b.iter(|| map.get(&Key::$get))
});
)*
$(
group.bench_with_input(BenchmarkId::new("array", $len), &$len, |b: &mut Bencher, _| {
#[allow(unused)]
#[repr(usize)]
pub enum Key { $($member,)* }
let mut it = 1u32..;
let mut map = [None; $len];
$(map[Key::$insert as usize] = Some(it.next().unwrap());)*
b.iter(|| map[Key::$get as usize])
});
)*
}
{
let mut group = criterion.benchmark_group("insert");
$(
group.bench_with_input(BenchmarkId::new("fixed", $len), &$len, |b: &mut Bencher, _| {
#[allow(unused)]
#[derive(Clone, Copy, fixed_map::Key)]
pub enum Key { $($member,)* }
b.iter(|| {
let mut map = fixed_map::Map::<Key, u32>::new();
$(map.insert(Key::$insert, 42u32);)*
($(map.get(Key::$insert).cloned(),)*)
})
});
)*
$(
group.bench_with_input(BenchmarkId::new("hashbrown", $len), &$len, |b: &mut Bencher, _| {
#[allow(unused)]
#[derive(Clone, PartialEq, Eq, Hash)]
pub enum Key { $($member,)* }
b.iter(|| {
let mut map = hashbrown::HashMap::<_, u32>::with_capacity($len);
$(map.insert(Key::$insert, 42u32);)*
($(map.get(&Key::$insert).cloned(),)*)
})
});
)*
$(
group.bench_with_input(BenchmarkId::new("array", $len), &$len, |b: &mut Bencher, _| {
#[allow(unused)]
#[repr(usize)]
pub enum Key { $($member,)* }
b.iter(|| {
let mut map = [None; $len];
$(map[Key::$insert as usize] = Some(42u32);)*
($(map[Key::$insert as usize].as_ref().cloned(),)*)
})
});
)*
}
{
let mut group = criterion.benchmark_group("iter");
$(
group.bench_with_input(BenchmarkId::new("fixed", $len), &$len, |b: &mut Bencher, _| {
#[allow(unused)]
#[derive(Clone, Copy, fixed_map::Key)]
pub enum Key { $($member,)* }
let mut it = 1u32..;
let mut map = fixed_map::Map::new();
$(map.insert(Key::$insert, it.next().unwrap());)*
b.iter(|| map.values().cloned().sum::<u32>())
});
)*
$(
group.bench_with_input(BenchmarkId::new("hashbrown", $len), &$len, |b: &mut Bencher, len| {
#[allow(unused)]
#[derive(PartialEq, Eq, Hash)]
pub enum Key { $($member,)* }
let mut it = 1u32..;
let mut map = hashbrown::HashMap::with_capacity(*len);
$(map.insert(Key::$insert, it.next().unwrap());)*
b.iter(|| map.values().cloned().sum::<u32>())
});
)*
$(
group.bench_with_input(BenchmarkId::new("array", $len), &$len, |b: &mut Bencher, _| {
#[allow(unused)]
#[repr(usize)]
pub enum Key { $($member,)* }
let mut it = 1u32..;
let mut map = [None; $len];
$(map[Key::$insert as usize] = Some(it.next().unwrap());)*
b.iter(|| map.iter().flat_map(|v| v.clone()).sum::<u32>())
});
)*
}
}}
}
benches! {
{
4,
(T00, T01, T02, T03),
(T00, T03),
T03
};
{
8,
(T00, T01, T02, T03, T04, T05, T06, T07),
(T00, T03, T06),
T03
};
{
16,
(T00, T01, T02, T03, T04, T05, T06, T07, T8, T9, T10, T11, T12, T13, T14, T15),
(T00, T03, T06, T12, T14),
T14
};
{
32,
(
T00, T01, T02, T03, T04, T05, T06, T07, T08, T09, T10, T11, T12, T13, T14, T15,
T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31
),
(T00, T03, T06, T12, T14, T23, T28, T31),
T28
};
}
criterion::criterion_group! {
name = map_group;
config = Criterion::default();
targets = benches
}
criterion::criterion_main!(map_group);
| 32.725888 | 107 | 0.39119 |
226392b42d0a142674aaae49c0451904a7f7f375 | 1,837 | // Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_exception::Result;
use crate::sql::optimizer::PhysicalProperty;
use crate::sql::optimizer::RelExpr;
use crate::sql::optimizer::RelationalProperty;
use crate::sql::optimizer::SExpr;
use crate::sql::plans::LogicalPlan;
use crate::sql::plans::Operator;
use crate::sql::plans::PhysicalPlan;
use crate::sql::plans::RelOp;
use crate::sql::IndexType;
#[derive(Clone, Debug)]
pub struct Sort {
pub items: Vec<SortItem>,
}
#[derive(Clone, Debug)]
pub struct SortItem {
pub index: IndexType,
pub asc: Option<bool>,
pub nulls_first: Option<bool>,
}
impl Operator for Sort {
fn rel_op(&self) -> RelOp {
RelOp::Sort
}
fn is_physical(&self) -> bool {
true
}
fn is_logical(&self) -> bool {
true
}
fn as_physical(&self) -> Option<&dyn PhysicalPlan> {
Some(self)
}
fn as_logical(&self) -> Option<&dyn LogicalPlan> {
Some(self)
}
}
impl PhysicalPlan for Sort {
fn compute_physical_prop(&self, _expression: &SExpr) -> PhysicalProperty {
todo!()
}
}
impl LogicalPlan for Sort {
fn derive_relational_prop<'a>(&self, rel_expr: &RelExpr<'a>) -> Result<RelationalProperty> {
rel_expr.derive_relational_prop_child(0)
}
}
| 25.513889 | 96 | 0.679369 |
fbbf2ac80d51e278fca7df3504fe0d16417188f6 | 17,615 | // Copyright 2012-2013 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.
#![allow(non_camel_case_types)]
pub use self::named_ty::*;
use middle::subst;
use trans::adt;
use trans::common::*;
use trans::foreign;
use trans::machine;
use middle::ty::{self, Ty};
use util::ppaux;
use util::ppaux::Repr;
use trans::type_::Type;
use std::num::Int;
use syntax::abi;
use syntax::ast;
// LLVM doesn't like objects that are too big. Issue #17913
fn ensure_array_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
llet: Type,
size: machine::llsize,
scapegoat: Ty<'tcx>) {
let esz = machine::llsize_of_alloc(ccx, llet);
match esz.checked_mul(size) {
Some(n) if n < ccx.obj_size_bound() => {}
_ => { ccx.report_overbig_object(scapegoat) }
}
}
pub fn arg_is_indirect<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
arg_ty: Ty<'tcx>) -> bool {
!type_is_immediate(ccx, arg_ty)
}
pub fn return_uses_outptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
ty: Ty<'tcx>) -> bool {
!type_is_immediate(ccx, ty)
}
pub fn type_of_explicit_arg<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
arg_ty: Ty<'tcx>) -> Type {
let llty = arg_type_of(ccx, arg_ty);
if arg_is_indirect(ccx, arg_ty) {
llty.ptr_to()
} else {
llty
}
}
/// Yields the types of the "real" arguments for this function. For most
/// functions, these are simply the types of the arguments. For functions with
/// the `RustCall` ABI, however, this untuples the arguments of the function.
pub fn untuple_arguments_if_necessary<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
inputs: &[Ty<'tcx>],
abi: abi::Abi)
-> Vec<Ty<'tcx>> {
if abi != abi::RustCall {
return inputs.iter().map(|x| (*x).clone()).collect()
}
if inputs.len() == 0 {
return Vec::new()
}
let mut result = Vec::new();
for (i, &arg_prior_to_tuple) in inputs.iter().enumerate() {
if i < inputs.len() - 1 {
result.push(arg_prior_to_tuple);
}
}
match inputs[inputs.len() - 1].sty {
ty::ty_tup(ref tupled_arguments) => {
debug!("untuple_arguments_if_necessary(): untupling arguments");
for &tupled_argument in tupled_arguments.iter() {
result.push(tupled_argument);
}
}
_ => {
ccx.tcx().sess.bug("argument to function with \"rust-call\" ABI \
is neither a tuple nor unit")
}
}
result
}
pub fn type_of_rust_fn<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
llenvironment_type: Option<Type>,
inputs: &[Ty<'tcx>],
output: ty::FnOutput<'tcx>,
abi: abi::Abi)
-> Type {
let mut atys: Vec<Type> = Vec::new();
// First, munge the inputs, if this has the `rust-call` ABI.
let inputs = untuple_arguments_if_necessary(cx, inputs, abi);
// Arg 0: Output pointer.
// (if the output type is non-immediate)
let lloutputtype = match output {
ty::FnConverging(output) => {
let use_out_pointer = return_uses_outptr(cx, output);
let lloutputtype = arg_type_of(cx, output);
// Use the output as the actual return value if it's immediate.
if use_out_pointer {
atys.push(lloutputtype.ptr_to());
Type::void(cx)
} else if return_type_is_void(cx, output) {
Type::void(cx)
} else {
lloutputtype
}
}
ty::FnDiverging => Type::void(cx)
};
// Arg 1: Environment
match llenvironment_type {
None => {}
Some(llenvironment_type) => atys.push(llenvironment_type),
}
// ... then explicit args.
let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty));
atys.extend(input_tys);
Type::func(atys[], &lloutputtype)
}
// Given a function type and a count of ty params, construct an llvm type
pub fn type_of_fn_from_ty<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, fty: Ty<'tcx>) -> Type {
match fty.sty {
ty::ty_closure(ref f) => {
type_of_rust_fn(cx,
Some(Type::i8p(cx)),
f.sig.0.inputs.as_slice(),
f.sig.0.output,
f.abi)
}
ty::ty_bare_fn(_, ref f) => {
// FIXME(#19925) once fn item types are
// zero-sized, we'll need to do something here
if f.abi == abi::Rust || f.abi == abi::RustCall {
type_of_rust_fn(cx,
None,
f.sig.0.inputs.as_slice(),
f.sig.0.output,
f.abi)
} else {
foreign::lltype_for_foreign_fn(cx, fty)
}
}
_ => {
cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn")
}
}
}
// A "sizing type" is an LLVM type, the size and alignment of which are
// guaranteed to be equivalent to what you would get out of `type_of()`. It's
// useful because:
//
// (1) It may be cheaper to compute the sizing type than the full type if all
// you're interested in is the size and/or alignment;
//
// (2) It won't make any recursive calls to determine the structure of the
// type behind pointers. This can help prevent infinite loops for
// recursive types. For example, enum types rely on this behavior.
pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
match cx.llsizingtypes().borrow().get(&t).cloned() {
Some(t) => return t,
None => ()
}
let llsizingty = match t.sty {
_ if !lltype_is_sized(cx.tcx(), t) => {
cx.sess().bug(format!("trying to take the sizing type of {}, an unsized type",
ppaux::ty_to_string(cx.tcx(), t))[])
}
ty::ty_bool => Type::bool(cx),
ty::ty_char => Type::char(cx),
ty::ty_int(t) => Type::int_from_ty(cx, t),
ty::ty_uint(t) => Type::uint_from_ty(cx, t),
ty::ty_float(t) => Type::float_from_ty(cx, t),
ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => {
if type_is_sized(cx.tcx(), ty) {
Type::i8p(cx)
} else {
Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
}
}
ty::ty_bare_fn(..) => Type::i8p(cx),
ty::ty_closure(..) => Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false),
ty::ty_vec(ty, Some(size)) => {
let llty = sizing_type_of(cx, ty);
let size = size as u64;
ensure_array_fits_in_address_space(cx, llty, size, t);
Type::array(&llty, size)
}
ty::ty_tup(ref tys) if tys.is_empty() => {
Type::nil(cx)
}
ty::ty_tup(..) | ty::ty_enum(..) | ty::ty_unboxed_closure(..) => {
let repr = adt::represent_type(cx, t);
adt::sizing_type_of(cx, &*repr, false)
}
ty::ty_struct(..) => {
if ty::type_is_simd(cx.tcx(), t) {
let llet = type_of(cx, ty::simd_type(cx.tcx(), t));
let n = ty::simd_size(cx.tcx(), t) as u64;
ensure_array_fits_in_address_space(cx, llet, n, t);
Type::vector(&llet, n)
} else {
let repr = adt::represent_type(cx, t);
adt::sizing_type_of(cx, &*repr, false)
}
}
ty::ty_open(_) => {
Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
}
ty::ty_projection(..) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) => {
cx.sess().bug(format!("fictitious type {} in sizing_type_of()",
ppaux::ty_to_string(cx.tcx(), t))[])
}
ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => panic!("unreachable")
};
cx.llsizingtypes().borrow_mut().insert(t, llsizingty);
llsizingty
}
pub fn arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
if ty::type_is_bool(t) {
Type::i1(cx)
} else {
type_of(cx, t)
}
}
// NB: If you update this, be sure to update `sizing_type_of()` as well.
pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
fn type_of_unsize_info<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
// It is possible to end up here with a sized type. This happens with a
// struct which might be unsized, but is monomorphised to a sized type.
// In this case we'll fake a fat pointer with no unsize info (we use 0).
// However, its still a fat pointer, so we need some type use.
if type_is_sized(cx.tcx(), t) {
return Type::i8p(cx);
}
match unsized_part_of_type(cx.tcx(), t).sty {
ty::ty_str | ty::ty_vec(..) => Type::uint_from_ty(cx, ast::TyU),
ty::ty_trait(_) => Type::vtable_ptr(cx),
_ => panic!("Unexpected type returned from unsized_part_of_type : {}",
t.repr(cx.tcx()))
}
}
// Check the cache.
match cx.lltypes().borrow().get(&t) {
Some(&llty) => return llty,
None => ()
}
debug!("type_of {} {}", t.repr(cx.tcx()), t.sty);
// Replace any typedef'd types with their equivalent non-typedef
// type. This ensures that all LLVM nominal types that contain
// Rust types are defined as the same LLVM types. If we don't do
// this then, e.g. `Option<{myfield: bool}>` would be a different
// type than `Option<myrec>`.
let t_norm = ty::normalize_ty(cx.tcx(), t);
if t != t_norm {
let llty = type_of(cx, t_norm);
debug!("--> normalized {} {} to {} {} llty={}",
t.repr(cx.tcx()),
t,
t_norm.repr(cx.tcx()),
t_norm,
cx.tn().type_to_string(llty));
cx.lltypes().borrow_mut().insert(t, llty);
return llty;
}
let mut llty = match t.sty {
ty::ty_bool => Type::bool(cx),
ty::ty_char => Type::char(cx),
ty::ty_int(t) => Type::int_from_ty(cx, t),
ty::ty_uint(t) => Type::uint_from_ty(cx, t),
ty::ty_float(t) => Type::float_from_ty(cx, t),
ty::ty_enum(did, ref substs) => {
// Only create the named struct, but don't fill it in. We
// fill it in *after* placing it into the type cache. This
// avoids creating more than one copy of the enum when one
// of the enum's variants refers to the enum itself.
let repr = adt::represent_type(cx, t);
let tps = substs.types.get_slice(subst::TypeSpace);
let name = llvm_type_name(cx, an_enum, did, tps);
adt::incomplete_type_of(cx, &*repr, name[])
}
ty::ty_unboxed_closure(did, _, ref substs) => {
// Only create the named struct, but don't fill it in. We
// fill it in *after* placing it into the type cache.
let repr = adt::represent_type(cx, t);
// Unboxed closures can have substitutions in all spaces
// inherited from their environment, so we use entire
// contents of the VecPerParamSpace to to construct the llvm
// name
let name = llvm_type_name(cx, an_unboxed_closure, did, substs.types.as_slice());
adt::incomplete_type_of(cx, &*repr, name[])
}
ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => {
match ty.sty {
ty::ty_str => {
// This means we get a nicer name in the output (str is always
// unsized).
cx.tn().find_type("str_slice").unwrap()
}
ty::ty_trait(..) => Type::opaque_trait(cx),
_ if !type_is_sized(cx.tcx(), ty) => {
let p_ty = type_of(cx, ty).ptr_to();
Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, ty)], false)
}
_ => type_of(cx, ty).ptr_to(),
}
}
ty::ty_vec(ty, Some(size)) => {
let size = size as u64;
let llty = type_of(cx, ty);
ensure_array_fits_in_address_space(cx, llty, size, t);
Type::array(&llty, size)
}
ty::ty_vec(ty, None) => {
type_of(cx, ty)
}
ty::ty_trait(..) => {
Type::opaque_trait_data(cx)
}
ty::ty_str => Type::i8(cx),
ty::ty_bare_fn(..) => {
type_of_fn_from_ty(cx, t).ptr_to()
}
ty::ty_closure(_) => {
let fn_ty = type_of_fn_from_ty(cx, t).ptr_to();
Type::struct_(cx, &[fn_ty, Type::i8p(cx)], false)
}
ty::ty_tup(ref tys) if tys.is_empty() => Type::nil(cx),
ty::ty_tup(..) => {
let repr = adt::represent_type(cx, t);
adt::type_of(cx, &*repr)
}
ty::ty_struct(did, ref substs) => {
if ty::type_is_simd(cx.tcx(), t) {
let llet = type_of(cx, ty::simd_type(cx.tcx(), t));
let n = ty::simd_size(cx.tcx(), t) as u64;
ensure_array_fits_in_address_space(cx, llet, n, t);
Type::vector(&llet, n)
} else {
// Only create the named struct, but don't fill it in. We fill it
// in *after* placing it into the type cache. This prevents
// infinite recursion with recursive struct types.
let repr = adt::represent_type(cx, t);
let tps = substs.types.get_slice(subst::TypeSpace);
let name = llvm_type_name(cx, a_struct, did, tps);
adt::incomplete_type_of(cx, &*repr, name[])
}
}
ty::ty_open(t) => match t.sty {
ty::ty_struct(..) => {
let p_ty = type_of(cx, t).ptr_to();
Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
}
ty::ty_vec(ty, None) => {
let p_ty = type_of(cx, ty).ptr_to();
Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
}
ty::ty_str => {
let p_ty = Type::i8p(cx);
Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
}
ty::ty_trait(..) => Type::opaque_trait(cx),
_ => cx.sess().bug(format!("ty_open with sized type: {}",
ppaux::ty_to_string(cx.tcx(), t))[])
},
ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"),
ty::ty_projection(..) => cx.sess().bug("type_of with ty_projection"),
ty::ty_param(..) => cx.sess().bug("type_of with ty_param"),
ty::ty_err(..) => cx.sess().bug("type_of with ty_err"),
};
debug!("--> mapped t={} {} to llty={}",
t.repr(cx.tcx()),
t,
cx.tn().type_to_string(llty));
cx.lltypes().borrow_mut().insert(t, llty);
// If this was an enum or struct, fill in the type now.
match t.sty {
ty::ty_enum(..) | ty::ty_struct(..) | ty::ty_unboxed_closure(..)
if !ty::type_is_simd(cx.tcx(), t) => {
let repr = adt::represent_type(cx, t);
adt::finish_type_of(cx, &*repr, &mut llty);
}
_ => ()
}
return llty;
}
pub fn align_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>)
-> machine::llalign {
let llty = sizing_type_of(cx, t);
machine::llalign_of_min(cx, llty)
}
// Want refinements! (Or case classes, I guess
#[derive(Copy)]
pub enum named_ty {
a_struct,
an_enum,
an_unboxed_closure,
}
pub fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
what: named_ty,
did: ast::DefId,
tps: &[Ty<'tcx>])
-> String {
let name = match what {
a_struct => "struct",
an_enum => "enum",
an_unboxed_closure => return "closure".to_string(),
};
let base = ty::item_path_str(cx.tcx(), did);
let strings: Vec<String> = tps.iter().map(|t| t.repr(cx.tcx())).collect();
let tstr = if strings.is_empty() {
base
} else {
format!("{}<{}>", base, strings)
};
if did.krate == 0 {
format!("{}.{}", name, tstr)
} else {
format!("{}.{}[{}{}]", name, tstr, "#", did.krate)
}
}
pub fn type_of_dtor<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, self_ty: Ty<'tcx>) -> Type {
let self_ty = type_of(ccx, self_ty).ptr_to();
Type::func(&[self_ty], &Type::void(ccx))
}
| 36.244856 | 90 | 0.517513 |
87d4ad1baa3bc3f5e07ee6ff47ab7b5bc5d9b558 | 2,676 | use super::opcode;
#[derive(Debug, PartialEq)]
pub enum IR {
SHR(u32),
SHL(u32),
ADD(u8),
SUB(u8),
PUTCHAR,
GETCHAR,
JIZ(u32),
JNZ(u32),
}
#[derive(Debug)]
pub struct Code {
pub instrs: Vec<IR>,
}
impl Code {
pub fn from(data: Vec<opcode::Opcode>) -> Result<Self, Box<dyn std::error::Error>> {
let mut instrs: Vec<IR> = Vec::new();
let mut jstack: Vec<u32> = Vec::new();
for e in data {
match e {
opcode::Opcode::SHR => match instrs.last_mut() {
Some(IR::SHR(x)) => {
*x += 1;
}
_ => {
instrs.push(IR::SHR(1));
}
},
opcode::Opcode::SHL => match instrs.last_mut() {
Some(IR::SHL(x)) => {
*x += 1;
}
_ => {
instrs.push(IR::SHL(1));
}
},
opcode::Opcode::ADD => match instrs.last_mut() {
Some(IR::ADD(x)) => {
let (b, _) = x.overflowing_add(1);
*x = b;
}
_ => {
instrs.push(IR::ADD(1));
}
},
opcode::Opcode::SUB => match instrs.last_mut() {
Some(IR::SUB(x)) => {
let (b, _) = x.overflowing_add(1);
*x = b;
}
_ => {
instrs.push(IR::SUB(1));
}
},
opcode::Opcode::GETCHAR => {
instrs.push(IR::GETCHAR);
}
opcode::Opcode::PUTCHAR => {
instrs.push(IR::PUTCHAR);
}
opcode::Opcode::LB => {
instrs.push(IR::JIZ(0));
jstack.push((instrs.len() - 1) as u32);
}
opcode::Opcode::RB => {
let j = jstack.pop().ok_or("pop from empty list")?;
instrs.push(IR::JNZ(j));
let instrs_len = instrs.len();
match &mut instrs[j as usize] {
IR::JIZ(x) => {
*x = (instrs_len - 1) as u32;
}
_ => {
unimplemented!();
}
}
}
}
}
Ok(Code { instrs })
}
}
| 30.409091 | 88 | 0.314275 |
8a716d7bf08fb5202ab3c5fe3788c1a1842aab25 | 1,319 | //! [POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}](https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-rooms-roomid-receipt-receipttype-eventid)
use std::convert::TryFrom;
use ruma_api::ruma_api;
use ruma_identifiers::{EventId, RoomId};
use strum::{Display, EnumString};
ruma_api! {
metadata: {
description: "Send a receipt event to a room.",
method: POST,
name: "create_receipt",
path: "/_matrix/client/r0/rooms/:room_id/receipt/:receipt_type/:event_id",
rate_limited: true,
requires_authentication: true,
}
request: {
/// The room in which to send the event.
#[ruma_api(path)]
pub room_id: RoomId,
/// The type of receipt to send.
#[ruma_api(path)]
pub receipt_type: ReceiptType,
/// The event ID to acknowledge up to.
#[ruma_api(path)]
pub event_id: EventId,
}
response: {}
error: crate::Error
}
/// The type of receipt.
#[derive(Clone, Copy, Debug, Display, EnumString)]
pub enum ReceiptType {
/// m.read
#[strum(serialize = "m.read")]
Read,
}
impl TryFrom<&'_ str> for ReceiptType {
type Error = strum::ParseError;
fn try_from(s: &str) -> Result<Self, Self::Error> {
s.parse()
}
}
| 24.886792 | 190 | 0.620167 |
4a112cc270b6566f546f0f59e11d9906b79f55ac | 255 | // https://www.codewars.com/kata/514b92a657cdc65150000006
const divisors: [i32; 2] = [3, 5];
fn solution(limit: i32) -> i32 {
let mut sum = 0;
for i in 3..limit {
if divisors.iter().any(|div| i % div == 0) {
sum += i;
}
}
sum
}
| 15 | 57 | 0.552941 |
29d8cfc6e5ad68ad111788eef126b52d9c17aab0 | 10,361 | use ckb_hash::{blake2b_256, new_blake2b};
use crate::{packed, prelude::*};
/*
* Calculate simple hash for packed bytes wrappers.
*/
// Do NOT use this trait directly.
// Please call the methods which specify the hash content.
pub(crate) trait CalcHash {
fn calc_hash(&self) -> packed::Byte32;
}
impl<'r, R> CalcHash for R
where
R: Reader<'r>,
{
fn calc_hash(&self) -> packed::Byte32 {
blake2b_256(self.as_slice()).pack()
}
}
/*
* Calculate special hash for packed bytes wrappers.
*/
macro_rules! impl_calc_special_hash_for_entity {
($entity:ident, $func_name:ident) => {
impl packed::$entity {
pub fn $func_name(&self) -> packed::Byte32 {
self.as_reader().$func_name()
}
}
};
}
impl packed::CellOutput {
pub fn calc_data_hash(data: &[u8]) -> packed::Byte32 {
if data.is_empty() {
packed::Byte32::zero()
} else {
blake2b_256(data).pack()
}
}
}
impl<'r> packed::ScriptReader<'r> {
pub fn calc_script_hash(&self) -> packed::Byte32 {
self.calc_hash()
}
}
impl_calc_special_hash_for_entity!(Script, calc_script_hash);
impl<'r> packed::CellOutputReader<'r> {
pub fn calc_lock_hash(&self) -> packed::Byte32 {
self.lock().calc_script_hash()
}
}
impl_calc_special_hash_for_entity!(CellOutput, calc_lock_hash);
impl<'r> packed::ProposalShortIdVecReader<'r> {
pub fn calc_proposals_hash(&self) -> packed::Byte32 {
if self.is_empty() {
packed::Byte32::zero()
} else {
let mut ret = [0u8; 32];
let mut blake2b = new_blake2b();
for id in self.iter() {
blake2b.update(id.as_slice());
}
blake2b.finalize(&mut ret);
ret.pack()
}
}
}
impl_calc_special_hash_for_entity!(ProposalShortIdVec, calc_proposals_hash);
impl<'r> packed::TransactionReader<'r> {
pub fn calc_tx_hash(&self) -> packed::Byte32 {
self.raw().calc_hash()
}
pub fn calc_witness_hash(&self) -> packed::Byte32 {
self.calc_hash()
}
}
impl_calc_special_hash_for_entity!(Transaction, calc_tx_hash);
impl_calc_special_hash_for_entity!(Transaction, calc_witness_hash);
impl<'r> packed::RawHeaderReader<'r> {
pub fn calc_pow_hash(&self) -> packed::Byte32 {
self.calc_hash()
}
}
impl_calc_special_hash_for_entity!(RawHeader, calc_pow_hash);
impl<'r> packed::HeaderReader<'r> {
pub fn calc_pow_hash(&self) -> packed::Byte32 {
self.raw().calc_pow_hash()
}
pub fn calc_header_hash(&self) -> packed::Byte32 {
self.calc_hash()
}
}
impl_calc_special_hash_for_entity!(Header, calc_pow_hash);
impl_calc_special_hash_for_entity!(Header, calc_header_hash);
impl<'r> packed::UncleBlockReader<'r> {
pub fn calc_header_hash(&self) -> packed::Byte32 {
self.header().calc_header_hash()
}
pub fn calc_proposals_hash(&self) -> packed::Byte32 {
self.proposals().calc_proposals_hash()
}
}
impl_calc_special_hash_for_entity!(UncleBlock, calc_header_hash);
impl_calc_special_hash_for_entity!(UncleBlock, calc_proposals_hash);
impl<'r> packed::UncleBlockVecReader<'r> {
pub fn calc_uncles_hash(&self) -> packed::Byte32 {
if self.is_empty() {
packed::Byte32::zero()
} else {
let mut ret = [0u8; 32];
let mut blake2b = new_blake2b();
for uncle in self.iter() {
blake2b.update(uncle.calc_header_hash().as_slice());
}
blake2b.finalize(&mut ret);
ret.pack()
}
}
}
impl_calc_special_hash_for_entity!(UncleBlockVec, calc_uncles_hash);
impl<'r> packed::BlockReader<'r> {
pub fn calc_header_hash(&self) -> packed::Byte32 {
self.header().calc_header_hash()
}
pub fn calc_proposals_hash(&self) -> packed::Byte32 {
self.proposals().calc_proposals_hash()
}
pub fn calc_uncles_hash(&self) -> packed::Byte32 {
self.uncles().calc_uncles_hash()
}
pub fn calc_tx_hashes(&self) -> Vec<packed::Byte32> {
self.transactions()
.iter()
.map(|tx| tx.calc_tx_hash())
.collect::<Vec<_>>()
}
pub fn calc_tx_witness_hashes(&self) -> Vec<packed::Byte32> {
self.transactions()
.iter()
.map(|tx| tx.calc_witness_hash())
.collect::<Vec<_>>()
}
}
impl_calc_special_hash_for_entity!(Block, calc_header_hash);
impl_calc_special_hash_for_entity!(Block, calc_proposals_hash);
impl_calc_special_hash_for_entity!(Block, calc_uncles_hash);
impl packed::Block {
pub fn calc_tx_hashes(&self) -> Vec<packed::Byte32> {
self.as_reader().calc_tx_hashes()
}
pub fn calc_tx_witness_hashes(&self) -> Vec<packed::Byte32> {
self.as_reader().calc_tx_witness_hashes()
}
}
impl<'r> packed::CompactBlockReader<'r> {
pub fn calc_header_hash(&self) -> packed::Byte32 {
self.header().calc_header_hash()
}
}
impl_calc_special_hash_for_entity!(CompactBlock, calc_header_hash);
impl<'r> packed::RawAlertReader<'r> {
pub fn calc_alert_hash(&self) -> packed::Byte32 {
self.calc_hash()
}
}
impl_calc_special_hash_for_entity!(RawAlert, calc_alert_hash);
impl<'r> packed::AlertReader<'r> {
pub fn calc_alert_hash(&self) -> packed::Byte32 {
self.raw().calc_alert_hash()
}
}
impl_calc_special_hash_for_entity!(Alert, calc_alert_hash);
#[cfg(test)]
mod tests {
use crate::{h256, packed, prelude::*, H256};
use ckb_hash::blake2b_256;
#[test]
fn proposals_hash() {
let proposal1 = [1; 10].pack();
let proposal2 = [2; 10].pack();
let proposals = vec![proposal1, proposal2].pack();
let expect = h256!("0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562");
assert_eq!(proposals.calc_proposals_hash(), expect.pack());
}
#[test]
fn empty_proposals_hash() {
let proposals = packed::ProposalShortIdVec::new_builder().build();
let expect = h256!("0x0");
assert_eq!(proposals.calc_proposals_hash(), expect.pack());
}
#[test]
fn uncles_hash() {
let uncle1_raw_header = packed::RawHeader::new_builder()
.version(0u32.pack())
.compact_target(0x1e08_3126u32.pack())
.timestamp(0x5cd2_b117u64.pack())
.number(0x400u64.pack())
.epoch(0x0007_0800_1800_0001u64.pack())
.parent_hash(
h256!("0x8381df265c9442d5c27559b167892c5a6a8322871112d3cc8ef45222c6624831").pack(),
)
.transactions_root(
h256!("0x12214693b8bd5c3d8f96e270dc8fe32b1702bd97630a9eab53a69793e6bc893f").pack(),
)
.proposals_hash(
h256!("0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562").pack(),
)
.uncles_hash(
h256!("0x0000000000000000000000000000000000000000000000000000000000000000").pack(),
)
.dao(h256!("0xb54bdd7f6be90000bb52f392d41cd70024f7ef29b437000000febffacf030000").pack())
.build();
let uncle1_header = packed::Header::new_builder()
.raw(uncle1_raw_header)
.nonce(0x5ff1_389a_f870_6543_11a2_bee6_1237u128.pack())
.build();
let uncle1_proposals = vec![[1; 10].pack(), [2; 10].pack()].pack();
let uncle1 = packed::UncleBlock::new_builder()
.header(uncle1_header)
.proposals(uncle1_proposals)
.build();
let uncle2_raw_header = packed::RawHeader::new_builder()
.version(0u32.pack())
.compact_target(0x2001_0000u32.pack())
.timestamp(0x5cd2_1a16u64.pack())
.number(0x400u64.pack())
.epoch(0x0007_0800_1800_0001u64.pack())
.parent_hash(
h256!("0x8381df265c9442d5c27559b167892c5a6a8322871112d3cc8ef45222c6624831").pack(),
)
.transactions_root(
h256!("0x12214693b8bd5c3d8f96e270dc8fe32b1702bd97630a9eab53a69793e6bc893f").pack(),
)
.proposals_hash(
h256!("0x0000000000000000000000000000000000000000000000000000000000000000").pack(),
)
.uncles_hash(
h256!("0x0000000000000000000000000000000000000000000000000000000000000000").pack(),
)
.dao(h256!("0xb54bdd7f6be90000bb52f392d41cd70024f7ef29b437000000febffacf030000").pack())
.build();
let uncle2_header = packed::Header::new_builder()
.raw(uncle2_raw_header)
.nonce(0x2f39_2d41_cd70_024fu128.pack())
.build();
let uncle2 = packed::UncleBlock::new_builder()
.header(uncle2_header)
.build();
let uncles = vec![uncle1, uncle2].pack();
let expect = h256!("0x0135d01f169a870bd9c92b2b37aecfa0fbfb7c1862cc176e03bb525fab0649d9");
assert_eq!(uncles.calc_uncles_hash(), expect.pack());
}
#[test]
fn empty_uncles_hash() {
let uncles = packed::UncleBlockVec::new_builder().build();
let expect = h256!("0x0");
assert_eq!(uncles.calc_uncles_hash(), expect.pack());
}
#[test]
fn empty_script_hash() {
let script = packed::Script::new_builder().build();
let expect = h256!("0x77c93b0632b5b6c3ef922c5b7cea208fb0a7c427a13d50e13d3fefad17e0c590");
assert_eq!(script.calc_script_hash(), expect.pack());
}
#[test]
fn always_success_script_hash() {
let always_success = include_bytes!("../../../../script/testdata/always_success");
let always_success_hash = blake2b_256(&always_success[..]);
let script = packed::Script::new_builder()
.code_hash(always_success_hash.pack())
.build();
let expect = h256!("0x4ceaa32f692948413e213ce6f3a83337145bde6e11fd8cb94377ce2637dcc412");
assert_eq!(script.calc_script_hash(), expect.pack());
}
#[test]
fn one_arg_script_hash() {
let script = packed::Script::new_builder().args(vec![1].pack()).build();
let expect = h256!("0x67951b34bce20cb71b7e235c1f8cda259628d99d94825bffe549c23b4dd2930f");
assert_eq!(script.calc_script_hash(), expect.pack());
}
}
| 32.277259 | 100 | 0.627449 |
d6bd4596aa6f055b9ada83219fb655cbab6618d8 | 49,987 | // This file is generated by rust-protobuf 2.0.2. Do not edit
// @generated
// https://github.com/Manishearth/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy)]
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(trivial_casts)]
#![allow(unsafe_code)]
#![allow(unused_imports)]
#![allow(unused_results)]
use protobuf::Message as Message_imported_for_functions;
use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions;
#[derive(PartialEq,Clone,Default,Debug)]
pub struct CastMessage {
// message fields
protocol_version: ::std::option::Option<CastMessage_ProtocolVersion>,
source_id: ::protobuf::SingularField<::std::string::String>,
destination_id: ::protobuf::SingularField<::std::string::String>,
namespace: ::protobuf::SingularField<::std::string::String>,
payload_type: ::std::option::Option<CastMessage_PayloadType>,
payload_utf8: ::protobuf::SingularField<::std::string::String>,
payload_binary: ::protobuf::SingularField<::std::vec::Vec<u8>>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl CastMessage {
pub fn new() -> CastMessage {
::std::default::Default::default()
}
// required .cast_channel.CastMessage.ProtocolVersion protocol_version = 1;
pub fn clear_protocol_version(&mut self) {
self.protocol_version = ::std::option::Option::None;
}
pub fn has_protocol_version(&self) -> bool {
self.protocol_version.is_some()
}
// Param is passed by value, moved
pub fn set_protocol_version(&mut self, v: CastMessage_ProtocolVersion) {
self.protocol_version = ::std::option::Option::Some(v);
}
pub fn get_protocol_version(&self) -> CastMessage_ProtocolVersion {
self.protocol_version.unwrap_or(CastMessage_ProtocolVersion::CASTV2_1_0)
}
// required string source_id = 2;
pub fn clear_source_id(&mut self) {
self.source_id.clear();
}
pub fn has_source_id(&self) -> bool {
self.source_id.is_some()
}
// Param is passed by value, moved
pub fn set_source_id(&mut self, v: ::std::string::String) {
self.source_id = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_source_id(&mut self) -> &mut ::std::string::String {
if self.source_id.is_none() {
self.source_id.set_default();
}
self.source_id.as_mut().unwrap()
}
// Take field
pub fn take_source_id(&mut self) -> ::std::string::String {
self.source_id.take().unwrap_or_else(|| ::std::string::String::new())
}
pub fn get_source_id(&self) -> &str {
match self.source_id.as_ref() {
Some(v) => &v,
None => "",
}
}
// required string destination_id = 3;
pub fn clear_destination_id(&mut self) {
self.destination_id.clear();
}
pub fn has_destination_id(&self) -> bool {
self.destination_id.is_some()
}
// Param is passed by value, moved
pub fn set_destination_id(&mut self, v: ::std::string::String) {
self.destination_id = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_destination_id(&mut self) -> &mut ::std::string::String {
if self.destination_id.is_none() {
self.destination_id.set_default();
}
self.destination_id.as_mut().unwrap()
}
// Take field
pub fn take_destination_id(&mut self) -> ::std::string::String {
self.destination_id.take().unwrap_or_else(|| ::std::string::String::new())
}
pub fn get_destination_id(&self) -> &str {
match self.destination_id.as_ref() {
Some(v) => &v,
None => "",
}
}
// required string namespace = 4;
pub fn clear_namespace(&mut self) {
self.namespace.clear();
}
pub fn has_namespace(&self) -> bool {
self.namespace.is_some()
}
// Param is passed by value, moved
pub fn set_namespace(&mut self, v: ::std::string::String) {
self.namespace = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_namespace(&mut self) -> &mut ::std::string::String {
if self.namespace.is_none() {
self.namespace.set_default();
}
self.namespace.as_mut().unwrap()
}
// Take field
pub fn take_namespace(&mut self) -> ::std::string::String {
self.namespace.take().unwrap_or_else(|| ::std::string::String::new())
}
pub fn get_namespace(&self) -> &str {
match self.namespace.as_ref() {
Some(v) => &v,
None => "",
}
}
// required .cast_channel.CastMessage.PayloadType payload_type = 5;
pub fn clear_payload_type(&mut self) {
self.payload_type = ::std::option::Option::None;
}
pub fn has_payload_type(&self) -> bool {
self.payload_type.is_some()
}
// Param is passed by value, moved
pub fn set_payload_type(&mut self, v: CastMessage_PayloadType) {
self.payload_type = ::std::option::Option::Some(v);
}
pub fn get_payload_type(&self) -> CastMessage_PayloadType {
self.payload_type.unwrap_or(CastMessage_PayloadType::STRING)
}
// optional string payload_utf8 = 6;
pub fn clear_payload_utf8(&mut self) {
self.payload_utf8.clear();
}
pub fn has_payload_utf8(&self) -> bool {
self.payload_utf8.is_some()
}
// Param is passed by value, moved
pub fn set_payload_utf8(&mut self, v: ::std::string::String) {
self.payload_utf8 = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_payload_utf8(&mut self) -> &mut ::std::string::String {
if self.payload_utf8.is_none() {
self.payload_utf8.set_default();
}
self.payload_utf8.as_mut().unwrap()
}
// Take field
pub fn take_payload_utf8(&mut self) -> ::std::string::String {
self.payload_utf8.take().unwrap_or_else(|| ::std::string::String::new())
}
pub fn get_payload_utf8(&self) -> &str {
match self.payload_utf8.as_ref() {
Some(v) => &v,
None => "",
}
}
// optional bytes payload_binary = 7;
pub fn clear_payload_binary(&mut self) {
self.payload_binary.clear();
}
pub fn has_payload_binary(&self) -> bool {
self.payload_binary.is_some()
}
// Param is passed by value, moved
pub fn set_payload_binary(&mut self, v: ::std::vec::Vec<u8>) {
self.payload_binary = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_payload_binary(&mut self) -> &mut ::std::vec::Vec<u8> {
if self.payload_binary.is_none() {
self.payload_binary.set_default();
}
self.payload_binary.as_mut().unwrap()
}
// Take field
pub fn take_payload_binary(&mut self) -> ::std::vec::Vec<u8> {
self.payload_binary.take().unwrap_or_else(|| ::std::vec::Vec::new())
}
pub fn get_payload_binary(&self) -> &[u8] {
match self.payload_binary.as_ref() {
Some(v) => &v,
None => &[],
}
}
}
impl ::protobuf::Message for CastMessage {
fn is_initialized(&self) -> bool {
if self.protocol_version.is_none() {
return false;
}
if self.source_id.is_none() {
return false;
}
if self.destination_id.is_none() {
return false;
}
if self.namespace.is_none() {
return false;
}
if self.payload_type.is_none() {
return false;
}
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
::protobuf::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.protocol_version, 1, &mut self.unknown_fields)?
},
2 => {
::protobuf::rt::read_singular_string_into(wire_type, is, &mut self.source_id)?;
},
3 => {
::protobuf::rt::read_singular_string_into(wire_type, is, &mut self.destination_id)?;
},
4 => {
::protobuf::rt::read_singular_string_into(wire_type, is, &mut self.namespace)?;
},
5 => {
::protobuf::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.payload_type, 5, &mut self.unknown_fields)?
},
6 => {
::protobuf::rt::read_singular_string_into(wire_type, is, &mut self.payload_utf8)?;
},
7 => {
::protobuf::rt::read_singular_bytes_into(wire_type, is, &mut self.payload_binary)?;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if let Some(v) = self.protocol_version {
my_size += ::protobuf::rt::enum_size(1, v);
}
if let Some(ref v) = self.source_id.as_ref() {
my_size += ::protobuf::rt::string_size(2, &v);
}
if let Some(ref v) = self.destination_id.as_ref() {
my_size += ::protobuf::rt::string_size(3, &v);
}
if let Some(ref v) = self.namespace.as_ref() {
my_size += ::protobuf::rt::string_size(4, &v);
}
if let Some(v) = self.payload_type {
my_size += ::protobuf::rt::enum_size(5, v);
}
if let Some(ref v) = self.payload_utf8.as_ref() {
my_size += ::protobuf::rt::string_size(6, &v);
}
if let Some(ref v) = self.payload_binary.as_ref() {
my_size += ::protobuf::rt::bytes_size(7, &v);
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if let Some(v) = self.protocol_version {
os.write_enum(1, v.value())?;
}
if let Some(ref v) = self.source_id.as_ref() {
os.write_string(2, &v)?;
}
if let Some(ref v) = self.destination_id.as_ref() {
os.write_string(3, &v)?;
}
if let Some(ref v) = self.namespace.as_ref() {
os.write_string(4, &v)?;
}
if let Some(v) = self.payload_type {
os.write_enum(5, v.value())?;
}
if let Some(ref v) = self.payload_utf8.as_ref() {
os.write_string(6, &v)?;
}
if let Some(ref v) = self.payload_binary.as_ref() {
os.write_bytes(7, &v)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> CastMessage {
CastMessage::new()
}
fn default_instance() -> &'static CastMessage {
static mut instance: ::protobuf::lazy::Lazy<CastMessage> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const CastMessage,
};
unsafe {
instance.get(CastMessage::new)
}
}
}
impl ::protobuf::Clear for CastMessage {
fn clear(&mut self) {
self.clear_protocol_version();
self.clear_source_id();
self.clear_destination_id();
self.clear_namespace();
self.clear_payload_type();
self.clear_payload_utf8();
self.clear_payload_binary();
self.unknown_fields.clear();
}
}
impl ::protobuf::reflect::ProtobufValue for CastMessage {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(Clone,PartialEq,Eq,Debug,Hash)]
pub enum CastMessage_ProtocolVersion {
CASTV2_1_0 = 0,
}
impl ::protobuf::ProtobufEnum for CastMessage_ProtocolVersion {
fn value(&self) -> i32 {
*self as i32
}
fn from_i32(value: i32) -> ::std::option::Option<CastMessage_ProtocolVersion> {
match value {
0 => ::std::option::Option::Some(CastMessage_ProtocolVersion::CASTV2_1_0),
_ => ::std::option::Option::None
}
}
fn values() -> &'static [Self] {
static values: &'static [CastMessage_ProtocolVersion] = &[
CastMessage_ProtocolVersion::CASTV2_1_0,
];
values
}
}
impl ::std::marker::Copy for CastMessage_ProtocolVersion {
}
impl ::protobuf::reflect::ProtobufValue for CastMessage_ProtocolVersion {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Enum(self.descriptor())
}
}
#[derive(Clone,PartialEq,Eq,Debug,Hash)]
pub enum CastMessage_PayloadType {
STRING = 0,
BINARY = 1,
}
impl ::protobuf::ProtobufEnum for CastMessage_PayloadType {
fn value(&self) -> i32 {
*self as i32
}
fn from_i32(value: i32) -> ::std::option::Option<CastMessage_PayloadType> {
match value {
0 => ::std::option::Option::Some(CastMessage_PayloadType::STRING),
1 => ::std::option::Option::Some(CastMessage_PayloadType::BINARY),
_ => ::std::option::Option::None
}
}
fn values() -> &'static [Self] {
static values: &'static [CastMessage_PayloadType] = &[
CastMessage_PayloadType::STRING,
CastMessage_PayloadType::BINARY,
];
values
}
}
impl ::std::marker::Copy for CastMessage_PayloadType {
}
impl ::protobuf::reflect::ProtobufValue for CastMessage_PayloadType {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Enum(self.descriptor())
}
}
#[derive(PartialEq,Clone,Default,Debug)]
pub struct AuthChallenge {
// message fields
signature_algorithm: ::std::option::Option<SignatureAlgorithm>,
sender_nonce: ::protobuf::SingularField<::std::vec::Vec<u8>>,
hash_algorithm: ::std::option::Option<HashAlgorithm>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl AuthChallenge {
pub fn new() -> AuthChallenge {
::std::default::Default::default()
}
// optional .cast_channel.SignatureAlgorithm signature_algorithm = 1;
pub fn clear_signature_algorithm(&mut self) {
self.signature_algorithm = ::std::option::Option::None;
}
pub fn has_signature_algorithm(&self) -> bool {
self.signature_algorithm.is_some()
}
// Param is passed by value, moved
pub fn set_signature_algorithm(&mut self, v: SignatureAlgorithm) {
self.signature_algorithm = ::std::option::Option::Some(v);
}
pub fn get_signature_algorithm(&self) -> SignatureAlgorithm {
self.signature_algorithm.unwrap_or(SignatureAlgorithm::RSASSA_PKCS1v15)
}
// optional bytes sender_nonce = 2;
pub fn clear_sender_nonce(&mut self) {
self.sender_nonce.clear();
}
pub fn has_sender_nonce(&self) -> bool {
self.sender_nonce.is_some()
}
// Param is passed by value, moved
pub fn set_sender_nonce(&mut self, v: ::std::vec::Vec<u8>) {
self.sender_nonce = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_sender_nonce(&mut self) -> &mut ::std::vec::Vec<u8> {
if self.sender_nonce.is_none() {
self.sender_nonce.set_default();
}
self.sender_nonce.as_mut().unwrap()
}
// Take field
pub fn take_sender_nonce(&mut self) -> ::std::vec::Vec<u8> {
self.sender_nonce.take().unwrap_or_else(|| ::std::vec::Vec::new())
}
pub fn get_sender_nonce(&self) -> &[u8] {
match self.sender_nonce.as_ref() {
Some(v) => &v,
None => &[],
}
}
// optional .cast_channel.HashAlgorithm hash_algorithm = 3;
pub fn clear_hash_algorithm(&mut self) {
self.hash_algorithm = ::std::option::Option::None;
}
pub fn has_hash_algorithm(&self) -> bool {
self.hash_algorithm.is_some()
}
// Param is passed by value, moved
pub fn set_hash_algorithm(&mut self, v: HashAlgorithm) {
self.hash_algorithm = ::std::option::Option::Some(v);
}
pub fn get_hash_algorithm(&self) -> HashAlgorithm {
self.hash_algorithm.unwrap_or(HashAlgorithm::SHA1)
}
}
impl ::protobuf::Message for AuthChallenge {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
::protobuf::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.signature_algorithm, 1, &mut self.unknown_fields)?
},
2 => {
::protobuf::rt::read_singular_bytes_into(wire_type, is, &mut self.sender_nonce)?;
},
3 => {
::protobuf::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.hash_algorithm, 3, &mut self.unknown_fields)?
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if let Some(v) = self.signature_algorithm {
my_size += ::protobuf::rt::enum_size(1, v);
}
if let Some(ref v) = self.sender_nonce.as_ref() {
my_size += ::protobuf::rt::bytes_size(2, &v);
}
if let Some(v) = self.hash_algorithm {
my_size += ::protobuf::rt::enum_size(3, v);
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if let Some(v) = self.signature_algorithm {
os.write_enum(1, v.value())?;
}
if let Some(ref v) = self.sender_nonce.as_ref() {
os.write_bytes(2, &v)?;
}
if let Some(v) = self.hash_algorithm {
os.write_enum(3, v.value())?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> AuthChallenge {
AuthChallenge::new()
}
fn default_instance() -> &'static AuthChallenge {
static mut instance: ::protobuf::lazy::Lazy<AuthChallenge> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const AuthChallenge,
};
unsafe {
instance.get(AuthChallenge::new)
}
}
}
impl ::protobuf::Clear for AuthChallenge {
fn clear(&mut self) {
self.clear_signature_algorithm();
self.clear_sender_nonce();
self.clear_hash_algorithm();
self.unknown_fields.clear();
}
}
impl ::protobuf::reflect::ProtobufValue for AuthChallenge {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(PartialEq,Clone,Default,Debug)]
pub struct AuthResponse {
// message fields
signature: ::protobuf::SingularField<::std::vec::Vec<u8>>,
client_auth_certificate: ::protobuf::SingularField<::std::vec::Vec<u8>>,
intermediate_certificate: ::protobuf::RepeatedField<::std::vec::Vec<u8>>,
signature_algorithm: ::std::option::Option<SignatureAlgorithm>,
sender_nonce: ::protobuf::SingularField<::std::vec::Vec<u8>>,
hash_algorithm: ::std::option::Option<HashAlgorithm>,
crl: ::protobuf::SingularField<::std::vec::Vec<u8>>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl AuthResponse {
pub fn new() -> AuthResponse {
::std::default::Default::default()
}
// required bytes signature = 1;
pub fn clear_signature(&mut self) {
self.signature.clear();
}
pub fn has_signature(&self) -> bool {
self.signature.is_some()
}
// Param is passed by value, moved
pub fn set_signature(&mut self, v: ::std::vec::Vec<u8>) {
self.signature = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_signature(&mut self) -> &mut ::std::vec::Vec<u8> {
if self.signature.is_none() {
self.signature.set_default();
}
self.signature.as_mut().unwrap()
}
// Take field
pub fn take_signature(&mut self) -> ::std::vec::Vec<u8> {
self.signature.take().unwrap_or_else(|| ::std::vec::Vec::new())
}
pub fn get_signature(&self) -> &[u8] {
match self.signature.as_ref() {
Some(v) => &v,
None => &[],
}
}
// required bytes client_auth_certificate = 2;
pub fn clear_client_auth_certificate(&mut self) {
self.client_auth_certificate.clear();
}
pub fn has_client_auth_certificate(&self) -> bool {
self.client_auth_certificate.is_some()
}
// Param is passed by value, moved
pub fn set_client_auth_certificate(&mut self, v: ::std::vec::Vec<u8>) {
self.client_auth_certificate = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_client_auth_certificate(&mut self) -> &mut ::std::vec::Vec<u8> {
if self.client_auth_certificate.is_none() {
self.client_auth_certificate.set_default();
}
self.client_auth_certificate.as_mut().unwrap()
}
// Take field
pub fn take_client_auth_certificate(&mut self) -> ::std::vec::Vec<u8> {
self.client_auth_certificate.take().unwrap_or_else(|| ::std::vec::Vec::new())
}
pub fn get_client_auth_certificate(&self) -> &[u8] {
match self.client_auth_certificate.as_ref() {
Some(v) => &v,
None => &[],
}
}
// repeated bytes intermediate_certificate = 3;
pub fn clear_intermediate_certificate(&mut self) {
self.intermediate_certificate.clear();
}
// Param is passed by value, moved
pub fn set_intermediate_certificate(&mut self, v: ::protobuf::RepeatedField<::std::vec::Vec<u8>>) {
self.intermediate_certificate = v;
}
// Mutable pointer to the field.
pub fn mut_intermediate_certificate(&mut self) -> &mut ::protobuf::RepeatedField<::std::vec::Vec<u8>> {
&mut self.intermediate_certificate
}
// Take field
pub fn take_intermediate_certificate(&mut self) -> ::protobuf::RepeatedField<::std::vec::Vec<u8>> {
::std::mem::replace(&mut self.intermediate_certificate, ::protobuf::RepeatedField::new())
}
pub fn get_intermediate_certificate(&self) -> &[::std::vec::Vec<u8>] {
&self.intermediate_certificate
}
// optional .cast_channel.SignatureAlgorithm signature_algorithm = 4;
pub fn clear_signature_algorithm(&mut self) {
self.signature_algorithm = ::std::option::Option::None;
}
pub fn has_signature_algorithm(&self) -> bool {
self.signature_algorithm.is_some()
}
// Param is passed by value, moved
pub fn set_signature_algorithm(&mut self, v: SignatureAlgorithm) {
self.signature_algorithm = ::std::option::Option::Some(v);
}
pub fn get_signature_algorithm(&self) -> SignatureAlgorithm {
self.signature_algorithm.unwrap_or(SignatureAlgorithm::RSASSA_PKCS1v15)
}
// optional bytes sender_nonce = 5;
pub fn clear_sender_nonce(&mut self) {
self.sender_nonce.clear();
}
pub fn has_sender_nonce(&self) -> bool {
self.sender_nonce.is_some()
}
// Param is passed by value, moved
pub fn set_sender_nonce(&mut self, v: ::std::vec::Vec<u8>) {
self.sender_nonce = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_sender_nonce(&mut self) -> &mut ::std::vec::Vec<u8> {
if self.sender_nonce.is_none() {
self.sender_nonce.set_default();
}
self.sender_nonce.as_mut().unwrap()
}
// Take field
pub fn take_sender_nonce(&mut self) -> ::std::vec::Vec<u8> {
self.sender_nonce.take().unwrap_or_else(|| ::std::vec::Vec::new())
}
pub fn get_sender_nonce(&self) -> &[u8] {
match self.sender_nonce.as_ref() {
Some(v) => &v,
None => &[],
}
}
// optional .cast_channel.HashAlgorithm hash_algorithm = 6;
pub fn clear_hash_algorithm(&mut self) {
self.hash_algorithm = ::std::option::Option::None;
}
pub fn has_hash_algorithm(&self) -> bool {
self.hash_algorithm.is_some()
}
// Param is passed by value, moved
pub fn set_hash_algorithm(&mut self, v: HashAlgorithm) {
self.hash_algorithm = ::std::option::Option::Some(v);
}
pub fn get_hash_algorithm(&self) -> HashAlgorithm {
self.hash_algorithm.unwrap_or(HashAlgorithm::SHA1)
}
// optional bytes crl = 7;
pub fn clear_crl(&mut self) {
self.crl.clear();
}
pub fn has_crl(&self) -> bool {
self.crl.is_some()
}
// Param is passed by value, moved
pub fn set_crl(&mut self, v: ::std::vec::Vec<u8>) {
self.crl = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_crl(&mut self) -> &mut ::std::vec::Vec<u8> {
if self.crl.is_none() {
self.crl.set_default();
}
self.crl.as_mut().unwrap()
}
// Take field
pub fn take_crl(&mut self) -> ::std::vec::Vec<u8> {
self.crl.take().unwrap_or_else(|| ::std::vec::Vec::new())
}
pub fn get_crl(&self) -> &[u8] {
match self.crl.as_ref() {
Some(v) => &v,
None => &[],
}
}
}
impl ::protobuf::Message for AuthResponse {
fn is_initialized(&self) -> bool {
if self.signature.is_none() {
return false;
}
if self.client_auth_certificate.is_none() {
return false;
}
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
::protobuf::rt::read_singular_bytes_into(wire_type, is, &mut self.signature)?;
},
2 => {
::protobuf::rt::read_singular_bytes_into(wire_type, is, &mut self.client_auth_certificate)?;
},
3 => {
::protobuf::rt::read_repeated_bytes_into(wire_type, is, &mut self.intermediate_certificate)?;
},
4 => {
::protobuf::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.signature_algorithm, 4, &mut self.unknown_fields)?
},
5 => {
::protobuf::rt::read_singular_bytes_into(wire_type, is, &mut self.sender_nonce)?;
},
6 => {
::protobuf::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.hash_algorithm, 6, &mut self.unknown_fields)?
},
7 => {
::protobuf::rt::read_singular_bytes_into(wire_type, is, &mut self.crl)?;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if let Some(ref v) = self.signature.as_ref() {
my_size += ::protobuf::rt::bytes_size(1, &v);
}
if let Some(ref v) = self.client_auth_certificate.as_ref() {
my_size += ::protobuf::rt::bytes_size(2, &v);
}
for value in &self.intermediate_certificate {
my_size += ::protobuf::rt::bytes_size(3, &value);
};
if let Some(v) = self.signature_algorithm {
my_size += ::protobuf::rt::enum_size(4, v);
}
if let Some(ref v) = self.sender_nonce.as_ref() {
my_size += ::protobuf::rt::bytes_size(5, &v);
}
if let Some(v) = self.hash_algorithm {
my_size += ::protobuf::rt::enum_size(6, v);
}
if let Some(ref v) = self.crl.as_ref() {
my_size += ::protobuf::rt::bytes_size(7, &v);
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if let Some(ref v) = self.signature.as_ref() {
os.write_bytes(1, &v)?;
}
if let Some(ref v) = self.client_auth_certificate.as_ref() {
os.write_bytes(2, &v)?;
}
for v in &self.intermediate_certificate {
os.write_bytes(3, &v)?;
};
if let Some(v) = self.signature_algorithm {
os.write_enum(4, v.value())?;
}
if let Some(ref v) = self.sender_nonce.as_ref() {
os.write_bytes(5, &v)?;
}
if let Some(v) = self.hash_algorithm {
os.write_enum(6, v.value())?;
}
if let Some(ref v) = self.crl.as_ref() {
os.write_bytes(7, &v)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> AuthResponse {
AuthResponse::new()
}
fn default_instance() -> &'static AuthResponse {
static mut instance: ::protobuf::lazy::Lazy<AuthResponse> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const AuthResponse,
};
unsafe {
instance.get(AuthResponse::new)
}
}
}
impl ::protobuf::Clear for AuthResponse {
fn clear(&mut self) {
self.clear_signature();
self.clear_client_auth_certificate();
self.clear_intermediate_certificate();
self.clear_signature_algorithm();
self.clear_sender_nonce();
self.clear_hash_algorithm();
self.clear_crl();
self.unknown_fields.clear();
}
}
impl ::protobuf::reflect::ProtobufValue for AuthResponse {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(PartialEq,Clone,Default,Debug)]
pub struct AuthError {
// message fields
error_type: ::std::option::Option<AuthError_ErrorType>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl AuthError {
pub fn new() -> AuthError {
::std::default::Default::default()
}
// required .cast_channel.AuthError.ErrorType error_type = 1;
pub fn clear_error_type(&mut self) {
self.error_type = ::std::option::Option::None;
}
pub fn has_error_type(&self) -> bool {
self.error_type.is_some()
}
// Param is passed by value, moved
pub fn set_error_type(&mut self, v: AuthError_ErrorType) {
self.error_type = ::std::option::Option::Some(v);
}
pub fn get_error_type(&self) -> AuthError_ErrorType {
self.error_type.unwrap_or(AuthError_ErrorType::INTERNAL_ERROR)
}
}
impl ::protobuf::Message for AuthError {
fn is_initialized(&self) -> bool {
if self.error_type.is_none() {
return false;
}
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
::protobuf::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.error_type, 1, &mut self.unknown_fields)?
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if let Some(v) = self.error_type {
my_size += ::protobuf::rt::enum_size(1, v);
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if let Some(v) = self.error_type {
os.write_enum(1, v.value())?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> AuthError {
AuthError::new()
}
fn default_instance() -> &'static AuthError {
static mut instance: ::protobuf::lazy::Lazy<AuthError> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const AuthError,
};
unsafe {
instance.get(AuthError::new)
}
}
}
impl ::protobuf::Clear for AuthError {
fn clear(&mut self) {
self.clear_error_type();
self.unknown_fields.clear();
}
}
impl ::protobuf::reflect::ProtobufValue for AuthError {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(Clone,PartialEq,Eq,Debug,Hash)]
pub enum AuthError_ErrorType {
INTERNAL_ERROR = 0,
NO_TLS = 1,
SIGNATURE_ALGORITHM_UNAVAILABLE = 2,
}
impl ::protobuf::ProtobufEnum for AuthError_ErrorType {
fn value(&self) -> i32 {
*self as i32
}
fn from_i32(value: i32) -> ::std::option::Option<AuthError_ErrorType> {
match value {
0 => ::std::option::Option::Some(AuthError_ErrorType::INTERNAL_ERROR),
1 => ::std::option::Option::Some(AuthError_ErrorType::NO_TLS),
2 => ::std::option::Option::Some(AuthError_ErrorType::SIGNATURE_ALGORITHM_UNAVAILABLE),
_ => ::std::option::Option::None
}
}
fn values() -> &'static [Self] {
static values: &'static [AuthError_ErrorType] = &[
AuthError_ErrorType::INTERNAL_ERROR,
AuthError_ErrorType::NO_TLS,
AuthError_ErrorType::SIGNATURE_ALGORITHM_UNAVAILABLE,
];
values
}
}
impl ::std::marker::Copy for AuthError_ErrorType {
}
impl ::protobuf::reflect::ProtobufValue for AuthError_ErrorType {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Enum(self.descriptor())
}
}
#[derive(PartialEq,Clone,Default,Debug)]
pub struct DeviceAuthMessage {
// message fields
challenge: ::protobuf::SingularPtrField<AuthChallenge>,
response: ::protobuf::SingularPtrField<AuthResponse>,
error: ::protobuf::SingularPtrField<AuthError>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl DeviceAuthMessage {
pub fn new() -> DeviceAuthMessage {
::std::default::Default::default()
}
// optional .cast_channel.AuthChallenge challenge = 1;
pub fn clear_challenge(&mut self) {
self.challenge.clear();
}
pub fn has_challenge(&self) -> bool {
self.challenge.is_some()
}
// Param is passed by value, moved
pub fn set_challenge(&mut self, v: AuthChallenge) {
self.challenge = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_challenge(&mut self) -> &mut AuthChallenge {
if self.challenge.is_none() {
self.challenge.set_default();
}
self.challenge.as_mut().unwrap()
}
// Take field
pub fn take_challenge(&mut self) -> AuthChallenge {
self.challenge.take().unwrap_or_else(|| AuthChallenge::new())
}
pub fn get_challenge(&self) -> &AuthChallenge {
self.challenge.as_ref().unwrap_or_else(|| AuthChallenge::default_instance())
}
// optional .cast_channel.AuthResponse response = 2;
pub fn clear_response(&mut self) {
self.response.clear();
}
pub fn has_response(&self) -> bool {
self.response.is_some()
}
// Param is passed by value, moved
pub fn set_response(&mut self, v: AuthResponse) {
self.response = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_response(&mut self) -> &mut AuthResponse {
if self.response.is_none() {
self.response.set_default();
}
self.response.as_mut().unwrap()
}
// Take field
pub fn take_response(&mut self) -> AuthResponse {
self.response.take().unwrap_or_else(|| AuthResponse::new())
}
pub fn get_response(&self) -> &AuthResponse {
self.response.as_ref().unwrap_or_else(|| AuthResponse::default_instance())
}
// optional .cast_channel.AuthError error = 3;
pub fn clear_error(&mut self) {
self.error.clear();
}
pub fn has_error(&self) -> bool {
self.error.is_some()
}
// Param is passed by value, moved
pub fn set_error(&mut self, v: AuthError) {
self.error = ::protobuf::SingularPtrField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_error(&mut self) -> &mut AuthError {
if self.error.is_none() {
self.error.set_default();
}
self.error.as_mut().unwrap()
}
// Take field
pub fn take_error(&mut self) -> AuthError {
self.error.take().unwrap_or_else(|| AuthError::new())
}
pub fn get_error(&self) -> &AuthError {
self.error.as_ref().unwrap_or_else(|| AuthError::default_instance())
}
}
impl ::protobuf::Message for DeviceAuthMessage {
fn is_initialized(&self) -> bool {
for v in &self.challenge {
if !v.is_initialized() {
return false;
}
};
for v in &self.response {
if !v.is_initialized() {
return false;
}
};
for v in &self.error {
if !v.is_initialized() {
return false;
}
};
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
1 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.challenge)?;
},
2 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.response)?;
},
3 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.error)?;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if let Some(ref v) = self.challenge.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
if let Some(ref v) = self.response.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
if let Some(ref v) = self.error.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if let Some(ref v) = self.challenge.as_ref() {
os.write_tag(1, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
if let Some(ref v) = self.response.as_ref() {
os.write_tag(2, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
if let Some(ref v) = self.error.as_ref() {
os.write_tag(3, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> DeviceAuthMessage {
DeviceAuthMessage::new()
}
fn default_instance() -> &'static DeviceAuthMessage {
static mut instance: ::protobuf::lazy::Lazy<DeviceAuthMessage> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const DeviceAuthMessage,
};
unsafe {
instance.get(DeviceAuthMessage::new)
}
}
}
impl ::protobuf::Clear for DeviceAuthMessage {
fn clear(&mut self) {
self.clear_challenge();
self.clear_response();
self.clear_error();
self.unknown_fields.clear();
}
}
impl ::protobuf::reflect::ProtobufValue for DeviceAuthMessage {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
#[derive(Clone,PartialEq,Eq,Debug,Hash)]
pub enum SignatureAlgorithm {
UNSPECIFIED = 0,
RSASSA_PKCS1v15 = 1,
RSASSA_PSS = 2,
}
impl ::protobuf::ProtobufEnum for SignatureAlgorithm {
fn value(&self) -> i32 {
*self as i32
}
fn from_i32(value: i32) -> ::std::option::Option<SignatureAlgorithm> {
match value {
0 => ::std::option::Option::Some(SignatureAlgorithm::UNSPECIFIED),
1 => ::std::option::Option::Some(SignatureAlgorithm::RSASSA_PKCS1v15),
2 => ::std::option::Option::Some(SignatureAlgorithm::RSASSA_PSS),
_ => ::std::option::Option::None
}
}
fn values() -> &'static [Self] {
static values: &'static [SignatureAlgorithm] = &[
SignatureAlgorithm::UNSPECIFIED,
SignatureAlgorithm::RSASSA_PKCS1v15,
SignatureAlgorithm::RSASSA_PSS,
];
values
}
}
impl ::std::marker::Copy for SignatureAlgorithm {
}
impl ::protobuf::reflect::ProtobufValue for SignatureAlgorithm {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Enum(self.descriptor())
}
}
#[derive(Clone,PartialEq,Eq,Debug,Hash)]
pub enum HashAlgorithm {
SHA1 = 0,
SHA256 = 1,
}
impl ::protobuf::ProtobufEnum for HashAlgorithm {
fn value(&self) -> i32 {
*self as i32
}
fn from_i32(value: i32) -> ::std::option::Option<HashAlgorithm> {
match value {
0 => ::std::option::Option::Some(HashAlgorithm::SHA1),
1 => ::std::option::Option::Some(HashAlgorithm::SHA256),
_ => ::std::option::Option::None
}
}
fn values() -> &'static [Self] {
static values: &'static [HashAlgorithm] = &[
HashAlgorithm::SHA1,
HashAlgorithm::SHA256,
];
values
}
}
impl ::std::marker::Copy for HashAlgorithm {
}
impl ::protobuf::reflect::ProtobufValue for HashAlgorithm {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Enum(self.descriptor())
}
}
| 31.300564 | 153 | 0.586913 |
f757b5160d37830813a17e157ab3f5a19c570601 | 507 | // TODO create error type
mod heketi;
mod plugin;
mod util;
use log::error;
#[tokio::main]
async fn main() {
env_logger::Builder::from_env(
env_logger::Env::new().default_filter_or("docker_volume_glusterfs_rs=INFO"),
)
.init();
let client = heketi::Client::new("http://localhost:8080".into(), "admin".into())
.expect("Failed to connect to client");
if let Err(e) = plugin::run_server("glusterfs.sock", "glusterfs.db", client).await {
error!("{}", e);
}
}
| 23.045455 | 88 | 0.623274 |
e9d6b30ff66e9e1ce294b22f4ebced5464dc01a8 | 9,944 | use std::any::Any;
use std::any::TypeId;
use std::fmt;
use std::io::Read;
use std::io::Write;
#[cfg(feature = "bytes")]
use bytes::Bytes;
use crate::clear::Clear;
use crate::coded_input_stream::CodedInputStream;
use crate::coded_input_stream::WithCodedInputStream;
use crate::coded_output_stream::with_coded_output_stream_to_bytes;
use crate::coded_output_stream::CodedOutputStream;
use crate::coded_output_stream::WithCodedOutputStream;
use crate::error::ProtobufError;
use crate::error::ProtobufResult;
use crate::reflect::MessageDescriptor;
use crate::unknown::UnknownFields;
/// Trait implemented for all generated structs for protobuf messages.
///
/// Also, generated messages implement `Clone + Default + PartialEq`
pub trait Message: fmt::Debug + Clear + Any + Send + Sync {
/// Message descriptor for this message, used for reflection.
fn descriptor(&self) -> &'static MessageDescriptor;
/// True iff all required fields are initialized.
/// Always returns `true` for protobuf 3.
fn is_initialized(&self) -> bool;
/// Update this message object with fields read from given stream.
fn merge_from(&mut self, is: &mut CodedInputStream) -> ProtobufResult<()>;
/// Parse message from stream.
fn parse_from(is: &mut CodedInputStream) -> ProtobufResult<Self>
where
Self: Sized,
{
let mut r: Self = Message::new();
r.merge_from(is)?;
r.check_initialized()?;
Ok(r)
}
/// Write message to the stream.
///
/// Sizes of this messages and nested messages must be cached
/// by calling `compute_size` prior to this call.
fn write_to_with_cached_sizes(&self, os: &mut CodedOutputStream) -> ProtobufResult<()>;
/// Compute and cache size of this message and all nested messages
fn compute_size(&self) -> u32;
/// Get size previously computed by `compute_size`.
fn get_cached_size(&self) -> u32;
/// Write the message to the stream.
///
/// Results in error if message is not fully initialized.
fn write_to(&self, os: &mut CodedOutputStream) -> ProtobufResult<()> {
self.check_initialized()?;
// cache sizes
self.compute_size();
// TODO: reserve additional
self.write_to_with_cached_sizes(os)?;
Ok(())
}
/// Write the message to the stream prepending the message with message length
/// encoded as varint.
fn write_length_delimited_to(&self, os: &mut CodedOutputStream) -> ProtobufResult<()> {
let size = self.compute_size();
os.write_raw_varint32(size)?;
self.write_to_with_cached_sizes(os)?;
// TODO: assert we've written same number of bytes as computed
Ok(())
}
/// Write the message to the vec, prepend the message with message length
/// encoded as varint.
fn write_length_delimited_to_vec(&self, vec: &mut Vec<u8>) -> ProtobufResult<()> {
let mut os = CodedOutputStream::vec(vec);
self.write_length_delimited_to(&mut os)?;
os.flush()?;
Ok(())
}
/// Update this message object with fields read from given stream.
fn merge_from_bytes(&mut self, bytes: &[u8]) -> ProtobufResult<()> {
let mut is = CodedInputStream::from_bytes(bytes);
self.merge_from(&mut is)
}
/// Parse message from reader.
/// Parse stops on EOF or when error encountered.
fn parse_from_reader(reader: &mut dyn Read) -> ProtobufResult<Self>
where
Self: Sized,
{
let mut is = CodedInputStream::new(reader);
let r = Message::parse_from(&mut is)?;
is.check_eof()?;
Ok(r)
}
/// Parse message from byte array.
fn parse_from_bytes(bytes: &[u8]) -> ProtobufResult<Self>
where
Self: Sized,
{
let mut is = CodedInputStream::from_bytes(bytes);
let r = Message::parse_from(&mut is)?;
is.check_eof()?;
Ok(r)
}
/// Parse message from `Bytes` object.
/// Resulting message may share references to the passed bytes object.
#[cfg(feature = "bytes")]
fn parse_from_carllerche_bytes(bytes: &Bytes) -> ProtobufResult<Self>
where
Self: Sized,
{
let mut is = CodedInputStream::from_carllerche_bytes(bytes);
let r = Self::parse_from(&mut is)?;
is.check_eof()?;
Ok(r)
}
/// Check if all required fields of this object are initialized.
fn check_initialized(&self) -> ProtobufResult<()> {
if !self.is_initialized() {
Err(ProtobufError::message_not_initialized(
self.descriptor().name(),
))
} else {
Ok(())
}
}
/// Write the message to the writer.
fn write_to_writer(&self, w: &mut dyn Write) -> ProtobufResult<()> {
w.with_coded_output_stream(|os| self.write_to(os))
}
/// Write the message to bytes vec.
fn write_to_vec(&self, v: &mut Vec<u8>) -> ProtobufResult<()> {
v.with_coded_output_stream(|os| self.write_to(os))
}
/// Write the message to bytes vec.
fn write_to_bytes(&self) -> ProtobufResult<Vec<u8>> {
self.check_initialized()?;
let size = self.compute_size() as usize;
let mut v = Vec::with_capacity(size);
// skip zerofill
unsafe {
v.set_len(size);
}
{
let mut os = CodedOutputStream::bytes(&mut v);
self.write_to_with_cached_sizes(&mut os)?;
os.check_eof();
}
Ok(v)
}
/// Write the message to the writer, prepend the message with message length
/// encoded as varint.
fn write_length_delimited_to_writer(&self, w: &mut dyn Write) -> ProtobufResult<()> {
w.with_coded_output_stream(|os| self.write_length_delimited_to(os))
}
/// Write the message to the bytes vec, prepend the message with message length
/// encoded as varint.
fn write_length_delimited_to_bytes(&self) -> ProtobufResult<Vec<u8>> {
with_coded_output_stream_to_bytes(|os| self.write_length_delimited_to(os))
}
/// Get a reference to unknown fields.
fn get_unknown_fields<'s>(&'s self) -> &'s UnknownFields;
/// Get a mutable reference to unknown fields.
fn mut_unknown_fields<'s>(&'s mut self) -> &'s mut UnknownFields;
/// Get type id for downcasting.
fn type_id(&self) -> TypeId {
TypeId::of::<Self>()
}
/// View self as `Any`.
fn as_any(&self) -> &dyn Any;
/// View self as mutable `Any`.
fn as_any_mut(&mut self) -> &mut dyn Any {
panic!()
}
/// Convert boxed self to boxed `Any`.
fn into_any(self: Box<Self>) -> Box<dyn Any> {
panic!()
}
// Rust does not allow implementation of trait for trait:
// impl<M : Message> fmt::Debug for M {
// ...
// }
/// Create an empty message object.
///
///
/// ```
/// # use protobuf::Message;
/// # fn foo<MyMessage: Message>() {
/// let m = MyMessage::new();
/// # }
/// ```
fn new() -> Self
where
Self: Sized;
/// Get message descriptor for message type.
///
/// ```
/// # use protobuf::Message;
/// # fn foo<MyMessage: Message>() {
/// let descriptor = MyMessage::descriptor_static();
/// assert_eq!("MyMessage", descriptor.name());
/// # }
/// ```
fn descriptor_static() -> &'static MessageDescriptor
where
Self: Sized,
{
panic!(
"descriptor_static is not implemented for message, \
LITE_RUNTIME must be used"
);
}
/// Return a pointer to default immutable message with static lifetime.
///
/// ```
/// # use protobuf::Message;
/// # fn foo<MyMessage: Message>() {
/// let m: &MyMessage = MyMessage::default_instance();
/// # }
/// ```
fn default_instance() -> &'static Self
where
Self: Sized;
}
pub fn message_down_cast<'a, M: Message + 'a>(m: &'a dyn Message) -> &'a M {
m.as_any().downcast_ref::<M>().unwrap()
}
/// Parse message from reader.
/// Parse stops on EOF or when error encountered.
#[deprecated(since = "2.19", note = "Use Message::parse_from_reader instead")]
pub fn parse_from_reader<M: Message>(reader: &mut dyn Read) -> ProtobufResult<M> {
M::parse_from_reader(reader)
}
/// Parse message from byte array.
#[deprecated(since = "2.19", note = "Use Message::parse_from_bytes instead")]
pub fn parse_from_bytes<M: Message>(bytes: &[u8]) -> ProtobufResult<M> {
M::parse_from_bytes(bytes)
}
/// Parse message from `Bytes` object.
/// Resulting message may share references to the passed bytes object.
#[cfg(feature = "bytes")]
#[deprecated(
since = "2.19",
note = "Use Message::parse_from_carllerche_bytes instead"
)]
pub fn parse_from_carllerche_bytes<M: Message>(bytes: &Bytes) -> ProtobufResult<M> {
M::parse_from_carllerche_bytes(bytes)
}
/// Parse length-delimited message from stream.
///
/// Read varint length first, and read messages of that length then.
///
/// This function is deprecated and will be removed in the next major release.
#[deprecated]
pub fn parse_length_delimited_from<M: Message>(is: &mut CodedInputStream) -> ProtobufResult<M> {
is.read_message::<M>()
}
/// Parse length-delimited message from `Read`.
///
/// This function is deprecated and will be removed in the next major release.
#[deprecated]
pub fn parse_length_delimited_from_reader<M: Message>(r: &mut dyn Read) -> ProtobufResult<M> {
// TODO: wrong: we may read length first, and then read exact number of bytes needed
r.with_coded_input_stream(|is| is.read_message::<M>())
}
/// Parse length-delimited message from bytes.
///
/// This function is deprecated and will be removed in the next major release.
#[deprecated]
pub fn parse_length_delimited_from_bytes<M: Message>(bytes: &[u8]) -> ProtobufResult<M> {
bytes.with_coded_input_stream(|is| is.read_message::<M>())
}
| 31.769968 | 96 | 0.63043 |
b9d20085c599cc4b61a42ce0b9637c0831649d1e | 431,091 | // DO NOT EDIT !
// This file was generated automatically from 'src/mako/cli/main.rs.mako'
// DO NOT EDIT !
#![allow(unused_variables, unused_imports, dead_code, unused_mut)]
#[macro_use]
extern crate clap;
extern crate yup_oauth2 as oauth2;
extern crate yup_hyper_mock as mock;
extern crate hyper_rustls;
extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate mime;
extern crate strsim;
extern crate google_androidenterprise1 as api;
use std::env;
use std::io::{self, Write};
use clap::{App, SubCommand, Arg};
mod cmn;
use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg,
input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol,
calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo};
use std::default::Default;
use std::str::FromStr;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, FlowType};
use serde_json as json;
use clap::ArgMatches;
enum DoitError {
IoError(String, io::Error),
ApiError(api::Error),
}
struct Engine<'n> {
opt: ArgMatches<'n>,
hub: api::AndroidEnterprise<hyper::Client, Authenticator<DefaultAuthenticatorDelegate, JsonTokenStorage, hyper::Client>>,
gp: Vec<&'static str>,
gpm: Vec<(&'static str, &'static str)>,
}
impl<'n> Engine<'n> {
fn _devices_force_report_upload(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.devices().force_report_upload(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _devices_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.devices().get(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _devices_get_state(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.devices().get_state(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _devices_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.devices().list(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _devices_patch(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"policy.auto-update-policy" => Some(("policy.autoUpdatePolicy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"policy.maintenance-window.start-time-after-midnight-ms" => Some(("policy.maintenanceWindow.startTimeAfterMidnightMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"policy.maintenance-window.duration-ms" => Some(("policy.maintenanceWindow.durationMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"policy.device-report-policy" => Some(("policy.deviceReportPolicy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"policy.product-availability-policy" => Some(("policy.productAvailabilityPolicy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"report.last-updated-timestamp-millis" => Some(("report.lastUpdatedTimestampMillis", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"management-type" => Some(("managementType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"android-id" => Some(("androidId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["android-id", "auto-update-policy", "device-report-policy", "duration-ms", "kind", "last-updated-timestamp-millis", "maintenance-window", "management-type", "policy", "product-availability-policy", "report", "start-time-after-midnight-ms"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::Device = json::value::from_value(object).unwrap();
let mut call = self.hub.devices().patch(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"update-mask" => {
call = call.update_mask(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["update-mask"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _devices_set_state(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"account-state" => Some(("accountState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["account-state", "kind"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::DeviceState = json::value::from_value(object).unwrap();
let mut call = self.hub.devices().set_state(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _devices_update(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"policy.auto-update-policy" => Some(("policy.autoUpdatePolicy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"policy.maintenance-window.start-time-after-midnight-ms" => Some(("policy.maintenanceWindow.startTimeAfterMidnightMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"policy.maintenance-window.duration-ms" => Some(("policy.maintenanceWindow.durationMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"policy.device-report-policy" => Some(("policy.deviceReportPolicy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"policy.product-availability-policy" => Some(("policy.productAvailabilityPolicy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"report.last-updated-timestamp-millis" => Some(("report.lastUpdatedTimestampMillis", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"management-type" => Some(("managementType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"android-id" => Some(("androidId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["android-id", "auto-update-policy", "device-report-policy", "duration-ms", "kind", "last-updated-timestamp-millis", "maintenance-window", "management-type", "policy", "product-availability-policy", "report", "start-time-after-midnight-ms"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::Device = json::value::from_value(object).unwrap();
let mut call = self.hub.devices().update(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"update-mask" => {
call = call.update_mask(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["update-mask"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_acknowledge_notification_set(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.enterprises().acknowledge_notification_set();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"notification-set-id" => {
call = call.notification_set_id(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["notification-set-id"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _enterprises_complete_signup(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.enterprises().complete_signup();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"enterprise-token" => {
call = call.enterprise_token(value.unwrap_or(""));
},
"completion-token" => {
call = call.completion_token(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["enterprise-token", "completion-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_create_web_token(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"store-builder.enabled" => Some(("storeBuilder.enabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })),
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"play-search.approve-apps" => Some(("playSearch.approveApps", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })),
"play-search.enabled" => Some(("playSearch.enabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })),
"parent" => Some(("parent", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"private-apps.enabled" => Some(("privateApps.enabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })),
"permission" => Some(("permission", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
"web-apps.enabled" => Some(("webApps.enabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })),
"managed-configurations.enabled" => Some(("managedConfigurations.enabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["approve-apps", "enabled", "kind", "managed-configurations", "parent", "permission", "play-search", "private-apps", "store-builder", "web-apps"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::AdministratorWebTokenSpec = json::value::from_value(object).unwrap();
let mut call = self.hub.enterprises().create_web_token(request, opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_enroll(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"primary-domain" => Some(("primaryDomain", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["id", "kind", "name", "primary-domain"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::Enterprise = json::value::from_value(object).unwrap();
let mut call = self.hub.enterprises().enroll(request, opt.value_of("token").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_generate_signup_url(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.enterprises().generate_signup_url();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"callback-url" => {
call = call.callback_url(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["callback-url"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.enterprises().get(opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_get_service_account(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.enterprises().get_service_account(opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"key-type" => {
call = call.key_type(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["key-type"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_get_store_layout(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.enterprises().get_store_layout(opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.enterprises().list(opt.value_of("domain").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_pull_notification_set(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.enterprises().pull_notification_set();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"request-mode" => {
call = call.request_mode(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["request-mode"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_send_test_push_notification(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.enterprises().send_test_push_notification(opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_set_account(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"account-email" => Some(("accountEmail", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["account-email", "kind"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::EnterpriseAccount = json::value::from_value(object).unwrap();
let mut call = self.hub.enterprises().set_account(request, opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_set_store_layout(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"homepage-id" => Some(("homepageId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"store-layout-type" => Some(("storeLayoutType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["homepage-id", "kind", "store-layout-type"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::StoreLayout = json::value::from_value(object).unwrap();
let mut call = self.hub.enterprises().set_store_layout(request, opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _enterprises_unenroll(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.enterprises().unenroll(opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _entitlements_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.entitlements().delete(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("entitlement-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _entitlements_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.entitlements().get(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("entitlement-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _entitlements_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.entitlements().list(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _entitlements_patch(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"reason" => Some(("reason", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["kind", "product-id", "reason"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::Entitlement = json::value::from_value(object).unwrap();
let mut call = self.hub.entitlements().patch(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("entitlement-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"install" => {
call = call.install(arg_from_str(value.unwrap_or("false"), err, "install", "boolean"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["install"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _entitlements_update(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"reason" => Some(("reason", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["kind", "product-id", "reason"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::Entitlement = json::value::from_value(object).unwrap();
let mut call = self.hub.entitlements().update(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("entitlement-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"install" => {
call = call.install(arg_from_str(value.unwrap_or("false"), err, "install", "boolean"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["install"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _grouplicenses_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.grouplicenses().get(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("group-license-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _grouplicenses_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.grouplicenses().list(opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _grouplicenseusers_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.grouplicenseusers().list(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("group-license-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _installs_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.installs().delete(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""), opt.value_of("install-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _installs_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.installs().get(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""), opt.value_of("install-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _installs_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.installs().list(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _installs_patch(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"install-state" => Some(("installState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"version-code" => Some(("versionCode", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["install-state", "kind", "product-id", "version-code"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::Install = json::value::from_value(object).unwrap();
let mut call = self.hub.installs().patch(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""), opt.value_of("install-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _installs_update(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"install-state" => Some(("installState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"version-code" => Some(("versionCode", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["install-state", "kind", "product-id", "version-code"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::Install = json::value::from_value(object).unwrap();
let mut call = self.hub.installs().update(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""), opt.value_of("install-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _managedconfigurationsfordevice_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.managedconfigurationsfordevice().delete(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""), opt.value_of("managed-configuration-for-device-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _managedconfigurationsfordevice_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.managedconfigurationsfordevice().get(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""), opt.value_of("managed-configuration-for-device-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _managedconfigurationsfordevice_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.managedconfigurationsfordevice().list(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _managedconfigurationsfordevice_patch(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"configuration-variables.kind" => Some(("configurationVariables.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"configuration-variables.mcm-id" => Some(("configurationVariables.mcmId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["configuration-variables", "kind", "mcm-id", "product-id"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::ManagedConfiguration = json::value::from_value(object).unwrap();
let mut call = self.hub.managedconfigurationsfordevice().patch(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""), opt.value_of("managed-configuration-for-device-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _managedconfigurationsfordevice_update(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"configuration-variables.kind" => Some(("configurationVariables.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"configuration-variables.mcm-id" => Some(("configurationVariables.mcmId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["configuration-variables", "kind", "mcm-id", "product-id"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::ManagedConfiguration = json::value::from_value(object).unwrap();
let mut call = self.hub.managedconfigurationsfordevice().update(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("device-id").unwrap_or(""), opt.value_of("managed-configuration-for-device-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _managedconfigurationsforuser_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.managedconfigurationsforuser().delete(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("managed-configuration-for-user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _managedconfigurationsforuser_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.managedconfigurationsforuser().get(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("managed-configuration-for-user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _managedconfigurationsforuser_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.managedconfigurationsforuser().list(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _managedconfigurationsforuser_patch(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"configuration-variables.kind" => Some(("configurationVariables.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"configuration-variables.mcm-id" => Some(("configurationVariables.mcmId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["configuration-variables", "kind", "mcm-id", "product-id"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::ManagedConfiguration = json::value::from_value(object).unwrap();
let mut call = self.hub.managedconfigurationsforuser().patch(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("managed-configuration-for-user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _managedconfigurationsforuser_update(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"configuration-variables.kind" => Some(("configurationVariables.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"configuration-variables.mcm-id" => Some(("configurationVariables.mcmId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["configuration-variables", "kind", "mcm-id", "product-id"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::ManagedConfiguration = json::value::from_value(object).unwrap();
let mut call = self.hub.managedconfigurationsforuser().update(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""), opt.value_of("managed-configuration-for-user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _managedconfigurationssettings_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.managedconfigurationssettings().list(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("product-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _permissions_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.permissions().get(opt.value_of("permission-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"language" => {
call = call.language(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["language"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _products_approve(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"approved-permissions" => Some(("approvedPermissions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"approval-url-info.kind" => Some(("approvalUrlInfo.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"approval-url-info.approval-url" => Some(("approvalUrlInfo.approvalUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["approval-url", "approval-url-info", "approved-permissions", "kind"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::ProductsApproveRequest = json::value::from_value(object).unwrap();
let mut call = self.hub.products().approve(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("product-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _products_generate_approval_url(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.products().generate_approval_url(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("product-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"language-code" => {
call = call.language_code(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["language-code"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _products_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.products().get(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("product-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"language" => {
call = call.language(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["language"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _products_get_app_restrictions_schema(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.products().get_app_restrictions_schema(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("product-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"language" => {
call = call.language(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["language"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _products_get_permissions(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.products().get_permissions(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("product-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _products_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.products().list(opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"token" => {
call = call.token(value.unwrap_or(""));
},
"query" => {
call = call.query(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
"language" => {
call = call.language(value.unwrap_or(""));
},
"approved" => {
call = call.approved(arg_from_str(value.unwrap_or("false"), err, "approved", "boolean"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["query", "token", "language", "max-results", "approved"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _products_unapprove(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.products().unapprove(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("product-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _serviceaccountkeys_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.serviceaccountkeys().delete(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("key-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _serviceaccountkeys_insert(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"public-data" => Some(("publicData", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"data" => Some(("data", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["data", "id", "kind", "public-data", "type"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::ServiceAccountKey = json::value::from_value(object).unwrap();
let mut call = self.hub.serviceaccountkeys().insert(request, opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _serviceaccountkeys_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.serviceaccountkeys().list(opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _storelayoutclusters_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.storelayoutclusters().delete(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("page-id").unwrap_or(""), opt.value_of("cluster-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _storelayoutclusters_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.storelayoutclusters().get(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("page-id").unwrap_or(""), opt.value_of("cluster-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _storelayoutclusters_insert(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"order-in-page" => Some(("orderInPage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["id", "kind", "order-in-page", "product-id"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::StoreCluster = json::value::from_value(object).unwrap();
let mut call = self.hub.storelayoutclusters().insert(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("page-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _storelayoutclusters_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.storelayoutclusters().list(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("page-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _storelayoutclusters_patch(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"order-in-page" => Some(("orderInPage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["id", "kind", "order-in-page", "product-id"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::StoreCluster = json::value::from_value(object).unwrap();
let mut call = self.hub.storelayoutclusters().patch(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("page-id").unwrap_or(""), opt.value_of("cluster-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _storelayoutclusters_update(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"order-in-page" => Some(("orderInPage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["id", "kind", "order-in-page", "product-id"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::StoreCluster = json::value::from_value(object).unwrap();
let mut call = self.hub.storelayoutclusters().update(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("page-id").unwrap_or(""), opt.value_of("cluster-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _storelayoutpages_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.storelayoutpages().delete(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("page-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _storelayoutpages_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.storelayoutpages().get(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("page-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _storelayoutpages_insert(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"link" => Some(("link", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
"id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["id", "kind", "link"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::StorePage = json::value::from_value(object).unwrap();
let mut call = self.hub.storelayoutpages().insert(request, opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _storelayoutpages_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.storelayoutpages().list(opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _storelayoutpages_patch(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"link" => Some(("link", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
"id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["id", "kind", "link"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::StorePage = json::value::from_value(object).unwrap();
let mut call = self.hub.storelayoutpages().patch(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("page-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _storelayoutpages_update(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"link" => Some(("link", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
"id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["id", "kind", "link"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::StorePage = json::value::from_value(object).unwrap();
let mut call = self.hub.storelayoutpages().update(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("page-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _users_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.users().delete(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _users_generate_authentication_token(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.users().generate_authentication_token(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _users_generate_token(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.users().generate_token(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _users_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.users().get(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _users_get_available_product_set(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.users().get_available_product_set(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _users_insert(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"display-name" => Some(("displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"account-identifier" => Some(("accountIdentifier", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"management-type" => Some(("managementType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"primary-email" => Some(("primaryEmail", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"account-type" => Some(("accountType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["account-identifier", "account-type", "display-name", "id", "kind", "management-type", "primary-email"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::User = json::value::from_value(object).unwrap();
let mut call = self.hub.users().insert(request, opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _users_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.users().list(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("email").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _users_patch(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"display-name" => Some(("displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"account-identifier" => Some(("accountIdentifier", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"management-type" => Some(("managementType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"primary-email" => Some(("primaryEmail", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"account-type" => Some(("accountType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["account-identifier", "account-type", "display-name", "id", "kind", "management-type", "primary-email"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::User = json::value::from_value(object).unwrap();
let mut call = self.hub.users().patch(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _users_revoke_device_access(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.users().revoke_device_access(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _users_revoke_token(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.users().revoke_token(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _users_set_available_product_set(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-set-behavior" => Some(("productSetBehavior", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["kind", "product-id", "product-set-behavior"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::ProductSet = json::value::from_value(object).unwrap();
let mut call = self.hub.users().set_available_product_set(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _users_update(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"display-name" => Some(("displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"account-identifier" => Some(("accountIdentifier", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"management-type" => Some(("managementType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"primary-email" => Some(("primaryEmail", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"account-type" => Some(("accountType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["account-identifier", "account-type", "display-name", "id", "kind", "management-type", "primary-email"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::User = json::value::from_value(object).unwrap();
let mut call = self.hub.users().update(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _webapps_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.webapps().delete(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("web-app-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
fn _webapps_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.webapps().get(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("web-app-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _webapps_insert(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"display-mode" => Some(("displayMode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"is-published" => Some(("isPublished", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })),
"web-app-id" => Some(("webAppId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"version-code" => Some(("versionCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"start-url" => Some(("startUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["display-mode", "is-published", "start-url", "title", "version-code", "web-app-id"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::WebApp = json::value::from_value(object).unwrap();
let mut call = self.hub.webapps().insert(request, opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _webapps_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.webapps().list(opt.value_of("enterprise-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _webapps_patch(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"display-mode" => Some(("displayMode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"is-published" => Some(("isPublished", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })),
"web-app-id" => Some(("webAppId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"version-code" => Some(("versionCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"start-url" => Some(("startUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["display-mode", "is-published", "start-url", "title", "version-code", "web-app-id"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::WebApp = json::value::from_value(object).unwrap();
let mut call = self.hub.webapps().patch(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("web-app-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _webapps_update(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"display-mode" => Some(("displayMode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"is-published" => Some(("isPublished", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })),
"web-app-id" => Some(("webAppId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"version-code" => Some(("versionCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"start-url" => Some(("startUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["display-mode", "is-published", "start-url", "title", "version-code", "web-app-id"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::WebApp = json::value::from_value(object).unwrap();
let mut call = self.hub.webapps().update(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("web-app-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _doit(&self, dry_run: bool) -> Result<Result<(), DoitError>, Option<InvalidOptionsError>> {
let mut err = InvalidOptionsError::new();
let mut call_result: Result<(), DoitError> = Ok(());
let mut err_opt: Option<InvalidOptionsError> = None;
match self.opt.subcommand() {
("devices", Some(opt)) => {
match opt.subcommand() {
("force-report-upload", Some(opt)) => {
call_result = self._devices_force_report_upload(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._devices_get(opt, dry_run, &mut err);
},
("get-state", Some(opt)) => {
call_result = self._devices_get_state(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._devices_list(opt, dry_run, &mut err);
},
("patch", Some(opt)) => {
call_result = self._devices_patch(opt, dry_run, &mut err);
},
("set-state", Some(opt)) => {
call_result = self._devices_set_state(opt, dry_run, &mut err);
},
("update", Some(opt)) => {
call_result = self._devices_update(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("devices".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("enterprises", Some(opt)) => {
match opt.subcommand() {
("acknowledge-notification-set", Some(opt)) => {
call_result = self._enterprises_acknowledge_notification_set(opt, dry_run, &mut err);
},
("complete-signup", Some(opt)) => {
call_result = self._enterprises_complete_signup(opt, dry_run, &mut err);
},
("create-web-token", Some(opt)) => {
call_result = self._enterprises_create_web_token(opt, dry_run, &mut err);
},
("enroll", Some(opt)) => {
call_result = self._enterprises_enroll(opt, dry_run, &mut err);
},
("generate-signup-url", Some(opt)) => {
call_result = self._enterprises_generate_signup_url(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._enterprises_get(opt, dry_run, &mut err);
},
("get-service-account", Some(opt)) => {
call_result = self._enterprises_get_service_account(opt, dry_run, &mut err);
},
("get-store-layout", Some(opt)) => {
call_result = self._enterprises_get_store_layout(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._enterprises_list(opt, dry_run, &mut err);
},
("pull-notification-set", Some(opt)) => {
call_result = self._enterprises_pull_notification_set(opt, dry_run, &mut err);
},
("send-test-push-notification", Some(opt)) => {
call_result = self._enterprises_send_test_push_notification(opt, dry_run, &mut err);
},
("set-account", Some(opt)) => {
call_result = self._enterprises_set_account(opt, dry_run, &mut err);
},
("set-store-layout", Some(opt)) => {
call_result = self._enterprises_set_store_layout(opt, dry_run, &mut err);
},
("unenroll", Some(opt)) => {
call_result = self._enterprises_unenroll(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("enterprises".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("entitlements", Some(opt)) => {
match opt.subcommand() {
("delete", Some(opt)) => {
call_result = self._entitlements_delete(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._entitlements_get(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._entitlements_list(opt, dry_run, &mut err);
},
("patch", Some(opt)) => {
call_result = self._entitlements_patch(opt, dry_run, &mut err);
},
("update", Some(opt)) => {
call_result = self._entitlements_update(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("entitlements".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("grouplicenses", Some(opt)) => {
match opt.subcommand() {
("get", Some(opt)) => {
call_result = self._grouplicenses_get(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._grouplicenses_list(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("grouplicenses".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("grouplicenseusers", Some(opt)) => {
match opt.subcommand() {
("list", Some(opt)) => {
call_result = self._grouplicenseusers_list(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("grouplicenseusers".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("installs", Some(opt)) => {
match opt.subcommand() {
("delete", Some(opt)) => {
call_result = self._installs_delete(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._installs_get(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._installs_list(opt, dry_run, &mut err);
},
("patch", Some(opt)) => {
call_result = self._installs_patch(opt, dry_run, &mut err);
},
("update", Some(opt)) => {
call_result = self._installs_update(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("installs".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("managedconfigurationsfordevice", Some(opt)) => {
match opt.subcommand() {
("delete", Some(opt)) => {
call_result = self._managedconfigurationsfordevice_delete(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._managedconfigurationsfordevice_get(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._managedconfigurationsfordevice_list(opt, dry_run, &mut err);
},
("patch", Some(opt)) => {
call_result = self._managedconfigurationsfordevice_patch(opt, dry_run, &mut err);
},
("update", Some(opt)) => {
call_result = self._managedconfigurationsfordevice_update(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("managedconfigurationsfordevice".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("managedconfigurationsforuser", Some(opt)) => {
match opt.subcommand() {
("delete", Some(opt)) => {
call_result = self._managedconfigurationsforuser_delete(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._managedconfigurationsforuser_get(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._managedconfigurationsforuser_list(opt, dry_run, &mut err);
},
("patch", Some(opt)) => {
call_result = self._managedconfigurationsforuser_patch(opt, dry_run, &mut err);
},
("update", Some(opt)) => {
call_result = self._managedconfigurationsforuser_update(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("managedconfigurationsforuser".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("managedconfigurationssettings", Some(opt)) => {
match opt.subcommand() {
("list", Some(opt)) => {
call_result = self._managedconfigurationssettings_list(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("managedconfigurationssettings".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("permissions", Some(opt)) => {
match opt.subcommand() {
("get", Some(opt)) => {
call_result = self._permissions_get(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("permissions".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("products", Some(opt)) => {
match opt.subcommand() {
("approve", Some(opt)) => {
call_result = self._products_approve(opt, dry_run, &mut err);
},
("generate-approval-url", Some(opt)) => {
call_result = self._products_generate_approval_url(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._products_get(opt, dry_run, &mut err);
},
("get-app-restrictions-schema", Some(opt)) => {
call_result = self._products_get_app_restrictions_schema(opt, dry_run, &mut err);
},
("get-permissions", Some(opt)) => {
call_result = self._products_get_permissions(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._products_list(opt, dry_run, &mut err);
},
("unapprove", Some(opt)) => {
call_result = self._products_unapprove(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("products".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("serviceaccountkeys", Some(opt)) => {
match opt.subcommand() {
("delete", Some(opt)) => {
call_result = self._serviceaccountkeys_delete(opt, dry_run, &mut err);
},
("insert", Some(opt)) => {
call_result = self._serviceaccountkeys_insert(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._serviceaccountkeys_list(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("serviceaccountkeys".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("storelayoutclusters", Some(opt)) => {
match opt.subcommand() {
("delete", Some(opt)) => {
call_result = self._storelayoutclusters_delete(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._storelayoutclusters_get(opt, dry_run, &mut err);
},
("insert", Some(opt)) => {
call_result = self._storelayoutclusters_insert(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._storelayoutclusters_list(opt, dry_run, &mut err);
},
("patch", Some(opt)) => {
call_result = self._storelayoutclusters_patch(opt, dry_run, &mut err);
},
("update", Some(opt)) => {
call_result = self._storelayoutclusters_update(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("storelayoutclusters".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("storelayoutpages", Some(opt)) => {
match opt.subcommand() {
("delete", Some(opt)) => {
call_result = self._storelayoutpages_delete(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._storelayoutpages_get(opt, dry_run, &mut err);
},
("insert", Some(opt)) => {
call_result = self._storelayoutpages_insert(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._storelayoutpages_list(opt, dry_run, &mut err);
},
("patch", Some(opt)) => {
call_result = self._storelayoutpages_patch(opt, dry_run, &mut err);
},
("update", Some(opt)) => {
call_result = self._storelayoutpages_update(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("storelayoutpages".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("users", Some(opt)) => {
match opt.subcommand() {
("delete", Some(opt)) => {
call_result = self._users_delete(opt, dry_run, &mut err);
},
("generate-authentication-token", Some(opt)) => {
call_result = self._users_generate_authentication_token(opt, dry_run, &mut err);
},
("generate-token", Some(opt)) => {
call_result = self._users_generate_token(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._users_get(opt, dry_run, &mut err);
},
("get-available-product-set", Some(opt)) => {
call_result = self._users_get_available_product_set(opt, dry_run, &mut err);
},
("insert", Some(opt)) => {
call_result = self._users_insert(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._users_list(opt, dry_run, &mut err);
},
("patch", Some(opt)) => {
call_result = self._users_patch(opt, dry_run, &mut err);
},
("revoke-device-access", Some(opt)) => {
call_result = self._users_revoke_device_access(opt, dry_run, &mut err);
},
("revoke-token", Some(opt)) => {
call_result = self._users_revoke_token(opt, dry_run, &mut err);
},
("set-available-product-set", Some(opt)) => {
call_result = self._users_set_available_product_set(opt, dry_run, &mut err);
},
("update", Some(opt)) => {
call_result = self._users_update(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("users".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("webapps", Some(opt)) => {
match opt.subcommand() {
("delete", Some(opt)) => {
call_result = self._webapps_delete(opt, dry_run, &mut err);
},
("get", Some(opt)) => {
call_result = self._webapps_get(opt, dry_run, &mut err);
},
("insert", Some(opt)) => {
call_result = self._webapps_insert(opt, dry_run, &mut err);
},
("list", Some(opt)) => {
call_result = self._webapps_list(opt, dry_run, &mut err);
},
("patch", Some(opt)) => {
call_result = self._webapps_patch(opt, dry_run, &mut err);
},
("update", Some(opt)) => {
call_result = self._webapps_update(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("webapps".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
_ => {
err.issues.push(CLIError::MissingCommandError);
writeln!(io::stderr(), "{}\n", self.opt.usage()).ok();
}
}
if dry_run {
if err.issues.len() > 0 {
err_opt = Some(err);
}
Err(err_opt)
} else {
Ok(call_result)
}
}
// Please note that this call will fail if any part of the opt can't be handled
fn new(opt: ArgMatches<'n>) -> Result<Engine<'n>, InvalidOptionsError> {
let (config_dir, secret) = {
let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) {
Err(e) => return Err(InvalidOptionsError::single(e, 3)),
Ok(p) => p,
};
match cmn::application_secret_from_directory(&config_dir, "androidenterprise1-secret.json",
"{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") {
Ok(secret) => (config_dir, secret),
Err(e) => return Err(InvalidOptionsError::single(e, 4))
}
};
let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate,
if opt.is_present("debug-auth") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
},
JsonTokenStorage {
program_name: "androidenterprise1",
db_dir: config_dir.clone(),
}, Some(FlowType::InstalledRedirect(54324)));
let client =
if opt.is_present("debug") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
};
let engine = Engine {
opt: opt,
hub: api::AndroidEnterprise::new(client, auth),
gp: vec!["alt", "fields", "key", "oauth-token", "pretty-print", "quota-user", "user-ip"],
gpm: vec![
("oauth-token", "oauth_token"),
("pretty-print", "prettyPrint"),
("quota-user", "quotaUser"),
("user-ip", "userIp"),
]
};
match engine._doit(true) {
Err(Some(err)) => Err(err),
Err(None) => Ok(engine),
Ok(_) => unreachable!(),
}
}
fn doit(&self) -> Result<(), DoitError> {
match self._doit(false) {
Ok(res) => res,
Err(_) => unreachable!(),
}
}
}
fn main() {
let mut exit_status = 0i32;
let arg_data = [
("devices", "methods: 'force-report-upload', 'get', 'get-state', 'list', 'patch', 'set-state' and 'update'", vec![
("force-report-upload",
Some(r##"Uploads a report containing any changes in app states on the device since the last report was generated. You can call this method up to 3 times every 24 hours for a given device."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/devices_force-report-upload",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The ID of the device."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("get",
Some(r##"Retrieves the details of a device."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/devices_get",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The ID of the device."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get-state",
Some(r##"Retrieves whether a device's access to Google services is enabled or disabled. The device state takes effect only if enforcing EMM policies on Android devices is enabled in the Google Admin Console. Otherwise, the device state is ignored and all devices are allowed access to Google services. This is only supported for Google-managed users."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/devices_get-state",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The ID of the device."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Retrieves the IDs of all of a user's devices."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/devices_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("patch",
Some(r##"Updates the device policy. This method supports patch semantics."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/devices_patch",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The ID of the device."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("set-state",
Some(r##"Sets whether a device's access to Google services is enabled or disabled. The device state takes effect only if enforcing EMM policies on Android devices is enabled in the Google Admin Console. Otherwise, the device state is ignored and all devices are allowed access to Google services. This is only supported for Google-managed users."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/devices_set-state",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The ID of the device."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("update",
Some(r##"Updates the device policy"##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/devices_update",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The ID of the device."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("enterprises", "methods: 'acknowledge-notification-set', 'complete-signup', 'create-web-token', 'enroll', 'generate-signup-url', 'get', 'get-service-account', 'get-store-layout', 'list', 'pull-notification-set', 'send-test-push-notification', 'set-account', 'set-store-layout' and 'unenroll'", vec![
("acknowledge-notification-set",
Some(r##"Acknowledges notifications that were received from Enterprises.PullNotificationSet to prevent subsequent calls from returning the same notifications."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_acknowledge-notification-set",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("complete-signup",
Some(r##"Completes the signup flow, by specifying the Completion token and Enterprise token. This request must not be called multiple times for a given Enterprise Token."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_complete-signup",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("create-web-token",
Some(r##"Returns a unique token to access an embeddable UI. To generate a web UI, pass the generated token into the managed Google Play javascript API. Each token may only be used to start one UI session. See the javascript API documentation for further information."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_create-web-token",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("enroll",
Some(r##"Enrolls an enterprise with the calling EMM."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_enroll",
vec![
(Some(r##"token"##),
None,
Some(r##"The token provided by the enterprise to register the EMM."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("generate-signup-url",
Some(r##"Generates a sign-up URL."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_generate-signup-url",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get",
Some(r##"Retrieves the name and domain of an enterprise."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_get",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get-service-account",
Some(r##"Returns a service account and credentials. The service account can be bound to the enterprise by calling setAccount. The service account is unique to this enterprise and EMM, and will be deleted if the enterprise is unbound. The credentials contain private key data and are not stored server-side.
This method can only be called after calling Enterprises.Enroll or Enterprises.CompleteSignup, and before Enterprises.SetAccount; at other times it will return an error.
Subsequent calls after the first will generate a new, unique set of credentials, and invalidate the previously generated credentials.
Once the service account is bound to the enterprise, it can be managed using the serviceAccountKeys resource."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_get-service-account",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get-store-layout",
Some(r##"Returns the store layout for the enterprise. If the store layout has not been set, returns "basic" as the store layout type and no homepage."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_get-store-layout",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Looks up an enterprise by domain name. This is only supported for enterprises created via the Google-initiated creation flow. Lookup of the id is not needed for enterprises created via the EMM-initiated flow since the EMM learns the enterprise ID in the callback specified in the Enterprises.generateSignupUrl call."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_list",
vec![
(Some(r##"domain"##),
None,
Some(r##"The exact primary domain name of the enterprise to look up."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("pull-notification-set",
Some(r##"Pulls and returns a notification set for the enterprises associated with the service account authenticated for the request. The notification set may be empty if no notification are pending.
A notification set returned needs to be acknowledged within 20 seconds by calling Enterprises.AcknowledgeNotificationSet, unless the notification set is empty.
Notifications that are not acknowledged within the 20 seconds will eventually be included again in the response to another PullNotificationSet request, and those that are never acknowledged will ultimately be deleted according to the Google Cloud Platform Pub/Sub system policy.
Multiple requests might be performed concurrently to retrieve notifications, in which case the pending notifications (if any) will be split among each caller, if any are pending.
If no notifications are present, an empty notification list is returned. Subsequent requests may return more notifications once they become available."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_pull-notification-set",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("send-test-push-notification",
Some(r##"Sends a test notification to validate the EMM integration with the Google Cloud Pub/Sub service for this enterprise."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_send-test-push-notification",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("set-account",
Some(r##"Sets the account that will be used to authenticate to the API as the enterprise."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_set-account",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("set-store-layout",
Some(r##"Sets the store layout for the enterprise. By default, storeLayoutType is set to "basic" and the basic store layout is enabled. The basic layout only contains apps approved by the admin, and that have been added to the available product set for a user (using the setAvailableProductSet call). Apps on the page are sorted in order of their product ID value. If you create a custom store layout (by setting storeLayoutType = "custom" and setting a homepage), the basic store layout is disabled."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_set-store-layout",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("unenroll",
Some(r##"Unenrolls an enterprise from the calling EMM."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_unenroll",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
]),
("entitlements", "methods: 'delete', 'get', 'list', 'patch' and 'update'", vec![
("delete",
Some(r##"Removes an entitlement to an app for a user."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/entitlements_delete",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"entitlement-id"##),
None,
Some(r##"The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("get",
Some(r##"Retrieves details of an entitlement."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/entitlements_get",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"entitlement-id"##),
None,
Some(r##"The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Lists all entitlements for the specified user. Only the ID is set."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/entitlements_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("patch",
Some(r##"Adds or updates an entitlement to an app for a user. This method supports patch semantics."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/entitlements_patch",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"entitlement-id"##),
None,
Some(r##"The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("update",
Some(r##"Adds or updates an entitlement to an app for a user."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/entitlements_update",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"entitlement-id"##),
None,
Some(r##"The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("grouplicenses", "methods: 'get' and 'list'", vec![
("get",
Some(r##"Retrieves details of an enterprise's group license for a product."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/grouplicenses_get",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"group-license-id"##),
None,
Some(r##"The ID of the product the group license is for, e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Retrieves IDs of all products for which the enterprise has a group license."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/grouplicenses_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("grouplicenseusers", "methods: 'list'", vec![
("list",
Some(r##"Retrieves the IDs of the users who have been granted entitlements under the license."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/grouplicenseusers_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"group-license-id"##),
None,
Some(r##"The ID of the product the group license is for, e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("installs", "methods: 'delete', 'get', 'list', 'patch' and 'update'", vec![
("delete",
Some(r##"Requests to remove an app from a device. A call to get or list will still show the app as installed on the device until it is actually removed."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/installs_delete",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The Android ID of the device."##),
Some(true),
Some(false)),
(Some(r##"install-id"##),
None,
Some(r##"The ID of the product represented by the install, e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("get",
Some(r##"Retrieves details of an installation of an app on a device."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/installs_get",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The Android ID of the device."##),
Some(true),
Some(false)),
(Some(r##"install-id"##),
None,
Some(r##"The ID of the product represented by the install, e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Retrieves the details of all apps installed on the specified device."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/installs_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The Android ID of the device."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("patch",
Some(r##"Requests to install the latest version of an app to a device. If the app is already installed, then it is updated to the latest version if necessary. This method supports patch semantics."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/installs_patch",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The Android ID of the device."##),
Some(true),
Some(false)),
(Some(r##"install-id"##),
None,
Some(r##"The ID of the product represented by the install, e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("update",
Some(r##"Requests to install the latest version of an app to a device. If the app is already installed, then it is updated to the latest version if necessary."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/installs_update",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The Android ID of the device."##),
Some(true),
Some(false)),
(Some(r##"install-id"##),
None,
Some(r##"The ID of the product represented by the install, e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("managedconfigurationsfordevice", "methods: 'delete', 'get', 'list', 'patch' and 'update'", vec![
("delete",
Some(r##"Removes a per-device managed configuration for an app for the specified device."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/managedconfigurationsfordevice_delete",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The Android ID of the device."##),
Some(true),
Some(false)),
(Some(r##"managed-configuration-for-device-id"##),
None,
Some(r##"The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("get",
Some(r##"Retrieves details of a per-device managed configuration."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/managedconfigurationsfordevice_get",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The Android ID of the device."##),
Some(true),
Some(false)),
(Some(r##"managed-configuration-for-device-id"##),
None,
Some(r##"The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Lists all the per-device managed configurations for the specified device. Only the ID is set."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/managedconfigurationsfordevice_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The Android ID of the device."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("patch",
Some(r##"Adds or updates a per-device managed configuration for an app for the specified device. This method supports patch semantics."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/managedconfigurationsfordevice_patch",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The Android ID of the device."##),
Some(true),
Some(false)),
(Some(r##"managed-configuration-for-device-id"##),
None,
Some(r##"The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("update",
Some(r##"Adds or updates a per-device managed configuration for an app for the specified device."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/managedconfigurationsfordevice_update",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"device-id"##),
None,
Some(r##"The Android ID of the device."##),
Some(true),
Some(false)),
(Some(r##"managed-configuration-for-device-id"##),
None,
Some(r##"The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("managedconfigurationsforuser", "methods: 'delete', 'get', 'list', 'patch' and 'update'", vec![
("delete",
Some(r##"Removes a per-user managed configuration for an app for the specified user."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/managedconfigurationsforuser_delete",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"managed-configuration-for-user-id"##),
None,
Some(r##"The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("get",
Some(r##"Retrieves details of a per-user managed configuration for an app for the specified user."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/managedconfigurationsforuser_get",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"managed-configuration-for-user-id"##),
None,
Some(r##"The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Lists all the per-user managed configurations for the specified user. Only the ID is set."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/managedconfigurationsforuser_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("patch",
Some(r##"Adds or updates the managed configuration settings for an app for the specified user. If you support the Managed configurations iframe, you can apply managed configurations to a user by specifying an mcmId and its associated configuration variables (if any) in the request. Alternatively, all EMMs can apply managed configurations by passing a list of managed properties. This method supports patch semantics."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/managedconfigurationsforuser_patch",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"managed-configuration-for-user-id"##),
None,
Some(r##"The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("update",
Some(r##"Adds or updates the managed configuration settings for an app for the specified user. If you support the Managed configurations iframe, you can apply managed configurations to a user by specifying an mcmId and its associated configuration variables (if any) in the request. Alternatively, all EMMs can apply managed configurations by passing a list of managed properties."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/managedconfigurationsforuser_update",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"managed-configuration-for-user-id"##),
None,
Some(r##"The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("managedconfigurationssettings", "methods: 'list'", vec![
("list",
Some(r##"Lists all the managed configurations settings for the specified app. Only the ID and the name is set."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/managedconfigurationssettings_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"product-id"##),
None,
Some(r##"The ID of the product for which the managed configurations settings applies to."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("permissions", "methods: 'get'", vec![
("get",
Some(r##"Retrieves details of an Android app permission for display to an enterprise admin."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/permissions_get",
vec![
(Some(r##"permission-id"##),
None,
Some(r##"The ID of the permission."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("products", "methods: 'approve', 'generate-approval-url', 'get', 'get-app-restrictions-schema', 'get-permissions', 'list' and 'unapprove'", vec![
("approve",
Some(r##"Approves the specified product and the relevant app permissions, if any. The maximum number of products that you can approve per enterprise customer is 1,000.
To learn how to use managed Google Play to design and create a store layout to display approved products to your users, see Store Layout Design."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/products_approve",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"product-id"##),
None,
Some(r##"The ID of the product."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("generate-approval-url",
Some(r##"Generates a URL that can be rendered in an iframe to display the permissions (if any) of a product. An enterprise admin must view these permissions and accept them on behalf of their organization in order to approve that product.
Admins should accept the displayed permissions by interacting with a separate UI element in the EMM console, which in turn should trigger the use of this URL as the approvalUrlInfo.approvalUrl property in a Products.approve call to approve the product. This URL can only be used to display permissions for up to 1 day."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/products_generate-approval-url",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"product-id"##),
None,
Some(r##"The ID of the product."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get",
Some(r##"Retrieves details of a product for display to an enterprise admin."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/products_get",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"product-id"##),
None,
Some(r##"The ID of the product, e.g. "app:com.google.android.gm"."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get-app-restrictions-schema",
Some(r##"Retrieves the schema that defines the configurable properties for this product. All products have a schema, but this schema may be empty if no managed configurations have been defined. This schema can be used to populate a UI that allows an admin to configure the product. To apply a managed configuration based on the schema obtained using this API, see Managed Configurations through Play."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/products_get-app-restrictions-schema",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"product-id"##),
None,
Some(r##"The ID of the product."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get-permissions",
Some(r##"Retrieves the Android app permissions required by this app."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/products_get-permissions",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"product-id"##),
None,
Some(r##"The ID of the product."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Finds approved products that match a query, or all approved products if there is no query."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/products_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("unapprove",
Some(r##"Unapproves the specified product (and the relevant app permissions, if any)"##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/products_unapprove",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"product-id"##),
None,
Some(r##"The ID of the product."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
]),
("serviceaccountkeys", "methods: 'delete', 'insert' and 'list'", vec![
("delete",
Some(r##"Removes and invalidates the specified credentials for the service account associated with this enterprise. The calling service account must have been retrieved by calling Enterprises.GetServiceAccount and must have been set as the enterprise service account by calling Enterprises.SetAccount."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/serviceaccountkeys_delete",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"key-id"##),
None,
Some(r##"The ID of the key."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("insert",
Some(r##"Generates new credentials for the service account associated with this enterprise. The calling service account must have been retrieved by calling Enterprises.GetServiceAccount and must have been set as the enterprise service account by calling Enterprises.SetAccount.
Only the type of the key should be populated in the resource to be inserted."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/serviceaccountkeys_insert",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Lists all active credentials for the service account associated with this enterprise. Only the ID and key type are returned. The calling service account must have been retrieved by calling Enterprises.GetServiceAccount and must have been set as the enterprise service account by calling Enterprises.SetAccount."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/serviceaccountkeys_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("storelayoutclusters", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![
("delete",
Some(r##"Deletes a cluster."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/storelayoutclusters_delete",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"page-id"##),
None,
Some(r##"The ID of the page."##),
Some(true),
Some(false)),
(Some(r##"cluster-id"##),
None,
Some(r##"The ID of the cluster."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("get",
Some(r##"Retrieves details of a cluster."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/storelayoutclusters_get",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"page-id"##),
None,
Some(r##"The ID of the page."##),
Some(true),
Some(false)),
(Some(r##"cluster-id"##),
None,
Some(r##"The ID of the cluster."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("insert",
Some(r##"Inserts a new cluster in a page."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/storelayoutclusters_insert",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"page-id"##),
None,
Some(r##"The ID of the page."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Retrieves the details of all clusters on the specified page."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/storelayoutclusters_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"page-id"##),
None,
Some(r##"The ID of the page."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("patch",
Some(r##"Updates a cluster. This method supports patch semantics."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/storelayoutclusters_patch",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"page-id"##),
None,
Some(r##"The ID of the page."##),
Some(true),
Some(false)),
(Some(r##"cluster-id"##),
None,
Some(r##"The ID of the cluster."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("update",
Some(r##"Updates a cluster."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/storelayoutclusters_update",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"page-id"##),
None,
Some(r##"The ID of the page."##),
Some(true),
Some(false)),
(Some(r##"cluster-id"##),
None,
Some(r##"The ID of the cluster."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("storelayoutpages", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![
("delete",
Some(r##"Deletes a store page."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/storelayoutpages_delete",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"page-id"##),
None,
Some(r##"The ID of the page."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("get",
Some(r##"Retrieves details of a store page."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/storelayoutpages_get",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"page-id"##),
None,
Some(r##"The ID of the page."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("insert",
Some(r##"Inserts a new store page."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/storelayoutpages_insert",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Retrieves the details of all pages in the store."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/storelayoutpages_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("patch",
Some(r##"Updates the content of a store page. This method supports patch semantics."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/storelayoutpages_patch",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"page-id"##),
None,
Some(r##"The ID of the page."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("update",
Some(r##"Updates the content of a store page."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/storelayoutpages_update",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"page-id"##),
None,
Some(r##"The ID of the page."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("users", "methods: 'delete', 'generate-authentication-token', 'generate-token', 'get', 'get-available-product-set', 'insert', 'list', 'patch', 'revoke-device-access', 'revoke-token', 'set-available-product-set' and 'update'", vec![
("delete",
Some(r##"Deleted an EMM-managed user."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_delete",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("generate-authentication-token",
Some(r##"Generates an authentication token which the device policy client can use to provision the given EMM-managed user account on a device. The generated token is single-use and expires after a few minutes.
You can provision a maximum of 10 devices per user.
This call only works with EMM-managed accounts."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_generate-authentication-token",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("generate-token",
Some(r##"Generates a token (activation code) to allow this user to configure their managed account in the Android Setup Wizard. Revokes any previously generated token.
This call only works with Google managed accounts."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_generate-token",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get",
Some(r##"Retrieves a user's details."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_get",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get-available-product-set",
Some(r##"Retrieves the set of products a user is entitled to access."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_get-available-product-set",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("insert",
Some(r##"Creates a new EMM-managed user.
The Users resource passed in the body of the request should include an accountIdentifier and an accountType.
If a corresponding user already exists with the same account identifier, the user will be updated with the resource. In this case only the displayName field can be changed."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_insert",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Looks up a user by primary email address. This is only supported for Google-managed users. Lookup of the id is not needed for EMM-managed users because the id is already returned in the result of the Users.insert call."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"email"##),
None,
Some(r##"The exact primary email address of the user to look up."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("patch",
Some(r##"Updates the details of an EMM-managed user.
Can be used with EMM-managed users only (not Google managed users). Pass the new details in the Users resource in the request body. Only the displayName field can be changed. Other fields must either be unset or have the currently active value. This method supports patch semantics."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_patch",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("revoke-device-access",
Some(r##"Revokes access to all devices currently provisioned to the user. The user will no longer be able to use the managed Play store on any of their managed devices.
This call only works with EMM-managed accounts."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_revoke-device-access",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("revoke-token",
Some(r##"Revokes a previously generated token (activation code) for the user."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_revoke-token",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("set-available-product-set",
Some(r##"Modifies the set of products that a user is entitled to access (referred to as whitelisted products). Only products that are approved or products that were previously approved (products with revoked approval) can be whitelisted."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_set-available-product-set",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("update",
Some(r##"Updates the details of an EMM-managed user.
Can be used with EMM-managed users only (not Google managed users). Pass the new details in the Users resource in the request body. Only the displayName field can be changed. Other fields must either be unset or have the currently active value."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_update",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"user-id"##),
None,
Some(r##"The ID of the user."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("webapps", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![
("delete",
Some(r##"Deletes an existing web app."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/webapps_delete",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"web-app-id"##),
None,
Some(r##"The ID of the web app."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("get",
Some(r##"Gets an existing web app."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/webapps_get",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"web-app-id"##),
None,
Some(r##"The ID of the web app."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("insert",
Some(r##"Creates a new web app for the enterprise."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/webapps_insert",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"Retrieves the details of all web apps for a given enterprise."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/webapps_list",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("patch",
Some(r##"Updates an existing web app. This method supports patch semantics."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/webapps_patch",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"web-app-id"##),
None,
Some(r##"The ID of the web app."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("update",
Some(r##"Updates an existing web app."##),
"Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/webapps_update",
vec![
(Some(r##"enterprise-id"##),
None,
Some(r##"The ID of the enterprise."##),
Some(true),
Some(false)),
(Some(r##"web-app-id"##),
None,
Some(r##"The ID of the web app."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
];
let mut app = App::new("androidenterprise1")
.author("Sebastian Thiel <[email protected]>")
.version("1.0.10+20190624")
.about("Manages the deployment of apps to Android for Work users.")
.after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli")
.arg(Arg::with_name("url")
.long("scope")
.help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.")
.multiple(true)
.takes_value(true))
.arg(Arg::with_name("folder")
.long("config-dir")
.help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli")
.multiple(false)
.takes_value(true))
.arg(Arg::with_name("debug")
.long("debug")
.help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false))
.arg(Arg::with_name("debug-auth")
.long("debug-auth")
.help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false));
for &(main_command_name, about, ref subcommands) in arg_data.iter() {
let mut mcmd = SubCommand::with_name(main_command_name).about(about);
for &(sub_command_name, ref desc, url_info, ref args) in subcommands {
let mut scmd = SubCommand::with_name(sub_command_name);
if let &Some(desc) = desc {
scmd = scmd.about(desc);
}
scmd = scmd.after_help(url_info);
for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args {
let arg_name_str =
match (arg_name, flag) {
(&Some(an), _ ) => an,
(_ , &Some(f)) => f,
_ => unreachable!(),
};
let mut arg = Arg::with_name(arg_name_str)
.empty_values(false);
if let &Some(short_flag) = flag {
arg = arg.short(short_flag);
}
if let &Some(desc) = desc {
arg = arg.help(desc);
}
if arg_name.is_some() && flag.is_some() {
arg = arg.takes_value(true);
}
if let &Some(required) = required {
arg = arg.required(required);
}
if let &Some(multi) = multi {
arg = arg.multiple(multi);
}
scmd = scmd.arg(arg);
}
mcmd = mcmd.subcommand(scmd);
}
app = app.subcommand(mcmd);
}
let matches = app.get_matches();
let debug = matches.is_present("debug");
match Engine::new(matches) {
Err(err) => {
exit_status = err.exit_code;
writeln!(io::stderr(), "{}", err).ok();
},
Ok(engine) => {
if let Err(doit_err) = engine.doit() {
exit_status = 1;
match doit_err {
DoitError::IoError(path, err) => {
writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok();
},
DoitError::ApiError(err) => {
if debug {
writeln!(io::stderr(), "{:#?}", err).ok();
} else {
writeln!(io::stderr(), "{}", err).ok();
}
}
}
}
}
}
std::process::exit(exit_status);
} | 49.256284 | 526 | 0.425704 |
160e247c23db4a1e50d06eff25e74b58702c0d88 | 3,183 | use std::convert::TryFrom;
use std::{io, sync::Arc};
use async_trait::async_trait;
use crate::{
app::dns_client::DnsClient,
proxy::{
stream::SimpleProxyStream, OutboundConnect, OutboundHandler, ProxyStream, TcpConnector,
TcpOutboundHandler,
},
session::{Session, SocksAddr},
};
pub struct Handler {
pub actors: Vec<Arc<dyn OutboundHandler>>,
pub dns_client: Arc<DnsClient>,
}
impl Handler {
fn next_tcp_connect_addr(&self, start: usize) -> Option<OutboundConnect> {
for i in start..self.actors.len() {
if let Some(addr) = self.actors[i].tcp_connect_addr() {
return Some(addr);
}
}
None
}
fn next_session(&self, mut sess: Session, start: usize) -> Session {
if let Some(OutboundConnect::Proxy(address, port, _)) = self.next_tcp_connect_addr(start) {
if let Ok(addr) = SocksAddr::try_from(format!("{}:{}", address, port)) {
sess.destination = addr;
}
}
sess
}
}
impl TcpConnector for Handler {}
#[async_trait]
impl TcpOutboundHandler for Handler {
fn name(&self) -> &str {
super::NAME
}
fn tcp_connect_addr(&self) -> Option<OutboundConnect> {
for a in self.actors.iter() {
if let Some(addr) = a.tcp_connect_addr() {
return Some(addr);
}
}
None
}
async fn handle_tcp<'a>(
&'a self,
sess: &'a Session,
mut stream: Option<Box<dyn ProxyStream>>,
) -> io::Result<Box<dyn ProxyStream>> {
if stream.is_none() {
match self.tcp_connect_addr() {
Some(OutboundConnect::Proxy(connect_addr, port, bind_addr)) => {
stream.replace(
self.dial_tcp_stream(
self.dns_client.clone(),
&bind_addr,
&connect_addr,
&port,
)
.await?,
);
}
Some(OutboundConnect::Direct(bind_addr)) => {
stream.replace(
self.dial_tcp_stream(
self.dns_client.clone(),
&bind_addr,
&sess.destination.host(),
&sess.destination.port(),
)
.await?,
);
}
Some(OutboundConnect::NoConnect) => (),
_ => {
return Err(io::Error::new(io::ErrorKind::Other, "invalid input"));
}
}
}
for (i, a) in self.actors.iter().enumerate() {
let new_sess = self.next_session(sess.clone(), i + 1);
let s = stream.take();
stream.replace(a.handle_tcp(&new_sess, s).await?);
}
if let Some(stream) = stream {
Ok(Box::new(SimpleProxyStream(stream)))
} else {
Err(io::Error::new(io::ErrorKind::Other, "invalid input"))
}
}
}
| 30.028302 | 99 | 0.477223 |
b944ea09369b09fdd99b5db2e36cbdccde1ccb59 | 49,790 | // Copyright (c) 2019 Ant Financial
//
// SPDX-License-Identifier: Apache-2.0
//
use std::collections::HashMap;
use std::fs;
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::iter;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;
use tokio::sync::Mutex;
use nix::mount::MsFlags;
use nix::unistd::Gid;
use regex::Regex;
use crate::device::{
get_scsi_device_name, get_virtio_blk_pci_device_name, online_device, wait_for_pmem_device,
DRIVER_9P_TYPE, DRIVER_BLK_CCW_TYPE, DRIVER_BLK_TYPE, DRIVER_EPHEMERAL_TYPE, DRIVER_LOCAL_TYPE,
DRIVER_MMIO_BLK_TYPE, DRIVER_NVDIMM_TYPE, DRIVER_OVERLAYFS_TYPE, DRIVER_SCSI_TYPE,
DRIVER_VIRTIOFS_TYPE, DRIVER_WATCHABLE_BIND_TYPE, FS_TYPE_HUGETLB,
};
use crate::linux_abi::*;
use crate::pci;
use crate::protocols::agent::Storage;
use crate::Sandbox;
#[cfg(target_arch = "s390x")]
use crate::{ccw, device::get_virtio_blk_ccw_device_name};
use anyhow::{anyhow, Context, Result};
use slog::Logger;
use tracing::instrument;
pub const TYPE_ROOTFS: &str = "rootfs";
const SYS_FS_HUGEPAGES_PREFIX: &str = "/sys/kernel/mm/hugepages";
pub const MOUNT_GUEST_TAG: &str = "kataShared";
// Allocating an FSGroup that owns the pod's volumes
const FS_GID: &str = "fsgid";
#[rustfmt::skip]
lazy_static! {
pub static ref FLAGS: HashMap<&'static str, (bool, MsFlags)> = {
let mut m = HashMap::new();
m.insert("defaults", (false, MsFlags::empty()));
m.insert("ro", (false, MsFlags::MS_RDONLY));
m.insert("rw", (true, MsFlags::MS_RDONLY));
m.insert("suid", (true, MsFlags::MS_NOSUID));
m.insert("nosuid", (false, MsFlags::MS_NOSUID));
m.insert("dev", (true, MsFlags::MS_NODEV));
m.insert("nodev", (false, MsFlags::MS_NODEV));
m.insert("exec", (true, MsFlags::MS_NOEXEC));
m.insert("noexec", (false, MsFlags::MS_NOEXEC));
m.insert("sync", (false, MsFlags::MS_SYNCHRONOUS));
m.insert("async", (true, MsFlags::MS_SYNCHRONOUS));
m.insert("dirsync", (false, MsFlags::MS_DIRSYNC));
m.insert("remount", (false, MsFlags::MS_REMOUNT));
m.insert("mand", (false, MsFlags::MS_MANDLOCK));
m.insert("nomand", (true, MsFlags::MS_MANDLOCK));
m.insert("atime", (true, MsFlags::MS_NOATIME));
m.insert("noatime", (false, MsFlags::MS_NOATIME));
m.insert("diratime", (true, MsFlags::MS_NODIRATIME));
m.insert("nodiratime", (false, MsFlags::MS_NODIRATIME));
m.insert("bind", (false, MsFlags::MS_BIND));
m.insert("rbind", (false, MsFlags::MS_BIND | MsFlags::MS_REC));
m.insert("unbindable", (false, MsFlags::MS_UNBINDABLE));
m.insert("runbindable", (false, MsFlags::MS_UNBINDABLE | MsFlags::MS_REC));
m.insert("private", (false, MsFlags::MS_PRIVATE));
m.insert("rprivate", (false, MsFlags::MS_PRIVATE | MsFlags::MS_REC));
m.insert("shared", (false, MsFlags::MS_SHARED));
m.insert("rshared", (false, MsFlags::MS_SHARED | MsFlags::MS_REC));
m.insert("slave", (false, MsFlags::MS_SLAVE));
m.insert("rslave", (false, MsFlags::MS_SLAVE | MsFlags::MS_REC));
m.insert("relatime", (false, MsFlags::MS_RELATIME));
m.insert("norelatime", (true, MsFlags::MS_RELATIME));
m.insert("strictatime", (false, MsFlags::MS_STRICTATIME));
m.insert("nostrictatime", (true, MsFlags::MS_STRICTATIME));
m
};
}
#[derive(Debug, PartialEq)]
pub struct InitMount {
fstype: &'static str,
src: &'static str,
dest: &'static str,
options: Vec<&'static str>,
}
#[rustfmt::skip]
lazy_static!{
static ref CGROUPS: HashMap<&'static str, &'static str> = {
let mut m = HashMap::new();
m.insert("cpu", "/sys/fs/cgroup/cpu");
m.insert("cpuacct", "/sys/fs/cgroup/cpuacct");
m.insert("blkio", "/sys/fs/cgroup/blkio");
m.insert("cpuset", "/sys/fs/cgroup/cpuset");
m.insert("memory", "/sys/fs/cgroup/memory");
m.insert("devices", "/sys/fs/cgroup/devices");
m.insert("freezer", "/sys/fs/cgroup/freezer");
m.insert("net_cls", "/sys/fs/cgroup/net_cls");
m.insert("perf_event", "/sys/fs/cgroup/perf_event");
m.insert("net_prio", "/sys/fs/cgroup/net_prio");
m.insert("hugetlb", "/sys/fs/cgroup/hugetlb");
m.insert("pids", "/sys/fs/cgroup/pids");
m.insert("rdma", "/sys/fs/cgroup/rdma");
m
};
}
#[rustfmt::skip]
lazy_static! {
pub static ref INIT_ROOTFS_MOUNTS: Vec<InitMount> = vec![
InitMount{fstype: "proc", src: "proc", dest: "/proc", options: vec!["nosuid", "nodev", "noexec"]},
InitMount{fstype: "sysfs", src: "sysfs", dest: "/sys", options: vec!["nosuid", "nodev", "noexec"]},
InitMount{fstype: "devtmpfs", src: "dev", dest: "/dev", options: vec!["nosuid"]},
InitMount{fstype: "tmpfs", src: "tmpfs", dest: "/dev/shm", options: vec!["nosuid", "nodev"]},
InitMount{fstype: "devpts", src: "devpts", dest: "/dev/pts", options: vec!["nosuid", "noexec"]},
InitMount{fstype: "tmpfs", src: "tmpfs", dest: "/run", options: vec!["nosuid", "nodev"]},
];
}
pub const STORAGE_HANDLER_LIST: &[&str] = &[
DRIVER_BLK_TYPE,
DRIVER_9P_TYPE,
DRIVER_VIRTIOFS_TYPE,
DRIVER_EPHEMERAL_TYPE,
DRIVER_OVERLAYFS_TYPE,
DRIVER_MMIO_BLK_TYPE,
DRIVER_LOCAL_TYPE,
DRIVER_SCSI_TYPE,
DRIVER_NVDIMM_TYPE,
DRIVER_WATCHABLE_BIND_TYPE,
];
#[instrument]
pub fn baremount(
source: &Path,
destination: &Path,
fs_type: &str,
flags: MsFlags,
options: &str,
logger: &Logger,
) -> Result<()> {
let logger = logger.new(o!("subsystem" => "baremount"));
if source.as_os_str().is_empty() {
return Err(anyhow!("need mount source"));
}
if destination.as_os_str().is_empty() {
return Err(anyhow!("need mount destination"));
}
if fs_type.is_empty() {
return Err(anyhow!("need mount FS type"));
}
info!(
logger,
"mount source={:?}, dest={:?}, fs_type={:?}, options={:?}",
source,
destination,
fs_type,
options
);
nix::mount::mount(
Some(source),
destination,
Some(fs_type),
flags,
Some(options),
)
.map_err(|e| {
anyhow!(
"failed to mount {:?} to {:?}, with error: {}",
source,
destination,
e
)
})
}
#[instrument]
async fn ephemeral_storage_handler(
logger: &Logger,
storage: &Storage,
sandbox: Arc<Mutex<Sandbox>>,
) -> Result<String> {
// hugetlbfs
if storage.fstype == FS_TYPE_HUGETLB {
return handle_hugetlbfs_storage(logger, storage).await;
}
// normal ephemeral storage
fs::create_dir_all(Path::new(&storage.mount_point))?;
// By now we only support one option field: "fsGroup" which
// isn't an valid mount option, thus we should remove it when
// do mount.
if storage.options.len() > 0 {
// ephemeral_storage didn't support mount options except fsGroup.
let mut new_storage = storage.clone();
new_storage.options = protobuf::RepeatedField::default();
common_storage_handler(logger, &new_storage)?;
let opts_vec: Vec<String> = storage.options.to_vec();
let opts = parse_options(opts_vec);
if let Some(fsgid) = opts.get(FS_GID) {
let gid = fsgid.parse::<u32>()?;
nix::unistd::chown(storage.mount_point.as_str(), None, Some(Gid::from_raw(gid)))?;
let meta = fs::metadata(&storage.mount_point)?;
let mut permission = meta.permissions();
let o_mode = meta.mode() | 0o2000;
permission.set_mode(o_mode);
fs::set_permissions(&storage.mount_point, permission)?;
}
} else {
common_storage_handler(logger, storage)?;
}
Ok("".to_string())
}
#[instrument]
async fn overlayfs_storage_handler(
logger: &Logger,
storage: &Storage,
_sandbox: Arc<Mutex<Sandbox>>,
) -> Result<String> {
common_storage_handler(logger, storage)
}
#[instrument]
async fn local_storage_handler(
_logger: &Logger,
storage: &Storage,
sandbox: Arc<Mutex<Sandbox>>,
) -> Result<String> {
fs::create_dir_all(&storage.mount_point).context(format!(
"failed to create dir all {:?}",
&storage.mount_point
))?;
let opts_vec: Vec<String> = storage.options.to_vec();
let opts = parse_options(opts_vec);
let mut need_set_fsgid = false;
if let Some(fsgid) = opts.get(FS_GID) {
let gid = fsgid.parse::<u32>()?;
nix::unistd::chown(storage.mount_point.as_str(), None, Some(Gid::from_raw(gid)))?;
need_set_fsgid = true;
}
if let Some(mode) = opts.get("mode") {
let mut permission = fs::metadata(&storage.mount_point)?.permissions();
let mut o_mode = u32::from_str_radix(mode, 8)?;
if need_set_fsgid {
// set SetGid mode mask.
o_mode |= 0o2000;
}
permission.set_mode(o_mode);
fs::set_permissions(&storage.mount_point, permission)?;
}
Ok("".to_string())
}
#[instrument]
async fn virtio9p_storage_handler(
logger: &Logger,
storage: &Storage,
_sandbox: Arc<Mutex<Sandbox>>,
) -> Result<String> {
common_storage_handler(logger, storage)
}
#[instrument]
async fn handle_hugetlbfs_storage(logger: &Logger, storage: &Storage) -> Result<String> {
info!(logger, "handle hugetlbfs storage");
// Allocate hugepages before mount
// /sys/kernel/mm/hugepages/hugepages-1048576kB/nr_hugepages
// /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
// options eg "pagesize=2097152,size=524288000"(2M, 500M)
allocate_hugepages(logger, &storage.options.to_vec()).context("allocate hugepages")?;
common_storage_handler(logger, storage)?;
// hugetlbfs return empty string as ephemeral_storage_handler do.
// this is a sandbox level storage, but not a container-level mount.
Ok("".to_string())
}
// Allocate hugepages by writing to sysfs
fn allocate_hugepages(logger: &Logger, options: &[String]) -> Result<()> {
info!(logger, "mounting hugePages storage options: {:?}", options);
let (pagesize, size) = get_pagesize_and_size_from_option(options)
.context(format!("parse mount options: {:?}", &options))?;
info!(
logger,
"allocate hugepages. pageSize: {}, size: {}", pagesize, size
);
// sysfs entry is always of the form hugepages-${pagesize}kB
// Ref: https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt
let path = Path::new(SYS_FS_HUGEPAGES_PREFIX)
.join(format!("hugepages-{}kB", pagesize / 1024))
.join("nr_hugepages");
// write numpages to nr_hugepages file.
let numpages = format!("{}", size / pagesize);
info!(logger, "write {} pages to {:?}", &numpages, &path);
let mut file = OpenOptions::new()
.write(true)
.open(&path)
.context(format!("open nr_hugepages directory {:?}", &path))?;
file.write_all(numpages.as_bytes())
.context(format!("write nr_hugepages failed: {:?}", &path))?;
// Even if the write succeeds, the kernel isn't guaranteed to be
// able to allocate all the pages we requested. Verify that it
// did.
let verify = fs::read_to_string(&path).context(format!("reading {:?}", &path))?;
let allocated = verify
.trim_end()
.parse::<u64>()
.map_err(|_| anyhow!("Unexpected text {:?} in {:?}", &verify, &path))?;
if allocated != size / pagesize {
return Err(anyhow!(
"Only allocated {} of {} hugepages of size {}",
allocated,
numpages,
pagesize
));
}
Ok(())
}
// Parse filesystem options string to retrieve hugepage details
// options eg "pagesize=2048,size=107374182"
fn get_pagesize_and_size_from_option(options: &[String]) -> Result<(u64, u64)> {
let mut pagesize_str: Option<&str> = None;
let mut size_str: Option<&str> = None;
for option in options {
let vars: Vec<&str> = option.trim().split(',').collect();
for var in vars {
if let Some(stripped) = var.strip_prefix("pagesize=") {
pagesize_str = Some(stripped);
} else if let Some(stripped) = var.strip_prefix("size=") {
size_str = Some(stripped);
}
if pagesize_str.is_some() && size_str.is_some() {
break;
}
}
}
if pagesize_str.is_none() || size_str.is_none() {
return Err(anyhow!("no pagesize/size options found"));
}
let pagesize = pagesize_str
.unwrap()
.parse::<u64>()
.context(format!("parse pagesize: {:?}", &pagesize_str))?;
let size = size_str
.unwrap()
.parse::<u64>()
.context(format!("parse size: {:?}", &pagesize_str))?;
Ok((pagesize, size))
}
// virtiommio_blk_storage_handler handles the storage for mmio blk driver.
#[instrument]
async fn virtiommio_blk_storage_handler(
logger: &Logger,
storage: &Storage,
sandbox: Arc<Mutex<Sandbox>>,
) -> Result<String> {
//The source path is VmPath
common_storage_handler(logger, storage)
}
// virtiofs_storage_handler handles the storage for virtio-fs.
#[instrument]
async fn virtiofs_storage_handler(
logger: &Logger,
storage: &Storage,
_sandbox: Arc<Mutex<Sandbox>>,
) -> Result<String> {
common_storage_handler(logger, storage)
}
// virtio_blk_storage_handler handles the storage for blk driver.
#[instrument]
async fn virtio_blk_storage_handler(
logger: &Logger,
storage: &Storage,
sandbox: Arc<Mutex<Sandbox>>,
) -> Result<String> {
let mut storage = storage.clone();
// If hot-plugged, get the device node path based on the PCI path
// otherwise use the virt path provided in Storage Source
if storage.source.starts_with("/dev") {
let metadata = fs::metadata(&storage.source)
.context(format!("get metadata on file {:?}", &storage.source))?;
let mode = metadata.permissions().mode();
if mode & libc::S_IFBLK == 0 {
return Err(anyhow!("Invalid device {}", &storage.source));
}
} else {
let pcipath = pci::Path::from_str(&storage.source)?;
let dev_path = get_virtio_blk_pci_device_name(&sandbox, &pcipath).await?;
storage.source = dev_path;
}
common_storage_handler(logger, &storage)
}
// virtio_blk_ccw_storage_handler handles storage for the blk-ccw driver (s390x)
#[cfg(target_arch = "s390x")]
#[instrument]
async fn virtio_blk_ccw_storage_handler(
logger: &Logger,
storage: &Storage,
sandbox: Arc<Mutex<Sandbox>>,
) -> Result<String> {
let mut storage = storage.clone();
let ccw_device = ccw::Device::from_str(&storage.source)?;
let dev_path = get_virtio_blk_ccw_device_name(&sandbox, &ccw_device).await?;
storage.source = dev_path;
common_storage_handler(logger, &storage)
}
#[cfg(not(target_arch = "s390x"))]
#[instrument]
async fn virtio_blk_ccw_storage_handler(
_: &Logger,
_: &Storage,
_: Arc<Mutex<Sandbox>>,
) -> Result<String> {
Err(anyhow!("CCW is only supported on s390x"))
}
// virtio_scsi_storage_handler handles the storage for scsi driver.
#[instrument]
async fn virtio_scsi_storage_handler(
logger: &Logger,
storage: &Storage,
sandbox: Arc<Mutex<Sandbox>>,
) -> Result<String> {
let mut storage = storage.clone();
// Retrieve the device path from SCSI address.
let dev_path = get_scsi_device_name(&sandbox, &storage.source).await?;
storage.source = dev_path;
common_storage_handler(logger, &storage)
}
#[instrument]
fn common_storage_handler(logger: &Logger, storage: &Storage) -> Result<String> {
// Mount the storage device.
let mount_point = storage.mount_point.to_string();
mount_storage(logger, storage).and(Ok(mount_point))
}
// nvdimm_storage_handler handles the storage for NVDIMM driver.
#[instrument]
async fn nvdimm_storage_handler(
logger: &Logger,
storage: &Storage,
sandbox: Arc<Mutex<Sandbox>>,
) -> Result<String> {
let storage = storage.clone();
// Retrieve the device path from NVDIMM address.
wait_for_pmem_device(&sandbox, &storage.source).await?;
common_storage_handler(logger, &storage)
}
async fn bind_watcher_storage_handler(
logger: &Logger,
storage: &Storage,
sandbox: Arc<Mutex<Sandbox>>,
cid: Option<String>,
) -> Result<()> {
let mut locked = sandbox.lock().await;
if let Some(cid) = cid {
locked
.bind_watcher
.add_container(cid, iter::once(storage.clone()), logger)
.await
} else {
Ok(())
}
}
// mount_storage performs the mount described by the storage structure.
#[instrument]
fn mount_storage(logger: &Logger, storage: &Storage) -> Result<()> {
let logger = logger.new(o!("subsystem" => "mount"));
// Check share before attempting to mount to see if the destination is already a mount point.
// If so, skip doing the mount. This facilitates mounting the sharedfs automatically
// in the guest before the agent service starts.
if storage.source == MOUNT_GUEST_TAG && is_mounted(&storage.mount_point)? {
warn!(
logger,
"{} already mounted on {}, ignoring...", MOUNT_GUEST_TAG, &storage.mount_point
);
return Ok(());
}
let mount_path = Path::new(&storage.mount_point);
let src_path = Path::new(&storage.source);
if storage.fstype == "bind" && !src_path.is_dir() {
ensure_destination_file_exists(mount_path)
} else {
fs::create_dir_all(mount_path).map_err(anyhow::Error::from)
}
.context("Could not create mountpoint")?;
let options_vec = storage.options.to_vec();
let options_vec = options_vec.iter().map(String::as_str).collect();
let (flags, options) = parse_mount_flags_and_options(options_vec);
let source = Path::new(&storage.source);
info!(logger, "mounting storage";
"mount-source" => source.display(),
"mount-destination" => mount_path.display(),
"mount-fstype" => storage.fstype.as_str(),
"mount-options" => options.as_str(),
);
baremount(
source,
mount_path,
storage.fstype.as_str(),
flags,
options.as_str(),
&logger,
)
}
/// Looks for `mount_point` entry in the /proc/mounts.
#[instrument]
pub fn is_mounted(mount_point: &str) -> Result<bool> {
let mount_point = mount_point.trim_end_matches('/');
let found = fs::metadata(mount_point).is_ok()
// Looks through /proc/mounts and check if the mount exists
&& fs::read_to_string("/proc/mounts")?
.lines()
.any(|line| {
// The 2nd column reveals the mount point.
line.split_whitespace()
.nth(1)
.map(|target| mount_point.eq(target))
.unwrap_or(false)
});
Ok(found)
}
#[instrument]
fn parse_mount_flags_and_options(options_vec: Vec<&str>) -> (MsFlags, String) {
let mut flags = MsFlags::empty();
let mut options: String = "".to_string();
for opt in options_vec {
if !opt.is_empty() {
match FLAGS.get(opt) {
Some(x) => {
let (clear, f) = *x;
if clear {
flags &= !f;
} else {
flags |= f;
}
}
None => {
if !options.is_empty() {
options.push_str(format!(",{}", opt).as_str());
} else {
options.push_str(opt.to_string().as_str());
}
}
};
}
}
(flags, options)
}
// add_storages takes a list of storages passed by the caller, and perform the
// associated operations such as waiting for the device to show up, and mount
// it to a specific location, according to the type of handler chosen, and for
// each storage.
#[instrument]
pub async fn add_storages(
logger: Logger,
storages: Vec<Storage>,
sandbox: Arc<Mutex<Sandbox>>,
cid: Option<String>,
) -> Result<Vec<String>> {
let mut mount_list = Vec::new();
for storage in storages {
let handler_name = storage.driver.clone();
let logger = logger.new(o!(
"subsystem" => "storage",
"storage-type" => handler_name.to_owned()));
{
let mut sb = sandbox.lock().await;
let new_storage = sb.set_sandbox_storage(&storage.mount_point);
if !new_storage {
continue;
}
}
let res = match handler_name.as_str() {
DRIVER_BLK_TYPE => virtio_blk_storage_handler(&logger, &storage, sandbox.clone()).await,
DRIVER_BLK_CCW_TYPE => {
virtio_blk_ccw_storage_handler(&logger, &storage, sandbox.clone()).await
}
DRIVER_9P_TYPE => virtio9p_storage_handler(&logger, &storage, sandbox.clone()).await,
DRIVER_VIRTIOFS_TYPE => {
virtiofs_storage_handler(&logger, &storage, sandbox.clone()).await
}
DRIVER_EPHEMERAL_TYPE => {
ephemeral_storage_handler(&logger, &storage, sandbox.clone()).await
}
DRIVER_OVERLAYFS_TYPE => {
overlayfs_storage_handler(&logger, &storage, sandbox.clone()).await
}
DRIVER_MMIO_BLK_TYPE => {
virtiommio_blk_storage_handler(&logger, &storage, sandbox.clone()).await
}
DRIVER_LOCAL_TYPE => local_storage_handler(&logger, &storage, sandbox.clone()).await,
DRIVER_SCSI_TYPE => {
virtio_scsi_storage_handler(&logger, &storage, sandbox.clone()).await
}
DRIVER_NVDIMM_TYPE => nvdimm_storage_handler(&logger, &storage, sandbox.clone()).await,
DRIVER_WATCHABLE_BIND_TYPE => {
bind_watcher_storage_handler(&logger, &storage, sandbox.clone(), cid.clone())
.await?;
// Don't register watch mounts, they're handled separately by the watcher.
Ok(String::new())
}
_ => {
return Err(anyhow!(
"Failed to find the storage handler {}",
storage.driver.to_owned()
));
}
};
// Todo need to rollback the mounted storage if err met.
let mount_point = res?;
if !mount_point.is_empty() {
mount_list.push(mount_point);
}
}
Ok(mount_list)
}
#[instrument]
fn mount_to_rootfs(logger: &Logger, m: &InitMount) -> Result<()> {
let options_vec: Vec<&str> = m.options.clone();
let (flags, options) = parse_mount_flags_and_options(options_vec);
fs::create_dir_all(Path::new(m.dest)).context("could not create directory")?;
let source = Path::new(m.src);
let dest = Path::new(m.dest);
baremount(source, dest, m.fstype, flags, &options, logger).or_else(|e| {
if m.src != "dev" {
return Err(e);
}
error!(
logger,
"Could not mount filesystem from {} to {}", m.src, m.dest
);
Ok(())
})?;
Ok(())
}
#[instrument]
pub fn general_mount(logger: &Logger) -> Result<()> {
let logger = logger.new(o!("subsystem" => "mount"));
for m in INIT_ROOTFS_MOUNTS.iter() {
mount_to_rootfs(&logger, m)?;
}
Ok(())
}
#[inline]
pub fn get_mount_fs_type(mount_point: &str) -> Result<String> {
get_mount_fs_type_from_file(PROC_MOUNTSTATS, mount_point)
}
// get_mount_fs_type_from_file returns the FS type corresponding to the passed mount point and
// any error ecountered.
#[instrument]
pub fn get_mount_fs_type_from_file(mount_file: &str, mount_point: &str) -> Result<String> {
if mount_point.is_empty() {
return Err(anyhow!("Invalid mount point {}", mount_point));
}
let file = File::open(mount_file)?;
let reader = BufReader::new(file);
let re = Regex::new(format!("device .+ mounted on {} with fstype (.+)", mount_point).as_str())?;
// Read the file line by line using the lines() iterator from std::io::BufRead.
for (_index, line) in reader.lines().enumerate() {
let line = line?;
let capes = match re.captures(line.as_str()) {
Some(c) => c,
None => continue,
};
if capes.len() > 1 {
return Ok(capes[1].to_string());
}
}
Err(anyhow!(
"failed to find FS type for mount point {}",
mount_point
))
}
#[instrument]
pub fn get_cgroup_mounts(
logger: &Logger,
cg_path: &str,
unified_cgroup_hierarchy: bool,
) -> Result<Vec<InitMount>> {
// cgroup v2
// https://github.com/kata-containers/agent/blob/8c9bbadcd448c9a67690fbe11a860aaacc69813c/agent.go#L1249
if unified_cgroup_hierarchy {
return Ok(vec![InitMount {
fstype: "cgroup2",
src: "cgroup2",
dest: "/sys/fs/cgroup",
options: vec!["nosuid", "nodev", "noexec", "relatime", "nsdelegate"],
}]);
}
let file = File::open(&cg_path)?;
let reader = BufReader::new(file);
let mut has_device_cgroup = false;
let mut cg_mounts: Vec<InitMount> = vec![InitMount {
fstype: "tmpfs",
src: "tmpfs",
dest: SYSFS_CGROUPPATH,
options: vec!["nosuid", "nodev", "noexec", "mode=755"],
}];
// #subsys_name hierarchy num_cgroups enabled
// fields[0] fields[1] fields[2] fields[3]
'outer: for (_, line) in reader.lines().enumerate() {
let line = line?;
let fields: Vec<&str> = line.split('\t').collect();
// Ignore comment header
if fields[0].starts_with('#') {
continue;
}
// Ignore truncated lines
if fields.len() < 4 {
continue;
}
// Ignore disabled cgroups
if fields[3] == "0" {
continue;
}
// Ignore fields containing invalid numerics
for f in [fields[1], fields[2], fields[3]].iter() {
if f.parse::<u64>().is_err() {
continue 'outer;
}
}
let subsystem_name = fields[0];
if subsystem_name.is_empty() {
continue;
}
if subsystem_name == "devices" {
has_device_cgroup = true;
}
if let Some((key, value)) = CGROUPS.get_key_value(subsystem_name) {
cg_mounts.push(InitMount {
fstype: "cgroup",
src: "cgroup",
dest: value,
options: vec!["nosuid", "nodev", "noexec", "relatime", key],
});
}
}
if !has_device_cgroup {
warn!(logger, "The system didn't support device cgroup, which is dangerous, thus agent initialized without cgroup support!\n");
return Ok(Vec::new());
}
cg_mounts.push(InitMount {
fstype: "tmpfs",
src: "tmpfs",
dest: SYSFS_CGROUPPATH,
options: vec!["remount", "ro", "nosuid", "nodev", "noexec", "mode=755"],
});
Ok(cg_mounts)
}
#[instrument]
pub fn cgroups_mount(logger: &Logger, unified_cgroup_hierarchy: bool) -> Result<()> {
let logger = logger.new(o!("subsystem" => "mount"));
let cgroups = get_cgroup_mounts(&logger, PROC_CGROUPS, unified_cgroup_hierarchy)?;
for cg in cgroups.iter() {
mount_to_rootfs(&logger, cg)?;
}
// Enable memory hierarchical account.
// For more information see https://www.kernel.org/doc/Documentation/cgroup-v1/memory.txt
online_device("/sys/fs/cgroup/memory/memory.use_hierarchy")?;
Ok(())
}
#[instrument]
pub fn remove_mounts(mounts: &[String]) -> Result<()> {
for m in mounts.iter() {
nix::mount::umount(m.as_str()).context(format!("failed to umount {:?}", m))?;
}
Ok(())
}
#[instrument]
fn ensure_destination_file_exists(path: &Path) -> Result<()> {
if path.is_file() {
return Ok(());
} else if path.exists() {
return Err(anyhow!("{:?} exists but is not a regular file", path));
}
let dir = path
.parent()
.ok_or_else(|| anyhow!("failed to find parent path for {:?}", path))?;
fs::create_dir_all(dir).context(format!("create_dir_all {:?}", dir))?;
fs::File::create(path).context(format!("create empty file {:?}", path))?;
Ok(())
}
#[instrument]
fn parse_options(option_list: Vec<String>) -> HashMap<String, String> {
let mut options = HashMap::new();
for opt in option_list.iter() {
let fields: Vec<&str> = opt.split('=').collect();
if fields.len() != 2 {
continue;
}
options.insert(fields[0].to_string(), fields[1].to_string());
}
options
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{skip_if_not_root, skip_loop_if_not_root, skip_loop_if_root};
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;
use tempfile::tempdir;
#[derive(Debug, PartialEq)]
enum TestUserType {
RootOnly,
NonRootOnly,
Any,
}
#[test]
fn test_mount() {
#[derive(Debug)]
struct TestData<'a> {
// User(s) who can run this test
test_user: TestUserType,
src: &'a str,
dest: &'a str,
fs_type: &'a str,
flags: MsFlags,
options: &'a str,
// If set, assume an error will be generated,
// else assume no error.
//
// If not set, assume root required to perform a
// successful mount.
error_contains: &'a str,
}
let dir = tempdir().expect("failed to create tmpdir");
let drain = slog::Discard;
let logger = slog::Logger::root(drain, o!());
let tests = &[
TestData {
test_user: TestUserType::Any,
src: "",
dest: "",
fs_type: "",
flags: MsFlags::empty(),
options: "",
error_contains: "need mount source",
},
TestData {
test_user: TestUserType::Any,
src: "from",
dest: "",
fs_type: "",
flags: MsFlags::empty(),
options: "",
error_contains: "need mount destination",
},
TestData {
test_user: TestUserType::Any,
src: "from",
dest: "to",
fs_type: "",
flags: MsFlags::empty(),
options: "",
error_contains: "need mount FS type",
},
TestData {
test_user: TestUserType::NonRootOnly,
src: "from",
dest: "to",
fs_type: "bind",
flags: MsFlags::empty(),
options: "bind",
error_contains: "Operation not permitted",
},
TestData {
test_user: TestUserType::NonRootOnly,
src: "from",
dest: "to",
fs_type: "bind",
flags: MsFlags::MS_BIND,
options: "",
error_contains: "Operation not permitted",
},
TestData {
test_user: TestUserType::RootOnly,
src: "from",
dest: "to",
fs_type: "bind",
flags: MsFlags::MS_BIND,
options: "",
error_contains: "",
},
];
for (i, d) in tests.iter().enumerate() {
let msg = format!("test[{}]: {:?}", i, d);
if d.test_user == TestUserType::RootOnly {
skip_loop_if_not_root!(msg);
} else if d.test_user == TestUserType::NonRootOnly {
skip_loop_if_root!(msg);
}
let src: PathBuf;
let dest: PathBuf;
let src_filename: String;
let dest_filename: String;
if !d.src.is_empty() {
src = dir.path().join(d.src);
src_filename = src
.to_str()
.expect("failed to convert src to filename")
.to_string();
} else {
src_filename = "".to_owned();
}
if !d.dest.is_empty() {
dest = dir.path().join(d.dest);
dest_filename = dest
.to_str()
.expect("failed to convert dest to filename")
.to_string();
} else {
dest_filename = "".to_owned();
}
// Create the mount directories
for d in [src_filename.clone(), dest_filename.clone()].iter() {
if d.is_empty() {
continue;
}
std::fs::create_dir_all(d).expect("failed to created directory");
}
let src = Path::new(&src_filename);
let dest = Path::new(&dest_filename);
let result = baremount(src, dest, d.fs_type, d.flags, d.options, &logger);
let msg = format!("{}: result: {:?}", msg, result);
if d.error_contains.is_empty() {
assert!(result.is_ok(), "{}", msg);
// Cleanup
nix::mount::umount(dest_filename.as_str()).unwrap();
continue;
}
let err = result.unwrap_err();
let error_msg = format!("{}", err);
assert!(error_msg.contains(d.error_contains), "{}", msg);
}
}
#[test]
fn test_is_mounted() {
assert!(is_mounted("/proc").unwrap());
assert!(!is_mounted("").unwrap());
assert!(!is_mounted("!").unwrap());
assert!(!is_mounted("/not_existing_path").unwrap());
}
#[test]
fn test_remove_mounts() {
skip_if_not_root!();
#[derive(Debug)]
struct TestData<'a> {
mounts: Vec<String>,
// If set, assume an error will be generated,
// else assume no error.
error_contains: &'a str,
}
let dir = tempdir().expect("failed to create tmpdir");
let drain = slog::Discard;
let logger = slog::Logger::root(drain, o!());
let test_dir_path = dir.path().join("dir");
let test_dir_filename = test_dir_path
.to_str()
.expect("failed to create mount dir filename");
let test_file_path = dir.path().join("file");
let test_file_filename = test_file_path
.to_str()
.expect("failed to create mount file filename");
OpenOptions::new()
.create(true)
.write(true)
.open(test_file_filename)
.expect("failed to create test file");
std::fs::create_dir_all(test_dir_filename).expect("failed to create dir");
let mnt_src = dir.path().join("mnt-src");
let mnt_src_filename = mnt_src
.to_str()
.expect("failed to create mount source filename");
let mnt_dest = dir.path().join("mnt-dest");
let mnt_dest_filename = mnt_dest
.to_str()
.expect("failed to create mount destination filename");
for d in [test_dir_filename, mnt_src_filename, mnt_dest_filename].iter() {
std::fs::create_dir_all(d)
.unwrap_or_else(|_| panic!("failed to create directory {}", d));
}
let src = Path::new(mnt_src_filename);
let dest = Path::new(mnt_dest_filename);
// Create an actual mount
let result = baremount(src, dest, "bind", MsFlags::MS_BIND, "", &logger);
assert!(result.is_ok(), "mount for test setup failed");
let tests = &[
TestData {
mounts: vec![],
error_contains: "",
},
TestData {
mounts: vec!["".to_string()],
error_contains: "ENOENT: No such file or directory",
},
TestData {
mounts: vec![test_file_filename.to_string()],
error_contains: "EINVAL: Invalid argument",
},
TestData {
mounts: vec![test_dir_filename.to_string()],
error_contains: "EINVAL: Invalid argument",
},
TestData {
mounts: vec![mnt_dest_filename.to_string()],
error_contains: "",
},
];
for (i, d) in tests.iter().enumerate() {
let msg = format!("test[{}]: {:?}", i, d);
let result = remove_mounts(&d.mounts);
let msg = format!("{}: result: {:?}", msg, result);
if d.error_contains.is_empty() {
assert!(result.is_ok(), "{}", msg);
continue;
}
let error_msg = format!("{:#}", result.unwrap_err());
assert!(error_msg.contains(d.error_contains), "{}", msg);
}
}
#[test]
fn test_get_mount_fs_type_from_file() {
#[derive(Debug)]
struct TestData<'a> {
// Create file with the specified contents
// (even if a nul string is specified).
contents: &'a str,
mount_point: &'a str,
// If set, assume an error will be generated,
// else assume no error.
error_contains: &'a str,
// successful return value
fs_type: &'a str,
}
let dir = tempdir().expect("failed to create tmpdir");
let tests = &[
TestData {
contents: "",
mount_point: "",
error_contains: "Invalid mount point",
fs_type: "",
},
TestData {
contents: "foo",
mount_point: "",
error_contains: "Invalid mount point",
fs_type: "",
},
TestData {
contents: "foo",
mount_point: "/",
error_contains: "failed to find FS type for mount point /",
fs_type: "",
},
TestData {
// contents missing fields
contents: "device /dev/mapper/root mounted on /",
mount_point: "/",
error_contains: "failed to find FS type for mount point /",
fs_type: "",
},
TestData {
contents: "device /dev/mapper/root mounted on / with fstype ext4",
mount_point: "/",
error_contains: "",
fs_type: "ext4",
},
];
let enoent_file_path = dir.path().join("enoent");
let enoent_filename = enoent_file_path
.to_str()
.expect("failed to create enoent filename");
// First, test that an empty mount file is handled
for (i, mp) in ["/", "/somewhere", "/tmp", enoent_filename]
.iter()
.enumerate()
{
let msg = format!("missing mount file test[{}] with mountpoint: {}", i, mp);
let result = get_mount_fs_type_from_file("", mp);
let err = result.unwrap_err();
let msg = format!("{}: error: {}", msg, err);
assert!(
format!("{}", err).contains("No such file or directory"),
"{}",
msg
);
}
// Now, test various combinations of file contents
for (i, d) in tests.iter().enumerate() {
let msg = format!("test[{}]: {:?}", i, d);
let file_path = dir.path().join("mount_stats");
let filename = file_path
.to_str()
.unwrap_or_else(|| panic!("{}: failed to create filename", msg));
let mut file =
File::create(filename).unwrap_or_else(|_| panic!("{}: failed to create file", msg));
file.write_all(d.contents.as_bytes())
.unwrap_or_else(|_| panic!("{}: failed to write file contents", msg));
let result = get_mount_fs_type_from_file(filename, d.mount_point);
// add more details if an assertion fails
let msg = format!("{}: result: {:?}", msg, result);
if d.error_contains.is_empty() {
let fs_type = result.unwrap();
assert!(d.fs_type == fs_type, "{}", msg);
continue;
}
let error_msg = format!("{}", result.unwrap_err());
assert!(error_msg.contains(d.error_contains), "{}", msg);
}
}
#[test]
fn test_get_cgroup_v2_mounts() {
let _ = tempdir().expect("failed to create tmpdir");
let drain = slog::Discard;
let logger = slog::Logger::root(drain, o!());
let result = get_cgroup_mounts(&logger, "", true);
assert!(result.is_ok());
let result = result.unwrap();
assert_eq!(1, result.len());
assert_eq!(result[0].fstype, "cgroup2");
assert_eq!(result[0].src, "cgroup2");
}
#[test]
fn test_get_cgroup_mounts() {
#[derive(Debug)]
struct TestData<'a> {
// Create file with the specified contents
// (even if a nul string is specified).
contents: &'a str,
// If set, assume an error will be generated,
// else assume no error.
error_contains: &'a str,
// Set if the devices cgroup is expected to be found
devices_cgroup: bool,
}
let dir = tempdir().expect("failed to create tmpdir");
let drain = slog::Discard;
let logger = slog::Logger::root(drain, o!());
let first_mount = InitMount {
fstype: "tmpfs",
src: "tmpfs",
dest: SYSFS_CGROUPPATH,
options: vec!["nosuid", "nodev", "noexec", "mode=755"],
};
let last_mount = InitMount {
fstype: "tmpfs",
src: "tmpfs",
dest: SYSFS_CGROUPPATH,
options: vec!["remount", "ro", "nosuid", "nodev", "noexec", "mode=755"],
};
let cg_devices_mount = InitMount {
fstype: "cgroup",
src: "cgroup",
dest: "/sys/fs/cgroup/devices",
options: vec!["nosuid", "nodev", "noexec", "relatime", "devices"],
};
let enoent_file_path = dir.path().join("enoent");
let enoent_filename = enoent_file_path
.to_str()
.expect("failed to create enoent filename");
let tests = &[
TestData {
// Empty file
contents: "",
error_contains: "",
devices_cgroup: false,
},
TestData {
// Only a comment line
contents: "#subsys_name hierarchy num_cgroups enabled",
error_contains: "",
devices_cgroup: false,
},
TestData {
// Single (invalid) field
contents: "foo",
error_contains: "",
devices_cgroup: false,
},
TestData {
// Multiple (invalid) fields
contents: "this\tis\tinvalid\tdata\n",
error_contains: "",
devices_cgroup: false,
},
TestData {
// Valid first field, but other fields missing
contents: "devices\n",
error_contains: "",
devices_cgroup: false,
},
TestData {
// Valid first field, but invalid others fields
contents: "devices\tinvalid\tinvalid\tinvalid\n",
error_contains: "",
devices_cgroup: false,
},
TestData {
// Valid first field, but lots of invalid others fields
contents: "devices\tinvalid\tinvalid\tinvalid\tinvalid\tinvalid\n",
error_contains: "",
devices_cgroup: false,
},
TestData {
// Valid, but disabled
contents: "devices\t1\t1\t0\n",
error_contains: "",
devices_cgroup: false,
},
TestData {
// Valid
contents: "devices\t1\t1\t1\n",
error_contains: "",
devices_cgroup: true,
},
];
// First, test a missing file
let result = get_cgroup_mounts(&logger, enoent_filename, false);
assert!(result.is_err());
let error_msg = format!("{}", result.unwrap_err());
assert!(
error_msg.contains("No such file or directory"),
"enoent test"
);
for (i, d) in tests.iter().enumerate() {
let msg = format!("test[{}]: {:?}", i, d);
let file_path = dir.path().join("cgroups");
let filename = file_path
.to_str()
.expect("failed to create cgroup file filename");
let mut file =
File::create(filename).unwrap_or_else(|_| panic!("{}: failed to create file", msg));
file.write_all(d.contents.as_bytes())
.unwrap_or_else(|_| panic!("{}: failed to write file contents", msg));
let result = get_cgroup_mounts(&logger, filename, false);
let msg = format!("{}: result: {:?}", msg, result);
if !d.error_contains.is_empty() {
assert!(result.is_err(), "{}", msg);
let error_msg = format!("{}", result.unwrap_err());
assert!(error_msg.contains(d.error_contains), "{}", msg);
continue;
}
assert!(result.is_ok(), "{}", msg);
let mounts = result.unwrap();
let count = mounts.len();
if !d.devices_cgroup {
assert!(count == 0, "{}", msg);
continue;
}
// get_cgroup_mounts() adds the device cgroup plus two other mounts.
assert!(count == (1 + 2), "{}", msg);
// First mount
assert!(mounts[0].eq(&first_mount), "{}", msg);
// Last mount
assert!(mounts[2].eq(&last_mount), "{}", msg);
// Devices cgroup
assert!(mounts[1].eq(&cg_devices_mount), "{}", msg);
}
}
#[test]
fn test_ensure_destination_file_exists() {
let dir = tempdir().expect("failed to create tmpdir");
let mut testfile = dir.into_path();
testfile.push("testfile");
let result = ensure_destination_file_exists(&testfile);
assert!(result.is_ok());
assert!(testfile.exists());
let result = ensure_destination_file_exists(&testfile);
assert!(result.is_ok());
assert!(testfile.is_file());
}
#[test]
fn test_get_pagesize_and_size_from_option() {
let expected_pagesize = 2048;
let expected_size = 107374182;
let expected = (expected_pagesize, expected_size);
let data = vec![
// (input, expected, is_ok)
("size-1=107374182,pagesize-1=2048", expected, false),
("size-1=107374182,pagesize=2048", expected, false),
("size=107374182,pagesize-1=2048", expected, false),
("size=107374182,pagesize=abc", expected, false),
("size=abc,pagesize=2048", expected, false),
("size=,pagesize=2048", expected, false),
("size=107374182,pagesize=", expected, false),
("size=107374182,pagesize=2048", expected, true),
("pagesize=2048,size=107374182", expected, true),
("foo=bar,pagesize=2048,size=107374182", expected, true),
(
"foo=bar,pagesize=2048,foo1=bar1,size=107374182",
expected,
true,
),
(
"pagesize=2048,foo1=bar1,foo=bar,size=107374182",
expected,
true,
),
(
"foo=bar,pagesize=2048,foo1=bar1,size=107374182,foo2=bar2",
expected,
true,
),
(
"foo=bar,size=107374182,foo1=bar1,pagesize=2048",
expected,
true,
),
];
for case in data {
let input = case.0;
let r = get_pagesize_and_size_from_option(&[input.to_string()]);
let is_ok = case.2;
if is_ok {
let expected = case.1;
let (pagesize, size) = r.unwrap();
assert_eq!(expected.0, pagesize);
assert_eq!(expected.1, size);
} else {
assert!(r.is_err());
}
}
}
}
| 31.998715 | 135 | 0.547218 |
db3d9539481ebc18c12bfa65d4a765b71890d115 | 801 | fn main() {
println!("part one: {}", find_last(&[1, 0, 15, 2, 10, 13], 2020));
println!("part one: {}", find_last(&[1, 0, 15, 2, 10, 13], 30000000));
}
fn find_last(nums: &[usize], nth_num: usize) -> usize {
let mut cache = vec![std::usize::MAX; nth_num];
for (i, &n) in nums.iter().enumerate() {
cache[n] = i;
}
let mut spoken = nums[nums.len() - 1];
for i in nums.len()..nth_num {
let n = cache[spoken];
cache[spoken] = i - 1;
spoken = (i - 1).saturating_sub(n);
}
spoken
}
mod tests {
#[test]
fn test_part_one() {
assert_eq!(211, super::find_last(&[1, 0, 15, 2, 10, 13], 2020));
}
#[test]
fn test_part_two() {
assert_eq!(2159626, super::find_last(&[1, 0, 15, 2, 10, 13], 30000000));
}
}
| 25.83871 | 80 | 0.518102 |
db159aad4c2648e0d4f6c54a01b4f3551b16ae71 | 182 | pub mod cidr;
pub mod hosts;
pub mod icmp;
pub mod ports;
pub use crate::hosts::{probe_host, HostStatus};
pub use crate::ports::{probe_port, PortStatus};
pub use cidr::IpAddrRange;
| 20.222222 | 47 | 0.741758 |
1d91abb0a76e0361d27bef3b4242491819da7f44 | 7,839 | #[macro_use] extern crate rocket;
use std::path::{Path, PathBuf};
use rocket::{Rocket, Build};
use rocket::config::Config;
use rocket_dyn_templates::{Template, Metadata};
#[get("/<engine>/<name>")]
fn template_check(md: Metadata<'_>, engine: &str, name: &str) -> Option<()> {
match md.contains_template(&format!("{}/{}", engine, name)) {
true => Some(()),
false => None
}
}
#[get("/is_reloading")]
fn is_reloading(md: Metadata<'_>) -> Option<()> {
if md.reloading() { Some(()) } else { None }
}
fn template_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests").join("templates")
}
fn rocket() -> Rocket<Build> {
rocket::custom(Config::figment().merge(("template_dir", template_root())))
.attach(Template::fairing())
.mount("/", routes![template_check, is_reloading])
}
#[test]
fn test_callback_error() {
use rocket::{local::blocking::Client, error::ErrorKind::FailedFairings};
let rocket = rocket::build().attach(Template::try_custom(|_| {
Err("error reloading templates!".into())
}));
let error = Client::debug(rocket).expect_err("client failure");
match error.kind() {
FailedFairings(failures) => assert_eq!(failures[0].name, "Templating"),
_ => panic!("Wrong kind of launch error"),
}
}
#[test]
fn test_sentinel() {
use rocket::{local::blocking::Client, error::ErrorKind::SentinelAborts};
let err = Client::debug_with(routes![is_reloading]).unwrap_err();
assert!(matches!(err.kind(), SentinelAborts(vec) if vec.len() == 1));
let err = Client::debug_with(routes![is_reloading, template_check]).unwrap_err();
assert!(matches!(err.kind(), SentinelAborts(vec) if vec.len() == 2));
#[get("/")]
fn return_template() -> Template {
Template::render("foo", ())
}
let err = Client::debug_with(routes![return_template]).unwrap_err();
assert!(matches!(err.kind(), SentinelAborts(vec) if vec.len() == 1));
#[get("/")]
fn return_opt_template() -> Option<Template> {
Some(Template::render("foo", ()))
}
let err = Client::debug_with(routes![return_opt_template]).unwrap_err();
assert!(matches!(err.kind(), SentinelAborts(vec) if vec.len() == 1));
#[derive(rocket::Responder)]
struct MyThing<T>(T);
#[get("/")]
fn return_custom_template() -> MyThing<Template> {
MyThing(Template::render("foo", ()))
}
let err = Client::debug_with(routes![return_custom_template]).unwrap_err();
assert!(matches!(err.kind(), SentinelAborts(vec) if vec.len() == 1));
#[derive(rocket::Responder)]
struct MyOkayThing<T>(Option<T>);
impl<T> rocket::Sentinel for MyOkayThing<T> {
fn abort(_: &Rocket<rocket::Ignite>) -> bool {
false
}
}
#[get("/")]
fn always_ok_sentinel() -> MyOkayThing<Template> {
MyOkayThing(None)
}
Client::debug_with(routes![always_ok_sentinel]).expect("no sentinel abort");
}
#[cfg(feature = "tera")]
mod tera_tests {
use super::*;
use std::collections::HashMap;
use rocket::http::Status;
use rocket::local::blocking::Client;
const UNESCAPED_EXPECTED: &'static str
= "\nh_start\ntitle: _test_\nh_end\n\n\n<script />\n\nfoot\n";
const ESCAPED_EXPECTED: &'static str
= "\nh_start\ntitle: _test_\nh_end\n\n\n<script />\n\nfoot\n";
#[test]
fn test_tera_templates() {
let client = Client::debug(rocket()).unwrap();
let mut map = HashMap::new();
map.insert("title", "_test_");
map.insert("content", "<script />");
// Test with a txt file, which shouldn't escape.
let template = Template::show(client.rocket(), "tera/txt_test", &map);
assert_eq!(template, Some(UNESCAPED_EXPECTED.into()));
// Now with an HTML file, which should.
let template = Template::show(client.rocket(), "tera/html_test", &map);
assert_eq!(template, Some(ESCAPED_EXPECTED.into()));
}
#[test]
fn test_template_metadata_with_tera() {
let client = Client::debug(rocket()).unwrap();
let response = client.get("/tera/txt_test").dispatch();
assert_eq!(response.status(), Status::Ok);
let response = client.get("/tera/html_test").dispatch();
assert_eq!(response.status(), Status::Ok);
let response = client.get("/tera/not_existing").dispatch();
assert_eq!(response.status(), Status::NotFound);
let response = client.get("/hbs/txt_test").dispatch();
assert_eq!(response.status(), Status::NotFound);
}
}
#[cfg(feature = "handlebars")]
mod handlebars_tests {
use super::*;
use std::collections::HashMap;
use rocket::http::Status;
use rocket::local::blocking::Client;
const EXPECTED: &'static str
= "Hello _test_!\n\n<main> <script /> hi </main>\nDone.\n\n";
#[test]
fn test_handlebars_templates() {
let client = Client::debug(rocket()).unwrap();
let mut map = HashMap::new();
map.insert("title", "_test_");
map.insert("content", "<script /> hi");
// Test with a txt file, which shouldn't escape.
let template = Template::show(client.rocket(), "hbs/test", &map);
assert_eq!(template, Some(EXPECTED.into()));
}
#[test]
fn test_template_metadata_with_handlebars() {
let client = Client::debug(rocket()).unwrap();
let response = client.get("/hbs/test").dispatch();
assert_eq!(response.status(), Status::Ok);
let response = client.get("/hbs/not_existing").dispatch();
assert_eq!(response.status(), Status::NotFound);
let response = client.get("/tera/test").dispatch();
assert_eq!(response.status(), Status::NotFound);
}
#[test]
#[cfg(debug_assertions)]
fn test_template_reload() {
use std::fs::File;
use std::io::Write;
use std::time::Duration;
use rocket::local::blocking::Client;
const RELOAD_TEMPLATE: &str = "hbs/reload";
const INITIAL_TEXT: &str = "initial";
const NEW_TEXT: &str = "reload";
fn write_file(path: &Path, text: &str) {
let mut file = File::create(path).expect("open file");
file.write_all(text.as_bytes()).expect("write file");
file.sync_all().expect("sync file");
}
// set up the template before initializing the Rocket instance so
// that it will be picked up in the initial loading of templates.
let reload_path = template_root().join("hbs").join("reload.txt.hbs");
write_file(&reload_path, INITIAL_TEXT);
// set up the client. if we can't reload templates, then just quit
let client = Client::debug(rocket()).unwrap();
let res = client.get("/is_reloading").dispatch();
if res.status() != Status::Ok {
return;
}
// verify that the initial content is correct
let initial_rendered = Template::show(client.rocket(), RELOAD_TEMPLATE, ());
assert_eq!(initial_rendered, Some(INITIAL_TEXT.into()));
// write a change to the file
write_file(&reload_path, NEW_TEXT);
for _ in 0..6 {
// dispatch any request to trigger a template reload
client.get("/").dispatch();
// if the new content is correct, we are done
let new_rendered = Template::show(client.rocket(), RELOAD_TEMPLATE, ());
if new_rendered == Some(NEW_TEXT.into()) {
write_file(&reload_path, INITIAL_TEXT);
return;
}
// otherwise, retry a few times, waiting 250ms in between
std::thread::sleep(Duration::from_millis(250));
}
panic!("failed to reload modified template in 1.5s");
}
}
| 32.799163 | 85 | 0.605307 |
7ab59a799205d72b0d59e2f1b991516ebfb10b06 | 2,188 | // Copyright (c) 2017-present PyO3 Project and Contributors
//! Context manager api
//! Trait and support implementation for context manager api
//!
use crate::class::methods::PyMethodDef;
use crate::err::PyResult;
use crate::typeob::PyTypeInfo;
/// Context manager interface
#[allow(unused_variables)]
pub trait PyContextProtocol<'p>: PyTypeInfo {
fn __enter__(&'p mut self) -> Self::Result
where
Self: PyContextEnterProtocol<'p>,
{
unimplemented!()
}
fn __exit__(
&'p mut self,
exc_type: Option<Self::ExcType>,
exc_value: Option<Self::ExcValue>,
traceback: Option<Self::Traceback>,
) -> Self::Result
where
Self: PyContextExitProtocol<'p>,
{
unimplemented!()
}
}
pub trait PyContextEnterProtocol<'p>: PyContextProtocol<'p> {
type Success: crate::IntoPyObject;
type Result: Into<PyResult<Self::Success>>;
}
pub trait PyContextExitProtocol<'p>: PyContextProtocol<'p> {
type ExcType: crate::FromPyObject<'p>;
type ExcValue: crate::FromPyObject<'p>;
type Traceback: crate::FromPyObject<'p>;
type Success: crate::IntoPyObject;
type Result: Into<PyResult<Self::Success>>;
}
#[doc(hidden)]
pub trait PyContextProtocolImpl {
fn methods() -> Vec<PyMethodDef> {
Vec::new()
}
}
impl<T> PyContextProtocolImpl for T {}
impl<'p, T> PyContextProtocolImpl for T
where
T: PyContextProtocol<'p>,
{
#[inline]
fn methods() -> Vec<PyMethodDef> {
let mut methods = Vec::new();
if let Some(def) = <Self as PyContextEnterProtocolImpl>::__enter__() {
methods.push(def)
}
if let Some(def) = <Self as PyContextExitProtocolImpl>::__exit__() {
methods.push(def)
}
methods
}
}
#[doc(hidden)]
pub trait PyContextEnterProtocolImpl {
fn __enter__() -> Option<PyMethodDef> {
None
}
}
impl<'p, T> PyContextEnterProtocolImpl for T where T: PyContextProtocol<'p> {}
#[doc(hidden)]
pub trait PyContextExitProtocolImpl {
fn __exit__() -> Option<PyMethodDef> {
None
}
}
impl<'p, T> PyContextExitProtocolImpl for T where T: PyContextProtocol<'p> {}
| 23.782609 | 78 | 0.64351 |
f57d462eef947ffe71c174c0bbf2e3fbedba9262 | 781 | use core::fmt;
use embedded_hal::{blocking::spi, digital::v2::OutputPin};
/// Error type throwable by vco operations
pub enum Error<SPI, LE>
where
SPI: spi::Transfer<u8>,
LE: OutputPin,
{
/// Error during SPI Transfer
Transfer(<SPI as spi::Transfer<u8>>::Error),
/// Error during Latch Enable
LatchEnable(<LE as OutputPin>::Error),
}
impl<SPI, LE> fmt::Debug for Error<SPI, LE>
where
SPI: spi::Transfer<u8>,
SPI::Error: fmt::Debug,
LE: OutputPin,
<LE as OutputPin>::Error: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Transfer(error) => write!(f, "Transfer({:?})", error),
Error::LatchEnable(error) => write!(f, "LatchEnable({:?})", error),
}
}
}
| 26.033333 | 79 | 0.597951 |
0ea44f118e29f45abf0a0ddfd992f572ef9b24a1 | 7,230 | use crate::messaging::mqtt::Request::{Subscription, Publication};
use std::collections::HashMap;
use std::future::Future;
use std::sync::{
Arc, Mutex, mpsc::{self, Sender, Receiver}
};
use rumqttc::{self, AsyncClient, Event, MqttOptions, Packet, QoS};
use tokio::task;
use tokio::task::JoinHandle;
use futures::future::{join3, Join3};
use delegate::delegate;
use Request::Unsubscription;
use log::{info, error};
pub enum Request {
Subscription(String, Box<dyn FnMut(&String, &String) + Send + 'static>),
Unsubscription(String),
Publication(String, String, bool),
}
pub struct Mosquitto {
running: Arc<Mutex<bool>>,
sender: Sender<Request>,
}
pub struct MosquittoArc {
inner: Arc<Mutex<Mosquitto>>
}
impl Clone for MosquittoArc {
fn clone(&self) -> Self {
MosquittoArc {
inner: Arc::clone(&self.inner),
}
}
}
impl MosquittoArc {
pub fn new(
id: impl Into<String>, host: impl Into<String>, port: u16, user: impl Into<String>
) -> (MosquittoArc, Join3<JoinHandle<()>, impl Future<Output=()>, JoinHandle<()>>) {
let (inner, future) = Mosquitto::new(id, host, port, user);
(
MosquittoArc {
inner: Arc::new(Mutex::new(inner)),
},
future
)
}
delegate! {
to self.inner.lock().unwrap() {
pub fn subscribe(&mut self, topic: impl Into<String>, callback: impl FnMut(&String, &String) + Send + 'static);
pub fn unsubscribe(&mut self, topic: impl Into<String>);
pub fn publish(&self, topic: impl Into<String>, payload: impl Into<String>);
pub fn retain(&self, topic: impl Into<String>, payload: impl Into<String>);
pub fn clear(&self, topic: impl Into<String>);
pub fn stop(&mut self);
}
}
}
impl Mosquitto {
pub fn new(
id: impl Into<String>, host: impl Into<String>, port: u16, user: impl Into<String>
) -> (Mosquitto, Join3<JoinHandle<()>, impl Future<Output=()>, JoinHandle<()>>) {
let user = user.into();
let mut mqttoptions = MqttOptions::new(id, host.into(), port);
mqttoptions.set_credentials(user, String::from(""));
mqttoptions.set_keep_alive(5);
let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10);
let callbacks = Arc::new(Mutex::new(HashMap::<String, Vec<Box<dyn FnMut(&String, &String) + Send + 'static>>>::new()));
let callbacks_for_thread = callbacks.clone();
let callbacks_for_poller = callbacks.clone();
let (event_sender, event_receiver): (Sender<(String, String)>, Receiver<(String, String)>) = mpsc::channel();
let event_sender = event_sender.clone();
let running = Arc::new(Mutex::from(true));
let running_for_eventloop = Arc::clone(&running);
let running_for_poller1 = Arc::clone(&running);
let running_for_poller2 = Arc::clone(&running);
let (subscription_sender, subscription_receiver): (Sender<Request>, Receiver<Request>) = mpsc::channel();
(
Mosquitto {
running: running,
sender: subscription_sender,
},
join3(
task::spawn(async move {
while *running_for_eventloop.lock().unwrap() {
if let Ok(event) = eventloop.poll().await {
if let Event::Incoming(incoming) = event {
if let Packet::Publish(publish) = incoming {
if let Ok(payload) = String::from_utf8(publish.payload.to_vec()) {
event_sender.send((publish.topic.clone(), payload.clone())).unwrap();
}
}
}
}
}
}),
async move {
while *running_for_poller1.lock().unwrap() {
if let Ok(request) = subscription_receiver.recv() {
match request {
Subscription(topic, callback) => {
info!("Subscribing to topic: {}", &topic);
let mut callbacks = callbacks_for_poller.lock().unwrap();
match callbacks.get_mut(&topic) {
Some(callbacks) => callbacks.push(callback),
None => {
callbacks.insert(topic.clone(), vec![callback]);
},
}
client.subscribe(&topic, QoS::ExactlyOnce).await.unwrap();
}
Publication(topic, payload, retain) => {
info!("Publishing to topic: {}, the following: {}", topic, payload);
client.publish(topic, QoS::ExactlyOnce, retain, payload).await.unwrap();
}
Unsubscription(topic) => {
callbacks_for_poller.lock().unwrap().remove(&topic);
client.unsubscribe(topic).await.unwrap();
}
}
}
}
},
task::spawn(async move {
while *running_for_poller2.lock().unwrap() {
if let Ok((topic, payload)) = event_receiver.recv() {
info!("Got a event!");
if let Some(callbacks) = callbacks_for_thread.lock().unwrap().get_mut(&topic) {
for callback in callbacks {
callback(&topic, &payload);
}
}
}
}
})
)
)
}
pub fn subscribe(&mut self, topic: impl Into<String>, callback: impl FnMut(&String, &String) + Send + 'static) {
self.sender.send(Subscription(topic.into(), Box::new(callback))).unwrap();
}
pub fn unsubscribe(&mut self, topic: impl Into<String>) {
self.sender.send(Unsubscription(topic.into())).unwrap();
}
pub fn publish(&self, topic: impl Into<String>, payload: impl Into<String>) {
self.sender.send(Publication(topic.into(), payload.into(), false)).unwrap();
}
pub fn retain(&self, topic: impl Into<String>, payload: impl Into<String>) {
self.sender.send(Publication(topic.into(), payload.into(), true)).unwrap();
}
pub fn clear(&self, topic: impl Into<String>) {
self.sender.send(Publication(topic.into(), String::new(), true)).unwrap();
}
pub fn stop(&mut self) {
match self.running.lock() {
Ok(mut running) => *running = false,
Err(error) => error!("Error while stopping mqtt: {:?}", error)
}
}
}
| 40.847458 | 127 | 0.497095 |
f40ceb1ebf2bd7b1029adce5691b2ece547d7b51 | 877 | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#![feature(async_closure)]
pub mod proto {
tonic::include_proto!("oak.session.stream.v1");
}
pub mod attestation;
pub mod grpc;
pub mod logger;
pub mod lookup;
#[cfg(feature = "oak-metrics")]
pub mod metrics;
pub mod server;
#[cfg(feature = "oak-tf")]
pub mod tf;
| 27.40625 | 75 | 0.724059 |
4a3b89ae9116cf25458ec542123cc6be6795f695 | 3,094 | // #![deny(
// warnings,
// missing_debug_implementations,
// missing_copy_implementations,
// missing_docs
// )]
//! This crate provides:
//! - A tracing layer, `TelemetryLayer`, that can be used to publish trace data to honeycomb.io
//! - Utilities for implementing distributed tracing against the honeycomb.io backend
//!
//! As a tracing layer, `TelemetryLayer` can be composed with other layers to provide stdout logging, filtering, etc.
mod opentelemetry;
mod visitor;
pub use crate::opentelemetry::OpenTelemetry;
pub use crate::visitor::OpenTelemetryVisitor;
pub use ::opentelemetry::api::trace::span_context::{SpanId, TraceId};
use ::opentelemetry::exporter::trace::SpanExporter;
use ::opentelemetry::sdk::Config;
use rand::Rng;
use std::collections::HashMap;
#[doc(no_inline)]
pub use tracing_distributed::{TelemetryLayer, TraceCtxError};
#[cfg(feature = "use_parking_lot")]
use parking_lot::Mutex;
#[cfg(not(feature = "use_parking_lot"))]
use std::sync::Mutex;
/// Register the current span as the local root of a distributed trace.
///
/// Specialized to the opentelemetry-specific SpanId and TraceId provided by this crate.
pub fn register_dist_tracing_root(
trace_id: TraceId,
remote_parent_span: Option<SpanId>,
) -> Result<(), TraceCtxError> {
tracing_distributed::register_dist_tracing_root(trace_id, remote_parent_span)
}
/// Retrieve the distributed trace context associated with the current span.
///
/// Returns the `TraceId`, if any, that the current span is associated with along with
/// the `SpanId` belonging to the current span.
///
/// Specialized to the opentelemetry-specific SpanId and TraceId provided by this crate.
pub fn current_dist_trace_ctx() -> Result<(TraceId, SpanId), TraceCtxError> {
tracing_distributed::current_dist_trace_ctx()
}
/// Construct a TelemetryLayer that does not publish telemetry to any backend.
///
/// Specialized to the opentelemetry-specific SpanId and TraceId provided by this crate.
pub fn new_blackhole_telemetry_layer(
) -> TelemetryLayer<tracing_distributed::BlackholeTelemetry<SpanId, TraceId>, SpanId, TraceId> {
TelemetryLayer::new(
"opentelemetry_blackhole_tracing_layer",
tracing_distributed::BlackholeTelemetry::default(),
|tracing_id| SpanId::from_u64(tracing_id.into_u64()),
)
}
/// Construct a TelemetryLayer that publishes telemetry to honeycomb.io using the provided honeycomb config.
///
/// Specialized to the honeycomb.io-specific SpanId and TraceId provided by this crate.
pub fn new_opentelemetry_layer(
service_name: &'static str,
exporter: Box<dyn SpanExporter>,
config: Config,
) -> TelemetryLayer<OpenTelemetry, SpanId, TraceId> {
// used to keep nodes in a multiprocess scenario from generating the same sequence of span ids
let r: u64 = rand::thread_rng().gen();
TelemetryLayer::new(
service_name,
OpenTelemetry {
exporter,
events: Mutex::new(HashMap::new()),
config,
},
move |tracing_id| SpanId::from_u64(tracing_id.into_u64() ^ r),
)
}
| 36.833333 | 117 | 0.730446 |
4aa235a7aeb91cbd7ab5827591cf62d8b1daa934 | 2,003 | /// State machine for the sprite evaluation phase.
#[derive(Clone, Copy)]
pub enum SpriteEvalutationState {
/// Idle until the end of the evaluation when all 64 sprites have been evaluated
Idle,
/// Copy the Y value from one OAM to another and check if the sprite is in the scanline. Takes 2 cycles,
CheckY,
/// Copy the 3 values from one OAM to another. Takes 6 cycles, 2 per values.
/// The inner value represent the current index of the data to copy
CopyOam(u8),
/// All 8 sprites have been found. Look (in a broken way) if the sprite overflow flag needs to be set.
/// Inner value is `m` register.
EvaluateOverflow(u8),
}
impl Default for SpriteEvalutationState {
fn default() -> Self {
Self::Idle
}
}
/// State of a sprite on the current scanline
#[derive(Clone, Copy)]
pub enum SpriteXCounter {
/// The sprite is not on the scanline at all. Happens when < 8 sprites are on the scanline
WontRender,
/// The sprite has not been rendered yet. Inner value represents number of X remaining before starting rendering.
NotRendered(u8),
/// The sprite is being renderes. Inner value represents the number of pixels left.
Rendering(u8),
/// The sprite is fully rendered.
Rendered,
}
impl Default for SpriteXCounter {
fn default() -> Self {
Self::WontRender
}
}
/// State of the sprite 0 hit
#[derive(Clone, Copy)]
pub enum SpriteZeroHitState {
/// The state machine is simply idle
Idle,
/// The sprite 0 has been loaded in secondary OAM
IsInOam,
/// The sprite 0 will be rendered on the current scanline
/// Inner value represents if it is also in the OAM of the next
OnCurrentScanline(bool),
/// The sprite 0 hit triggers 2 cycle after the actual pixel is evaluated.
/// The inner value represent the remaining cycles before the flag is set
Delay(u8),
}
impl Default for SpriteZeroHitState {
fn default() -> Self {
Self::Idle
}
}
| 28.614286 | 117 | 0.677484 |
763c239eee6e59454d456e239679a2eb7609c147 | 1,329 | #[doc = "Reader of register DBGCTRL"]
pub type R = crate::R<u8, super::DBGCTRL>;
#[doc = "Writer for register DBGCTRL"]
pub type W = crate::W<u8, super::DBGCTRL>;
#[doc = "Register DBGCTRL `reset()`'s with value 0"]
impl crate::ResetValue for super::DBGCTRL {
type Type = u8;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `DBGRUN`"]
pub type DBGRUN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBGRUN`"]
pub struct DBGRUN_W<'a> {
w: &'a mut W,
}
impl<'a> DBGRUN_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 u8) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 0 - Run During Debug"]
#[inline(always)]
pub fn dbgrun(&self) -> DBGRUN_R {
DBGRUN_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Run During Debug"]
#[inline(always)]
pub fn dbgrun(&mut self) -> DBGRUN_W {
DBGRUN_W { w: self }
}
}
| 26.058824 | 69 | 0.553047 |
4baa94e91441d9e1d21e3ab85fd20aeaef23f463 | 776 | // vec2.rs
// A Vec of even numbers is given. Your task is to complete the loop
// so that each number in the Vec is multiplied by 2.
//
// Make me pass the test!
//
// Execute the command `rustlings hint vec2` if you need
// hints.
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
for i in v.iter_mut() {
*i *=2;
// TODO: Fill this up so that each element in the Vec `v` is
// multiplied by 2.
}
// At this point, `v` should be equal to [4, 8, 12, 16, 20].
v
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_vec_loop() {
let v: Vec<i32> = (1..).filter(|x| x % 2 == 0).take(5).collect();
let ans = vec_loop(v.clone());
assert_eq!(ans, v.iter().map(|x| x * 2).collect::<Vec<i32>>());
}
}
| 22.171429 | 73 | 0.548969 |
c17ac2fe1fc8cd14105e6244bd6c231cb0478b5a | 5,612 | #[doc = "Register `sf3_if_io_dly_3` reader"]
pub struct R(crate::R<SF3_IF_IO_DLY_3_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<SF3_IF_IO_DLY_3_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<SF3_IF_IO_DLY_3_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<SF3_IF_IO_DLY_3_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `sf3_if_io_dly_3` writer"]
pub struct W(crate::W<SF3_IF_IO_DLY_3_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<SF3_IF_IO_DLY_3_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<SF3_IF_IO_DLY_3_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<SF3_IF_IO_DLY_3_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `sf3_io_2_do_dly_sel` reader - "]
pub struct SF3_IO_2_DO_DLY_SEL_R(crate::FieldReader<u8, u8>);
impl SF3_IO_2_DO_DLY_SEL_R {
pub(crate) fn new(bits: u8) -> Self {
SF3_IO_2_DO_DLY_SEL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SF3_IO_2_DO_DLY_SEL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `sf3_io_2_do_dly_sel` writer - "]
pub struct SF3_IO_2_DO_DLY_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> SF3_IO_2_DO_DLY_SEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 16)) | ((value as u32 & 0x03) << 16);
self.w
}
}
#[doc = "Field `sf3_io_2_di_dly_sel` reader - "]
pub struct SF3_IO_2_DI_DLY_SEL_R(crate::FieldReader<u8, u8>);
impl SF3_IO_2_DI_DLY_SEL_R {
pub(crate) fn new(bits: u8) -> Self {
SF3_IO_2_DI_DLY_SEL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SF3_IO_2_DI_DLY_SEL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `sf3_io_2_di_dly_sel` writer - "]
pub struct SF3_IO_2_DI_DLY_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> SF3_IO_2_DI_DLY_SEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 8)) | ((value as u32 & 0x03) << 8);
self.w
}
}
#[doc = "Field `sf3_io_2_oe_dly_sel` reader - "]
pub struct SF3_IO_2_OE_DLY_SEL_R(crate::FieldReader<u8, u8>);
impl SF3_IO_2_OE_DLY_SEL_R {
pub(crate) fn new(bits: u8) -> Self {
SF3_IO_2_OE_DLY_SEL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SF3_IO_2_OE_DLY_SEL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `sf3_io_2_oe_dly_sel` writer - "]
pub struct SF3_IO_2_OE_DLY_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> SF3_IO_2_OE_DLY_SEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x03) | (value as u32 & 0x03);
self.w
}
}
impl R {
#[doc = "Bits 16:17"]
#[inline(always)]
pub fn sf3_io_2_do_dly_sel(&self) -> SF3_IO_2_DO_DLY_SEL_R {
SF3_IO_2_DO_DLY_SEL_R::new(((self.bits >> 16) & 0x03) as u8)
}
#[doc = "Bits 8:9"]
#[inline(always)]
pub fn sf3_io_2_di_dly_sel(&self) -> SF3_IO_2_DI_DLY_SEL_R {
SF3_IO_2_DI_DLY_SEL_R::new(((self.bits >> 8) & 0x03) as u8)
}
#[doc = "Bits 0:1"]
#[inline(always)]
pub fn sf3_io_2_oe_dly_sel(&self) -> SF3_IO_2_OE_DLY_SEL_R {
SF3_IO_2_OE_DLY_SEL_R::new((self.bits & 0x03) as u8)
}
}
impl W {
#[doc = "Bits 16:17"]
#[inline(always)]
pub fn sf3_io_2_do_dly_sel(&mut self) -> SF3_IO_2_DO_DLY_SEL_W {
SF3_IO_2_DO_DLY_SEL_W { w: self }
}
#[doc = "Bits 8:9"]
#[inline(always)]
pub fn sf3_io_2_di_dly_sel(&mut self) -> SF3_IO_2_DI_DLY_SEL_W {
SF3_IO_2_DI_DLY_SEL_W { w: self }
}
#[doc = "Bits 0:1"]
#[inline(always)]
pub fn sf3_io_2_oe_dly_sel(&mut self) -> SF3_IO_2_OE_DLY_SEL_W {
SF3_IO_2_OE_DLY_SEL_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 = "sf3_if_io_dly_3.\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 [sf3_if_io_dly_3](index.html) module"]
pub struct SF3_IF_IO_DLY_3_SPEC;
impl crate::RegisterSpec for SF3_IF_IO_DLY_3_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [sf3_if_io_dly_3::R](R) reader structure"]
impl crate::Readable for SF3_IF_IO_DLY_3_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [sf3_if_io_dly_3::W](W) writer structure"]
impl crate::Writable for SF3_IF_IO_DLY_3_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets sf3_if_io_dly_3 to value 0"]
impl crate::Resettable for SF3_IF_IO_DLY_3_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 32.068571 | 412 | 0.625624 |
deec5f40e0b3be794b543d3815f7dc54eead9b4e | 14,577 | #![cfg(target_arch = "x86_64")]
use std::arch::x86_64::*;
use druid::kurbo::{BezPath};
use druid::piet::{FontFamily, FontStyle, ImageFormat, InterpolationMode};
use druid::kurbo;
use druid::widget::prelude::*;
use druid::{
Affine, AppLauncher, ArcStr, Color, Data, FontDescriptor, LocalizedString, MouseEvent,
Point as DruidPoint, TextLayout, WindowDesc,
};
use klein::*;
#[derive(Default)]
struct CustomWidget {
lower_y: f64,
upper_y: f64,
left_x: f64,
right_x: f64,
lower_plane: Plane,
upper_plane: Plane,
left_plane: Plane,
right_plane: Plane,
//center_point: Rc<PGA3D>,
center_point: Point,
left: f64,
top: f64,
scale: f64,
window_pixels: kurbo::Size,
}
impl CustomWidget {
fn to_druid_point(&self, p: &Point) -> DruidPoint {
let pn = p;//.normalized();
DruidPoint::new(
(pn.x() as f64 - self.left) / self.scale,
(self.top - pn.y() as f64) / self.scale,
)
}
fn new() -> CustomWidget {
CustomWidget {
lower_y: -2.,
upper_y: 2.,
left_x: -2.,
right_x: 2.,
..Default::default()
}
}
pub fn set_window_boundary_planes(&mut self, _state: &State, window: &kurbo::Size) {
let desired_width = self.right_x - self.left_x;
let desired_height = self.upper_y - self.lower_y;
let desired_aspect_ratio = desired_width / desired_height;
let center_x = (self.right_x + self.left_x) / 2.;
let center_y = (self.upper_y + self.lower_y) / 2.;
self.window_pixels = *window;
let window_aspect_ratio = window.width / window.height;
self.top = self.upper_y;
self.left = self.left_x;
let mut right = self.right_x;
let mut bottom = self.lower_y;
if window_aspect_ratio > desired_aspect_ratio {
// actual window is wider than desired viewport
self.scale = desired_height / window.height;
let half_width = self.scale * 0.5 * window.width;
right = center_x + half_width;
self.left = center_x - half_width;
} else {
// actual window is taller than desired viewport
self.scale = desired_width / window.width;
let half_height = self.scale * 0.5 * window.height;
self.top = center_y + half_height;
bottom = center_y - half_height;
}
self.lower_plane = Plane::new(0., 1., 0., bottom as f32);
self.upper_plane = Plane::new(0., 1., 0., self.top as f32);
self.left_plane = Plane::new(1., 0., 0., self.left as f32);
self.right_plane = Plane::new(1., 0., 0., right as f32);
self.center_point = Point::new(center_x as f32, center_y as f32, 0.);
}
pub fn mouse_move(&self, mouse: &MouseEvent, data: &mut State) {
let x_portion = mouse.pos.x / self.window_pixels.width;
let x_coord = self.left_plane.x() * self.left_plane.d() * (1. - x_portion as f32)
+ (self.right_plane.x() * self.right_plane.d()) * x_portion as f32;
let y_portion = mouse.pos.y / self.window_pixels.height;
let y_coord = self.upper_plane.y() * self.upper_plane.d() * (1. - y_portion as f32)
+ self.lower_plane.y() * self.lower_plane.d() * y_portion as f32;
// let mouse_point = (x_plane^y_plane.normalized()^PGA3D::e3());
// let mouse_y = mouse.pos.y;
// let y_plane =
let mouse = Point::new(x_coord, y_coord, 0.);
data.mouse_over = None;
for (i, p) in data.points.iter().enumerate() {
// println!("mouse point {} {}",i, (mouse & *p).norm());
if (mouse & *p).norm() < 0.07 {
println!("over point {}", i);
data.mouse_over = Some(i);
}
}
// println!("mosue pos {} {}",mouse_point.get032(), mouse_point.get013())
}
}
use std::rc::Rc;
#[derive(Clone, Data, Default)]
struct State {
points: Rc<Vec<Point>>,
mouse_over: Option<usize>,
scene: Rc<Vec<Object>>,
time: f64,
perspective: Rc<Mat4x4>,
camera_transform: Rc<Motor>,
}
impl Widget<State> for CustomWidget {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut State, _env: &Env) {
match event {
Event::WindowConnected => {
ctx.request_focus();
ctx.request_anim_frame();
}
Event::KeyDown(e) => {
println!("key down event {:?}", e);
}
Event::MouseMove(e) => {
let old = data.mouse_over;
self.mouse_move(e, data);
if data.mouse_over != old {
ctx.request_paint();
}
}
Event::AnimFrame(_interval) => {
data.time += 0.01;
ctx.request_paint();
ctx.request_anim_frame();
}
_ => {
println!("unhandled input event {:?}", event);
}
}
}
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &State, _env: &Env) {
match event {
LifeCycle::Size(s) => {
self.set_window_boundary_planes(data, s);
}
LifeCycle::WidgetAdded => {
ctx.register_for_focus();
}
_ => println!("unhandled lifecycle event: {:?}", event),
}
}
fn update(&mut self, _ctx: &mut UpdateCtx, _old_data: &State, _data: &State, _env: &Env) {
// println!("update event: {}", );
}
fn layout(
&mut self,
_layout_ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &State,
_env: &Env,
) -> Size {
// BoxConstraints are passed by the parent widget.
// This method can return any Size within those constraints:
// bc.constrain(my_size)
//
// To check if a dimension is infinite or not (e.g. scrolling):
// bc.is_width_bounded() / bc.is_height_bounded()
bc.max()
}
// The paint method gets called last, after an event flow.
// It goes event -> update -> layout -> paint, and each method can influence the next.
// Basically, anything that changes the appearance of a widget causes a paint.
fn paint(&mut self, ctx: &mut PaintCtx, data: &State, env: &Env) {
// Let's draw a picture with Piet!
// Clear the whole widget with the color of your choice
// (ctx.size() returns the size of the layout rect we're painting in)
let size = ctx.size();
let rect = size.to_rect();
ctx.fill(rect, &Color::BLACK);
// // for p in (&data.points).borrow().iter() {
// for p in (&data.points).iter() {
// println!("label: {}", p.label);
// }
// Note: ctx also has a `clear` method, but that clears the whole context,
// and we only want to clear this widget's area.
let fill_color = Color::rgba8(0xa3, 0xa3, 0xa3, 0xFF);
// let r = Rotor::new(data.time as f32, 1., -1., 0.5);
let r = Rotor::new(data.time as f32, 0., 1., 0.);
let mut faces = Vec::<Vec::<Point>>::new();
for obj in data.scene.iter() {
let m: Motor = obj.world_positioning_motor;
let s = obj.scale;
for face in obj.mesh.faces.iter() {
let mut verts = Vec::<Point>::new();
for v_idx in face.iter() {
verts.push(
Point::from(data.perspective.apply_to(
__m128::from(
data.camera_transform.apply_to(
r.apply_to(m.apply_to(obj.mesh.vertices[*v_idx].scaled(s)))))))
.normalized());
}
faces.push(verts);
}
}
// for p in data.scene[0].mesh.faces.iter() {
// let m: Motor = data.scene[0].world_positioning_motor;
// let mut path = BezPath::new();
// path.move_to(self.to_druid_point(&r.apply_to(m.apply_to(data.scene[0].mesh.vertices[p[0]]))));
// path.line_to(self.to_druid_point(&r.apply_to(m.apply_to(data.scene[0].mesh.vertices[p[1]]))));
// path.line_to(self.to_druid_point(&r.apply_to(m.apply_to(data.scene[0].mesh.vertices[p[2]]))));
// path.line_to(self.to_druid_point(&r.apply_to(m.apply_to(data.scene[0].mesh.vertices[p[0]]))));
// let stroke_color = Color::rgb8(240, 240, 240);
// ctx.stroke(path, &stroke_color, 4.0);
// }
for f in faces.iter() {
let mut path = BezPath::new();
path.move_to(self.to_druid_point(&f[0]));
for p in f.iter().skip(1) {
path.line_to(self.to_druid_point(p));
}
path.line_to(self.to_druid_point(&f[0]));
// path.line_to(self.to_druid_point(&f[2]));
// path.line_to(self.to_druid_point(&f[0]));
let stroke_color = Color::rgb8(240, 240, 240);
ctx.stroke(path, &stroke_color, 4.0);
}
// Text is easy; in real use TextLayout should be stored in the widget
// and reused.
let mut layout = TextLayout::<ArcStr>::from_text("klein rust"); //data.to_owned());
layout.set_font(
FontDescriptor::new(FontFamily::SANS_SERIF)
.with_size(24.0) //.with_weight(FontWeight::BOLD)
.with_style(FontStyle::Italic),
);
layout.set_text_color(fill_color);
// layout.set_text_style(FontStyle::Italic);
layout.rebuild_if_needed(ctx.text(), env);
// Let's rotate our text slightly. First we save our current (default) context:
ctx.with_save(|ctx| {
// Now we can rotate the context (or set a clip path, for instance):
ctx.transform(Affine::rotate(0.0));
layout.draw(ctx, (80.0, 40.0));
});
// Let's burn some CPU to make a (partially transparent) image buffer
let image_data = make_image_data(256, 256);
let image = ctx
.make_image(256, 256, &image_data, ImageFormat::RgbaSeparate)
.unwrap();
// The image is automatically scaled to fit the rect you pass to draw_image
ctx.draw_image(&image, size.to_rect(), InterpolationMode::Bilinear);
}
}
struct Mesh {
vertices: Vec<Point>,
faces: Vec<Vec<usize>>,
}
struct Object {
mesh: Mesh,
scale: f32,
world_positioning_motor: Motor,
}
impl Mesh {
fn tetrahedron() -> Self {
let v1 = Point::new(0., 1., 0.);
let v2 = Rotor::new(f32::acos(-1. / 3.), 1., 0., 0.).apply_to(v1);
let r = Rotor::new(f32::acos(-0.5), 0., 1., 0.);
let v3 = r.apply_to(v2);
let v4 = r.apply_to(v3);
let vertices = vec![v1, v2, v3, v4];
let position = Motor::default();
Self {vertices: vec![v1,v2,v3,v4], faces:
vec![vec![0, 1, 2], vec![0, 2, 3], vec![0, 3, 1], vec![1, 3, 2]]
}
}
}
impl Mesh {
fn cube() -> Self {
let a = Point::new(1., 1., 1.);
let b = Point::new(1., 1., -1.);
let c = Point::new(-1., 1., -1.);
let d = Point::new(-1., 1., 1.);
let e = Point::new(1., -1., 1.);
let f = Point::new(1., -1., -1.);
let g = Point::new(-1., -1., -1.);
let h = Point::new(-1., -1., 1.);
let vertices = vec![a, b, c, d, e, f, g, h];
let position = Motor::default();
Self {vertices, faces:
vec![vec![0, 1, 2, 3], vec![4, 5, 6, 7], vec![0,4], vec![1,5], vec![2,6], vec![3,7], ]
}
}
}
impl From<Mesh> for Object {
fn from(mesh: Mesh) -> Self {
Object {
scale: 1.,
world_positioning_motor: Motor::default(),
mesh
}
}
}
impl Object {
fn mesh_at(mesh: Mesh, at: Motor) -> Self {
Object {
scale: 1.,
world_positioning_motor: at,
mesh
}
}
fn scaled_mesh_at(mesh: Mesh, scale: f32, at: Motor) -> Self {
Object {
scale,
world_positioning_motor: at,
mesh
}
}
}
fn main() {
let window = WindowDesc::new(|| CustomWidget::new()).title(
LocalizedString::new("custom-widget-demo-window-title").with_placeholder("klein rust demo"),
);
let mut s = State {
perspective: Rc::new(Mat4x4::perspective(10., 50., -3., 3., -3., 3.)),
camera_transform: Rc::new(Motor::from(Translator::new(-4., 0., 0., 1.))),
..Default::default()
};
// let origin & Point::new(1.,0.,0.);
// scene.push(Object::mesh_at(Mesh::tetrahedron(), Motor::from_screw_line(0.,0.,l)));
let origin = origin();
// let m = Motor::from_screw_line(2.*std::f32::consts::PI,0.,l);
let l: Line = origin & Point::new(1.,0.,0.);
let m = Motor::from_screw_line(0.,0.,l);
let scene = Rc::get_mut(&mut s.scene).unwrap();
scene.push(Object::mesh_at(Mesh::tetrahedron(), Motor::from_screw_line(1.,0.,l)));
// let m2 = Motor::from(Translator::new(1.,1.,0.,0.));
scene.push(Object::mesh_at(Mesh::tetrahedron(), Motor::from(Translator::new(1.,0.,1.,0.))));
// scene.push(Object::mesh_at(Mesh::tetrahedron(), m));
scene.push(Object::scaled_mesh_at(Mesh::tetrahedron(), 0.1, Motor::default()));
scene.push(Object::scaled_mesh_at(Mesh::tetrahedron(), 0.5, Motor::default()));
scene.push(Object::scaled_mesh_at(Mesh::tetrahedron(), 0.5, Motor::from(Translator::new(1.,1.,0.,0.))));
scene.push(Object::mesh_at(Mesh::tetrahedron(), Motor::from(Translator::new(2.,3.,1.5,0.))));
scene.push(Object::mesh_at(Mesh::cube(), Motor::from(Translator::new(2.,-3.,0.,0.))));
let ps = Rc::get_mut(&mut s.points).unwrap();
ps.push(Point::new(0., 0.6, 0.));
ps.push(Point::new(0.94, 0., 0.));
AppLauncher::with_window(window)
.use_simple_logger()
.launch(s)
// .launch("Druid + Piet".to_string())
.expect("launch failed");
}
fn make_image_data(width: usize, height: usize) -> Vec<u8> {
let mut result = vec![0; width * height * 4];
for y in 0..height {
for x in 0..width {
let ix = (y * width + x) * 4;
result[ix] = x as u8;
result[ix + 1] = y as u8;
result[ix + 2] = !(x as u8);
result[ix + 3] = 127;
}
}
result
}
| 34.542654 | 109 | 0.538863 |
23e17b391c94549fe56f9ad40150ceec287fcb90 | 5,747 | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
//! External storage support.
//!
//! This crate define an abstraction of external storage. Currently, it
//! supports local storage.
#[macro_use]
extern crate slog_global;
#[allow(unused_extern_crates)]
extern crate tikv_alloc;
use std::io;
use std::marker::Unpin;
use std::path::Path;
use std::sync::Arc;
use futures_io::AsyncRead;
#[cfg(feature = "prost-codec")]
use kvproto::backup::storage_backend::Backend;
#[cfg(feature = "protobuf-codec")]
use kvproto::backup::StorageBackend_oneof_backend as Backend;
#[cfg_attr(feature = "protobuf-codec", allow(unused_imports))]
use kvproto::backup::{Local, Noop, StorageBackend, S3};
mod local;
pub use local::LocalStorage;
mod noop;
pub use noop::NoopStorage;
mod s3;
pub use s3::S3Storage;
mod util;
pub use util::block_on_external_io;
/// Create a new storage from the given storage backend description.
pub fn create_storage(backend: &StorageBackend) -> io::Result<Arc<dyn ExternalStorage>> {
match &backend.backend {
Some(Backend::Local(local)) => {
let p = Path::new(&local.path);
LocalStorage::new(p).map(|s| Arc::new(s) as _)
}
Some(Backend::Noop(_)) => Ok(Arc::new(NoopStorage::default()) as _),
Some(Backend::S3(config)) => S3Storage::new(config).map(|s| Arc::new(s) as _),
_ => {
let u = url_of_backend(backend);
error!("unknown storage"; "scheme" => u.scheme());
Err(io::Error::new(
io::ErrorKind::Other,
format!("unknown storage {}", u),
))
}
}
}
/// Formats the storage backend as a URL.
pub fn url_of_backend(backend: &StorageBackend) -> url::Url {
let mut u = url::Url::parse("unknown:///").unwrap();
match &backend.backend {
Some(Backend::Local(local)) => {
u.set_scheme("local").unwrap();
u.set_path(&local.path);
}
Some(Backend::Noop(_)) => {
u.set_scheme("noop").unwrap();
}
Some(Backend::S3(s3)) => {
u.set_scheme("s3").unwrap();
if let Err(e) = u.set_host(Some(&s3.bucket)) {
warn!("ignoring invalid S3 bucket name"; "bucket" => &s3.bucket, "error" => %e);
}
u.set_path(s3.get_prefix());
}
Some(Backend::Gcs(_)) => unimplemented!(),
None => {}
}
u
}
/// Creates a local `StorageBackend` to the given path.
pub fn make_local_backend(path: &Path) -> StorageBackend {
let path = path.display().to_string();
#[cfg(feature = "prost-codec")]
{
StorageBackend {
backend: Some(Backend::Local(Local { path })),
}
}
#[cfg(feature = "protobuf-codec")]
{
let mut backend = StorageBackend::default();
backend.mut_local().set_path(path);
backend
}
}
/// Creates a noop `StorageBackend`.
pub fn make_noop_backend() -> StorageBackend {
let noop = Noop::default();
#[cfg(feature = "prost-codec")]
{
StorageBackend {
backend: Some(Backend::Noop(noop)),
}
}
#[cfg(feature = "protobuf-codec")]
{
let mut backend = StorageBackend::default();
backend.set_noop(noop);
backend
}
}
// Creates a S3 `StorageBackend`
pub fn make_s3_backend(config: S3) -> StorageBackend {
#[cfg(feature = "prost-codec")]
{
StorageBackend {
backend: Some(Backend::S3(config)),
}
}
#[cfg(feature = "protobuf-codec")]
{
let mut backend = StorageBackend::default();
backend.set_s3(config);
backend
}
}
/// An abstraction of an external storage.
// TODO: these should all be returning a future (i.e. async fn).
pub trait ExternalStorage: 'static {
/// Write all contents of the read to the given path.
fn write(
&self,
name: &str,
reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()>;
/// Read all contents of the given path.
fn read(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_>;
}
impl ExternalStorage for Arc<dyn ExternalStorage> {
fn write(
&self,
name: &str,
reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()> {
(**self).write(name, reader, content_length)
}
fn read(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_> {
(**self).read(name)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_storage() {
let backend = make_local_backend(Path::new("/tmp/a"));
create_storage(&backend).unwrap();
let backend = make_noop_backend();
create_storage(&backend).unwrap();
let backend = StorageBackend::default();
assert!(create_storage(&backend).is_err());
}
#[test]
fn test_url_of_backend() {
use kvproto::backup::S3;
let backend = make_local_backend(Path::new("/tmp/a"));
assert_eq!(url_of_backend(&backend).to_string(), "local:///tmp/a");
let backend = make_noop_backend();
assert_eq!(url_of_backend(&backend).to_string(), "noop:///");
let mut backend = StorageBackend::default();
backend.backend = Some(Backend::S3(S3 {
bucket: "bucket".to_owned(),
prefix: "/backup 01/prefix/".to_owned(),
endpoint: "http://endpoint.com".to_owned(),
// ^ only 'bucket' and 'prefix' should be visible in url_of_backend()
..S3::default()
}));
assert_eq!(
url_of_backend(&backend).to_string(),
"s3://bucket/backup%2001/prefix/"
);
}
}
| 29.172589 | 96 | 0.580129 |
393b95692554ca200ab9e5ac37f998e350f37d99 | 305 | // run-rustfix
#![allow(unused_imports)]
#![warn(clippy::flat_map_identity)]
use std::convert;
fn main() {
let iterator = [[0, 1], [2, 3], [4, 5]].iter();
let _ = iterator.flat_map(|x| x);
let iterator = [[0, 1], [2, 3], [4, 5]].iter();
let _ = iterator.flat_map(convert::identity);
}
| 20.333333 | 51 | 0.570492 |
22cb5653d4205eb01393f35268ced914f45f6aa6 | 1,526 | #![cfg(target_os = "emscripten")]
use Api;
use ContextError;
use CreationError;
use GlAttributes;
use GlContext;
use PixelFormat;
use PixelFormatRequirements;
pub use api::emscripten::{Window, WindowProxy, MonitorId, get_available_monitors};
pub use api::emscripten::{get_primary_monitor, WaitEventsIterator, PollEventsIterator};
pub struct HeadlessContext(Window);
impl HeadlessContext {
/// See the docs in the crate root file.
#[inline]
pub fn new(_: (u32, u32), _: &PixelFormatRequirements, _: &GlAttributes<&HeadlessContext>)
-> Result<HeadlessContext, CreationError>
{
unimplemented!()
}
}
impl GlContext for HeadlessContext {
#[inline]
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.0.make_current()
}
#[inline]
fn is_current(&self) -> bool {
self.0.is_current()
}
#[inline]
fn get_proc_address(&self, addr: &str) -> *const () {
self.0.get_proc_address(addr)
}
#[inline]
fn swap_buffers(&self) -> Result<(), ContextError> {
self.0.swap_buffers()
}
#[inline]
fn get_api(&self) -> Api {
self.0.get_api()
}
#[inline]
fn get_pixel_format(&self) -> PixelFormat {
self.0.get_pixel_format()
}
}
unsafe impl Send for HeadlessContext {}
unsafe impl Sync for HeadlessContext {}
#[derive(Clone, Default)]
pub struct PlatformSpecificWindowBuilderAttributes;
#[derive(Clone, Default)]
pub struct PlatformSpecificHeadlessBuilderAttributes;
| 23.476923 | 94 | 0.666448 |
690816a95ca1926af4385fc6e0b423ae64e0cbbd | 7,349 | //! Semihosting for ARM Cortex-M processors
//!
//! # What is semihosting?
//!
//! "Semihosting is a mechanism that enables code running on an ARM target to communicate and use
//! the Input/Output facilities on a host computer that is running a debugger." - ARM
//!
//! # Interface
//!
//! This crate provides implementations of
//! [`core::fmt::Write`](https://doc.rust-lang.org/core/fmt/trait.Write.html), so you can use it,
//! in conjunction with
//! [`core::format_args!`](https://doc.rust-lang.org/core/macro.format_args.html) or the [`write!` macro](https://doc.rust-lang.org/core/macro.write.html), for user-friendly construction and printing of formatted strings.
//!
//! Since semihosting operations are modeled as [system calls][sc], this crate exposes an untyped
//! `syscall!` interface just like the [`sc`] crate does.
//!
//! [sc]: https://en.wikipedia.org/wiki/System_call
//! [`sc`]: https://crates.io/crates/sc
//!
//! # Forewarning
//!
//! Semihosting operations are *very* slow. Like, each WRITE operation can take hundreds of
//! milliseconds.
//!
//! # Example
//!
//! ## Using `hio::HStdout`
//!
//! This example will demonstrate how to print formatted strings.
//!
//! ```no_run
//! use cortex_m_semihosting::hio;
//! use core::fmt::Write;
//!
//! // This function will be called by the application
//! fn print() -> Result<(), core::fmt::Error> {
//! let mut stdout = match hio::hstdout() {
//! Ok(fd) => fd,
//! Err(()) => return Err(core::fmt::Error),
//! };
//!
//! let language = "Rust";
//! let ranking = 1;
//!
//! write!(stdout, "{} on embedded is #{}!", language, ranking)?;
//!
//! Ok(())
//! }
//! ```
//!
//! On the host side:
//!
//! ``` text
//! $ openocd -f $INTERFACE -f $TARGET -l /tmp/openocd.log
//! Open On-Chip Debugger 0.9.0 (2016-04-27-23:18)
//! Licensed under GNU GPL v2
//! For bug reports, read
//! http://openocd.org/doc/doxygen/bugs.html
//! # the command will block at this point
//! ```
//!
//! The OpenOCD logs will be redirected to `/tmp/openocd.log`. You can view those logs in "real
//! time" using `tail`
//!
//! ``` text
//! $ tail -f /tmp/openocd.log
//! Info : Unable to match requested speed 1000 kHz, using 950 kHz
//! Info : Unable to match requested speed 1000 kHz, using 950 kHz
//! Info : clock speed 950 kHz
//! Info : STLINK v1 JTAG v11 API v2 SWIM v0 VID 0x0483 PID 0x3744
//! Info : using stlink api v2
//! Info : nrf51.cpu: hardware has 4 breakpoints, 2 watchpoints
//! ```
//!
//! Alternatively you could omit the `-l` flag from the `openocd` call, and the `tail -f` command
//! but the OpenOCD output will have intermingled in it logs from its normal operation.
//!
//! Then, we run the program:
//!
//! ``` text
//! $ arm-none-eabi-gdb hello-world
//! (gdb) # Connect to OpenOCD
//! (gdb) target remote :3333
//!
//! (gdb) # Enable OpenOCD's semihosting support
//! (gdb) monitor arm semihosting enable
//!
//! (gdb) # Flash the program
//! (gdb) load
//!
//! (gdb) # Run the program
//! (gdb) continue
//! ```
//!
//! And you'll see the output under OpenOCD's terminal
//!
//! ``` text
//! # openocd -f $INTERFACE -f $TARGET -l /tmp/openocd.log
//! (..)
//! Rust on embedded is #1!
//! ```
//! ## Using the syscall interface
//!
//! This example will show how to print "Hello, world!" on the host.
//!
//! Target program:
//!
//! ```no_run
//! use cortex_m_semihosting::syscall;
//!
//! // This function will be called by the application
//! fn print() {
//! // File descriptor (on the host)
//! const STDOUT: usize = 1; // NOTE the host stdout may not always be fd 1
//! static MSG: &'static [u8] = b"Hello, world!\n";
//!
//! // Signature: fn write(fd: usize, ptr: *const u8, len: usize) -> usize
//! let r = unsafe { syscall!(WRITE, STDOUT, MSG.as_ptr(), MSG.len()) };
//! }
//! ```
//! Output and monitoring proceed as in the above example.
//!
//! ## The `dbg!` macro
//!
//! Analogous to [`std::dbg`](https://doc.rust-lang.org/std/macro.dbg.html) the macro
//! `dbg!` returns a given expression and prints it using `heprintln!` including context
//! for quick and dirty debugging.
//!
//! Panics if `heprintln!` returns an error.
//!
//! Example:
//!
//! ```no_run
//! const UUID: *mut u32 = 0x0009_FC70 as *mut u32;
//! dbg!(UUID);
//! let mut uuid: [u32; 4] = [0; 4];
//! for i in 0..4 {
//! dbg!(i);
//! uuid[i] = unsafe { dbg!(UUID.offset(i as isize).read_volatile()) };
//! }
//! ```
//! outputs
//! ```text
//! [examples/semihosting.rs:37] UUID = 0x0009fc70
//! [examples/semihosting.rs:40] i = 0
//! [examples/semihosting.rs:41] UUID.offset(i as isize).read_volatile() = 3370045464
//! [examples/semihosting.rs:40] i = 1
//! [examples/semihosting.rs:41] UUID.offset(i as isize).read_volatile() = 1426218275
//! [examples/semihosting.rs:40] i = 2
//! [examples/semihosting.rs:41] UUID.offset(i as isize).read_volatile() = 2422621116
//! [examples/semihosting.rs:40] i = 3
//! [examples/semihosting.rs:41] UUID.offset(i as isize).read_volatile() = 1044138593
//! ```
//!
//! # Optional features
//!
//! ## `inline-asm`
//!
//! When this feature is enabled semihosting is implemented using inline assembly (`llvm_asm!`) and
//! compiling this crate requires nightly.
//!
//! When this feature is disabled semihosting is implemented using FFI calls into an external
//! assembly file and compiling this crate works on stable and beta.
//!
//! ## `jlink-quirks`
//!
//! When this feature is enabled, return values above `0xfffffff0` from semihosting operation
//! `SYS_WRITE` (0x05) are interpreted as if the entire buffer had been written. The current
//! latest version 6.48b of J-Link exhibits such behaviour, causing a panic if this feature
//! is not enabled.
//!
//! ## `no-semihosting`
//!
//! When this feature is enabled, the underlying system calls to `bkpt` are patched out.
//!
//! # Reference
//!
//! For documentation about the semihosting operations, check:
//!
//! 'Chapter 8 - Semihosting' of the ['ARM Compiler toolchain Version 5.0'][pdf]
//! manual.
//!
//! [pdf]: http://infocenter.arm.com/help/topic/com.arm.doc.dui0471e/DUI0471E_developing_for_arm_processors.pdf
#![cfg_attr(feature = "inline-asm", feature(llvm_asm))]
#![deny(missing_docs)]
#![no_std]
#[macro_use]
mod macros;
pub mod debug;
#[doc(hidden)]
pub mod export;
pub mod hio;
pub mod nr;
#[cfg(all(thumb, not(feature = "inline-asm")))]
extern "C" {
fn __c_m_sh_syscall(nr: usize, arg: usize) -> usize;
}
/// Performs a semihosting operation, takes a pointer to an argument block
#[inline(always)]
pub unsafe fn syscall<T>(nr: usize, arg: &T) -> usize {
syscall1(nr, arg as *const T as usize)
}
/// Performs a semihosting operation, takes one integer as an argument
#[inline(always)]
pub unsafe fn syscall1(_nr: usize, _arg: usize) -> usize {
match () {
#[cfg(all(thumb, not(feature = "inline-asm"), not(feature = "no-semihosting")))]
() => __c_m_sh_syscall(_nr, _arg),
#[cfg(all(thumb, feature = "inline-asm", not(feature = "no-semihosting")))]
() => {
let mut nr = _nr;
llvm_asm!("bkpt 0xAB" : "+{r0}"(nr) : "{r1}"(_arg) :: "volatile");
nr
}
#[cfg(all(thumb, feature = "no-semihosting"))]
() => {
0
}
#[cfg(not(thumb))]
() => unimplemented!(),
}
}
| 31.540773 | 221 | 0.629882 |
9bd90e70abad0ed8f4feb5c721a88b7a894fbc15 | 233 | struct S(Vec<isize>);
fn unpack<F>(_unpack: F) where F: FnOnce(&S) -> Vec<isize> {}
fn main() {
let _foo = unpack(|s| {
// Test that `s` is moved here.
match *s { S(v) => v } //~ ERROR cannot move out
});
}
| 21.181818 | 61 | 0.515021 |
0963a03c8abe3f11d4a54001aa46aec9ebf6e420 | 1,884 | use benchmarks_ddlog::{api::HDDlog as DDlog, typedefs::twitter::Edge, Relations};
use benchmarks_differential_datalog::{
ddval::{DDValConvert, DDValue},
program::{RelId, Update},
DDlog as _,
};
use csv::Reader;
use flate2::bufread::GzDecoder;
use std::{fs::File, io::BufReader};
pub fn dataset(samples: Option<usize>) -> Vec<Update<DDValue>> {
// The indices of the csv rows
const NODE_ID: usize = 0;
const TWITTER_ID: usize = 1;
// Grab the file and wrap it in a buffered reader so it doesn't take forever
// to read the entire thing in one go
let reader = Reader::from_reader(GzDecoder::new(BufReader::new(
File::open(concat!(
env!("CARGO_MANIFEST_DIR"),
"/data/twitter-2010-ids.csv.gz",
))
.expect("could not open data file"),
)));
let mut edges = Vec::with_capacity(samples.unwrap_or(40_000_000));
for record in reader
.into_records()
.flat_map(|record| record.ok())
.take(samples.unwrap_or_else(usize::max_value))
{
let edge = Edge {
from: record.get(NODE_ID).unwrap().parse().unwrap(),
to: record.get(TWITTER_ID).unwrap().parse().unwrap(),
};
edges.push(Update::Insert {
relid: Relations::twitter_Edge as RelId,
v: edge.into_ddvalue(),
});
}
edges
}
pub fn init(workers: usize) -> DDlog {
let (ddlog, _) = DDlog::run(workers, false).expect("failed to create DDlog instance");
ddlog
}
pub fn run(ddlog: DDlog, dataset: Vec<Update<DDValue>>) -> DDlog {
ddlog
.transaction_start()
.expect("failed to start transaction");
ddlog
.apply_valupdates(dataset.into_iter())
.expect("failed to give transaction input");
ddlog
.transaction_commit()
.expect("failed to commit transaction");
ddlog
}
| 28.984615 | 90 | 0.61518 |
3a1ac1306f430b43182168d9c2ebba27dcac1078 | 6,689 | use std::cell::{Ref, RefCell, RefMut};
use std::collections::VecDeque;
use std::rc::Rc;
use crate::extensions::Extensions;
use crate::http::{HeaderMap, Method, StatusCode, Uri, Version};
/// Represents various types of connection
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ConnectionType {
/// Close connection after response
Close,
/// Keep connection alive after response
KeepAlive,
/// Connection is upgraded to different type
Upgrade,
}
#[doc(hidden)]
pub trait Head: Default + 'static {
fn clear(&mut self);
/// Read the message headers.
fn headers(&self) -> &HeaderMap;
/// Mutable reference to the message headers.
fn headers_mut(&mut self) -> &mut HeaderMap;
/// Connection type
fn connection_type(&self) -> ConnectionType;
/// Set connection type of the message
fn set_connection_type(&mut self, ctype: ConnectionType);
fn upgrade(&self) -> bool {
self.connection_type() == ConnectionType::Upgrade
}
/// Check if keep-alive is enabled
fn keep_alive(&self) -> bool {
self.connection_type() == ConnectionType::KeepAlive
}
fn pool() -> &'static MessagePool<Self>;
}
#[derive(Debug)]
pub struct RequestHead {
pub uri: Uri,
pub method: Method,
pub version: Version,
pub headers: HeaderMap,
pub ctype: Option<ConnectionType>,
pub no_chunking: bool,
pub extensions: RefCell<Extensions>,
}
impl Default for RequestHead {
fn default() -> RequestHead {
RequestHead {
uri: Uri::default(),
method: Method::default(),
version: Version::HTTP_11,
headers: HeaderMap::with_capacity(16),
ctype: None,
no_chunking: false,
extensions: RefCell::new(Extensions::new()),
}
}
}
impl Head for RequestHead {
fn clear(&mut self) {
self.ctype = None;
self.headers.clear();
self.extensions.borrow_mut().clear();
}
fn headers(&self) -> &HeaderMap {
&self.headers
}
fn headers_mut(&mut self) -> &mut HeaderMap {
&mut self.headers
}
fn set_connection_type(&mut self, ctype: ConnectionType) {
self.ctype = Some(ctype)
}
fn connection_type(&self) -> ConnectionType {
if let Some(ct) = self.ctype {
ct
} else if self.version < Version::HTTP_11 {
ConnectionType::Close
} else {
ConnectionType::KeepAlive
}
}
fn pool() -> &'static MessagePool<Self> {
REQUEST_POOL.with(|p| *p)
}
}
impl RequestHead {
/// Message extensions
#[inline]
pub fn extensions(&self) -> Ref<Extensions> {
self.extensions.borrow()
}
/// Mutable reference to a the message's extensions
#[inline]
pub fn extensions_mut(&self) -> RefMut<Extensions> {
self.extensions.borrow_mut()
}
}
#[derive(Debug)]
pub struct ResponseHead {
pub version: Version,
pub status: StatusCode,
pub headers: HeaderMap,
pub reason: Option<&'static str>,
pub no_chunking: bool,
pub(crate) ctype: Option<ConnectionType>,
}
impl Default for ResponseHead {
fn default() -> ResponseHead {
ResponseHead {
version: Version::default(),
status: StatusCode::OK,
headers: HeaderMap::with_capacity(16),
reason: None,
no_chunking: false,
ctype: None,
}
}
}
impl Head for ResponseHead {
fn clear(&mut self) {
self.ctype = None;
self.reason = None;
self.no_chunking = false;
self.headers.clear();
}
fn headers(&self) -> &HeaderMap {
&self.headers
}
fn headers_mut(&mut self) -> &mut HeaderMap {
&mut self.headers
}
fn set_connection_type(&mut self, ctype: ConnectionType) {
self.ctype = Some(ctype)
}
fn connection_type(&self) -> ConnectionType {
if let Some(ct) = self.ctype {
ct
} else if self.version < Version::HTTP_11 {
ConnectionType::Close
} else {
ConnectionType::KeepAlive
}
}
fn pool() -> &'static MessagePool<Self> {
RESPONSE_POOL.with(|p| *p)
}
}
impl ResponseHead {
/// Get custom reason for the response
#[inline]
pub fn reason(&self) -> &str {
if let Some(reason) = self.reason {
reason
} else {
self.status
.canonical_reason()
.unwrap_or("<unknown status code>")
}
}
}
pub struct Message<T: Head> {
head: Rc<T>,
pool: &'static MessagePool<T>,
}
impl<T: Head> Message<T> {
/// Get new message from the pool of objects
pub fn new() -> Self {
T::pool().get_message()
}
}
impl<T: Head> Clone for Message<T> {
fn clone(&self) -> Self {
Message {
head: self.head.clone(),
pool: self.pool,
}
}
}
impl<T: Head> std::ops::Deref for Message<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.head.as_ref()
}
}
impl<T: Head> std::ops::DerefMut for Message<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
Rc::get_mut(&mut self.head).expect("Multiple copies exist")
}
}
impl<T: Head> Drop for Message<T> {
fn drop(&mut self) {
if Rc::strong_count(&self.head) == 1 {
self.pool.release(self.head.clone());
}
}
}
#[doc(hidden)]
/// Request's objects pool
pub struct MessagePool<T: Head>(RefCell<VecDeque<Rc<T>>>);
thread_local!(static REQUEST_POOL: &'static MessagePool<RequestHead> = MessagePool::<RequestHead>::create());
thread_local!(static RESPONSE_POOL: &'static MessagePool<ResponseHead> = MessagePool::<ResponseHead>::create());
impl<T: Head> MessagePool<T> {
fn create() -> &'static MessagePool<T> {
let pool = MessagePool(RefCell::new(VecDeque::with_capacity(128)));
Box::leak(Box::new(pool))
}
/// Get message from the pool
#[inline]
fn get_message(&'static self) -> Message<T> {
if let Some(mut msg) = self.0.borrow_mut().pop_front() {
if let Some(r) = Rc::get_mut(&mut msg) {
r.clear();
}
Message {
head: msg,
pool: self,
}
} else {
Message {
head: Rc::new(T::default()),
pool: self,
}
}
}
#[inline]
/// Release request instance
fn release(&self, msg: Rc<T>) {
let v = &mut self.0.borrow_mut();
if v.len() < 128 {
v.push_front(msg);
}
}
}
| 24.235507 | 112 | 0.567798 |
9b71abf3653318c21fbc558cdb07822bba9845a5 | 1,413 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Checks that the Fn trait hierarchy rules permit
// any Fn trait to be used where Fn is implemented.
// pretty-expanded FIXME #23616
#![feature(unboxed_closures, core)]
use std::ops::{Fn,FnMut,FnOnce};
struct S;
impl Fn<(i32,)> for S {
extern "rust-call" fn call(&self, (x,): (i32,)) -> i32 {
x * x
}
}
impl FnMut<(i32,)> for S {
extern "rust-call" fn call_mut(&mut self, args: (i32,)) -> i32 { self.call(args) }
}
impl FnOnce<(i32,)> for S {
type Output = i32;
extern "rust-call" fn call_once(self, args: (i32,)) -> i32 { self.call(args) }
}
fn call_it<F:Fn(i32)->i32>(f: &F, x: i32) -> i32 {
f(x)
}
fn call_it_mut<F:FnMut(i32)->i32>(f: &mut F, x: i32) -> i32 {
f(x)
}
fn call_it_once<F:FnOnce(i32)->i32>(f: F, x: i32) -> i32 {
f(x)
}
fn main() {
let x = call_it(&S, 22);
let y = call_it_mut(&mut S, 22);
let z = call_it_once(S, 22);
assert_eq!(x, y);
assert_eq!(y, z);
}
| 25.232143 | 86 | 0.629866 |
482faea2da8964f479924107c290908c32859fd4 | 32,577 | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
//
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
extern crate devices;
#[cfg(feature = "pci_support")]
extern crate pci;
extern crate vm_allocator;
extern crate vm_memory;
extern crate vmm_sys_util;
use super::VirtioPciCommonConfig;
use crate::transport::VirtioTransport;
use crate::{
Queue, VirtioDevice, VirtioDeviceType, VirtioInterrupt, VirtioInterruptType,
VirtioIommuRemapping, DEVICE_ACKNOWLEDGE, DEVICE_DRIVER, DEVICE_DRIVER_OK, DEVICE_FAILED,
DEVICE_FEATURES_OK, DEVICE_INIT, VIRTIO_MSI_NO_VECTOR,
};
use devices::BusDevice;
use libc::EFD_NONBLOCK;
use pci::{
BarReprogrammingParams, MsixCap, MsixConfig, PciBarConfiguration, PciBarRegionType,
PciCapability, PciCapabilityID, PciClassCode, PciConfiguration, PciDevice, PciDeviceError,
PciHeaderType, PciMassStorageSubclass, PciNetworkControllerSubclass, PciSubclass,
};
use std::any::Any;
use std::cmp;
use std::io::Write;
use std::result;
use std::sync::atomic::{AtomicU16, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use vm_allocator::SystemAllocator;
use vm_device::interrupt::{
InterruptIndex, InterruptManager, InterruptSourceGroup, MsiIrqGroupConfig,
};
use vm_memory::{
Address, ByteValued, GuestAddress, GuestAddressSpace, GuestMemoryAtomic, GuestMemoryMmap,
GuestUsize, Le32,
};
use vm_migration::{Migratable, MigratableError, Pausable, Snapshottable, Transportable};
use vmm_sys_util::{errno::Result, eventfd::EventFd};
#[allow(clippy::enum_variant_names)]
enum PciCapabilityType {
CommonConfig = 1,
NotifyConfig = 2,
IsrConfig = 3,
DeviceConfig = 4,
PciConfig = 5,
SharedMemoryConfig = 8,
}
// This offset represents the 2 bytes omitted from the VirtioPciCap structure
// as they are already handled through add_capability(). These 2 bytes are the
// fields cap_vndr (1 byte) and cap_next (1 byte) defined in the virtio spec.
const VIRTIO_PCI_CAP_OFFSET: usize = 2;
#[allow(dead_code)]
#[repr(packed)]
#[derive(Clone, Copy, Default)]
struct VirtioPciCap {
cap_len: u8, // Generic PCI field: capability length
cfg_type: u8, // Identifies the structure.
pci_bar: u8, // Where to find it.
id: u8, // Multiple capabilities of the same type
padding: [u8; 2], // Pad to full dword.
offset: Le32, // Offset within bar.
length: Le32, // Length of the structure, in bytes.
}
// It is safe to implement ByteValued. All members are simple numbers and any value is valid.
unsafe impl ByteValued for VirtioPciCap {}
impl PciCapability for VirtioPciCap {
fn bytes(&self) -> &[u8] {
self.as_slice()
}
fn id(&self) -> PciCapabilityID {
PciCapabilityID::VendorSpecific
}
}
const VIRTIO_PCI_CAP_LEN_OFFSET: u8 = 2;
impl VirtioPciCap {
pub fn new(cfg_type: PciCapabilityType, pci_bar: u8, offset: u32, length: u32) -> Self {
VirtioPciCap {
cap_len: (std::mem::size_of::<VirtioPciCap>() as u8) + VIRTIO_PCI_CAP_LEN_OFFSET,
cfg_type: cfg_type as u8,
pci_bar,
id: 0,
padding: [0; 2],
offset: Le32::from(offset),
length: Le32::from(length),
}
}
}
#[allow(dead_code)]
#[repr(packed)]
#[derive(Clone, Copy, Default)]
struct VirtioPciNotifyCap {
cap: VirtioPciCap,
notify_off_multiplier: Le32,
}
// It is safe to implement ByteValued. All members are simple numbers and any value is valid.
unsafe impl ByteValued for VirtioPciNotifyCap {}
impl PciCapability for VirtioPciNotifyCap {
fn bytes(&self) -> &[u8] {
self.as_slice()
}
fn id(&self) -> PciCapabilityID {
PciCapabilityID::VendorSpecific
}
}
impl VirtioPciNotifyCap {
pub fn new(
cfg_type: PciCapabilityType,
pci_bar: u8,
offset: u32,
length: u32,
multiplier: Le32,
) -> Self {
VirtioPciNotifyCap {
cap: VirtioPciCap {
cap_len: (std::mem::size_of::<VirtioPciNotifyCap>() as u8)
+ VIRTIO_PCI_CAP_LEN_OFFSET,
cfg_type: cfg_type as u8,
pci_bar,
id: 0,
padding: [0; 2],
offset: Le32::from(offset),
length: Le32::from(length),
},
notify_off_multiplier: multiplier,
}
}
}
#[allow(dead_code)]
#[repr(packed)]
#[derive(Clone, Copy, Default)]
struct VirtioPciCap64 {
cap: VirtioPciCap,
offset_hi: Le32,
length_hi: Le32,
}
// It is safe to implement ByteValued. All members are simple numbers and any value is valid.
unsafe impl ByteValued for VirtioPciCap64 {}
impl PciCapability for VirtioPciCap64 {
fn bytes(&self) -> &[u8] {
self.as_slice()
}
fn id(&self) -> PciCapabilityID {
PciCapabilityID::VendorSpecific
}
}
impl VirtioPciCap64 {
pub fn new(cfg_type: PciCapabilityType, pci_bar: u8, id: u8, offset: u64, length: u64) -> Self {
VirtioPciCap64 {
cap: VirtioPciCap {
cap_len: (std::mem::size_of::<VirtioPciCap64>() as u8) + VIRTIO_PCI_CAP_LEN_OFFSET,
cfg_type: cfg_type as u8,
pci_bar,
id,
padding: [0; 2],
offset: Le32::from(offset as u32),
length: Le32::from(length as u32),
},
offset_hi: Le32::from((offset >> 32) as u32),
length_hi: Le32::from((length >> 32) as u32),
}
}
}
#[allow(dead_code)]
#[repr(packed)]
#[derive(Clone, Copy, Default)]
struct VirtioPciCfgCap {
cap: VirtioPciCap,
pci_cfg_data: [u8; 4],
}
// It is safe to implement ByteValued. All members are simple numbers and any value is valid.
unsafe impl ByteValued for VirtioPciCfgCap {}
impl PciCapability for VirtioPciCfgCap {
fn bytes(&self) -> &[u8] {
self.as_slice()
}
fn id(&self) -> PciCapabilityID {
PciCapabilityID::VendorSpecific
}
}
impl VirtioPciCfgCap {
fn new() -> Self {
VirtioPciCfgCap {
cap: VirtioPciCap::new(PciCapabilityType::PciConfig, 0, 0, 0),
..Default::default()
}
}
}
#[derive(Clone, Copy, Default)]
struct VirtioPciCfgCapInfo {
offset: usize,
cap: VirtioPciCfgCap,
}
#[allow(dead_code)]
#[derive(Copy, Clone)]
pub enum PciVirtioSubclass {
NonTransitionalBase = 0xff,
}
impl PciSubclass for PciVirtioSubclass {
fn get_register_value(&self) -> u8 {
*self as u8
}
}
// Allocate one bar for the structs pointed to by the capability structures.
// As per the PCI specification, because the same BAR shares MSI-X and non
// MSI-X structures, it is recommended to use 8KiB alignment for all those
// structures.
const COMMON_CONFIG_BAR_OFFSET: u64 = 0x0000;
const COMMON_CONFIG_SIZE: u64 = 56;
const ISR_CONFIG_BAR_OFFSET: u64 = 0x2000;
const ISR_CONFIG_SIZE: u64 = 1;
const DEVICE_CONFIG_BAR_OFFSET: u64 = 0x4000;
const DEVICE_CONFIG_SIZE: u64 = 0x1000;
const NOTIFICATION_BAR_OFFSET: u64 = 0x6000;
const NOTIFICATION_SIZE: u64 = 0x1000;
const MSIX_TABLE_BAR_OFFSET: u64 = 0x8000;
// The size is 256KiB because the table can hold up to 2048 entries, with each
// entry being 128 bits (4 DWORDS).
const MSIX_TABLE_SIZE: u64 = 0x40000;
const MSIX_PBA_BAR_OFFSET: u64 = 0x48000;
// The size is 2KiB because the Pending Bit Array has one bit per vector and it
// can support up to 2048 vectors.
const MSIX_PBA_SIZE: u64 = 0x800;
// The BAR size must be a power of 2.
const CAPABILITY_BAR_SIZE: u64 = 0x80000;
const NOTIFY_OFF_MULTIPLIER: u32 = 4; // A dword per notification address.
const VIRTIO_PCI_VENDOR_ID: u16 = 0x1af4;
const VIRTIO_PCI_DEVICE_ID_BASE: u16 = 0x1040; // Add to device type to get device ID.
pub struct VirtioPciDevice {
// PCI configuration registers.
configuration: PciConfiguration,
// virtio PCI common configuration
common_config: VirtioPciCommonConfig,
// MSI-X config
msix_config: Option<Arc<Mutex<MsixConfig>>>,
// Number of MSI-X vectors
msix_num: u16,
// Virtio device reference and status
device: Arc<Mutex<dyn VirtioDevice>>,
device_activated: bool,
// PCI interrupts.
interrupt_status: Arc<AtomicUsize>,
virtio_interrupt: Option<Arc<dyn VirtioInterrupt>>,
interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>,
// virtio queues
queues: Vec<Queue>,
queue_evts: Vec<EventFd>,
// Guest memory
memory: Option<GuestMemoryAtomic<GuestMemoryMmap>>,
// Setting PCI BAR
settings_bar: u8,
// Whether to use 64-bit bar location or 32-bit
use_64bit_bar: bool,
// Add a dedicated structure to hold information about the very specific
// virtio-pci capability VIRTIO_PCI_CAP_PCI_CFG. This is needed to support
// the legacy/backward compatible mechanism of letting the guest access the
// other virtio capabilities without mapping the PCI BARs. This can be
// needed when the guest tries to early access the virtio configuration of
// a device.
cap_pci_cfg_info: VirtioPciCfgCapInfo,
}
impl VirtioPciDevice {
/// Constructs a new PCI transport for the given virtio device.
pub fn new(
memory: GuestMemoryAtomic<GuestMemoryMmap>,
device: Arc<Mutex<dyn VirtioDevice>>,
msix_num: u16,
iommu_mapping_cb: Option<Arc<VirtioIommuRemapping>>,
interrupt_manager: &Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>,
) -> Result<Self> {
let device_clone = device.clone();
let locked_device = device_clone.lock().unwrap();
let mut queue_evts = Vec::new();
for _ in locked_device.queue_max_sizes().iter() {
queue_evts.push(EventFd::new(EFD_NONBLOCK)?)
}
let queues = locked_device
.queue_max_sizes()
.iter()
.map(|&s| {
let mut queue = Queue::new(s);
queue.iommu_mapping_cb = iommu_mapping_cb.clone();
queue
})
.collect();
let pci_device_id = VIRTIO_PCI_DEVICE_ID_BASE + locked_device.device_type() as u16;
let interrupt_source_group = interrupt_manager.create_group(MsiIrqGroupConfig {
base: 0,
count: msix_num as InterruptIndex,
})?;
let (msix_config, msix_config_clone) = if msix_num > 0 {
let msix_config = Arc::new(Mutex::new(MsixConfig::new(
msix_num,
interrupt_source_group.clone(),
)));
let msix_config_clone = msix_config.clone();
(Some(msix_config), Some(msix_config_clone))
} else {
(None, None)
};
// All device types *except* virtio block devices should be allocated a 64-bit bar
// The block devices should be given a 32-bit BAR so that they are easily accessible
// to firmware without requiring excessive identity mapping.
let mut use_64bit_bar = true;
let (class, subclass) = match VirtioDeviceType::from(locked_device.device_type()) {
VirtioDeviceType::TYPE_NET => (
PciClassCode::NetworkController,
&PciNetworkControllerSubclass::EthernetController as &dyn PciSubclass,
),
VirtioDeviceType::TYPE_BLOCK => {
use_64bit_bar = false;
(
PciClassCode::MassStorage,
&PciMassStorageSubclass::MassStorage as &dyn PciSubclass,
)
}
_ => (
PciClassCode::Other,
&PciVirtioSubclass::NonTransitionalBase as &dyn PciSubclass,
),
};
let configuration = PciConfiguration::new(
VIRTIO_PCI_VENDOR_ID,
pci_device_id,
class,
subclass,
None,
PciHeaderType::Device,
VIRTIO_PCI_VENDOR_ID,
pci_device_id,
msix_config_clone,
);
let mut virtio_pci_device = VirtioPciDevice {
configuration,
common_config: VirtioPciCommonConfig {
driver_status: 0,
config_generation: 0,
device_feature_select: 0,
driver_feature_select: 0,
queue_select: 0,
msix_config: Arc::new(AtomicU16::new(0)),
},
msix_config,
msix_num,
device,
device_activated: false,
interrupt_status: Arc::new(AtomicUsize::new(0)),
virtio_interrupt: None,
queues,
queue_evts,
memory: Some(memory),
settings_bar: 0,
use_64bit_bar,
interrupt_source_group,
cap_pci_cfg_info: VirtioPciCfgCapInfo::default(),
};
if let Some(msix_config) = &virtio_pci_device.msix_config {
virtio_pci_device.virtio_interrupt = Some(Arc::new(VirtioInterruptMsix::new(
msix_config.clone(),
virtio_pci_device.common_config.msix_config.clone(),
virtio_pci_device.interrupt_source_group.clone(),
)));
}
Ok(virtio_pci_device)
}
/// Gets the list of queue events that must be triggered whenever the VM writes to
/// `virtio::NOTIFY_REG_OFFSET` past the MMIO base. Each event must be triggered when the
/// value being written equals the index of the event in this list.
fn queue_evts(&self) -> &[EventFd] {
self.queue_evts.as_slice()
}
fn is_driver_ready(&self) -> bool {
let ready_bits =
(DEVICE_ACKNOWLEDGE | DEVICE_DRIVER | DEVICE_DRIVER_OK | DEVICE_FEATURES_OK) as u8;
self.common_config.driver_status == ready_bits
&& self.common_config.driver_status & DEVICE_FAILED as u8 == 0
}
/// Determines if the driver has requested the device (re)init / reset itself
fn is_driver_init(&self) -> bool {
self.common_config.driver_status == DEVICE_INIT as u8
}
fn are_queues_valid(&self) -> bool {
if let Some(mem) = self.memory.as_ref() {
self.queues.iter().all(|q| q.is_valid(&mem.memory()))
} else {
false
}
}
pub fn config_bar_addr(&self) -> u64 {
self.configuration.get_bar_addr(self.settings_bar as usize)
}
fn add_pci_capabilities(
&mut self,
settings_bar: u8,
) -> std::result::Result<(), PciDeviceError> {
// Add pointers to the different configuration structures from the PCI capabilities.
let common_cap = VirtioPciCap::new(
PciCapabilityType::CommonConfig,
settings_bar,
COMMON_CONFIG_BAR_OFFSET as u32,
COMMON_CONFIG_SIZE as u32,
);
self.configuration
.add_capability(&common_cap)
.map_err(PciDeviceError::CapabilitiesSetup)?;
let isr_cap = VirtioPciCap::new(
PciCapabilityType::IsrConfig,
settings_bar,
ISR_CONFIG_BAR_OFFSET as u32,
ISR_CONFIG_SIZE as u32,
);
self.configuration
.add_capability(&isr_cap)
.map_err(PciDeviceError::CapabilitiesSetup)?;
// TODO(dgreid) - set based on device's configuration size?
let device_cap = VirtioPciCap::new(
PciCapabilityType::DeviceConfig,
settings_bar,
DEVICE_CONFIG_BAR_OFFSET as u32,
DEVICE_CONFIG_SIZE as u32,
);
self.configuration
.add_capability(&device_cap)
.map_err(PciDeviceError::CapabilitiesSetup)?;
let notify_cap = VirtioPciNotifyCap::new(
PciCapabilityType::NotifyConfig,
settings_bar,
NOTIFICATION_BAR_OFFSET as u32,
NOTIFICATION_SIZE as u32,
Le32::from(NOTIFY_OFF_MULTIPLIER),
);
self.configuration
.add_capability(¬ify_cap)
.map_err(PciDeviceError::CapabilitiesSetup)?;
let configuration_cap = VirtioPciCfgCap::new();
self.cap_pci_cfg_info.offset = self
.configuration
.add_capability(&configuration_cap)
.map_err(PciDeviceError::CapabilitiesSetup)?
+ VIRTIO_PCI_CAP_OFFSET;
self.cap_pci_cfg_info.cap = configuration_cap;
if self.msix_config.is_some() {
let msix_cap = MsixCap::new(
settings_bar,
self.msix_num,
MSIX_TABLE_BAR_OFFSET as u32,
settings_bar,
MSIX_PBA_BAR_OFFSET as u32,
);
self.configuration
.add_capability(&msix_cap)
.map_err(PciDeviceError::CapabilitiesSetup)?;
}
self.settings_bar = settings_bar;
Ok(())
}
fn read_cap_pci_cfg(&mut self, offset: usize, mut data: &mut [u8]) {
let cap_slice = self.cap_pci_cfg_info.cap.as_slice();
let data_len = data.len();
let cap_len = cap_slice.len();
if offset + data_len > cap_len {
error!("Failed to read cap_pci_cfg from config space");
return;
}
if offset < std::mem::size_of::<VirtioPciCap>() {
if let Some(end) = offset.checked_add(data_len) {
// This write can't fail, offset and end are checked against config_len.
data.write_all(&cap_slice[offset..cmp::min(end, cap_len)])
.unwrap();
}
} else {
// Safe since we know self.cap_pci_cfg_info.cap.cap.offset is 32bits long.
let bar_offset: u32 =
unsafe { std::mem::transmute(self.cap_pci_cfg_info.cap.cap.offset) };
self.read_bar(0, bar_offset as u64, data)
}
}
fn write_cap_pci_cfg(&mut self, offset: usize, data: &[u8]) {
let cap_slice = self.cap_pci_cfg_info.cap.as_mut_slice();
let data_len = data.len();
let cap_len = cap_slice.len();
if offset + data_len > cap_len {
error!("Failed to write cap_pci_cfg to config space");
return;
}
if offset < std::mem::size_of::<VirtioPciCap>() {
let (_, right) = cap_slice.split_at_mut(offset);
right[..data_len].copy_from_slice(&data[..]);
} else {
// Safe since we know self.cap_pci_cfg_info.cap.cap.offset is 32bits long.
let bar_offset: u32 =
unsafe { std::mem::transmute(self.cap_pci_cfg_info.cap.cap.offset) };
self.write_bar(0, bar_offset as u64, data)
}
}
}
impl VirtioTransport for VirtioPciDevice {
fn ioeventfds(&self, base_addr: u64) -> Vec<(&EventFd, u64)> {
let notify_base = base_addr + NOTIFICATION_BAR_OFFSET;
self.queue_evts()
.iter()
.enumerate()
.map(|(i, event)| {
(
event,
notify_base + i as u64 * u64::from(NOTIFY_OFF_MULTIPLIER),
)
})
.collect()
}
}
pub struct VirtioInterruptMsix {
msix_config: Arc<Mutex<MsixConfig>>,
config_vector: Arc<AtomicU16>,
interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>,
}
impl VirtioInterruptMsix {
pub fn new(
msix_config: Arc<Mutex<MsixConfig>>,
config_vector: Arc<AtomicU16>,
interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>,
) -> Self {
VirtioInterruptMsix {
msix_config,
config_vector,
interrupt_source_group,
}
}
}
impl VirtioInterrupt for VirtioInterruptMsix {
fn trigger(
&self,
int_type: &VirtioInterruptType,
queue: Option<&Queue>,
) -> std::result::Result<(), std::io::Error> {
let vector = match int_type {
VirtioInterruptType::Config => self.config_vector.load(Ordering::SeqCst),
VirtioInterruptType::Queue => {
if let Some(q) = queue {
q.vector
} else {
0
}
}
};
if vector == VIRTIO_MSI_NO_VECTOR {
return Ok(());
}
let config = &mut self.msix_config.lock().unwrap();
let entry = &config.table_entries[vector as usize];
// In case the vector control register associated with the entry
// has its first bit set, this means the vector is masked and the
// device should not inject the interrupt.
// Instead, the Pending Bit Array table is updated to reflect there
// is a pending interrupt for this specific vector.
if config.masked() || entry.masked() {
config.set_pba_bit(vector, false);
return Ok(());
}
self.interrupt_source_group
.trigger(vector as InterruptIndex)
}
fn notifier(&self, int_type: &VirtioInterruptType, queue: Option<&Queue>) -> Option<&EventFd> {
let vector = match int_type {
VirtioInterruptType::Config => self.config_vector.load(Ordering::SeqCst),
VirtioInterruptType::Queue => {
if let Some(q) = queue {
q.vector
} else {
0
}
}
};
self.interrupt_source_group
.notifier(vector as InterruptIndex)
}
}
impl PciDevice for VirtioPciDevice {
fn write_config_register(&mut self, reg_idx: usize, offset: u64, data: &[u8]) {
// Handle the special case where the capability VIRTIO_PCI_CAP_PCI_CFG
// is accessed. This capability has a special meaning as it allows the
// guest to access other capabilities without mapping the PCI BAR.
let base = reg_idx * 4;
if base + offset as usize >= self.cap_pci_cfg_info.offset
&& base + offset as usize + data.len()
<= self.cap_pci_cfg_info.offset + self.cap_pci_cfg_info.cap.bytes().len()
{
let offset = base + offset as usize - self.cap_pci_cfg_info.offset;
self.write_cap_pci_cfg(offset, data);
} else {
self.configuration
.write_config_register(reg_idx, offset, data);
}
}
fn read_config_register(&mut self, reg_idx: usize) -> u32 {
// Handle the special case where the capability VIRTIO_PCI_CAP_PCI_CFG
// is accessed. This capability has a special meaning as it allows the
// guest to access other capabilities without mapping the PCI BAR.
let base = reg_idx * 4;
if base >= self.cap_pci_cfg_info.offset
&& base + 4 <= self.cap_pci_cfg_info.offset + self.cap_pci_cfg_info.cap.bytes().len()
{
let offset = base - self.cap_pci_cfg_info.offset;
let mut data = [0u8; 4];
self.read_cap_pci_cfg(offset, &mut data);
u32::from_le_bytes(data)
} else {
self.configuration.read_reg(reg_idx)
}
}
fn detect_bar_reprogramming(
&mut self,
reg_idx: usize,
data: &[u8],
) -> Option<BarReprogrammingParams> {
self.configuration.detect_bar_reprogramming(reg_idx, data)
}
fn allocate_bars(
&mut self,
allocator: &mut SystemAllocator,
) -> std::result::Result<Vec<(GuestAddress, GuestUsize, PciBarRegionType)>, PciDeviceError>
{
let mut ranges = Vec::new();
let device_clone = self.device.clone();
let device = device_clone.lock().unwrap();
// Allocate the virtio-pci capability BAR.
// See http://docs.oasis-open.org/virtio/virtio/v1.0/cs04/virtio-v1.0-cs04.html#x1-740004
let (virtio_pci_bar_addr, region_type) = if self.use_64bit_bar {
let region_type = PciBarRegionType::Memory64BitRegion;
let addr = allocator
.allocate_mmio_addresses(None, CAPABILITY_BAR_SIZE, None)
.ok_or(PciDeviceError::IoAllocationFailed(CAPABILITY_BAR_SIZE))?;
ranges.push((addr, CAPABILITY_BAR_SIZE, region_type));
(addr, region_type)
} else {
let region_type = PciBarRegionType::Memory32BitRegion;
let addr = allocator
.allocate_mmio_hole_addresses(None, CAPABILITY_BAR_SIZE, None)
.ok_or(PciDeviceError::IoAllocationFailed(CAPABILITY_BAR_SIZE))?;
ranges.push((addr, CAPABILITY_BAR_SIZE, region_type));
(addr, region_type)
};
let config = PciBarConfiguration::default()
.set_register_index(0)
.set_address(virtio_pci_bar_addr.raw_value())
.set_size(CAPABILITY_BAR_SIZE)
.set_region_type(region_type);
let virtio_pci_bar =
self.configuration.add_pci_bar(&config).map_err(|e| {
PciDeviceError::IoRegistrationFailed(virtio_pci_bar_addr.raw_value(), e)
})? as u8;
// Once the BARs are allocated, the capabilities can be added to the PCI configuration.
self.add_pci_capabilities(virtio_pci_bar)?;
// Allocate a dedicated BAR if there are some shared memory regions.
if let Some(shm_list) = device.get_shm_regions() {
let config = PciBarConfiguration::default()
.set_register_index(2)
.set_address(shm_list.addr.raw_value())
.set_size(shm_list.len);
let virtio_pci_shm_bar =
self.configuration.add_pci_bar(&config).map_err(|e| {
PciDeviceError::IoRegistrationFailed(shm_list.addr.raw_value(), e)
})? as u8;
for (idx, shm) in shm_list.region_list.iter().enumerate() {
let shm_cap = VirtioPciCap64::new(
PciCapabilityType::SharedMemoryConfig,
virtio_pci_shm_bar,
idx as u8,
shm.offset,
shm.len,
);
self.configuration
.add_capability(&shm_cap)
.map_err(PciDeviceError::CapabilitiesSetup)?;
}
}
Ok(ranges)
}
fn read_bar(&mut self, _base: u64, offset: u64, data: &mut [u8]) {
match offset {
o if o < COMMON_CONFIG_BAR_OFFSET + COMMON_CONFIG_SIZE => self.common_config.read(
o - COMMON_CONFIG_BAR_OFFSET,
data,
&mut self.queues,
self.device.clone(),
),
o if ISR_CONFIG_BAR_OFFSET <= o && o < ISR_CONFIG_BAR_OFFSET + ISR_CONFIG_SIZE => {
if let Some(v) = data.get_mut(0) {
// Reading this register resets it to 0.
*v = self.interrupt_status.swap(0, Ordering::SeqCst) as u8;
}
}
o if DEVICE_CONFIG_BAR_OFFSET <= o
&& o < DEVICE_CONFIG_BAR_OFFSET + DEVICE_CONFIG_SIZE =>
{
let device = self.device.lock().unwrap();
device.read_config(o - DEVICE_CONFIG_BAR_OFFSET, data);
}
o if NOTIFICATION_BAR_OFFSET <= o
&& o < NOTIFICATION_BAR_OFFSET + NOTIFICATION_SIZE =>
{
// Handled with ioeventfds.
}
o if MSIX_TABLE_BAR_OFFSET <= o && o < MSIX_TABLE_BAR_OFFSET + MSIX_TABLE_SIZE => {
if let Some(msix_config) = &self.msix_config {
msix_config
.lock()
.unwrap()
.read_table(o - MSIX_TABLE_BAR_OFFSET, data);
}
}
o if MSIX_PBA_BAR_OFFSET <= o && o < MSIX_PBA_BAR_OFFSET + MSIX_PBA_SIZE => {
if let Some(msix_config) = &self.msix_config {
msix_config
.lock()
.unwrap()
.read_pba(o - MSIX_PBA_BAR_OFFSET, data);
}
}
_ => (),
}
}
fn write_bar(&mut self, _base: u64, offset: u64, data: &[u8]) {
match offset {
o if o < COMMON_CONFIG_BAR_OFFSET + COMMON_CONFIG_SIZE => self.common_config.write(
o - COMMON_CONFIG_BAR_OFFSET,
data,
&mut self.queues,
self.device.clone(),
),
o if ISR_CONFIG_BAR_OFFSET <= o && o < ISR_CONFIG_BAR_OFFSET + ISR_CONFIG_SIZE => {
if let Some(v) = data.get(0) {
self.interrupt_status
.fetch_and(!(*v as usize), Ordering::SeqCst);
}
}
o if DEVICE_CONFIG_BAR_OFFSET <= o
&& o < DEVICE_CONFIG_BAR_OFFSET + DEVICE_CONFIG_SIZE =>
{
let mut device = self.device.lock().unwrap();
device.write_config(o - DEVICE_CONFIG_BAR_OFFSET, data);
}
o if NOTIFICATION_BAR_OFFSET <= o
&& o < NOTIFICATION_BAR_OFFSET + NOTIFICATION_SIZE =>
{
// Handled with ioeventfds.
}
o if MSIX_TABLE_BAR_OFFSET <= o && o < MSIX_TABLE_BAR_OFFSET + MSIX_TABLE_SIZE => {
if let Some(msix_config) = &self.msix_config {
msix_config
.lock()
.unwrap()
.write_table(o - MSIX_TABLE_BAR_OFFSET, data);
}
}
o if MSIX_PBA_BAR_OFFSET <= o && o < MSIX_PBA_BAR_OFFSET + MSIX_PBA_SIZE => {
if let Some(msix_config) = &self.msix_config {
msix_config
.lock()
.unwrap()
.write_pba(o - MSIX_PBA_BAR_OFFSET, data);
}
}
_ => (),
};
if !self.device_activated && self.is_driver_ready() && self.are_queues_valid() {
if let Some(virtio_interrupt) = self.virtio_interrupt.take() {
if self.memory.is_some() {
let mem = self.memory.as_ref().unwrap().clone();
let mut device = self.device.lock().unwrap();
device
.activate(
mem,
virtio_interrupt,
self.queues.clone(),
self.queue_evts.split_off(0),
)
.expect("Failed to activate device");
self.device_activated = true;
}
}
}
// Device has been reset by the driver
if self.device_activated && self.is_driver_init() {
let mut device = self.device.lock().unwrap();
if let Some((virtio_interrupt, mut queue_evts)) = device.reset() {
// Upon reset the device returns its interrupt EventFD and it's queue EventFDs
self.virtio_interrupt = Some(virtio_interrupt);
self.queue_evts.append(&mut queue_evts);
self.device_activated = false;
// Reset queue readiness (changes queue_enable), queue sizes
// and selected_queue as per spec for reset
self.queues.iter_mut().for_each(Queue::reset);
self.common_config.queue_select = 0;
} else {
error!("Attempt to reset device when not implemented in underlying device");
self.common_config.driver_status = crate::DEVICE_FAILED as u8;
}
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}
impl BusDevice for VirtioPciDevice {
fn read(&mut self, base: u64, offset: u64, data: &mut [u8]) {
self.read_bar(base, offset, data)
}
fn write(&mut self, base: u64, offset: u64, data: &[u8]) {
self.write_bar(base, offset, data)
}
}
impl Pausable for VirtioPciDevice {
fn pause(&mut self) -> result::Result<(), MigratableError> {
Ok(())
}
fn resume(&mut self) -> result::Result<(), MigratableError> {
Ok(())
}
}
impl Snapshottable for VirtioPciDevice {}
impl Transportable for VirtioPciDevice {}
impl Migratable for VirtioPciDevice {}
| 35.332972 | 100 | 0.589588 |
d7003f51f4c8ad36d86f928eb258ae531219df72 | 11,862 | #![allow(non_camel_case_types)]
use cfmt_b::{
fmt::{ComputeStrLength, Error, Formatter, FormattingFlags, StrWriter, StrWriterMut},
impl_fmt, try_,
wrapper_types::PWrapper,
};
use arrayvec::ArrayString;
use core::{fmt::Write, marker::PhantomData};
////////////////////////////////////////////////////////////////////////////////
struct Delegating<T>(T);
////////////////////////////////////////////////////////////////////////////////
struct BracedStruct<T: 'static> {
a: T,
b: &'static [T],
c: TupleStruct<T>,
d: UnitStruct,
}
struct TupleStruct<T>(T, u32);
struct UnitStruct;
impl_fmt! {
impl[] BracedStruct<u32>;
#[allow(dead_code)]
impl[] BracedStruct<u64>;
const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
let mut f = f.debug_struct("BracedStruct");
try_!(PWrapper(self.a).const_debug_fmt(f.field("a")));
try_!(PWrapper(self.b).const_debug_fmt(f.field("b")));
try_!(self.c.const_debug_fmt(f.field("c")));
try_!(self.d.const_debug_fmt(f.field("d")));
f.finish()
}
}
impl_fmt! {
#[allow(dead_code)]
impl[] TupleStruct<u64>;
impl[] TupleStruct<u32>;
const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
let mut f = f.debug_tuple("TupleStruct");
try_!(PWrapper(self.0).const_debug_fmt(f.field()));
try_!(PWrapper(self.1).const_debug_fmt(f.field()));
f.finish()
}
}
impl_fmt! {
impl[] UnitStruct;
const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
f.debug_tuple("UnitStruct").finish()
}
}
macro_rules! declare_test_case_fns {
( $Ty:ty ) => {
impl_fmt! {
impl[] Delegating<&$Ty>;
const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
self.0.const_debug_fmt(f)
}
}
const fn inner_delegating(
this: Delegating<&$Ty>,
writer: &mut StrWriterMut<'_>,
flags: FormattingFlags,
) -> Result<usize, Error> {
try_!(this.const_debug_fmt(&mut writer.make_formatter(flags)));
let mut str_len = ComputeStrLength::new();
try_!(this.const_debug_fmt(&mut str_len.make_formatter(flags)));
Ok(str_len.len())
}
const fn inner(
this: &$Ty,
writer: &mut StrWriterMut<'_>,
flags: FormattingFlags,
) -> Result<usize, Error> {
try_!(this.const_debug_fmt(&mut writer.make_formatter(flags)));
let mut str_len = ComputeStrLength::new();
try_!(this.const_debug_fmt(&mut str_len.make_formatter(flags)));
Ok(str_len.len())
}
fn test_case(this: &$Ty, writer: &mut StrWriter, flags: FormattingFlags, expected: &str) {
let writer = &mut writer.as_mut();
{
writer.clear();
let len = inner(this, writer, flags).unwrap();
assert_eq!(writer.as_str(), expected);
assert_eq!(writer.len(), len, "{}", writer.as_str());
}
{
writer.clear();
let len = inner_delegating(Delegating(this), writer, flags).unwrap();
assert_eq!(writer.as_str(), expected);
assert_eq!(writer.len(), len, "{}", writer.as_str());
}
}
};
}
#[test]
fn struct_debug_impl() {
declare_test_case_fns!(BracedStruct<u32>);
let foo = BracedStruct {
a: 10,
b: &[20, 30],
c: TupleStruct(40, 50),
d: UnitStruct,
};
let writer: &mut StrWriter = &mut StrWriter::new([0; 512]);
test_case(
&foo,
writer,
FormattingFlags::NEW.set_alternate(false),
"BracedStruct { a: 10, b: [20, 30], c: TupleStruct(40, 50), d: UnitStruct }",
);
const ALT: &str = "\
BracedStruct {
a: 10,
b: [
20,
30,
],
c: TupleStruct(
40,
50,
),
d: UnitStruct,
}\
";
test_case(&foo, writer, FormattingFlags::NEW.set_alternate(true), ALT);
const ALT_HEX: &str = "\
BracedStruct {
a: 0xA,
b: [
0x14,
0x1E,
],
c: TupleStruct(
0x28,
0x32,
),
d: UnitStruct,
}\
";
test_case(
&foo,
writer,
FormattingFlags::NEW.set_alternate(true).set_hexadecimal(),
ALT_HEX,
);
}
#[allow(dead_code)]
struct BracedStructNE<T: 'static> {
a: T,
b: &'static [T],
c: TupleStructNE<T, UnDebug>,
d: UnitStruct,
e: u8,
f: (),
}
struct UnDebug;
struct TupleStructNE<T, U>(T, u32, PhantomData<U>);
impl_fmt! {
impl BracedStructNE<u32>;
#[allow(dead_code)]
impl[] BracedStructNE<u64>;
const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
let mut f = f.debug_struct("BracedStructNE");
try_!(PWrapper(self.a).const_debug_fmt(f.field("a")));
try_!(PWrapper(self.b).const_debug_fmt(f.field("b")));
try_!(self.c.const_debug_fmt(f.field("c")));
try_!(self.d.const_debug_fmt(f.field("d")));
f.finish()
}
}
impl_fmt! {
#[allow(dead_code)]
impl[] TupleStructNE<u64, UnDebug>;
impl[T,] TupleStructNE<u32, T>
where[ T: 'static, ];
const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
let mut f = f.debug_tuple("TupleStructNE");
try_!(PWrapper(self.0).const_debug_fmt(f.field()));
try_!(PWrapper(self.1).const_debug_fmt(f.field()));
f.finish()
}
}
#[test]
fn struct_nonexhaustive_debug_impl() {
declare_test_case_fns!(BracedStructNE<u32>);
let foo = BracedStructNE {
a: 10u32,
b: &[20, 30],
c: TupleStructNE(40, 50, PhantomData),
d: UnitStruct,
e: 0,
f: (),
};
let writer: &mut StrWriter = &mut StrWriter::new([0; 512]);
test_case(
&foo,
writer,
FormattingFlags::NEW.set_alternate(false),
"BracedStructNE { a: 10, b: [20, 30], c: TupleStructNE(40, 50), d: UnitStruct }",
);
}
////////////////////////////////////////////////////////////////////////////////
enum EnumA<T> {
Tupled(T, u8),
Braced {
a: u16,
b: u16,
c: UnitStruct,
d: UnitStruct,
},
Unit,
}
impl_fmt! {
impl[] EnumA<u32>;
#[allow(dead_code)]
impl[] EnumA<u64>;
const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
match self {
Self::Tupled(f0, f1)=>{
let mut f = f.debug_tuple("Tupled");
try_!(PWrapper(*f0).const_debug_fmt(f.field()));
try_!(PWrapper(*f1).const_debug_fmt(f.field()));
f.finish()
}
Self::Braced {a,b,c,d} => {
let mut f = f.debug_struct("Braced");
try_!(PWrapper(*a).const_debug_fmt(f.field("a")));
try_!(PWrapper(*b).const_debug_fmt(f.field("b")));
try_!(c.const_debug_fmt(f.field("c")));
try_!(d.const_debug_fmt(f.field("d")));
f.finish()
}
Self::Unit => f.debug_struct("Unit").finish()
}
}
}
#[test]
fn enum_debug_impl() {
declare_test_case_fns!(EnumA<u32>);
let writer: &mut StrWriter = &mut StrWriter::new([0; 512]);
{
let tupled = EnumA::Tupled(3, 5);
test_case(
&tupled,
writer,
FormattingFlags::NEW.set_alternate(false),
"Tupled(3, 5)",
);
test_case(
&tupled,
writer,
FormattingFlags::NEW.set_alternate(true),
"Tupled(\n 3,\n 5,\n)",
);
}
{
let braced = EnumA::Braced {
a: 8,
b: 13,
c: UnitStruct,
d: UnitStruct,
};
test_case(
&braced,
writer,
FormattingFlags::NEW.set_alternate(false),
"Braced { a: 8, b: 13, c: UnitStruct, d: UnitStruct }",
);
test_case(
&braced,
writer,
FormattingFlags::NEW.set_alternate(true),
"Braced {\n a: 8,\n b: 13,\n c: UnitStruct,\n d: UnitStruct,\n}",
);
}
{
let unit = EnumA::Unit;
test_case(
&unit,
writer,
FormattingFlags::NEW.set_alternate(false),
"Unit",
);
test_case(
&unit,
writer,
FormattingFlags::NEW.set_alternate(true),
"Unit",
);
}
}
#[allow(dead_code)]
enum EnumA_NE<T> {
Tupled(T, u8, ()),
Braced {
a: u16,
b: u16,
c: UnitStruct,
d: UnitStruct,
e: (),
f: (),
},
Unit,
}
impl_fmt! {
impl[] EnumA_NE<u32>;
#[allow(dead_code)]
impl[] EnumA_NE<u64>;
const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
match self {
Self::Tupled(f0, f1,..)=>{
let mut f = f.debug_tuple("Tupled");
try_!(PWrapper(*f0).const_debug_fmt(f.field()));
try_!(PWrapper(*f1).const_debug_fmt(f.field()));
f.finish()
}
Self::Braced {a,b,c,d,..} => {
let mut f = f.debug_struct("Braced");
try_!(PWrapper(*a).const_debug_fmt(f.field("a")));
try_!(PWrapper(*b).const_debug_fmt(f.field("b")));
try_!(c.const_debug_fmt(f.field("c")));
try_!(d.const_debug_fmt(f.field("d")));
f.finish()
}
Self::Unit => f.debug_struct("<unknown_variant>").finish()
}
}
}
#[test]
fn enum_nonexhaustive_debug_impl() {
declare_test_case_fns!(EnumA_NE<u32>);
let writer: &mut StrWriter = &mut StrWriter::new([0; 512]);
{
let tupled = EnumA_NE::Tupled(3, 5, ());
test_case(&tupled, writer, FormattingFlags::NEW, "Tupled(3, 5)");
}
{
let braced = EnumA_NE::Braced {
a: 8,
b: 13,
c: UnitStruct,
d: UnitStruct,
e: (),
f: (),
};
test_case(
&braced,
writer,
FormattingFlags::NEW,
"Braced { a: 8, b: 13, c: UnitStruct, d: UnitStruct }",
);
}
{
let braced = EnumA_NE::Unit;
test_case(&braced, writer, FormattingFlags::NEW, "<unknown_variant>");
}
}
////////////////////////////////////////////////////////////////////////////////
struct StructWE<T>(EnumA<T>);
impl_fmt! {
impl[] StructWE<u32>;
#[allow(dead_code)]
impl[] StructWE<u64>;
const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
let mut f = f.debug_tuple("StructWE");
try_!(self.0.const_debug_fmt(f.field()));
f.finish()
}
}
#[test]
fn enum_inside_struct() {
declare_test_case_fns!(StructWE<u32>);
let writer: &mut StrWriter = &mut StrWriter::new([0; 512]);
let mut string = ArrayString::<[u8; 512]>::new();
{
let tupled = StructWE(EnumA::Tupled(3, 5));
test_case(
&tupled,
writer,
FormattingFlags::NEW.set_alternate(false),
"StructWE(Tupled(3, 5))",
);
string.clear();
write!(
string,
"StructWE({NL4}Tupled({NL8}3,{NL8}5,{NL4}),\n)",
NL4 = "\n ",
NL8 = "\n ",
)
.unwrap();
test_case(
&tupled,
writer,
FormattingFlags::NEW.set_alternate(true),
string.as_str(),
);
}
}
| 24.559006 | 98 | 0.494605 |
d7b24a7791253f33af38658532f85280c550bbdc | 9,930 | // Copyright 2021 The Grin Developers
//
// 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 self::chain::types::NoopAdapter;
use self::chain::ErrorKind;
use self::core::core::verifier_cache::LruVerifierCache;
use self::core::core::KernelFeatures;
use self::core::global::{self, ChainTypes};
use self::core::libtx::{self, build, ProofBuilder};
use self::core::{consensus, pow};
use self::keychain::{ExtKeychain, ExtKeychainPath, Keychain};
use self::util::RwLock;
use chrono::Duration;
use grin_chain as chain;
use grin_core as core;
use grin_keychain as keychain;
use grin_util as util;
use std::fs;
use std::sync::Arc;
fn clean_output_dir(dir_name: &str) {
let _ = fs::remove_dir_all(dir_name);
}
#[test]
fn test_coinbase_maturity() {
util::init_test_logger();
let chain_dir = ".grin_coinbase";
clean_output_dir(chain_dir);
global::set_local_chain_type(ChainTypes::AutomatedTesting);
let genesis_block = pow::mine_genesis_block().unwrap();
let verifier_cache = Arc::new(RwLock::new(LruVerifierCache::new()));
{
let chain = chain::Chain::init(
chain_dir.to_string(),
Arc::new(NoopAdapter {}),
genesis_block,
pow::verify_size,
verifier_cache,
false,
)
.unwrap();
let prev = chain.head_header().unwrap();
let keychain = ExtKeychain::from_random_seed(false).unwrap();
let builder = ProofBuilder::new(&keychain);
let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier();
let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier();
let key_id3 = ExtKeychainPath::new(1, 3, 0, 0, 0).to_identifier();
let key_id4 = ExtKeychainPath::new(1, 4, 0, 0, 0).to_identifier();
let next_header_info =
consensus::next_difficulty(prev.height + 1, chain.difficulty_iter().unwrap());
let reward = libtx::reward::output(&keychain, &builder, &key_id1, 0, false).unwrap();
let mut block =
core::core::Block::new(&prev, &[], next_header_info.difficulty, reward).unwrap();
block.header.timestamp = prev.timestamp + Duration::seconds(60);
block.header.pow.secondary_scaling = next_header_info.secondary_scaling;
chain.set_txhashset_roots(&mut block).unwrap();
pow::pow_size(
&mut block.header,
next_header_info.difficulty,
global::proofsize(),
global::min_edge_bits(),
)
.unwrap();
assert_eq!(block.outputs().len(), 1);
let coinbase_output = block.outputs()[0];
assert!(coinbase_output.is_coinbase());
chain
.process_block(block.clone(), chain::Options::MINE)
.unwrap();
let prev = chain.head_header().unwrap();
let amount = consensus::REWARD;
let lock_height = 1 + global::coinbase_maturity();
assert_eq!(lock_height, 4);
// here we build a tx that attempts to spend the earlier coinbase output
// this is not a valid tx as the coinbase output cannot be spent yet
let coinbase_txn = build::transaction(
KernelFeatures::Plain { fee: 2.into() },
&[
build::coinbase_input(amount, key_id1.clone()),
build::output(amount - 2, key_id2.clone()),
],
&keychain,
&builder,
)
.unwrap();
let txs = &[coinbase_txn.clone()];
let fees = txs.iter().map(|tx| tx.fee(prev.height + 1)).sum();
let reward = libtx::reward::output(&keychain, &builder, &key_id3, fees, false).unwrap();
let next_header_info =
consensus::next_difficulty(prev.height + 1, chain.difficulty_iter().unwrap());
let mut block =
core::core::Block::new(&prev, txs, next_header_info.difficulty, reward).unwrap();
block.header.timestamp = prev.timestamp + Duration::seconds(60);
block.header.pow.secondary_scaling = next_header_info.secondary_scaling;
chain.set_txhashset_roots(&mut block).unwrap();
// Confirm the tx attempting to spend the coinbase output
// is not valid at the current block height given the current chain state.
match chain.verify_coinbase_maturity(&coinbase_txn.inputs()) {
Ok(_) => {}
Err(e) => match e.kind() {
ErrorKind::ImmatureCoinbase => {}
_ => panic!("Expected transaction error with immature coinbase."),
},
}
pow::pow_size(
&mut block.header,
next_header_info.difficulty,
global::proofsize(),
global::min_edge_bits(),
)
.unwrap();
// mine enough blocks to increase the height sufficiently for
// coinbase to reach maturity and be spendable in the next block
for _ in 0..3 {
let prev = chain.head_header().unwrap();
let keychain = ExtKeychain::from_random_seed(false).unwrap();
let builder = ProofBuilder::new(&keychain);
let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier();
let next_header_info =
consensus::next_difficulty(prev.height + 1, chain.difficulty_iter().unwrap());
let reward = libtx::reward::output(&keychain, &builder, &key_id1, 0, false).unwrap();
let mut block =
core::core::Block::new(&prev, &[], next_header_info.difficulty, reward).unwrap();
block.header.timestamp = prev.timestamp + Duration::seconds(60);
block.header.pow.secondary_scaling = next_header_info.secondary_scaling;
chain.set_txhashset_roots(&mut block).unwrap();
pow::pow_size(
&mut block.header,
next_header_info.difficulty,
global::proofsize(),
global::min_edge_bits(),
)
.unwrap();
assert_eq!(block.outputs().len(), 1);
let coinbase_output = block.outputs()[0];
assert!(coinbase_output.is_coinbase());
chain
.process_block(block.clone(), chain::Options::MINE)
.unwrap();
let prev = chain.head_header().unwrap();
let amount = consensus::REWARD;
let lock_height = 1 + global::coinbase_maturity();
assert_eq!(lock_height, 4);
// here we build a tx that attempts to spend the earlier coinbase output
// this is not a valid tx as the coinbase output cannot be spent yet
let coinbase_txn = build::transaction(
KernelFeatures::Plain { fee: 2.into() },
&[
build::coinbase_input(amount, key_id1.clone()),
build::output(amount - 2, key_id2.clone()),
],
&keychain,
&builder,
)
.unwrap();
let txs = &[coinbase_txn.clone()];
let fees = txs.iter().map(|tx| tx.fee(prev.height + 1)).sum();
let reward = libtx::reward::output(&keychain, &builder, &key_id3, fees, false).unwrap();
let next_header_info =
consensus::next_difficulty(prev.height + 1, chain.difficulty_iter().unwrap());
let mut block =
core::core::Block::new(&prev, txs, next_header_info.difficulty, reward).unwrap();
block.header.timestamp = prev.timestamp + Duration::seconds(60);
block.header.pow.secondary_scaling = next_header_info.secondary_scaling;
chain.set_txhashset_roots(&mut block).unwrap();
// Confirm the tx attempting to spend the coinbase output
// is not valid at the current block height given the current chain state.
match chain.verify_coinbase_maturity(&coinbase_txn.inputs()) {
Ok(_) => {}
Err(e) => match e.kind() {
ErrorKind::ImmatureCoinbase => {}
_ => panic!("Expected transaction error with immature coinbase."),
},
}
pow::pow_size(
&mut block.header,
next_header_info.difficulty,
global::proofsize(),
global::min_edge_bits(),
)
.unwrap();
// mine enough blocks to increase the height sufficiently for
// coinbase to reach maturity and be spendable in the next block
for _ in 0..3 {
let prev = chain.head_header().unwrap();
let keychain = ExtKeychain::from_random_seed(false).unwrap();
let builder = ProofBuilder::new(&keychain);
let pk = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier();
let reward = libtx::reward::output(&keychain, &builder, &pk, 0, false).unwrap();
let next_header_info =
consensus::next_difficulty(prev.height + 1, chain.difficulty_iter().unwrap());
let mut block =
core::core::Block::new(&prev, &[], next_header_info.difficulty, reward)
.unwrap();
block.header.timestamp = prev.timestamp + Duration::seconds(60);
block.header.pow.secondary_scaling = next_header_info.secondary_scaling;
chain.set_txhashset_roots(&mut block).unwrap();
pow::pow_size(
&mut block.header,
next_header_info.difficulty,
global::proofsize(),
global::min_edge_bits(),
)
.unwrap();
chain.process_block(block, chain::Options::MINE).unwrap();
}
let prev = chain.head_header().unwrap();
// Confirm the tx spending the coinbase output is now valid.
// The coinbase output has matured sufficiently based on current chain state.
chain
.verify_coinbase_maturity(&coinbase_txn.inputs())
.unwrap();
let txs = &[coinbase_txn];
let fees = txs.iter().map(|tx| tx.fee(prev.height + 1)).sum();
let next_header_info =
consensus::next_difficulty(prev.height + 1, chain.difficulty_iter().unwrap());
let reward = libtx::reward::output(&keychain, &builder, &key_id4, fees, false).unwrap();
let mut block =
core::core::Block::new(&prev, txs, next_header_info.difficulty, reward).unwrap();
block.header.timestamp = prev.timestamp + Duration::seconds(60);
block.header.pow.secondary_scaling = next_header_info.secondary_scaling;
chain.set_txhashset_roots(&mut block).unwrap();
pow::pow_size(
&mut block.header,
next_header_info.difficulty,
global::proofsize(),
global::min_edge_bits(),
)
.unwrap();
let result = chain.process_block(block, chain::Options::MINE);
match result {
Ok(_) => (),
Err(_) => panic!("we did not expect an error here"),
};
}
}
// Cleanup chain directory
clean_output_dir(chain_dir);
}
| 33.210702 | 91 | 0.69144 |
18b7813fff24252e7c52b8d34cdaea3c8144ce87 | 155 | #![cfg(feature = "util")]
#![allow(clippy::type_complexity)]
mod call_all;
mod oneshot;
mod service_fn;
#[path = "../support.rs"]
pub(crate) mod support;
| 17.222222 | 34 | 0.677419 |
1c6a4167bfdba753b1efb94ecfc911d5d7a951fa | 1,926 | #[cfg(windows_by_handle)]
use crate::fs::Metadata;
use crate::fs::MetadataExt;
use std::{fs, io};
/// Determine if `a` and `b` refer to the same inode on the same device.
pub(crate) fn is_same_file(a: &fs::File, b: &fs::File) -> io::Result<bool> {
let a_metadata = MetadataExt::from(a, &a.metadata()?)?;
let b_metadata = MetadataExt::from(b, &b.metadata()?)?;
Ok(a_metadata.is_same_file(&b_metadata))
}
/// Determine if `a` and `b` are metadata for the same inode on the same device.
#[cfg(windows_by_handle)]
#[allow(dead_code)]
pub(crate) fn is_same_file_metadata(a: &Metadata, b: &Metadata) -> io::Result<bool> {
use std::os::windows::fs::MetadataExt;
Ok(a.volume_serial_number() == b.volume_serial_number() && a.file_index() == b.file_index())
}
/// Determine if `a` and `b` definitely refer to different inodes.
///
/// This is similar to `is_same_file`, but is conservative, and doesn't depend
/// on nightly-only features.
#[cfg(racy_asserts)]
pub(crate) fn is_different_file(a: &fs::File, b: &fs::File) -> io::Result<bool> {
#[cfg(windows_by_handle)]
{
is_same_file(a, b).map(|same| !same)
}
#[cfg(not(windows_by_handle))]
{
let a_metadata = Metadata::from_std(a.metadata()?);
let b_metadata = Metadata::from_std(b.metadata()?);
is_different_file_metadata(&a_metadata, &b_metadata)
}
}
/// Determine if `a` and `b` are metadata for definitely different inodes.
///
/// This is similar to `is_same_file_metadata`, but is conservative, and doesn't depend
/// on nightly-only features.
#[cfg(racy_asserts)]
pub(crate) fn is_different_file_metadata(a: &Metadata, b: &Metadata) -> io::Result<bool> {
#[cfg(windows_by_handle)]
{
is_same_file_metadata(a, b).map(|same| !same)
}
#[cfg(not(windows_by_handle))]
{
// Conservatively just compare creation times.
Ok(a.created()? != b.created()?)
}
}
| 33.789474 | 96 | 0.65784 |
5b6da7dd086fb5577a247caa6966f67bffdcf913 | 2,320 | extern crate docopt;
extern crate rustc_serialize;
extern crate libracerd;
extern crate env_logger;
use libracerd::{Config, engine, http};
use libracerd::engine::SemanticEngine;
use std::convert::Into;
use docopt::Docopt;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const USAGE: &'static str = "
racerd - a JSON/HTTP layer on top of racer
Usage:
racerd serve [--secret-file=<path>] [--port=<int>] [--addr=<address>] [-l] [--rust-src-path=<path>]
racerd (-h | --help)
racerd --version
Options:
-c, --rust-src-path=<path> Use the given path for std library completions
-l, --logging Print http logs.
-h, --help Show this message.
-p, --port=<int> Listen on this port [default: 3048].
-a, --addr=<address> Listen on this address [default: 127.0.0.1].
-s, --secret-file=<path> Path to the HMAC secret file. File will be destroyed after being read.
--version Print the version and exit.
";
#[derive(Debug, RustcDecodable)]
struct Args {
flag_port: u16,
flag_addr: String,
flag_version: bool,
flag_secret_file: Option<String>,
flag_logging: bool,
flag_rust_src_path: Option<String>,
cmd_serve: bool
}
impl Into<Config> for Args {
fn into(self) -> Config {
Config {
port: self.flag_port as u16,
secret_file: self.flag_secret_file,
print_http_logs: self.flag_logging,
rust_src_path: self.flag_rust_src_path,
addr: self.flag_addr
}
}
}
fn main() {
// Start logging
::env_logger::init().unwrap();
// Parse arguments
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
// Print version and exit if --version was specified
if args.flag_version {
println!("racerd version {}", VERSION);
::std::process::exit(0);
}
// build config object
let config: Config = args.into();
// TODO start specified semantic engine. For now, hard coded racer.
let racer = engine::Racer::new();
racer.initialize(&config).unwrap();
// Start serving
let server = http::serve(&config, racer).unwrap();
println!("racerd listening at {}", server.addr());
}
| 28.641975 | 101 | 0.610776 |
3a7c7ea9a714b76fe995b72a30bc90cb8a9b8529 | 830 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
use std::result::Result;
use std::result::Result::Ok;
static C: Result<(), Box<isize>> = Ok(());
// This is because of yet another bad assertion (ICE) about the null side of a nullable enum.
// So we won't actually compile if the bug is present, but we check the value in main anyway.
pub fn main() {
assert!(C.is_ok());
}
| 34.583333 | 93 | 0.716867 |
ab30913998f7a5bbd34bd1fd8e4c602dd33cbb01 | 52 | include!(concat!(env!("OUT_DIR"), "/messages.rs"));
| 26 | 51 | 0.634615 |
33861432514fc5efb0be264bec63118a066061a1 | 3,534 | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use super::{Procedure, ProcedureError, ProcedureMarker, ProcedureRequest};
use at_commands as at;
use crate::peer::{service_level_connection::SlcState, update::AgUpdate};
/// The HF may disable or enable the Call Waiting Notifications via this
/// procedure. See HFP v1.8, Section 4.21.
///
/// The AG may send Call Waiting Notifications via this procedure. See HFP v1.8, Section 4.22
///
/// This procedure is implemented from the perspective of the AG. Namely, outgoing `requests`
/// typically request information about the current state of the AG, to be sent to the remote
/// peer acting as the HF.
#[derive(Debug, Default)]
pub struct CallWaitingNotificationsProcedure {
/// The current state of the procedure
terminated: bool,
}
impl CallWaitingNotificationsProcedure {
/// Create a new CallWaitingNotifications procedure in the Start state.
pub fn new() -> Self {
Self::default()
}
}
impl Procedure for CallWaitingNotificationsProcedure {
fn marker(&self) -> ProcedureMarker {
ProcedureMarker::CallWaitingNotifications
}
fn hf_update(&mut self, update: at::Command, state: &mut SlcState) -> ProcedureRequest {
match (self.terminated, update) {
(false, at::Command::Ccwa { enable }) => {
self.terminated = true;
state.call_waiting_notifications = enable;
AgUpdate::Ok.into()
}
(_, update) => ProcedureRequest::Error(ProcedureError::UnexpectedHf(update)),
}
}
fn ag_update(&mut self, update: AgUpdate, state: &mut SlcState) -> ProcedureRequest {
match (self.terminated, update) {
(false, AgUpdate::CallWaiting(call)) => {
// Only send the update if call waiting notifications are enabled for the SLC.
self.terminated = true;
if state.call_waiting_notifications {
AgUpdate::CallWaiting(call).into()
} else {
ProcedureRequest::None
}
}
(_, update) => ProcedureRequest::Error(ProcedureError::UnexpectedAg(update)),
}
}
fn is_terminated(&self) -> bool {
self.terminated
}
}
#[cfg(test)]
mod tests {
use super::*;
use matches::assert_matches;
#[test]
fn correct_marker() {
let marker = CallWaitingNotificationsProcedure::new().marker();
assert_eq!(marker, ProcedureMarker::CallWaitingNotifications);
}
#[test]
fn procedure_handles_invalid_messages() {
let mut proc = CallWaitingNotificationsProcedure::new();
let req = proc.hf_update(at::Command::CopsRead {}, &mut SlcState::default());
assert_matches!(req, ProcedureRequest::Error(ProcedureError::UnexpectedHf(_)));
let req = proc.ag_update(AgUpdate::ThreeWaySupport, &mut SlcState::default());
assert_matches!(req, ProcedureRequest::Error(ProcedureError::UnexpectedAg(_)));
}
#[test]
fn procedure_with_response() {
let mut proc = CallWaitingNotificationsProcedure::new();
let req = proc.hf_update(at::Command::Ccwa { enable: true }, &mut SlcState::default());
assert_matches!(
req,
ProcedureRequest::SendMessages(msgs) if msgs == vec![at::Response::Ok]
);
assert!(proc.is_terminated());
}
}
| 35.34 | 95 | 0.641766 |
e9602ba959cea4a91e6764e0440972560a2fd097 | 290,626 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct AssociateDelegateToResourceError {
pub kind: AssociateDelegateToResourceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum AssociateDelegateToResourceErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for AssociateDelegateToResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
AssociateDelegateToResourceErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
AssociateDelegateToResourceErrorKind::EntityStateException(_inner) => _inner.fmt(f),
AssociateDelegateToResourceErrorKind::InvalidParameterException(_inner) => {
_inner.fmt(f)
}
AssociateDelegateToResourceErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
AssociateDelegateToResourceErrorKind::OrganizationStateException(_inner) => {
_inner.fmt(f)
}
AssociateDelegateToResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for AssociateDelegateToResourceError {
fn code(&self) -> Option<&str> {
AssociateDelegateToResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl AssociateDelegateToResourceError {
pub fn new(kind: AssociateDelegateToResourceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: AssociateDelegateToResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: AssociateDelegateToResourceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
AssociateDelegateToResourceErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(
&self.kind,
AssociateDelegateToResourceErrorKind::EntityStateException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
AssociateDelegateToResourceErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
AssociateDelegateToResourceErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
AssociateDelegateToResourceErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for AssociateDelegateToResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
AssociateDelegateToResourceErrorKind::EntityNotFoundException(_inner) => Some(_inner),
AssociateDelegateToResourceErrorKind::EntityStateException(_inner) => Some(_inner),
AssociateDelegateToResourceErrorKind::InvalidParameterException(_inner) => Some(_inner),
AssociateDelegateToResourceErrorKind::OrganizationNotFoundException(_inner) => {
Some(_inner)
}
AssociateDelegateToResourceErrorKind::OrganizationStateException(_inner) => {
Some(_inner)
}
AssociateDelegateToResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct AssociateMemberToGroupError {
pub kind: AssociateMemberToGroupErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum AssociateMemberToGroupErrorKind {
DirectoryServiceAuthenticationFailedException(
crate::error::DirectoryServiceAuthenticationFailedException,
),
DirectoryUnavailableException(crate::error::DirectoryUnavailableException),
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
UnsupportedOperationException(crate::error::UnsupportedOperationException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for AssociateMemberToGroupError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
AssociateMemberToGroupErrorKind::DirectoryServiceAuthenticationFailedException(
_inner,
) => _inner.fmt(f),
AssociateMemberToGroupErrorKind::DirectoryUnavailableException(_inner) => _inner.fmt(f),
AssociateMemberToGroupErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
AssociateMemberToGroupErrorKind::EntityStateException(_inner) => _inner.fmt(f),
AssociateMemberToGroupErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
AssociateMemberToGroupErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
AssociateMemberToGroupErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
AssociateMemberToGroupErrorKind::UnsupportedOperationException(_inner) => _inner.fmt(f),
AssociateMemberToGroupErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for AssociateMemberToGroupError {
fn code(&self) -> Option<&str> {
AssociateMemberToGroupError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl AssociateMemberToGroupError {
pub fn new(kind: AssociateMemberToGroupErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: AssociateMemberToGroupErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: AssociateMemberToGroupErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_directory_service_authentication_failed_exception(&self) -> bool {
matches!(
&self.kind,
AssociateMemberToGroupErrorKind::DirectoryServiceAuthenticationFailedException(_)
)
}
pub fn is_directory_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
AssociateMemberToGroupErrorKind::DirectoryUnavailableException(_)
)
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
AssociateMemberToGroupErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(
&self.kind,
AssociateMemberToGroupErrorKind::EntityStateException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
AssociateMemberToGroupErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
AssociateMemberToGroupErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
AssociateMemberToGroupErrorKind::OrganizationStateException(_)
)
}
pub fn is_unsupported_operation_exception(&self) -> bool {
matches!(
&self.kind,
AssociateMemberToGroupErrorKind::UnsupportedOperationException(_)
)
}
}
impl std::error::Error for AssociateMemberToGroupError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
AssociateMemberToGroupErrorKind::DirectoryServiceAuthenticationFailedException(
_inner,
) => Some(_inner),
AssociateMemberToGroupErrorKind::DirectoryUnavailableException(_inner) => Some(_inner),
AssociateMemberToGroupErrorKind::EntityNotFoundException(_inner) => Some(_inner),
AssociateMemberToGroupErrorKind::EntityStateException(_inner) => Some(_inner),
AssociateMemberToGroupErrorKind::InvalidParameterException(_inner) => Some(_inner),
AssociateMemberToGroupErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
AssociateMemberToGroupErrorKind::OrganizationStateException(_inner) => Some(_inner),
AssociateMemberToGroupErrorKind::UnsupportedOperationException(_inner) => Some(_inner),
AssociateMemberToGroupErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CancelMailboxExportJobError {
pub kind: CancelMailboxExportJobErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CancelMailboxExportJobErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CancelMailboxExportJobError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CancelMailboxExportJobErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
CancelMailboxExportJobErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
CancelMailboxExportJobErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
CancelMailboxExportJobErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
CancelMailboxExportJobErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CancelMailboxExportJobError {
fn code(&self) -> Option<&str> {
CancelMailboxExportJobError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CancelMailboxExportJobError {
pub fn new(kind: CancelMailboxExportJobErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CancelMailboxExportJobErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CancelMailboxExportJobErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
CancelMailboxExportJobErrorKind::EntityNotFoundException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
CancelMailboxExportJobErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
CancelMailboxExportJobErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
CancelMailboxExportJobErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for CancelMailboxExportJobError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CancelMailboxExportJobErrorKind::EntityNotFoundException(_inner) => Some(_inner),
CancelMailboxExportJobErrorKind::InvalidParameterException(_inner) => Some(_inner),
CancelMailboxExportJobErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
CancelMailboxExportJobErrorKind::OrganizationStateException(_inner) => Some(_inner),
CancelMailboxExportJobErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateAliasError {
pub kind: CreateAliasErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateAliasErrorKind {
EmailAddressInUseException(crate::error::EmailAddressInUseException),
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
LimitExceededException(crate::error::LimitExceededException),
MailDomainNotFoundException(crate::error::MailDomainNotFoundException),
MailDomainStateException(crate::error::MailDomainStateException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateAliasError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateAliasErrorKind::EmailAddressInUseException(_inner) => _inner.fmt(f),
CreateAliasErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
CreateAliasErrorKind::EntityStateException(_inner) => _inner.fmt(f),
CreateAliasErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
CreateAliasErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
CreateAliasErrorKind::MailDomainNotFoundException(_inner) => _inner.fmt(f),
CreateAliasErrorKind::MailDomainStateException(_inner) => _inner.fmt(f),
CreateAliasErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
CreateAliasErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
CreateAliasErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateAliasError {
fn code(&self) -> Option<&str> {
CreateAliasError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateAliasError {
pub fn new(kind: CreateAliasErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateAliasErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateAliasErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_email_address_in_use_exception(&self) -> bool {
matches!(
&self.kind,
CreateAliasErrorKind::EmailAddressInUseException(_)
)
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(&self.kind, CreateAliasErrorKind::EntityNotFoundException(_))
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(&self.kind, CreateAliasErrorKind::EntityStateException(_))
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
CreateAliasErrorKind::InvalidParameterException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, CreateAliasErrorKind::LimitExceededException(_))
}
pub fn is_mail_domain_not_found_exception(&self) -> bool {
matches!(
&self.kind,
CreateAliasErrorKind::MailDomainNotFoundException(_)
)
}
pub fn is_mail_domain_state_exception(&self) -> bool {
matches!(
&self.kind,
CreateAliasErrorKind::MailDomainStateException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
CreateAliasErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
CreateAliasErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for CreateAliasError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateAliasErrorKind::EmailAddressInUseException(_inner) => Some(_inner),
CreateAliasErrorKind::EntityNotFoundException(_inner) => Some(_inner),
CreateAliasErrorKind::EntityStateException(_inner) => Some(_inner),
CreateAliasErrorKind::InvalidParameterException(_inner) => Some(_inner),
CreateAliasErrorKind::LimitExceededException(_inner) => Some(_inner),
CreateAliasErrorKind::MailDomainNotFoundException(_inner) => Some(_inner),
CreateAliasErrorKind::MailDomainStateException(_inner) => Some(_inner),
CreateAliasErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
CreateAliasErrorKind::OrganizationStateException(_inner) => Some(_inner),
CreateAliasErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateGroupError {
pub kind: CreateGroupErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateGroupErrorKind {
DirectoryServiceAuthenticationFailedException(
crate::error::DirectoryServiceAuthenticationFailedException,
),
DirectoryUnavailableException(crate::error::DirectoryUnavailableException),
InvalidParameterException(crate::error::InvalidParameterException),
NameAvailabilityException(crate::error::NameAvailabilityException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
ReservedNameException(crate::error::ReservedNameException),
UnsupportedOperationException(crate::error::UnsupportedOperationException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateGroupError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateGroupErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
_inner.fmt(f)
}
CreateGroupErrorKind::DirectoryUnavailableException(_inner) => _inner.fmt(f),
CreateGroupErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
CreateGroupErrorKind::NameAvailabilityException(_inner) => _inner.fmt(f),
CreateGroupErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
CreateGroupErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
CreateGroupErrorKind::ReservedNameException(_inner) => _inner.fmt(f),
CreateGroupErrorKind::UnsupportedOperationException(_inner) => _inner.fmt(f),
CreateGroupErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateGroupError {
fn code(&self) -> Option<&str> {
CreateGroupError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateGroupError {
pub fn new(kind: CreateGroupErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateGroupErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateGroupErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_directory_service_authentication_failed_exception(&self) -> bool {
matches!(
&self.kind,
CreateGroupErrorKind::DirectoryServiceAuthenticationFailedException(_)
)
}
pub fn is_directory_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
CreateGroupErrorKind::DirectoryUnavailableException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
CreateGroupErrorKind::InvalidParameterException(_)
)
}
pub fn is_name_availability_exception(&self) -> bool {
matches!(
&self.kind,
CreateGroupErrorKind::NameAvailabilityException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
CreateGroupErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
CreateGroupErrorKind::OrganizationStateException(_)
)
}
pub fn is_reserved_name_exception(&self) -> bool {
matches!(&self.kind, CreateGroupErrorKind::ReservedNameException(_))
}
pub fn is_unsupported_operation_exception(&self) -> bool {
matches!(
&self.kind,
CreateGroupErrorKind::UnsupportedOperationException(_)
)
}
}
impl std::error::Error for CreateGroupError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateGroupErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
Some(_inner)
}
CreateGroupErrorKind::DirectoryUnavailableException(_inner) => Some(_inner),
CreateGroupErrorKind::InvalidParameterException(_inner) => Some(_inner),
CreateGroupErrorKind::NameAvailabilityException(_inner) => Some(_inner),
CreateGroupErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
CreateGroupErrorKind::OrganizationStateException(_inner) => Some(_inner),
CreateGroupErrorKind::ReservedNameException(_inner) => Some(_inner),
CreateGroupErrorKind::UnsupportedOperationException(_inner) => Some(_inner),
CreateGroupErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateMobileDeviceAccessRuleError {
pub kind: CreateMobileDeviceAccessRuleErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateMobileDeviceAccessRuleErrorKind {
InvalidParameterException(crate::error::InvalidParameterException),
LimitExceededException(crate::error::LimitExceededException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateMobileDeviceAccessRuleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateMobileDeviceAccessRuleErrorKind::InvalidParameterException(_inner) => {
_inner.fmt(f)
}
CreateMobileDeviceAccessRuleErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
CreateMobileDeviceAccessRuleErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
CreateMobileDeviceAccessRuleErrorKind::OrganizationStateException(_inner) => {
_inner.fmt(f)
}
CreateMobileDeviceAccessRuleErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateMobileDeviceAccessRuleError {
fn code(&self) -> Option<&str> {
CreateMobileDeviceAccessRuleError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateMobileDeviceAccessRuleError {
pub fn new(kind: CreateMobileDeviceAccessRuleErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateMobileDeviceAccessRuleErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateMobileDeviceAccessRuleErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
CreateMobileDeviceAccessRuleErrorKind::InvalidParameterException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateMobileDeviceAccessRuleErrorKind::LimitExceededException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
CreateMobileDeviceAccessRuleErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
CreateMobileDeviceAccessRuleErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for CreateMobileDeviceAccessRuleError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateMobileDeviceAccessRuleErrorKind::InvalidParameterException(_inner) => {
Some(_inner)
}
CreateMobileDeviceAccessRuleErrorKind::LimitExceededException(_inner) => Some(_inner),
CreateMobileDeviceAccessRuleErrorKind::OrganizationNotFoundException(_inner) => {
Some(_inner)
}
CreateMobileDeviceAccessRuleErrorKind::OrganizationStateException(_inner) => {
Some(_inner)
}
CreateMobileDeviceAccessRuleErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateOrganizationError {
pub kind: CreateOrganizationErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateOrganizationErrorKind {
DirectoryInUseException(crate::error::DirectoryInUseException),
DirectoryUnavailableException(crate::error::DirectoryUnavailableException),
InvalidParameterException(crate::error::InvalidParameterException),
LimitExceededException(crate::error::LimitExceededException),
NameAvailabilityException(crate::error::NameAvailabilityException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateOrganizationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateOrganizationErrorKind::DirectoryInUseException(_inner) => _inner.fmt(f),
CreateOrganizationErrorKind::DirectoryUnavailableException(_inner) => _inner.fmt(f),
CreateOrganizationErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
CreateOrganizationErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
CreateOrganizationErrorKind::NameAvailabilityException(_inner) => _inner.fmt(f),
CreateOrganizationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateOrganizationError {
fn code(&self) -> Option<&str> {
CreateOrganizationError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateOrganizationError {
pub fn new(kind: CreateOrganizationErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateOrganizationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateOrganizationErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_directory_in_use_exception(&self) -> bool {
matches!(
&self.kind,
CreateOrganizationErrorKind::DirectoryInUseException(_)
)
}
pub fn is_directory_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
CreateOrganizationErrorKind::DirectoryUnavailableException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
CreateOrganizationErrorKind::InvalidParameterException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateOrganizationErrorKind::LimitExceededException(_)
)
}
pub fn is_name_availability_exception(&self) -> bool {
matches!(
&self.kind,
CreateOrganizationErrorKind::NameAvailabilityException(_)
)
}
}
impl std::error::Error for CreateOrganizationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateOrganizationErrorKind::DirectoryInUseException(_inner) => Some(_inner),
CreateOrganizationErrorKind::DirectoryUnavailableException(_inner) => Some(_inner),
CreateOrganizationErrorKind::InvalidParameterException(_inner) => Some(_inner),
CreateOrganizationErrorKind::LimitExceededException(_inner) => Some(_inner),
CreateOrganizationErrorKind::NameAvailabilityException(_inner) => Some(_inner),
CreateOrganizationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateResourceError {
pub kind: CreateResourceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateResourceErrorKind {
DirectoryServiceAuthenticationFailedException(
crate::error::DirectoryServiceAuthenticationFailedException,
),
DirectoryUnavailableException(crate::error::DirectoryUnavailableException),
InvalidParameterException(crate::error::InvalidParameterException),
NameAvailabilityException(crate::error::NameAvailabilityException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
ReservedNameException(crate::error::ReservedNameException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateResourceErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
_inner.fmt(f)
}
CreateResourceErrorKind::DirectoryUnavailableException(_inner) => _inner.fmt(f),
CreateResourceErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
CreateResourceErrorKind::NameAvailabilityException(_inner) => _inner.fmt(f),
CreateResourceErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
CreateResourceErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
CreateResourceErrorKind::ReservedNameException(_inner) => _inner.fmt(f),
CreateResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateResourceError {
fn code(&self) -> Option<&str> {
CreateResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateResourceError {
pub fn new(kind: CreateResourceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateResourceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_directory_service_authentication_failed_exception(&self) -> bool {
matches!(
&self.kind,
CreateResourceErrorKind::DirectoryServiceAuthenticationFailedException(_)
)
}
pub fn is_directory_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
CreateResourceErrorKind::DirectoryUnavailableException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
CreateResourceErrorKind::InvalidParameterException(_)
)
}
pub fn is_name_availability_exception(&self) -> bool {
matches!(
&self.kind,
CreateResourceErrorKind::NameAvailabilityException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
CreateResourceErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
CreateResourceErrorKind::OrganizationStateException(_)
)
}
pub fn is_reserved_name_exception(&self) -> bool {
matches!(
&self.kind,
CreateResourceErrorKind::ReservedNameException(_)
)
}
}
impl std::error::Error for CreateResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateResourceErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
Some(_inner)
}
CreateResourceErrorKind::DirectoryUnavailableException(_inner) => Some(_inner),
CreateResourceErrorKind::InvalidParameterException(_inner) => Some(_inner),
CreateResourceErrorKind::NameAvailabilityException(_inner) => Some(_inner),
CreateResourceErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
CreateResourceErrorKind::OrganizationStateException(_inner) => Some(_inner),
CreateResourceErrorKind::ReservedNameException(_inner) => Some(_inner),
CreateResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateUserError {
pub kind: CreateUserErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateUserErrorKind {
DirectoryServiceAuthenticationFailedException(
crate::error::DirectoryServiceAuthenticationFailedException,
),
DirectoryUnavailableException(crate::error::DirectoryUnavailableException),
InvalidParameterException(crate::error::InvalidParameterException),
InvalidPasswordException(crate::error::InvalidPasswordException),
NameAvailabilityException(crate::error::NameAvailabilityException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
ReservedNameException(crate::error::ReservedNameException),
UnsupportedOperationException(crate::error::UnsupportedOperationException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateUserError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateUserErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
_inner.fmt(f)
}
CreateUserErrorKind::DirectoryUnavailableException(_inner) => _inner.fmt(f),
CreateUserErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
CreateUserErrorKind::InvalidPasswordException(_inner) => _inner.fmt(f),
CreateUserErrorKind::NameAvailabilityException(_inner) => _inner.fmt(f),
CreateUserErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
CreateUserErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
CreateUserErrorKind::ReservedNameException(_inner) => _inner.fmt(f),
CreateUserErrorKind::UnsupportedOperationException(_inner) => _inner.fmt(f),
CreateUserErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateUserError {
fn code(&self) -> Option<&str> {
CreateUserError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateUserError {
pub fn new(kind: CreateUserErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateUserErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateUserErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_directory_service_authentication_failed_exception(&self) -> bool {
matches!(
&self.kind,
CreateUserErrorKind::DirectoryServiceAuthenticationFailedException(_)
)
}
pub fn is_directory_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
CreateUserErrorKind::DirectoryUnavailableException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
CreateUserErrorKind::InvalidParameterException(_)
)
}
pub fn is_invalid_password_exception(&self) -> bool {
matches!(&self.kind, CreateUserErrorKind::InvalidPasswordException(_))
}
pub fn is_name_availability_exception(&self) -> bool {
matches!(
&self.kind,
CreateUserErrorKind::NameAvailabilityException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
CreateUserErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
CreateUserErrorKind::OrganizationStateException(_)
)
}
pub fn is_reserved_name_exception(&self) -> bool {
matches!(&self.kind, CreateUserErrorKind::ReservedNameException(_))
}
pub fn is_unsupported_operation_exception(&self) -> bool {
matches!(
&self.kind,
CreateUserErrorKind::UnsupportedOperationException(_)
)
}
}
impl std::error::Error for CreateUserError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateUserErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
Some(_inner)
}
CreateUserErrorKind::DirectoryUnavailableException(_inner) => Some(_inner),
CreateUserErrorKind::InvalidParameterException(_inner) => Some(_inner),
CreateUserErrorKind::InvalidPasswordException(_inner) => Some(_inner),
CreateUserErrorKind::NameAvailabilityException(_inner) => Some(_inner),
CreateUserErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
CreateUserErrorKind::OrganizationStateException(_inner) => Some(_inner),
CreateUserErrorKind::ReservedNameException(_inner) => Some(_inner),
CreateUserErrorKind::UnsupportedOperationException(_inner) => Some(_inner),
CreateUserErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteAccessControlRuleError {
pub kind: DeleteAccessControlRuleErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteAccessControlRuleErrorKind {
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteAccessControlRuleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteAccessControlRuleErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
DeleteAccessControlRuleErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DeleteAccessControlRuleErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteAccessControlRuleError {
fn code(&self) -> Option<&str> {
DeleteAccessControlRuleError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteAccessControlRuleError {
pub fn new(kind: DeleteAccessControlRuleErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteAccessControlRuleErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteAccessControlRuleErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteAccessControlRuleErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DeleteAccessControlRuleErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DeleteAccessControlRuleError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteAccessControlRuleErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
DeleteAccessControlRuleErrorKind::OrganizationStateException(_inner) => Some(_inner),
DeleteAccessControlRuleErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteAliasError {
pub kind: DeleteAliasErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteAliasErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteAliasError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteAliasErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
DeleteAliasErrorKind::EntityStateException(_inner) => _inner.fmt(f),
DeleteAliasErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DeleteAliasErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
DeleteAliasErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DeleteAliasErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteAliasError {
fn code(&self) -> Option<&str> {
DeleteAliasError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteAliasError {
pub fn new(kind: DeleteAliasErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteAliasErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteAliasErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(&self.kind, DeleteAliasErrorKind::EntityNotFoundException(_))
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(&self.kind, DeleteAliasErrorKind::EntityStateException(_))
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DeleteAliasErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteAliasErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DeleteAliasErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DeleteAliasError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteAliasErrorKind::EntityNotFoundException(_inner) => Some(_inner),
DeleteAliasErrorKind::EntityStateException(_inner) => Some(_inner),
DeleteAliasErrorKind::InvalidParameterException(_inner) => Some(_inner),
DeleteAliasErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
DeleteAliasErrorKind::OrganizationStateException(_inner) => Some(_inner),
DeleteAliasErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteGroupError {
pub kind: DeleteGroupErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteGroupErrorKind {
DirectoryServiceAuthenticationFailedException(
crate::error::DirectoryServiceAuthenticationFailedException,
),
DirectoryUnavailableException(crate::error::DirectoryUnavailableException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
UnsupportedOperationException(crate::error::UnsupportedOperationException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteGroupError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteGroupErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
_inner.fmt(f)
}
DeleteGroupErrorKind::DirectoryUnavailableException(_inner) => _inner.fmt(f),
DeleteGroupErrorKind::EntityStateException(_inner) => _inner.fmt(f),
DeleteGroupErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DeleteGroupErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
DeleteGroupErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DeleteGroupErrorKind::UnsupportedOperationException(_inner) => _inner.fmt(f),
DeleteGroupErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteGroupError {
fn code(&self) -> Option<&str> {
DeleteGroupError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteGroupError {
pub fn new(kind: DeleteGroupErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteGroupErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteGroupErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_directory_service_authentication_failed_exception(&self) -> bool {
matches!(
&self.kind,
DeleteGroupErrorKind::DirectoryServiceAuthenticationFailedException(_)
)
}
pub fn is_directory_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
DeleteGroupErrorKind::DirectoryUnavailableException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(&self.kind, DeleteGroupErrorKind::EntityStateException(_))
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DeleteGroupErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteGroupErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DeleteGroupErrorKind::OrganizationStateException(_)
)
}
pub fn is_unsupported_operation_exception(&self) -> bool {
matches!(
&self.kind,
DeleteGroupErrorKind::UnsupportedOperationException(_)
)
}
}
impl std::error::Error for DeleteGroupError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteGroupErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
Some(_inner)
}
DeleteGroupErrorKind::DirectoryUnavailableException(_inner) => Some(_inner),
DeleteGroupErrorKind::EntityStateException(_inner) => Some(_inner),
DeleteGroupErrorKind::InvalidParameterException(_inner) => Some(_inner),
DeleteGroupErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
DeleteGroupErrorKind::OrganizationStateException(_inner) => Some(_inner),
DeleteGroupErrorKind::UnsupportedOperationException(_inner) => Some(_inner),
DeleteGroupErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteMailboxPermissionsError {
pub kind: DeleteMailboxPermissionsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteMailboxPermissionsErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteMailboxPermissionsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteMailboxPermissionsErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
DeleteMailboxPermissionsErrorKind::EntityStateException(_inner) => _inner.fmt(f),
DeleteMailboxPermissionsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DeleteMailboxPermissionsErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
DeleteMailboxPermissionsErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DeleteMailboxPermissionsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteMailboxPermissionsError {
fn code(&self) -> Option<&str> {
DeleteMailboxPermissionsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteMailboxPermissionsError {
pub fn new(kind: DeleteMailboxPermissionsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteMailboxPermissionsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteMailboxPermissionsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteMailboxPermissionsErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(
&self.kind,
DeleteMailboxPermissionsErrorKind::EntityStateException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DeleteMailboxPermissionsErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteMailboxPermissionsErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DeleteMailboxPermissionsErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DeleteMailboxPermissionsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteMailboxPermissionsErrorKind::EntityNotFoundException(_inner) => Some(_inner),
DeleteMailboxPermissionsErrorKind::EntityStateException(_inner) => Some(_inner),
DeleteMailboxPermissionsErrorKind::InvalidParameterException(_inner) => Some(_inner),
DeleteMailboxPermissionsErrorKind::OrganizationNotFoundException(_inner) => {
Some(_inner)
}
DeleteMailboxPermissionsErrorKind::OrganizationStateException(_inner) => Some(_inner),
DeleteMailboxPermissionsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteMobileDeviceAccessRuleError {
pub kind: DeleteMobileDeviceAccessRuleErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteMobileDeviceAccessRuleErrorKind {
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteMobileDeviceAccessRuleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteMobileDeviceAccessRuleErrorKind::InvalidParameterException(_inner) => {
_inner.fmt(f)
}
DeleteMobileDeviceAccessRuleErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
DeleteMobileDeviceAccessRuleErrorKind::OrganizationStateException(_inner) => {
_inner.fmt(f)
}
DeleteMobileDeviceAccessRuleErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteMobileDeviceAccessRuleError {
fn code(&self) -> Option<&str> {
DeleteMobileDeviceAccessRuleError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteMobileDeviceAccessRuleError {
pub fn new(kind: DeleteMobileDeviceAccessRuleErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteMobileDeviceAccessRuleErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteMobileDeviceAccessRuleErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DeleteMobileDeviceAccessRuleErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteMobileDeviceAccessRuleErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DeleteMobileDeviceAccessRuleErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DeleteMobileDeviceAccessRuleError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteMobileDeviceAccessRuleErrorKind::InvalidParameterException(_inner) => {
Some(_inner)
}
DeleteMobileDeviceAccessRuleErrorKind::OrganizationNotFoundException(_inner) => {
Some(_inner)
}
DeleteMobileDeviceAccessRuleErrorKind::OrganizationStateException(_inner) => {
Some(_inner)
}
DeleteMobileDeviceAccessRuleErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteOrganizationError {
pub kind: DeleteOrganizationErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteOrganizationErrorKind {
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteOrganizationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteOrganizationErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DeleteOrganizationErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
DeleteOrganizationErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DeleteOrganizationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteOrganizationError {
fn code(&self) -> Option<&str> {
DeleteOrganizationError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteOrganizationError {
pub fn new(kind: DeleteOrganizationErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteOrganizationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteOrganizationErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DeleteOrganizationErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteOrganizationErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DeleteOrganizationErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DeleteOrganizationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteOrganizationErrorKind::InvalidParameterException(_inner) => Some(_inner),
DeleteOrganizationErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
DeleteOrganizationErrorKind::OrganizationStateException(_inner) => Some(_inner),
DeleteOrganizationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteResourceError {
pub kind: DeleteResourceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteResourceErrorKind {
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteResourceErrorKind::EntityStateException(_inner) => _inner.fmt(f),
DeleteResourceErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DeleteResourceErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
DeleteResourceErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DeleteResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteResourceError {
fn code(&self) -> Option<&str> {
DeleteResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteResourceError {
pub fn new(kind: DeleteResourceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteResourceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(&self.kind, DeleteResourceErrorKind::EntityStateException(_))
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DeleteResourceErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteResourceErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DeleteResourceErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DeleteResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteResourceErrorKind::EntityStateException(_inner) => Some(_inner),
DeleteResourceErrorKind::InvalidParameterException(_inner) => Some(_inner),
DeleteResourceErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
DeleteResourceErrorKind::OrganizationStateException(_inner) => Some(_inner),
DeleteResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteRetentionPolicyError {
pub kind: DeleteRetentionPolicyErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteRetentionPolicyErrorKind {
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteRetentionPolicyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteRetentionPolicyErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DeleteRetentionPolicyErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
DeleteRetentionPolicyErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DeleteRetentionPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteRetentionPolicyError {
fn code(&self) -> Option<&str> {
DeleteRetentionPolicyError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteRetentionPolicyError {
pub fn new(kind: DeleteRetentionPolicyErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteRetentionPolicyErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteRetentionPolicyErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DeleteRetentionPolicyErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteRetentionPolicyErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DeleteRetentionPolicyErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DeleteRetentionPolicyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteRetentionPolicyErrorKind::InvalidParameterException(_inner) => Some(_inner),
DeleteRetentionPolicyErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
DeleteRetentionPolicyErrorKind::OrganizationStateException(_inner) => Some(_inner),
DeleteRetentionPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteUserError {
pub kind: DeleteUserErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteUserErrorKind {
DirectoryServiceAuthenticationFailedException(
crate::error::DirectoryServiceAuthenticationFailedException,
),
DirectoryUnavailableException(crate::error::DirectoryUnavailableException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
UnsupportedOperationException(crate::error::UnsupportedOperationException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteUserError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteUserErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
_inner.fmt(f)
}
DeleteUserErrorKind::DirectoryUnavailableException(_inner) => _inner.fmt(f),
DeleteUserErrorKind::EntityStateException(_inner) => _inner.fmt(f),
DeleteUserErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DeleteUserErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
DeleteUserErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DeleteUserErrorKind::UnsupportedOperationException(_inner) => _inner.fmt(f),
DeleteUserErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteUserError {
fn code(&self) -> Option<&str> {
DeleteUserError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteUserError {
pub fn new(kind: DeleteUserErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteUserErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteUserErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_directory_service_authentication_failed_exception(&self) -> bool {
matches!(
&self.kind,
DeleteUserErrorKind::DirectoryServiceAuthenticationFailedException(_)
)
}
pub fn is_directory_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
DeleteUserErrorKind::DirectoryUnavailableException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(&self.kind, DeleteUserErrorKind::EntityStateException(_))
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DeleteUserErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteUserErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DeleteUserErrorKind::OrganizationStateException(_)
)
}
pub fn is_unsupported_operation_exception(&self) -> bool {
matches!(
&self.kind,
DeleteUserErrorKind::UnsupportedOperationException(_)
)
}
}
impl std::error::Error for DeleteUserError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteUserErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
Some(_inner)
}
DeleteUserErrorKind::DirectoryUnavailableException(_inner) => Some(_inner),
DeleteUserErrorKind::EntityStateException(_inner) => Some(_inner),
DeleteUserErrorKind::InvalidParameterException(_inner) => Some(_inner),
DeleteUserErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
DeleteUserErrorKind::OrganizationStateException(_inner) => Some(_inner),
DeleteUserErrorKind::UnsupportedOperationException(_inner) => Some(_inner),
DeleteUserErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeregisterFromWorkMailError {
pub kind: DeregisterFromWorkMailErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeregisterFromWorkMailErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeregisterFromWorkMailError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeregisterFromWorkMailErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
DeregisterFromWorkMailErrorKind::EntityStateException(_inner) => _inner.fmt(f),
DeregisterFromWorkMailErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DeregisterFromWorkMailErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
DeregisterFromWorkMailErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DeregisterFromWorkMailErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeregisterFromWorkMailError {
fn code(&self) -> Option<&str> {
DeregisterFromWorkMailError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeregisterFromWorkMailError {
pub fn new(kind: DeregisterFromWorkMailErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeregisterFromWorkMailErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeregisterFromWorkMailErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeregisterFromWorkMailErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(
&self.kind,
DeregisterFromWorkMailErrorKind::EntityStateException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DeregisterFromWorkMailErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeregisterFromWorkMailErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DeregisterFromWorkMailErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DeregisterFromWorkMailError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeregisterFromWorkMailErrorKind::EntityNotFoundException(_inner) => Some(_inner),
DeregisterFromWorkMailErrorKind::EntityStateException(_inner) => Some(_inner),
DeregisterFromWorkMailErrorKind::InvalidParameterException(_inner) => Some(_inner),
DeregisterFromWorkMailErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
DeregisterFromWorkMailErrorKind::OrganizationStateException(_inner) => Some(_inner),
DeregisterFromWorkMailErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DescribeGroupError {
pub kind: DescribeGroupErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DescribeGroupErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DescribeGroupError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DescribeGroupErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
DescribeGroupErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DescribeGroupErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
DescribeGroupErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DescribeGroupErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DescribeGroupError {
fn code(&self) -> Option<&str> {
DescribeGroupError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DescribeGroupError {
pub fn new(kind: DescribeGroupErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DescribeGroupErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DescribeGroupErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DescribeGroupErrorKind::EntityNotFoundException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DescribeGroupErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DescribeGroupErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DescribeGroupErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DescribeGroupError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DescribeGroupErrorKind::EntityNotFoundException(_inner) => Some(_inner),
DescribeGroupErrorKind::InvalidParameterException(_inner) => Some(_inner),
DescribeGroupErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
DescribeGroupErrorKind::OrganizationStateException(_inner) => Some(_inner),
DescribeGroupErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DescribeMailboxExportJobError {
pub kind: DescribeMailboxExportJobErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DescribeMailboxExportJobErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DescribeMailboxExportJobError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DescribeMailboxExportJobErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
DescribeMailboxExportJobErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DescribeMailboxExportJobErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
DescribeMailboxExportJobErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DescribeMailboxExportJobErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DescribeMailboxExportJobError {
fn code(&self) -> Option<&str> {
DescribeMailboxExportJobError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DescribeMailboxExportJobError {
pub fn new(kind: DescribeMailboxExportJobErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DescribeMailboxExportJobErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DescribeMailboxExportJobErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DescribeMailboxExportJobErrorKind::EntityNotFoundException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DescribeMailboxExportJobErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DescribeMailboxExportJobErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DescribeMailboxExportJobErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DescribeMailboxExportJobError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DescribeMailboxExportJobErrorKind::EntityNotFoundException(_inner) => Some(_inner),
DescribeMailboxExportJobErrorKind::InvalidParameterException(_inner) => Some(_inner),
DescribeMailboxExportJobErrorKind::OrganizationNotFoundException(_inner) => {
Some(_inner)
}
DescribeMailboxExportJobErrorKind::OrganizationStateException(_inner) => Some(_inner),
DescribeMailboxExportJobErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DescribeOrganizationError {
pub kind: DescribeOrganizationErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DescribeOrganizationErrorKind {
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DescribeOrganizationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DescribeOrganizationErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DescribeOrganizationErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
DescribeOrganizationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DescribeOrganizationError {
fn code(&self) -> Option<&str> {
DescribeOrganizationError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DescribeOrganizationError {
pub fn new(kind: DescribeOrganizationErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DescribeOrganizationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DescribeOrganizationErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DescribeOrganizationErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DescribeOrganizationErrorKind::OrganizationNotFoundException(_)
)
}
}
impl std::error::Error for DescribeOrganizationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DescribeOrganizationErrorKind::InvalidParameterException(_inner) => Some(_inner),
DescribeOrganizationErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
DescribeOrganizationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DescribeResourceError {
pub kind: DescribeResourceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DescribeResourceErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DescribeResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DescribeResourceErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
DescribeResourceErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DescribeResourceErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
DescribeResourceErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DescribeResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DescribeResourceError {
fn code(&self) -> Option<&str> {
DescribeResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DescribeResourceError {
pub fn new(kind: DescribeResourceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DescribeResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DescribeResourceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DescribeResourceErrorKind::EntityNotFoundException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DescribeResourceErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DescribeResourceErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DescribeResourceErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DescribeResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DescribeResourceErrorKind::EntityNotFoundException(_inner) => Some(_inner),
DescribeResourceErrorKind::InvalidParameterException(_inner) => Some(_inner),
DescribeResourceErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
DescribeResourceErrorKind::OrganizationStateException(_inner) => Some(_inner),
DescribeResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DescribeUserError {
pub kind: DescribeUserErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DescribeUserErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DescribeUserError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DescribeUserErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
DescribeUserErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
DescribeUserErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
DescribeUserErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
DescribeUserErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DescribeUserError {
fn code(&self) -> Option<&str> {
DescribeUserError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DescribeUserError {
pub fn new(kind: DescribeUserErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DescribeUserErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DescribeUserErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DescribeUserErrorKind::EntityNotFoundException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DescribeUserErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DescribeUserErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DescribeUserErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DescribeUserError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DescribeUserErrorKind::EntityNotFoundException(_inner) => Some(_inner),
DescribeUserErrorKind::InvalidParameterException(_inner) => Some(_inner),
DescribeUserErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
DescribeUserErrorKind::OrganizationStateException(_inner) => Some(_inner),
DescribeUserErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DisassociateDelegateFromResourceError {
pub kind: DisassociateDelegateFromResourceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DisassociateDelegateFromResourceErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DisassociateDelegateFromResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DisassociateDelegateFromResourceErrorKind::EntityNotFoundException(_inner) => {
_inner.fmt(f)
}
DisassociateDelegateFromResourceErrorKind::EntityStateException(_inner) => {
_inner.fmt(f)
}
DisassociateDelegateFromResourceErrorKind::InvalidParameterException(_inner) => {
_inner.fmt(f)
}
DisassociateDelegateFromResourceErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
DisassociateDelegateFromResourceErrorKind::OrganizationStateException(_inner) => {
_inner.fmt(f)
}
DisassociateDelegateFromResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DisassociateDelegateFromResourceError {
fn code(&self) -> Option<&str> {
DisassociateDelegateFromResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DisassociateDelegateFromResourceError {
pub fn new(kind: DisassociateDelegateFromResourceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DisassociateDelegateFromResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DisassociateDelegateFromResourceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateDelegateFromResourceErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateDelegateFromResourceErrorKind::EntityStateException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateDelegateFromResourceErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateDelegateFromResourceErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateDelegateFromResourceErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for DisassociateDelegateFromResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DisassociateDelegateFromResourceErrorKind::EntityNotFoundException(_inner) => {
Some(_inner)
}
DisassociateDelegateFromResourceErrorKind::EntityStateException(_inner) => Some(_inner),
DisassociateDelegateFromResourceErrorKind::InvalidParameterException(_inner) => {
Some(_inner)
}
DisassociateDelegateFromResourceErrorKind::OrganizationNotFoundException(_inner) => {
Some(_inner)
}
DisassociateDelegateFromResourceErrorKind::OrganizationStateException(_inner) => {
Some(_inner)
}
DisassociateDelegateFromResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DisassociateMemberFromGroupError {
pub kind: DisassociateMemberFromGroupErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DisassociateMemberFromGroupErrorKind {
DirectoryServiceAuthenticationFailedException(
crate::error::DirectoryServiceAuthenticationFailedException,
),
DirectoryUnavailableException(crate::error::DirectoryUnavailableException),
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
UnsupportedOperationException(crate::error::UnsupportedOperationException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DisassociateMemberFromGroupError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DisassociateMemberFromGroupErrorKind::DirectoryServiceAuthenticationFailedException(
_inner,
) => _inner.fmt(f),
DisassociateMemberFromGroupErrorKind::DirectoryUnavailableException(_inner) => {
_inner.fmt(f)
}
DisassociateMemberFromGroupErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
DisassociateMemberFromGroupErrorKind::EntityStateException(_inner) => _inner.fmt(f),
DisassociateMemberFromGroupErrorKind::InvalidParameterException(_inner) => {
_inner.fmt(f)
}
DisassociateMemberFromGroupErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
DisassociateMemberFromGroupErrorKind::OrganizationStateException(_inner) => {
_inner.fmt(f)
}
DisassociateMemberFromGroupErrorKind::UnsupportedOperationException(_inner) => {
_inner.fmt(f)
}
DisassociateMemberFromGroupErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DisassociateMemberFromGroupError {
fn code(&self) -> Option<&str> {
DisassociateMemberFromGroupError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DisassociateMemberFromGroupError {
pub fn new(kind: DisassociateMemberFromGroupErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DisassociateMemberFromGroupErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DisassociateMemberFromGroupErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_directory_service_authentication_failed_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateMemberFromGroupErrorKind::DirectoryServiceAuthenticationFailedException(_)
)
}
pub fn is_directory_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateMemberFromGroupErrorKind::DirectoryUnavailableException(_)
)
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateMemberFromGroupErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateMemberFromGroupErrorKind::EntityStateException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateMemberFromGroupErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateMemberFromGroupErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateMemberFromGroupErrorKind::OrganizationStateException(_)
)
}
pub fn is_unsupported_operation_exception(&self) -> bool {
matches!(
&self.kind,
DisassociateMemberFromGroupErrorKind::UnsupportedOperationException(_)
)
}
}
impl std::error::Error for DisassociateMemberFromGroupError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DisassociateMemberFromGroupErrorKind::DirectoryServiceAuthenticationFailedException(
_inner,
) => Some(_inner),
DisassociateMemberFromGroupErrorKind::DirectoryUnavailableException(_inner) => {
Some(_inner)
}
DisassociateMemberFromGroupErrorKind::EntityNotFoundException(_inner) => Some(_inner),
DisassociateMemberFromGroupErrorKind::EntityStateException(_inner) => Some(_inner),
DisassociateMemberFromGroupErrorKind::InvalidParameterException(_inner) => Some(_inner),
DisassociateMemberFromGroupErrorKind::OrganizationNotFoundException(_inner) => {
Some(_inner)
}
DisassociateMemberFromGroupErrorKind::OrganizationStateException(_inner) => {
Some(_inner)
}
DisassociateMemberFromGroupErrorKind::UnsupportedOperationException(_inner) => {
Some(_inner)
}
DisassociateMemberFromGroupErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetAccessControlEffectError {
pub kind: GetAccessControlEffectErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetAccessControlEffectErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetAccessControlEffectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetAccessControlEffectErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
GetAccessControlEffectErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
GetAccessControlEffectErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
GetAccessControlEffectErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
GetAccessControlEffectErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetAccessControlEffectError {
fn code(&self) -> Option<&str> {
GetAccessControlEffectError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetAccessControlEffectError {
pub fn new(kind: GetAccessControlEffectErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetAccessControlEffectErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetAccessControlEffectErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetAccessControlEffectErrorKind::EntityNotFoundException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
GetAccessControlEffectErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetAccessControlEffectErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
GetAccessControlEffectErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for GetAccessControlEffectError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetAccessControlEffectErrorKind::EntityNotFoundException(_inner) => Some(_inner),
GetAccessControlEffectErrorKind::InvalidParameterException(_inner) => Some(_inner),
GetAccessControlEffectErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
GetAccessControlEffectErrorKind::OrganizationStateException(_inner) => Some(_inner),
GetAccessControlEffectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetDefaultRetentionPolicyError {
pub kind: GetDefaultRetentionPolicyErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetDefaultRetentionPolicyErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetDefaultRetentionPolicyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetDefaultRetentionPolicyErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
GetDefaultRetentionPolicyErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
GetDefaultRetentionPolicyErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
GetDefaultRetentionPolicyErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
GetDefaultRetentionPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetDefaultRetentionPolicyError {
fn code(&self) -> Option<&str> {
GetDefaultRetentionPolicyError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetDefaultRetentionPolicyError {
pub fn new(kind: GetDefaultRetentionPolicyErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetDefaultRetentionPolicyErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetDefaultRetentionPolicyErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetDefaultRetentionPolicyErrorKind::EntityNotFoundException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
GetDefaultRetentionPolicyErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetDefaultRetentionPolicyErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
GetDefaultRetentionPolicyErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for GetDefaultRetentionPolicyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetDefaultRetentionPolicyErrorKind::EntityNotFoundException(_inner) => Some(_inner),
GetDefaultRetentionPolicyErrorKind::InvalidParameterException(_inner) => Some(_inner),
GetDefaultRetentionPolicyErrorKind::OrganizationNotFoundException(_inner) => {
Some(_inner)
}
GetDefaultRetentionPolicyErrorKind::OrganizationStateException(_inner) => Some(_inner),
GetDefaultRetentionPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetMailboxDetailsError {
pub kind: GetMailboxDetailsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetMailboxDetailsErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetMailboxDetailsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetMailboxDetailsErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
GetMailboxDetailsErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
GetMailboxDetailsErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
GetMailboxDetailsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetMailboxDetailsError {
fn code(&self) -> Option<&str> {
GetMailboxDetailsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetMailboxDetailsError {
pub fn new(kind: GetMailboxDetailsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetMailboxDetailsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetMailboxDetailsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetMailboxDetailsErrorKind::EntityNotFoundException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetMailboxDetailsErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
GetMailboxDetailsErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for GetMailboxDetailsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetMailboxDetailsErrorKind::EntityNotFoundException(_inner) => Some(_inner),
GetMailboxDetailsErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
GetMailboxDetailsErrorKind::OrganizationStateException(_inner) => Some(_inner),
GetMailboxDetailsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetMobileDeviceAccessEffectError {
pub kind: GetMobileDeviceAccessEffectErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetMobileDeviceAccessEffectErrorKind {
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetMobileDeviceAccessEffectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetMobileDeviceAccessEffectErrorKind::InvalidParameterException(_inner) => {
_inner.fmt(f)
}
GetMobileDeviceAccessEffectErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
GetMobileDeviceAccessEffectErrorKind::OrganizationStateException(_inner) => {
_inner.fmt(f)
}
GetMobileDeviceAccessEffectErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetMobileDeviceAccessEffectError {
fn code(&self) -> Option<&str> {
GetMobileDeviceAccessEffectError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetMobileDeviceAccessEffectError {
pub fn new(kind: GetMobileDeviceAccessEffectErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetMobileDeviceAccessEffectErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetMobileDeviceAccessEffectErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
GetMobileDeviceAccessEffectErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetMobileDeviceAccessEffectErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
GetMobileDeviceAccessEffectErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for GetMobileDeviceAccessEffectError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetMobileDeviceAccessEffectErrorKind::InvalidParameterException(_inner) => Some(_inner),
GetMobileDeviceAccessEffectErrorKind::OrganizationNotFoundException(_inner) => {
Some(_inner)
}
GetMobileDeviceAccessEffectErrorKind::OrganizationStateException(_inner) => {
Some(_inner)
}
GetMobileDeviceAccessEffectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListAccessControlRulesError {
pub kind: ListAccessControlRulesErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListAccessControlRulesErrorKind {
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListAccessControlRulesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListAccessControlRulesErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
ListAccessControlRulesErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
ListAccessControlRulesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListAccessControlRulesError {
fn code(&self) -> Option<&str> {
ListAccessControlRulesError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListAccessControlRulesError {
pub fn new(kind: ListAccessControlRulesErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListAccessControlRulesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListAccessControlRulesErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListAccessControlRulesErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
ListAccessControlRulesErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for ListAccessControlRulesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListAccessControlRulesErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
ListAccessControlRulesErrorKind::OrganizationStateException(_inner) => Some(_inner),
ListAccessControlRulesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListAliasesError {
pub kind: ListAliasesErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListAliasesErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListAliasesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListAliasesErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
ListAliasesErrorKind::EntityStateException(_inner) => _inner.fmt(f),
ListAliasesErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
ListAliasesErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
ListAliasesErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
ListAliasesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListAliasesError {
fn code(&self) -> Option<&str> {
ListAliasesError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListAliasesError {
pub fn new(kind: ListAliasesErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListAliasesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListAliasesErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(&self.kind, ListAliasesErrorKind::EntityNotFoundException(_))
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(&self.kind, ListAliasesErrorKind::EntityStateException(_))
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
ListAliasesErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListAliasesErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
ListAliasesErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for ListAliasesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListAliasesErrorKind::EntityNotFoundException(_inner) => Some(_inner),
ListAliasesErrorKind::EntityStateException(_inner) => Some(_inner),
ListAliasesErrorKind::InvalidParameterException(_inner) => Some(_inner),
ListAliasesErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
ListAliasesErrorKind::OrganizationStateException(_inner) => Some(_inner),
ListAliasesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListGroupMembersError {
pub kind: ListGroupMembersErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListGroupMembersErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListGroupMembersError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListGroupMembersErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
ListGroupMembersErrorKind::EntityStateException(_inner) => _inner.fmt(f),
ListGroupMembersErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
ListGroupMembersErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
ListGroupMembersErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
ListGroupMembersErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListGroupMembersError {
fn code(&self) -> Option<&str> {
ListGroupMembersError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListGroupMembersError {
pub fn new(kind: ListGroupMembersErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListGroupMembersErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListGroupMembersErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListGroupMembersErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(
&self.kind,
ListGroupMembersErrorKind::EntityStateException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
ListGroupMembersErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListGroupMembersErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
ListGroupMembersErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for ListGroupMembersError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListGroupMembersErrorKind::EntityNotFoundException(_inner) => Some(_inner),
ListGroupMembersErrorKind::EntityStateException(_inner) => Some(_inner),
ListGroupMembersErrorKind::InvalidParameterException(_inner) => Some(_inner),
ListGroupMembersErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
ListGroupMembersErrorKind::OrganizationStateException(_inner) => Some(_inner),
ListGroupMembersErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListGroupsError {
pub kind: ListGroupsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListGroupsErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListGroupsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListGroupsErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
ListGroupsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
ListGroupsErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
ListGroupsErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
ListGroupsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListGroupsError {
fn code(&self) -> Option<&str> {
ListGroupsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListGroupsError {
pub fn new(kind: ListGroupsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListGroupsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListGroupsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(&self.kind, ListGroupsErrorKind::EntityNotFoundException(_))
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
ListGroupsErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListGroupsErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
ListGroupsErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for ListGroupsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListGroupsErrorKind::EntityNotFoundException(_inner) => Some(_inner),
ListGroupsErrorKind::InvalidParameterException(_inner) => Some(_inner),
ListGroupsErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
ListGroupsErrorKind::OrganizationStateException(_inner) => Some(_inner),
ListGroupsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListMailboxExportJobsError {
pub kind: ListMailboxExportJobsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListMailboxExportJobsErrorKind {
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListMailboxExportJobsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListMailboxExportJobsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
ListMailboxExportJobsErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
ListMailboxExportJobsErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
ListMailboxExportJobsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListMailboxExportJobsError {
fn code(&self) -> Option<&str> {
ListMailboxExportJobsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListMailboxExportJobsError {
pub fn new(kind: ListMailboxExportJobsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListMailboxExportJobsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListMailboxExportJobsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
ListMailboxExportJobsErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListMailboxExportJobsErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
ListMailboxExportJobsErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for ListMailboxExportJobsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListMailboxExportJobsErrorKind::InvalidParameterException(_inner) => Some(_inner),
ListMailboxExportJobsErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
ListMailboxExportJobsErrorKind::OrganizationStateException(_inner) => Some(_inner),
ListMailboxExportJobsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListMailboxPermissionsError {
pub kind: ListMailboxPermissionsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListMailboxPermissionsErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListMailboxPermissionsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListMailboxPermissionsErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
ListMailboxPermissionsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
ListMailboxPermissionsErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
ListMailboxPermissionsErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
ListMailboxPermissionsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListMailboxPermissionsError {
fn code(&self) -> Option<&str> {
ListMailboxPermissionsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListMailboxPermissionsError {
pub fn new(kind: ListMailboxPermissionsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListMailboxPermissionsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListMailboxPermissionsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListMailboxPermissionsErrorKind::EntityNotFoundException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
ListMailboxPermissionsErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListMailboxPermissionsErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
ListMailboxPermissionsErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for ListMailboxPermissionsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListMailboxPermissionsErrorKind::EntityNotFoundException(_inner) => Some(_inner),
ListMailboxPermissionsErrorKind::InvalidParameterException(_inner) => Some(_inner),
ListMailboxPermissionsErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
ListMailboxPermissionsErrorKind::OrganizationStateException(_inner) => Some(_inner),
ListMailboxPermissionsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListMobileDeviceAccessRulesError {
pub kind: ListMobileDeviceAccessRulesErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListMobileDeviceAccessRulesErrorKind {
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListMobileDeviceAccessRulesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListMobileDeviceAccessRulesErrorKind::InvalidParameterException(_inner) => {
_inner.fmt(f)
}
ListMobileDeviceAccessRulesErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
ListMobileDeviceAccessRulesErrorKind::OrganizationStateException(_inner) => {
_inner.fmt(f)
}
ListMobileDeviceAccessRulesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListMobileDeviceAccessRulesError {
fn code(&self) -> Option<&str> {
ListMobileDeviceAccessRulesError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListMobileDeviceAccessRulesError {
pub fn new(kind: ListMobileDeviceAccessRulesErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListMobileDeviceAccessRulesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListMobileDeviceAccessRulesErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
ListMobileDeviceAccessRulesErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListMobileDeviceAccessRulesErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
ListMobileDeviceAccessRulesErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for ListMobileDeviceAccessRulesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListMobileDeviceAccessRulesErrorKind::InvalidParameterException(_inner) => Some(_inner),
ListMobileDeviceAccessRulesErrorKind::OrganizationNotFoundException(_inner) => {
Some(_inner)
}
ListMobileDeviceAccessRulesErrorKind::OrganizationStateException(_inner) => {
Some(_inner)
}
ListMobileDeviceAccessRulesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListOrganizationsError {
pub kind: ListOrganizationsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListOrganizationsErrorKind {
InvalidParameterException(crate::error::InvalidParameterException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListOrganizationsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListOrganizationsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
ListOrganizationsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListOrganizationsError {
fn code(&self) -> Option<&str> {
ListOrganizationsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListOrganizationsError {
pub fn new(kind: ListOrganizationsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListOrganizationsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListOrganizationsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
ListOrganizationsErrorKind::InvalidParameterException(_)
)
}
}
impl std::error::Error for ListOrganizationsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListOrganizationsErrorKind::InvalidParameterException(_inner) => Some(_inner),
ListOrganizationsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListResourceDelegatesError {
pub kind: ListResourceDelegatesErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListResourceDelegatesErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListResourceDelegatesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListResourceDelegatesErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
ListResourceDelegatesErrorKind::EntityStateException(_inner) => _inner.fmt(f),
ListResourceDelegatesErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
ListResourceDelegatesErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
ListResourceDelegatesErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
ListResourceDelegatesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListResourceDelegatesError {
fn code(&self) -> Option<&str> {
ListResourceDelegatesError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListResourceDelegatesError {
pub fn new(kind: ListResourceDelegatesErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListResourceDelegatesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListResourceDelegatesErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListResourceDelegatesErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(
&self.kind,
ListResourceDelegatesErrorKind::EntityStateException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
ListResourceDelegatesErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListResourceDelegatesErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
ListResourceDelegatesErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for ListResourceDelegatesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListResourceDelegatesErrorKind::EntityNotFoundException(_inner) => Some(_inner),
ListResourceDelegatesErrorKind::EntityStateException(_inner) => Some(_inner),
ListResourceDelegatesErrorKind::InvalidParameterException(_inner) => Some(_inner),
ListResourceDelegatesErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
ListResourceDelegatesErrorKind::OrganizationStateException(_inner) => Some(_inner),
ListResourceDelegatesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListResourcesError {
pub kind: ListResourcesErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListResourcesErrorKind {
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListResourcesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListResourcesErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
ListResourcesErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
ListResourcesErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
ListResourcesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListResourcesError {
fn code(&self) -> Option<&str> {
ListResourcesError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListResourcesError {
pub fn new(kind: ListResourcesErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListResourcesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListResourcesErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
ListResourcesErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListResourcesErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
ListResourcesErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for ListResourcesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListResourcesErrorKind::InvalidParameterException(_inner) => Some(_inner),
ListResourcesErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
ListResourcesErrorKind::OrganizationStateException(_inner) => Some(_inner),
ListResourcesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListTagsForResourceError {
pub kind: ListTagsForResourceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListTagsForResourceErrorKind {
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListTagsForResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListTagsForResourceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
ListTagsForResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListTagsForResourceError {
fn code(&self) -> Option<&str> {
ListTagsForResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListTagsForResourceError {
pub fn new(kind: ListTagsForResourceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListTagsForResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListTagsForResourceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListTagsForResourceErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for ListTagsForResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListTagsForResourceErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
ListTagsForResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListUsersError {
pub kind: ListUsersErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListUsersErrorKind {
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListUsersError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListUsersErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
ListUsersErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
ListUsersErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
ListUsersErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListUsersError {
fn code(&self) -> Option<&str> {
ListUsersError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListUsersError {
pub fn new(kind: ListUsersErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListUsersErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListUsersErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(&self.kind, ListUsersErrorKind::InvalidParameterException(_))
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListUsersErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
ListUsersErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for ListUsersError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListUsersErrorKind::InvalidParameterException(_inner) => Some(_inner),
ListUsersErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
ListUsersErrorKind::OrganizationStateException(_inner) => Some(_inner),
ListUsersErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct PutAccessControlRuleError {
pub kind: PutAccessControlRuleErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum PutAccessControlRuleErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
InvalidParameterException(crate::error::InvalidParameterException),
LimitExceededException(crate::error::LimitExceededException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for PutAccessControlRuleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
PutAccessControlRuleErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
PutAccessControlRuleErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
PutAccessControlRuleErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
PutAccessControlRuleErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
PutAccessControlRuleErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
PutAccessControlRuleErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for PutAccessControlRuleError {
fn code(&self) -> Option<&str> {
PutAccessControlRuleError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl PutAccessControlRuleError {
pub fn new(kind: PutAccessControlRuleErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: PutAccessControlRuleErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: PutAccessControlRuleErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
PutAccessControlRuleErrorKind::EntityNotFoundException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
PutAccessControlRuleErrorKind::InvalidParameterException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
PutAccessControlRuleErrorKind::LimitExceededException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
PutAccessControlRuleErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
PutAccessControlRuleErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for PutAccessControlRuleError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
PutAccessControlRuleErrorKind::EntityNotFoundException(_inner) => Some(_inner),
PutAccessControlRuleErrorKind::InvalidParameterException(_inner) => Some(_inner),
PutAccessControlRuleErrorKind::LimitExceededException(_inner) => Some(_inner),
PutAccessControlRuleErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
PutAccessControlRuleErrorKind::OrganizationStateException(_inner) => Some(_inner),
PutAccessControlRuleErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct PutMailboxPermissionsError {
pub kind: PutMailboxPermissionsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum PutMailboxPermissionsErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for PutMailboxPermissionsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
PutMailboxPermissionsErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
PutMailboxPermissionsErrorKind::EntityStateException(_inner) => _inner.fmt(f),
PutMailboxPermissionsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
PutMailboxPermissionsErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
PutMailboxPermissionsErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
PutMailboxPermissionsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for PutMailboxPermissionsError {
fn code(&self) -> Option<&str> {
PutMailboxPermissionsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl PutMailboxPermissionsError {
pub fn new(kind: PutMailboxPermissionsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: PutMailboxPermissionsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: PutMailboxPermissionsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
PutMailboxPermissionsErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(
&self.kind,
PutMailboxPermissionsErrorKind::EntityStateException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
PutMailboxPermissionsErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
PutMailboxPermissionsErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
PutMailboxPermissionsErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for PutMailboxPermissionsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
PutMailboxPermissionsErrorKind::EntityNotFoundException(_inner) => Some(_inner),
PutMailboxPermissionsErrorKind::EntityStateException(_inner) => Some(_inner),
PutMailboxPermissionsErrorKind::InvalidParameterException(_inner) => Some(_inner),
PutMailboxPermissionsErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
PutMailboxPermissionsErrorKind::OrganizationStateException(_inner) => Some(_inner),
PutMailboxPermissionsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct PutRetentionPolicyError {
pub kind: PutRetentionPolicyErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum PutRetentionPolicyErrorKind {
InvalidParameterException(crate::error::InvalidParameterException),
LimitExceededException(crate::error::LimitExceededException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for PutRetentionPolicyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
PutRetentionPolicyErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
PutRetentionPolicyErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
PutRetentionPolicyErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
PutRetentionPolicyErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
PutRetentionPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for PutRetentionPolicyError {
fn code(&self) -> Option<&str> {
PutRetentionPolicyError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl PutRetentionPolicyError {
pub fn new(kind: PutRetentionPolicyErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: PutRetentionPolicyErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: PutRetentionPolicyErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
PutRetentionPolicyErrorKind::InvalidParameterException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
PutRetentionPolicyErrorKind::LimitExceededException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
PutRetentionPolicyErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
PutRetentionPolicyErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for PutRetentionPolicyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
PutRetentionPolicyErrorKind::InvalidParameterException(_inner) => Some(_inner),
PutRetentionPolicyErrorKind::LimitExceededException(_inner) => Some(_inner),
PutRetentionPolicyErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
PutRetentionPolicyErrorKind::OrganizationStateException(_inner) => Some(_inner),
PutRetentionPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct RegisterToWorkMailError {
pub kind: RegisterToWorkMailErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum RegisterToWorkMailErrorKind {
DirectoryServiceAuthenticationFailedException(
crate::error::DirectoryServiceAuthenticationFailedException,
),
DirectoryUnavailableException(crate::error::DirectoryUnavailableException),
EmailAddressInUseException(crate::error::EmailAddressInUseException),
EntityAlreadyRegisteredException(crate::error::EntityAlreadyRegisteredException),
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
MailDomainNotFoundException(crate::error::MailDomainNotFoundException),
MailDomainStateException(crate::error::MailDomainStateException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for RegisterToWorkMailError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
RegisterToWorkMailErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
_inner.fmt(f)
}
RegisterToWorkMailErrorKind::DirectoryUnavailableException(_inner) => _inner.fmt(f),
RegisterToWorkMailErrorKind::EmailAddressInUseException(_inner) => _inner.fmt(f),
RegisterToWorkMailErrorKind::EntityAlreadyRegisteredException(_inner) => _inner.fmt(f),
RegisterToWorkMailErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
RegisterToWorkMailErrorKind::EntityStateException(_inner) => _inner.fmt(f),
RegisterToWorkMailErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
RegisterToWorkMailErrorKind::MailDomainNotFoundException(_inner) => _inner.fmt(f),
RegisterToWorkMailErrorKind::MailDomainStateException(_inner) => _inner.fmt(f),
RegisterToWorkMailErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
RegisterToWorkMailErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
RegisterToWorkMailErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for RegisterToWorkMailError {
fn code(&self) -> Option<&str> {
RegisterToWorkMailError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl RegisterToWorkMailError {
pub fn new(kind: RegisterToWorkMailErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: RegisterToWorkMailErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: RegisterToWorkMailErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_directory_service_authentication_failed_exception(&self) -> bool {
matches!(
&self.kind,
RegisterToWorkMailErrorKind::DirectoryServiceAuthenticationFailedException(_)
)
}
pub fn is_directory_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
RegisterToWorkMailErrorKind::DirectoryUnavailableException(_)
)
}
pub fn is_email_address_in_use_exception(&self) -> bool {
matches!(
&self.kind,
RegisterToWorkMailErrorKind::EmailAddressInUseException(_)
)
}
pub fn is_entity_already_registered_exception(&self) -> bool {
matches!(
&self.kind,
RegisterToWorkMailErrorKind::EntityAlreadyRegisteredException(_)
)
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
RegisterToWorkMailErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(
&self.kind,
RegisterToWorkMailErrorKind::EntityStateException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
RegisterToWorkMailErrorKind::InvalidParameterException(_)
)
}
pub fn is_mail_domain_not_found_exception(&self) -> bool {
matches!(
&self.kind,
RegisterToWorkMailErrorKind::MailDomainNotFoundException(_)
)
}
pub fn is_mail_domain_state_exception(&self) -> bool {
matches!(
&self.kind,
RegisterToWorkMailErrorKind::MailDomainStateException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
RegisterToWorkMailErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
RegisterToWorkMailErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for RegisterToWorkMailError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
RegisterToWorkMailErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
Some(_inner)
}
RegisterToWorkMailErrorKind::DirectoryUnavailableException(_inner) => Some(_inner),
RegisterToWorkMailErrorKind::EmailAddressInUseException(_inner) => Some(_inner),
RegisterToWorkMailErrorKind::EntityAlreadyRegisteredException(_inner) => Some(_inner),
RegisterToWorkMailErrorKind::EntityNotFoundException(_inner) => Some(_inner),
RegisterToWorkMailErrorKind::EntityStateException(_inner) => Some(_inner),
RegisterToWorkMailErrorKind::InvalidParameterException(_inner) => Some(_inner),
RegisterToWorkMailErrorKind::MailDomainNotFoundException(_inner) => Some(_inner),
RegisterToWorkMailErrorKind::MailDomainStateException(_inner) => Some(_inner),
RegisterToWorkMailErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
RegisterToWorkMailErrorKind::OrganizationStateException(_inner) => Some(_inner),
RegisterToWorkMailErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ResetPasswordError {
pub kind: ResetPasswordErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ResetPasswordErrorKind {
DirectoryServiceAuthenticationFailedException(
crate::error::DirectoryServiceAuthenticationFailedException,
),
DirectoryUnavailableException(crate::error::DirectoryUnavailableException),
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
InvalidPasswordException(crate::error::InvalidPasswordException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
UnsupportedOperationException(crate::error::UnsupportedOperationException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ResetPasswordError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ResetPasswordErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
_inner.fmt(f)
}
ResetPasswordErrorKind::DirectoryUnavailableException(_inner) => _inner.fmt(f),
ResetPasswordErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
ResetPasswordErrorKind::EntityStateException(_inner) => _inner.fmt(f),
ResetPasswordErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
ResetPasswordErrorKind::InvalidPasswordException(_inner) => _inner.fmt(f),
ResetPasswordErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
ResetPasswordErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
ResetPasswordErrorKind::UnsupportedOperationException(_inner) => _inner.fmt(f),
ResetPasswordErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ResetPasswordError {
fn code(&self) -> Option<&str> {
ResetPasswordError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ResetPasswordError {
pub fn new(kind: ResetPasswordErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ResetPasswordErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ResetPasswordErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_directory_service_authentication_failed_exception(&self) -> bool {
matches!(
&self.kind,
ResetPasswordErrorKind::DirectoryServiceAuthenticationFailedException(_)
)
}
pub fn is_directory_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ResetPasswordErrorKind::DirectoryUnavailableException(_)
)
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ResetPasswordErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(&self.kind, ResetPasswordErrorKind::EntityStateException(_))
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
ResetPasswordErrorKind::InvalidParameterException(_)
)
}
pub fn is_invalid_password_exception(&self) -> bool {
matches!(
&self.kind,
ResetPasswordErrorKind::InvalidPasswordException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ResetPasswordErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
ResetPasswordErrorKind::OrganizationStateException(_)
)
}
pub fn is_unsupported_operation_exception(&self) -> bool {
matches!(
&self.kind,
ResetPasswordErrorKind::UnsupportedOperationException(_)
)
}
}
impl std::error::Error for ResetPasswordError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ResetPasswordErrorKind::DirectoryServiceAuthenticationFailedException(_inner) => {
Some(_inner)
}
ResetPasswordErrorKind::DirectoryUnavailableException(_inner) => Some(_inner),
ResetPasswordErrorKind::EntityNotFoundException(_inner) => Some(_inner),
ResetPasswordErrorKind::EntityStateException(_inner) => Some(_inner),
ResetPasswordErrorKind::InvalidParameterException(_inner) => Some(_inner),
ResetPasswordErrorKind::InvalidPasswordException(_inner) => Some(_inner),
ResetPasswordErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
ResetPasswordErrorKind::OrganizationStateException(_inner) => Some(_inner),
ResetPasswordErrorKind::UnsupportedOperationException(_inner) => Some(_inner),
ResetPasswordErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct StartMailboxExportJobError {
pub kind: StartMailboxExportJobErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum StartMailboxExportJobErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
InvalidParameterException(crate::error::InvalidParameterException),
LimitExceededException(crate::error::LimitExceededException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for StartMailboxExportJobError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
StartMailboxExportJobErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
StartMailboxExportJobErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
StartMailboxExportJobErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
StartMailboxExportJobErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
StartMailboxExportJobErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
StartMailboxExportJobErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for StartMailboxExportJobError {
fn code(&self) -> Option<&str> {
StartMailboxExportJobError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl StartMailboxExportJobError {
pub fn new(kind: StartMailboxExportJobErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: StartMailboxExportJobErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: StartMailboxExportJobErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
StartMailboxExportJobErrorKind::EntityNotFoundException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
StartMailboxExportJobErrorKind::InvalidParameterException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
StartMailboxExportJobErrorKind::LimitExceededException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
StartMailboxExportJobErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
StartMailboxExportJobErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for StartMailboxExportJobError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
StartMailboxExportJobErrorKind::EntityNotFoundException(_inner) => Some(_inner),
StartMailboxExportJobErrorKind::InvalidParameterException(_inner) => Some(_inner),
StartMailboxExportJobErrorKind::LimitExceededException(_inner) => Some(_inner),
StartMailboxExportJobErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
StartMailboxExportJobErrorKind::OrganizationStateException(_inner) => Some(_inner),
StartMailboxExportJobErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct TagResourceError {
pub kind: TagResourceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum TagResourceErrorKind {
OrganizationStateException(crate::error::OrganizationStateException),
ResourceNotFoundException(crate::error::ResourceNotFoundException),
TooManyTagsException(crate::error::TooManyTagsException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for TagResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
TagResourceErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
TagResourceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
TagResourceErrorKind::TooManyTagsException(_inner) => _inner.fmt(f),
TagResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for TagResourceError {
fn code(&self) -> Option<&str> {
TagResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl TagResourceError {
pub fn new(kind: TagResourceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: TagResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: TagResourceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
TagResourceErrorKind::OrganizationStateException(_)
)
}
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
TagResourceErrorKind::ResourceNotFoundException(_)
)
}
pub fn is_too_many_tags_exception(&self) -> bool {
matches!(&self.kind, TagResourceErrorKind::TooManyTagsException(_))
}
}
impl std::error::Error for TagResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
TagResourceErrorKind::OrganizationStateException(_inner) => Some(_inner),
TagResourceErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
TagResourceErrorKind::TooManyTagsException(_inner) => Some(_inner),
TagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UntagResourceError {
pub kind: UntagResourceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UntagResourceErrorKind {
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UntagResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UntagResourceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
UntagResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UntagResourceError {
fn code(&self) -> Option<&str> {
UntagResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UntagResourceError {
pub fn new(kind: UntagResourceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UntagResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UntagResourceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UntagResourceErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for UntagResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UntagResourceErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
UntagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateMailboxQuotaError {
pub kind: UpdateMailboxQuotaErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateMailboxQuotaErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdateMailboxQuotaError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateMailboxQuotaErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
UpdateMailboxQuotaErrorKind::EntityStateException(_inner) => _inner.fmt(f),
UpdateMailboxQuotaErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
UpdateMailboxQuotaErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
UpdateMailboxQuotaErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
UpdateMailboxQuotaErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UpdateMailboxQuotaError {
fn code(&self) -> Option<&str> {
UpdateMailboxQuotaError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateMailboxQuotaError {
pub fn new(kind: UpdateMailboxQuotaErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateMailboxQuotaErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateMailboxQuotaErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateMailboxQuotaErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(
&self.kind,
UpdateMailboxQuotaErrorKind::EntityStateException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
UpdateMailboxQuotaErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateMailboxQuotaErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
UpdateMailboxQuotaErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for UpdateMailboxQuotaError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateMailboxQuotaErrorKind::EntityNotFoundException(_inner) => Some(_inner),
UpdateMailboxQuotaErrorKind::EntityStateException(_inner) => Some(_inner),
UpdateMailboxQuotaErrorKind::InvalidParameterException(_inner) => Some(_inner),
UpdateMailboxQuotaErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
UpdateMailboxQuotaErrorKind::OrganizationStateException(_inner) => Some(_inner),
UpdateMailboxQuotaErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateMobileDeviceAccessRuleError {
pub kind: UpdateMobileDeviceAccessRuleErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateMobileDeviceAccessRuleErrorKind {
EntityNotFoundException(crate::error::EntityNotFoundException),
InvalidParameterException(crate::error::InvalidParameterException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdateMobileDeviceAccessRuleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateMobileDeviceAccessRuleErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
UpdateMobileDeviceAccessRuleErrorKind::InvalidParameterException(_inner) => {
_inner.fmt(f)
}
UpdateMobileDeviceAccessRuleErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
UpdateMobileDeviceAccessRuleErrorKind::OrganizationStateException(_inner) => {
_inner.fmt(f)
}
UpdateMobileDeviceAccessRuleErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UpdateMobileDeviceAccessRuleError {
fn code(&self) -> Option<&str> {
UpdateMobileDeviceAccessRuleError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateMobileDeviceAccessRuleError {
pub fn new(kind: UpdateMobileDeviceAccessRuleErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateMobileDeviceAccessRuleErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateMobileDeviceAccessRuleErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateMobileDeviceAccessRuleErrorKind::EntityNotFoundException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
UpdateMobileDeviceAccessRuleErrorKind::InvalidParameterException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateMobileDeviceAccessRuleErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
UpdateMobileDeviceAccessRuleErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for UpdateMobileDeviceAccessRuleError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateMobileDeviceAccessRuleErrorKind::EntityNotFoundException(_inner) => Some(_inner),
UpdateMobileDeviceAccessRuleErrorKind::InvalidParameterException(_inner) => {
Some(_inner)
}
UpdateMobileDeviceAccessRuleErrorKind::OrganizationNotFoundException(_inner) => {
Some(_inner)
}
UpdateMobileDeviceAccessRuleErrorKind::OrganizationStateException(_inner) => {
Some(_inner)
}
UpdateMobileDeviceAccessRuleErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdatePrimaryEmailAddressError {
pub kind: UpdatePrimaryEmailAddressErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdatePrimaryEmailAddressErrorKind {
DirectoryServiceAuthenticationFailedException(
crate::error::DirectoryServiceAuthenticationFailedException,
),
DirectoryUnavailableException(crate::error::DirectoryUnavailableException),
EmailAddressInUseException(crate::error::EmailAddressInUseException),
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidParameterException(crate::error::InvalidParameterException),
MailDomainNotFoundException(crate::error::MailDomainNotFoundException),
MailDomainStateException(crate::error::MailDomainStateException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
UnsupportedOperationException(crate::error::UnsupportedOperationException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdatePrimaryEmailAddressError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdatePrimaryEmailAddressErrorKind::DirectoryServiceAuthenticationFailedException(
_inner,
) => _inner.fmt(f),
UpdatePrimaryEmailAddressErrorKind::DirectoryUnavailableException(_inner) => {
_inner.fmt(f)
}
UpdatePrimaryEmailAddressErrorKind::EmailAddressInUseException(_inner) => _inner.fmt(f),
UpdatePrimaryEmailAddressErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
UpdatePrimaryEmailAddressErrorKind::EntityStateException(_inner) => _inner.fmt(f),
UpdatePrimaryEmailAddressErrorKind::InvalidParameterException(_inner) => _inner.fmt(f),
UpdatePrimaryEmailAddressErrorKind::MailDomainNotFoundException(_inner) => {
_inner.fmt(f)
}
UpdatePrimaryEmailAddressErrorKind::MailDomainStateException(_inner) => _inner.fmt(f),
UpdatePrimaryEmailAddressErrorKind::OrganizationNotFoundException(_inner) => {
_inner.fmt(f)
}
UpdatePrimaryEmailAddressErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
UpdatePrimaryEmailAddressErrorKind::UnsupportedOperationException(_inner) => {
_inner.fmt(f)
}
UpdatePrimaryEmailAddressErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UpdatePrimaryEmailAddressError {
fn code(&self) -> Option<&str> {
UpdatePrimaryEmailAddressError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UpdatePrimaryEmailAddressError {
pub fn new(kind: UpdatePrimaryEmailAddressErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdatePrimaryEmailAddressErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdatePrimaryEmailAddressErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_directory_service_authentication_failed_exception(&self) -> bool {
matches!(
&self.kind,
UpdatePrimaryEmailAddressErrorKind::DirectoryServiceAuthenticationFailedException(_)
)
}
pub fn is_directory_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
UpdatePrimaryEmailAddressErrorKind::DirectoryUnavailableException(_)
)
}
pub fn is_email_address_in_use_exception(&self) -> bool {
matches!(
&self.kind,
UpdatePrimaryEmailAddressErrorKind::EmailAddressInUseException(_)
)
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdatePrimaryEmailAddressErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(
&self.kind,
UpdatePrimaryEmailAddressErrorKind::EntityStateException(_)
)
}
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
UpdatePrimaryEmailAddressErrorKind::InvalidParameterException(_)
)
}
pub fn is_mail_domain_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdatePrimaryEmailAddressErrorKind::MailDomainNotFoundException(_)
)
}
pub fn is_mail_domain_state_exception(&self) -> bool {
matches!(
&self.kind,
UpdatePrimaryEmailAddressErrorKind::MailDomainStateException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdatePrimaryEmailAddressErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
UpdatePrimaryEmailAddressErrorKind::OrganizationStateException(_)
)
}
pub fn is_unsupported_operation_exception(&self) -> bool {
matches!(
&self.kind,
UpdatePrimaryEmailAddressErrorKind::UnsupportedOperationException(_)
)
}
}
impl std::error::Error for UpdatePrimaryEmailAddressError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdatePrimaryEmailAddressErrorKind::DirectoryServiceAuthenticationFailedException(
_inner,
) => Some(_inner),
UpdatePrimaryEmailAddressErrorKind::DirectoryUnavailableException(_inner) => {
Some(_inner)
}
UpdatePrimaryEmailAddressErrorKind::EmailAddressInUseException(_inner) => Some(_inner),
UpdatePrimaryEmailAddressErrorKind::EntityNotFoundException(_inner) => Some(_inner),
UpdatePrimaryEmailAddressErrorKind::EntityStateException(_inner) => Some(_inner),
UpdatePrimaryEmailAddressErrorKind::InvalidParameterException(_inner) => Some(_inner),
UpdatePrimaryEmailAddressErrorKind::MailDomainNotFoundException(_inner) => Some(_inner),
UpdatePrimaryEmailAddressErrorKind::MailDomainStateException(_inner) => Some(_inner),
UpdatePrimaryEmailAddressErrorKind::OrganizationNotFoundException(_inner) => {
Some(_inner)
}
UpdatePrimaryEmailAddressErrorKind::OrganizationStateException(_inner) => Some(_inner),
UpdatePrimaryEmailAddressErrorKind::UnsupportedOperationException(_inner) => {
Some(_inner)
}
UpdatePrimaryEmailAddressErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateResourceError {
pub kind: UpdateResourceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateResourceErrorKind {
DirectoryUnavailableException(crate::error::DirectoryUnavailableException),
EmailAddressInUseException(crate::error::EmailAddressInUseException),
EntityNotFoundException(crate::error::EntityNotFoundException),
EntityStateException(crate::error::EntityStateException),
InvalidConfigurationException(crate::error::InvalidConfigurationException),
MailDomainNotFoundException(crate::error::MailDomainNotFoundException),
MailDomainStateException(crate::error::MailDomainStateException),
NameAvailabilityException(crate::error::NameAvailabilityException),
OrganizationNotFoundException(crate::error::OrganizationNotFoundException),
OrganizationStateException(crate::error::OrganizationStateException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdateResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateResourceErrorKind::DirectoryUnavailableException(_inner) => _inner.fmt(f),
UpdateResourceErrorKind::EmailAddressInUseException(_inner) => _inner.fmt(f),
UpdateResourceErrorKind::EntityNotFoundException(_inner) => _inner.fmt(f),
UpdateResourceErrorKind::EntityStateException(_inner) => _inner.fmt(f),
UpdateResourceErrorKind::InvalidConfigurationException(_inner) => _inner.fmt(f),
UpdateResourceErrorKind::MailDomainNotFoundException(_inner) => _inner.fmt(f),
UpdateResourceErrorKind::MailDomainStateException(_inner) => _inner.fmt(f),
UpdateResourceErrorKind::NameAvailabilityException(_inner) => _inner.fmt(f),
UpdateResourceErrorKind::OrganizationNotFoundException(_inner) => _inner.fmt(f),
UpdateResourceErrorKind::OrganizationStateException(_inner) => _inner.fmt(f),
UpdateResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UpdateResourceError {
fn code(&self) -> Option<&str> {
UpdateResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateResourceError {
pub fn new(kind: UpdateResourceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateResourceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display as implemented
// by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_directory_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
UpdateResourceErrorKind::DirectoryUnavailableException(_)
)
}
pub fn is_email_address_in_use_exception(&self) -> bool {
matches!(
&self.kind,
UpdateResourceErrorKind::EmailAddressInUseException(_)
)
}
pub fn is_entity_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateResourceErrorKind::EntityNotFoundException(_)
)
}
pub fn is_entity_state_exception(&self) -> bool {
matches!(&self.kind, UpdateResourceErrorKind::EntityStateException(_))
}
pub fn is_invalid_configuration_exception(&self) -> bool {
matches!(
&self.kind,
UpdateResourceErrorKind::InvalidConfigurationException(_)
)
}
pub fn is_mail_domain_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateResourceErrorKind::MailDomainNotFoundException(_)
)
}
pub fn is_mail_domain_state_exception(&self) -> bool {
matches!(
&self.kind,
UpdateResourceErrorKind::MailDomainStateException(_)
)
}
pub fn is_name_availability_exception(&self) -> bool {
matches!(
&self.kind,
UpdateResourceErrorKind::NameAvailabilityException(_)
)
}
pub fn is_organization_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateResourceErrorKind::OrganizationNotFoundException(_)
)
}
pub fn is_organization_state_exception(&self) -> bool {
matches!(
&self.kind,
UpdateResourceErrorKind::OrganizationStateException(_)
)
}
}
impl std::error::Error for UpdateResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateResourceErrorKind::DirectoryUnavailableException(_inner) => Some(_inner),
UpdateResourceErrorKind::EmailAddressInUseException(_inner) => Some(_inner),
UpdateResourceErrorKind::EntityNotFoundException(_inner) => Some(_inner),
UpdateResourceErrorKind::EntityStateException(_inner) => Some(_inner),
UpdateResourceErrorKind::InvalidConfigurationException(_inner) => Some(_inner),
UpdateResourceErrorKind::MailDomainNotFoundException(_inner) => Some(_inner),
UpdateResourceErrorKind::MailDomainStateException(_inner) => Some(_inner),
UpdateResourceErrorKind::NameAvailabilityException(_inner) => Some(_inner),
UpdateResourceErrorKind::OrganizationNotFoundException(_inner) => Some(_inner),
UpdateResourceErrorKind::OrganizationStateException(_inner) => Some(_inner),
UpdateResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// <p>The organization must have a valid state to perform certain
/// operations on the organization or its members.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct OrganizationStateException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for OrganizationStateException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("OrganizationStateException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl OrganizationStateException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for OrganizationStateException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "OrganizationStateException")?;
if let Some(inner_1) = &self.message {
write!(f, ": {}", inner_1)?;
}
Ok(())
}
}
impl std::error::Error for OrganizationStateException {}
/// See [`OrganizationStateException`](crate::error::OrganizationStateException)
pub mod organization_state_exception {
/// A builder for [`OrganizationStateException`](crate::error::OrganizationStateException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`OrganizationStateException`](crate::error::OrganizationStateException)
pub fn build(self) -> crate::error::OrganizationStateException {
crate::error::OrganizationStateException {
message: self.message,
}
}
}
}
impl OrganizationStateException {
/// Creates a new builder-style object to manufacture [`OrganizationStateException`](crate::error::OrganizationStateException)
pub fn builder() -> crate::error::organization_state_exception::Builder {
crate::error::organization_state_exception::Builder::default()
}
}
/// <p>An operation received a valid organization identifier that either doesn't belong or
/// exist in the system.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct OrganizationNotFoundException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for OrganizationNotFoundException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("OrganizationNotFoundException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl OrganizationNotFoundException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for OrganizationNotFoundException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "OrganizationNotFoundException")?;
if let Some(inner_2) = &self.message {
write!(f, ": {}", inner_2)?;
}
Ok(())
}
}
impl std::error::Error for OrganizationNotFoundException {}
/// See [`OrganizationNotFoundException`](crate::error::OrganizationNotFoundException)
pub mod organization_not_found_exception {
/// A builder for [`OrganizationNotFoundException`](crate::error::OrganizationNotFoundException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`OrganizationNotFoundException`](crate::error::OrganizationNotFoundException)
pub fn build(self) -> crate::error::OrganizationNotFoundException {
crate::error::OrganizationNotFoundException {
message: self.message,
}
}
}
}
impl OrganizationNotFoundException {
/// Creates a new builder-style object to manufacture [`OrganizationNotFoundException`](crate::error::OrganizationNotFoundException)
pub fn builder() -> crate::error::organization_not_found_exception::Builder {
crate::error::organization_not_found_exception::Builder::default()
}
}
/// <p>The user, group, or resource name isn't unique in Amazon WorkMail.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct NameAvailabilityException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for NameAvailabilityException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("NameAvailabilityException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl NameAvailabilityException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for NameAvailabilityException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "NameAvailabilityException")?;
if let Some(inner_3) = &self.message {
write!(f, ": {}", inner_3)?;
}
Ok(())
}
}
impl std::error::Error for NameAvailabilityException {}
/// See [`NameAvailabilityException`](crate::error::NameAvailabilityException)
pub mod name_availability_exception {
/// A builder for [`NameAvailabilityException`](crate::error::NameAvailabilityException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`NameAvailabilityException`](crate::error::NameAvailabilityException)
pub fn build(self) -> crate::error::NameAvailabilityException {
crate::error::NameAvailabilityException {
message: self.message,
}
}
}
}
impl NameAvailabilityException {
/// Creates a new builder-style object to manufacture [`NameAvailabilityException`](crate::error::NameAvailabilityException)
pub fn builder() -> crate::error::name_availability_exception::Builder {
crate::error::name_availability_exception::Builder::default()
}
}
/// <p>After a domain has been added to the organization, it must be verified. The domain is
/// not yet verified.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct MailDomainStateException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for MailDomainStateException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("MailDomainStateException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl MailDomainStateException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for MailDomainStateException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "MailDomainStateException")?;
if let Some(inner_4) = &self.message {
write!(f, ": {}", inner_4)?;
}
Ok(())
}
}
impl std::error::Error for MailDomainStateException {}
/// See [`MailDomainStateException`](crate::error::MailDomainStateException)
pub mod mail_domain_state_exception {
/// A builder for [`MailDomainStateException`](crate::error::MailDomainStateException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`MailDomainStateException`](crate::error::MailDomainStateException)
pub fn build(self) -> crate::error::MailDomainStateException {
crate::error::MailDomainStateException {
message: self.message,
}
}
}
}
impl MailDomainStateException {
/// Creates a new builder-style object to manufacture [`MailDomainStateException`](crate::error::MailDomainStateException)
pub fn builder() -> crate::error::mail_domain_state_exception::Builder {
crate::error::mail_domain_state_exception::Builder::default()
}
}
/// <p>For an email or alias to be created in Amazon WorkMail, the included domain must be defined
/// in the organization.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct MailDomainNotFoundException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for MailDomainNotFoundException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("MailDomainNotFoundException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl MailDomainNotFoundException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for MailDomainNotFoundException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "MailDomainNotFoundException")?;
if let Some(inner_5) = &self.message {
write!(f, ": {}", inner_5)?;
}
Ok(())
}
}
impl std::error::Error for MailDomainNotFoundException {}
/// See [`MailDomainNotFoundException`](crate::error::MailDomainNotFoundException)
pub mod mail_domain_not_found_exception {
/// A builder for [`MailDomainNotFoundException`](crate::error::MailDomainNotFoundException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`MailDomainNotFoundException`](crate::error::MailDomainNotFoundException)
pub fn build(self) -> crate::error::MailDomainNotFoundException {
crate::error::MailDomainNotFoundException {
message: self.message,
}
}
}
}
impl MailDomainNotFoundException {
/// Creates a new builder-style object to manufacture [`MailDomainNotFoundException`](crate::error::MailDomainNotFoundException)
pub fn builder() -> crate::error::mail_domain_not_found_exception::Builder {
crate::error::mail_domain_not_found_exception::Builder::default()
}
}
/// <p>The configuration for a resource isn't valid. A resource must either be able to
/// auto-respond to requests or have at least one delegate associated that can do so on its
/// behalf.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InvalidConfigurationException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for InvalidConfigurationException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("InvalidConfigurationException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl InvalidConfigurationException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for InvalidConfigurationException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InvalidConfigurationException")?;
if let Some(inner_6) = &self.message {
write!(f, ": {}", inner_6)?;
}
Ok(())
}
}
impl std::error::Error for InvalidConfigurationException {}
/// See [`InvalidConfigurationException`](crate::error::InvalidConfigurationException)
pub mod invalid_configuration_exception {
/// A builder for [`InvalidConfigurationException`](crate::error::InvalidConfigurationException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`InvalidConfigurationException`](crate::error::InvalidConfigurationException)
pub fn build(self) -> crate::error::InvalidConfigurationException {
crate::error::InvalidConfigurationException {
message: self.message,
}
}
}
}
impl InvalidConfigurationException {
/// Creates a new builder-style object to manufacture [`InvalidConfigurationException`](crate::error::InvalidConfigurationException)
pub fn builder() -> crate::error::invalid_configuration_exception::Builder {
crate::error::invalid_configuration_exception::Builder::default()
}
}
/// <p>You are performing an operation on a user, group, or resource that isn't in the
/// expected state, such as trying to delete an active user.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct EntityStateException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for EntityStateException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("EntityStateException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl EntityStateException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for EntityStateException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "EntityStateException")?;
if let Some(inner_7) = &self.message {
write!(f, ": {}", inner_7)?;
}
Ok(())
}
}
impl std::error::Error for EntityStateException {}
/// See [`EntityStateException`](crate::error::EntityStateException)
pub mod entity_state_exception {
/// A builder for [`EntityStateException`](crate::error::EntityStateException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`EntityStateException`](crate::error::EntityStateException)
pub fn build(self) -> crate::error::EntityStateException {
crate::error::EntityStateException {
message: self.message,
}
}
}
}
impl EntityStateException {
/// Creates a new builder-style object to manufacture [`EntityStateException`](crate::error::EntityStateException)
pub fn builder() -> crate::error::entity_state_exception::Builder {
crate::error::entity_state_exception::Builder::default()
}
}
/// <p>The identifier supplied for the user, group, or resource does not exist in your
/// organization.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct EntityNotFoundException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for EntityNotFoundException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("EntityNotFoundException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl EntityNotFoundException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for EntityNotFoundException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "EntityNotFoundException")?;
if let Some(inner_8) = &self.message {
write!(f, ": {}", inner_8)?;
}
Ok(())
}
}
impl std::error::Error for EntityNotFoundException {}
/// See [`EntityNotFoundException`](crate::error::EntityNotFoundException)
pub mod entity_not_found_exception {
/// A builder for [`EntityNotFoundException`](crate::error::EntityNotFoundException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`EntityNotFoundException`](crate::error::EntityNotFoundException)
pub fn build(self) -> crate::error::EntityNotFoundException {
crate::error::EntityNotFoundException {
message: self.message,
}
}
}
}
impl EntityNotFoundException {
/// Creates a new builder-style object to manufacture [`EntityNotFoundException`](crate::error::EntityNotFoundException)
pub fn builder() -> crate::error::entity_not_found_exception::Builder {
crate::error::entity_not_found_exception::Builder::default()
}
}
/// <p>The email address that you're trying to assign is already created for a different
/// user, group, or resource.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct EmailAddressInUseException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for EmailAddressInUseException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("EmailAddressInUseException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl EmailAddressInUseException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for EmailAddressInUseException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "EmailAddressInUseException")?;
if let Some(inner_9) = &self.message {
write!(f, ": {}", inner_9)?;
}
Ok(())
}
}
impl std::error::Error for EmailAddressInUseException {}
/// See [`EmailAddressInUseException`](crate::error::EmailAddressInUseException)
pub mod email_address_in_use_exception {
/// A builder for [`EmailAddressInUseException`](crate::error::EmailAddressInUseException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`EmailAddressInUseException`](crate::error::EmailAddressInUseException)
pub fn build(self) -> crate::error::EmailAddressInUseException {
crate::error::EmailAddressInUseException {
message: self.message,
}
}
}
}
impl EmailAddressInUseException {
/// Creates a new builder-style object to manufacture [`EmailAddressInUseException`](crate::error::EmailAddressInUseException)
pub fn builder() -> crate::error::email_address_in_use_exception::Builder {
crate::error::email_address_in_use_exception::Builder::default()
}
}
/// <p>The directory is unavailable. It might be located in another Region or deleted.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DirectoryUnavailableException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for DirectoryUnavailableException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DirectoryUnavailableException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl DirectoryUnavailableException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for DirectoryUnavailableException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "DirectoryUnavailableException")?;
if let Some(inner_10) = &self.message {
write!(f, ": {}", inner_10)?;
}
Ok(())
}
}
impl std::error::Error for DirectoryUnavailableException {}
/// See [`DirectoryUnavailableException`](crate::error::DirectoryUnavailableException)
pub mod directory_unavailable_exception {
/// A builder for [`DirectoryUnavailableException`](crate::error::DirectoryUnavailableException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`DirectoryUnavailableException`](crate::error::DirectoryUnavailableException)
pub fn build(self) -> crate::error::DirectoryUnavailableException {
crate::error::DirectoryUnavailableException {
message: self.message,
}
}
}
}
impl DirectoryUnavailableException {
/// Creates a new builder-style object to manufacture [`DirectoryUnavailableException`](crate::error::DirectoryUnavailableException)
pub fn builder() -> crate::error::directory_unavailable_exception::Builder {
crate::error::directory_unavailable_exception::Builder::default()
}
}
/// <p>You can't perform a write operation against a read-only directory.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UnsupportedOperationException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for UnsupportedOperationException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UnsupportedOperationException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl UnsupportedOperationException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for UnsupportedOperationException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "UnsupportedOperationException")?;
if let Some(inner_11) = &self.message {
write!(f, ": {}", inner_11)?;
}
Ok(())
}
}
impl std::error::Error for UnsupportedOperationException {}
/// See [`UnsupportedOperationException`](crate::error::UnsupportedOperationException)
pub mod unsupported_operation_exception {
/// A builder for [`UnsupportedOperationException`](crate::error::UnsupportedOperationException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`UnsupportedOperationException`](crate::error::UnsupportedOperationException)
pub fn build(self) -> crate::error::UnsupportedOperationException {
crate::error::UnsupportedOperationException {
message: self.message,
}
}
}
}
impl UnsupportedOperationException {
/// Creates a new builder-style object to manufacture [`UnsupportedOperationException`](crate::error::UnsupportedOperationException)
pub fn builder() -> crate::error::unsupported_operation_exception::Builder {
crate::error::unsupported_operation_exception::Builder::default()
}
}
/// <p>One or more of the input parameters don't match the service's restrictions.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InvalidParameterException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for InvalidParameterException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("InvalidParameterException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl InvalidParameterException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for InvalidParameterException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InvalidParameterException")?;
if let Some(inner_12) = &self.message {
write!(f, ": {}", inner_12)?;
}
Ok(())
}
}
impl std::error::Error for InvalidParameterException {}
/// See [`InvalidParameterException`](crate::error::InvalidParameterException)
pub mod invalid_parameter_exception {
/// A builder for [`InvalidParameterException`](crate::error::InvalidParameterException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`InvalidParameterException`](crate::error::InvalidParameterException)
pub fn build(self) -> crate::error::InvalidParameterException {
crate::error::InvalidParameterException {
message: self.message,
}
}
}
}
impl InvalidParameterException {
/// Creates a new builder-style object to manufacture [`InvalidParameterException`](crate::error::InvalidParameterException)
pub fn builder() -> crate::error::invalid_parameter_exception::Builder {
crate::error::invalid_parameter_exception::Builder::default()
}
}
/// <p>The directory service doesn't recognize the credentials supplied by WorkMail.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DirectoryServiceAuthenticationFailedException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for DirectoryServiceAuthenticationFailedException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DirectoryServiceAuthenticationFailedException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl DirectoryServiceAuthenticationFailedException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for DirectoryServiceAuthenticationFailedException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "DirectoryServiceAuthenticationFailedException")?;
if let Some(inner_13) = &self.message {
write!(f, ": {}", inner_13)?;
}
Ok(())
}
}
impl std::error::Error for DirectoryServiceAuthenticationFailedException {}
/// See [`DirectoryServiceAuthenticationFailedException`](crate::error::DirectoryServiceAuthenticationFailedException)
pub mod directory_service_authentication_failed_exception {
/// A builder for [`DirectoryServiceAuthenticationFailedException`](crate::error::DirectoryServiceAuthenticationFailedException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`DirectoryServiceAuthenticationFailedException`](crate::error::DirectoryServiceAuthenticationFailedException)
pub fn build(self) -> crate::error::DirectoryServiceAuthenticationFailedException {
crate::error::DirectoryServiceAuthenticationFailedException {
message: self.message,
}
}
}
}
impl DirectoryServiceAuthenticationFailedException {
/// Creates a new builder-style object to manufacture [`DirectoryServiceAuthenticationFailedException`](crate::error::DirectoryServiceAuthenticationFailedException)
pub fn builder() -> crate::error::directory_service_authentication_failed_exception::Builder {
crate::error::directory_service_authentication_failed_exception::Builder::default()
}
}
/// <p>The resource cannot be found.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ResourceNotFoundException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for ResourceNotFoundException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ResourceNotFoundException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ResourceNotFoundException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ResourceNotFoundException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ResourceNotFoundException")?;
if let Some(inner_14) = &self.message {
write!(f, ": {}", inner_14)?;
}
Ok(())
}
}
impl std::error::Error for ResourceNotFoundException {}
/// See [`ResourceNotFoundException`](crate::error::ResourceNotFoundException)
pub mod resource_not_found_exception {
/// A builder for [`ResourceNotFoundException`](crate::error::ResourceNotFoundException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`ResourceNotFoundException`](crate::error::ResourceNotFoundException)
pub fn build(self) -> crate::error::ResourceNotFoundException {
crate::error::ResourceNotFoundException {
message: self.message,
}
}
}
}
impl ResourceNotFoundException {
/// Creates a new builder-style object to manufacture [`ResourceNotFoundException`](crate::error::ResourceNotFoundException)
pub fn builder() -> crate::error::resource_not_found_exception::Builder {
crate::error::resource_not_found_exception::Builder::default()
}
}
/// <p>The resource can have up to 50 user-applied tags.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct TooManyTagsException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for TooManyTagsException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("TooManyTagsException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl TooManyTagsException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for TooManyTagsException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "TooManyTagsException")?;
if let Some(inner_15) = &self.message {
write!(f, ": {}", inner_15)?;
}
Ok(())
}
}
impl std::error::Error for TooManyTagsException {}
/// See [`TooManyTagsException`](crate::error::TooManyTagsException)
pub mod too_many_tags_exception {
/// A builder for [`TooManyTagsException`](crate::error::TooManyTagsException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`TooManyTagsException`](crate::error::TooManyTagsException)
pub fn build(self) -> crate::error::TooManyTagsException {
crate::error::TooManyTagsException {
message: self.message,
}
}
}
}
impl TooManyTagsException {
/// Creates a new builder-style object to manufacture [`TooManyTagsException`](crate::error::TooManyTagsException)
pub fn builder() -> crate::error::too_many_tags_exception::Builder {
crate::error::too_many_tags_exception::Builder::default()
}
}
/// <p>The request exceeds the limit of the resource.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct LimitExceededException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for LimitExceededException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("LimitExceededException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl LimitExceededException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for LimitExceededException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "LimitExceededException")?;
if let Some(inner_16) = &self.message {
write!(f, ": {}", inner_16)?;
}
Ok(())
}
}
impl std::error::Error for LimitExceededException {}
/// See [`LimitExceededException`](crate::error::LimitExceededException)
pub mod limit_exceeded_exception {
/// A builder for [`LimitExceededException`](crate::error::LimitExceededException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`LimitExceededException`](crate::error::LimitExceededException)
pub fn build(self) -> crate::error::LimitExceededException {
crate::error::LimitExceededException {
message: self.message,
}
}
}
}
impl LimitExceededException {
/// Creates a new builder-style object to manufacture [`LimitExceededException`](crate::error::LimitExceededException)
pub fn builder() -> crate::error::limit_exceeded_exception::Builder {
crate::error::limit_exceeded_exception::Builder::default()
}
}
/// <p>The supplied password doesn't match the minimum security constraints, such as length
/// or use of special characters.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InvalidPasswordException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for InvalidPasswordException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("InvalidPasswordException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl InvalidPasswordException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for InvalidPasswordException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InvalidPasswordException")?;
if let Some(inner_17) = &self.message {
write!(f, ": {}", inner_17)?;
}
Ok(())
}
}
impl std::error::Error for InvalidPasswordException {}
/// See [`InvalidPasswordException`](crate::error::InvalidPasswordException)
pub mod invalid_password_exception {
/// A builder for [`InvalidPasswordException`](crate::error::InvalidPasswordException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`InvalidPasswordException`](crate::error::InvalidPasswordException)
pub fn build(self) -> crate::error::InvalidPasswordException {
crate::error::InvalidPasswordException {
message: self.message,
}
}
}
}
impl InvalidPasswordException {
/// Creates a new builder-style object to manufacture [`InvalidPasswordException`](crate::error::InvalidPasswordException)
pub fn builder() -> crate::error::invalid_password_exception::Builder {
crate::error::invalid_password_exception::Builder::default()
}
}
/// <p>The user, group, or resource that you're trying to register is already
/// registered.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct EntityAlreadyRegisteredException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for EntityAlreadyRegisteredException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("EntityAlreadyRegisteredException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl EntityAlreadyRegisteredException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for EntityAlreadyRegisteredException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "EntityAlreadyRegisteredException")?;
if let Some(inner_18) = &self.message {
write!(f, ": {}", inner_18)?;
}
Ok(())
}
}
impl std::error::Error for EntityAlreadyRegisteredException {}
/// See [`EntityAlreadyRegisteredException`](crate::error::EntityAlreadyRegisteredException)
pub mod entity_already_registered_exception {
/// A builder for [`EntityAlreadyRegisteredException`](crate::error::EntityAlreadyRegisteredException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`EntityAlreadyRegisteredException`](crate::error::EntityAlreadyRegisteredException)
pub fn build(self) -> crate::error::EntityAlreadyRegisteredException {
crate::error::EntityAlreadyRegisteredException {
message: self.message,
}
}
}
}
impl EntityAlreadyRegisteredException {
/// Creates a new builder-style object to manufacture [`EntityAlreadyRegisteredException`](crate::error::EntityAlreadyRegisteredException)
pub fn builder() -> crate::error::entity_already_registered_exception::Builder {
crate::error::entity_already_registered_exception::Builder::default()
}
}
/// <p>This user, group, or resource name is not allowed in Amazon WorkMail.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ReservedNameException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for ReservedNameException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ReservedNameException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ReservedNameException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ReservedNameException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ReservedNameException")?;
if let Some(inner_19) = &self.message {
write!(f, ": {}", inner_19)?;
}
Ok(())
}
}
impl std::error::Error for ReservedNameException {}
/// See [`ReservedNameException`](crate::error::ReservedNameException)
pub mod reserved_name_exception {
/// A builder for [`ReservedNameException`](crate::error::ReservedNameException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`ReservedNameException`](crate::error::ReservedNameException)
pub fn build(self) -> crate::error::ReservedNameException {
crate::error::ReservedNameException {
message: self.message,
}
}
}
}
impl ReservedNameException {
/// Creates a new builder-style object to manufacture [`ReservedNameException`](crate::error::ReservedNameException)
pub fn builder() -> crate::error::reserved_name_exception::Builder {
crate::error::reserved_name_exception::Builder::default()
}
}
/// <p>The directory is already in use by another WorkMail organization in the same account and Region.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DirectoryInUseException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for DirectoryInUseException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DirectoryInUseException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl DirectoryInUseException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for DirectoryInUseException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "DirectoryInUseException")?;
if let Some(inner_20) = &self.message {
write!(f, ": {}", inner_20)?;
}
Ok(())
}
}
impl std::error::Error for DirectoryInUseException {}
/// See [`DirectoryInUseException`](crate::error::DirectoryInUseException)
pub mod directory_in_use_exception {
/// A builder for [`DirectoryInUseException`](crate::error::DirectoryInUseException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`DirectoryInUseException`](crate::error::DirectoryInUseException)
pub fn build(self) -> crate::error::DirectoryInUseException {
crate::error::DirectoryInUseException {
message: self.message,
}
}
}
}
impl DirectoryInUseException {
/// Creates a new builder-style object to manufacture [`DirectoryInUseException`](crate::error::DirectoryInUseException)
pub fn builder() -> crate::error::directory_in_use_exception::Builder {
crate::error::directory_in_use_exception::Builder::default()
}
}
| 38.361404 | 168 | 0.653197 |
226644db72196ff4a02903ae2c5931c57492857a | 11,325 | #![feature(test)]
extern crate rustdct;
extern crate test;
use rustdct::mdct::{window_fn, Mdct, MdctNaive};
use rustdct::{
algorithm::{Dct1Naive, Dst6And7Naive, Type2And3Naive, Type4Naive},
RequiredScratch,
};
use rustdct::{Dct1, Dct2, Dct3, Dct4, Dst6, Dst7};
use test::Bencher;
/// Times just the DCT1 execution (not allocation and pre-calculation)
/// for a given length
fn bench_dct1_naive(b: &mut Bencher, len: usize) {
let dct = Dct1Naive::new(len);
let mut buffer = vec![0_f32; len];
let mut scratch = vec![0_f32; dct.get_scratch_len()];
b.iter(|| {
dct.process_dct1_with_scratch(&mut buffer, &mut scratch);
});
}
#[bench]
fn dct1_naive_002(b: &mut Bencher) {
bench_dct1_naive(b, 2);
}
#[bench]
fn dct1_naive_004(b: &mut Bencher) {
bench_dct1_naive(b, 4);
}
#[bench]
fn dct1_naive_006(b: &mut Bencher) {
bench_dct1_naive(b, 6);
}
#[bench]
fn dct1_naive_008(b: &mut Bencher) {
bench_dct1_naive(b, 8);
}
#[bench]
fn dct1_naive_010(b: &mut Bencher) {
bench_dct1_naive(b, 10);
}
/// Times just the DCT2 execution (not allocation and pre-calculation)
/// for a given length
fn bench_dct2_naive(b: &mut Bencher, len: usize) {
let dct = Type2And3Naive::new(len);
let mut buffer = vec![0_f32; len];
let mut scratch = vec![0_f32; dct.get_scratch_len()];
b.iter(|| {
dct.process_dct2_with_scratch(&mut buffer, &mut scratch);
});
}
#[bench]
fn dct2_naive_06(b: &mut Bencher) {
bench_dct2_naive(b, 6);
}
#[bench]
fn dct2_naive_05(b: &mut Bencher) {
bench_dct2_naive(b, 5);
}
#[bench]
fn dct2_naive_04(b: &mut Bencher) {
bench_dct2_naive(b, 4);
}
#[bench]
fn dct2_naive_03(b: &mut Bencher) {
bench_dct2_naive(b, 3);
}
#[bench]
fn dct2_naive_02(b: &mut Bencher) {
bench_dct2_naive(b, 2);
}
#[bench]
fn dct2_naive_01(b: &mut Bencher) {
bench_dct2_naive(b, 1);
}
/// Times just the DCT3 execution (not allocation and pre-calculation)
/// for a given length
fn bench_dct3_naive(b: &mut Bencher, len: usize) {
let dct = Type2And3Naive::new(len);
let mut buffer = vec![0_f32; len];
let mut scratch = vec![0_f32; dct.get_scratch_len()];
b.iter(|| {
dct.process_dct3_with_scratch(&mut buffer, &mut scratch);
});
}
#[bench]
fn dct3_naive_0002(b: &mut Bencher) {
bench_dct3_naive(b, 2);
}
#[bench]
fn dct3_naive_0003(b: &mut Bencher) {
bench_dct3_naive(b, 3);
}
#[bench]
fn dct3_naive_0004(b: &mut Bencher) {
bench_dct3_naive(b, 4);
}
#[bench]
fn dct3_naive_0005(b: &mut Bencher) {
bench_dct3_naive(b, 5);
}
#[bench]
fn dct3_naive_0006(b: &mut Bencher) {
bench_dct3_naive(b, 6);
}
/// Times just the DCT4 execution (not allocation and pre-calculation)
/// for a given length
fn bench_dct4_naive(b: &mut Bencher, len: usize) {
let dct = Type4Naive::new(len);
let mut buffer = vec![0_f32; len];
let mut scratch = vec![0_f32; dct.get_scratch_len()];
b.iter(|| {
dct.process_dct4_with_scratch(&mut buffer, &mut scratch);
});
}
#[bench]
fn dct4_even_naive_02(b: &mut Bencher) {
bench_dct4_naive(b, 2);
}
#[bench]
fn dct4_even_naive_04(b: &mut Bencher) {
bench_dct4_naive(b, 4);
}
#[bench]
fn dct4_even_naive_06(b: &mut Bencher) {
bench_dct4_naive(b, 6);
}
#[bench]
fn dct4_even_naive_08(b: &mut Bencher) {
bench_dct4_naive(b, 8);
}
#[bench]
fn dct4_even_naive_10(b: &mut Bencher) {
bench_dct4_naive(b, 10);
}
#[bench]
fn dct4_odd_naive_01(b: &mut Bencher) {
bench_dct4_naive(b, 1);
}
#[bench]
fn dct4_odd_naive_03(b: &mut Bencher) {
bench_dct4_naive(b, 3);
}
#[bench]
fn dct4_odd_naive_05(b: &mut Bencher) {
bench_dct4_naive(b, 5);
}
#[bench]
fn dct4_odd_naive_07(b: &mut Bencher) {
bench_dct4_naive(b, 7);
}
#[bench]
fn dct4_odd_naive_09(b: &mut Bencher) {
bench_dct4_naive(b, 9);
}
/// Times just the MDCT execution (not allocation and pre-calculation)
/// for a given length
fn bench_mdct_naive(b: &mut Bencher, len: usize) {
let dct = MdctNaive::new(len, window_fn::mp3);
let input = vec![0_f32; len * 2];
let (input_a, input_b) = input.split_at(len);
let mut output = vec![0_f32; len];
let mut scratch = vec![0_f32; dct.get_scratch_len()];
b.iter(|| {
dct.process_mdct_with_scratch(input_a, input_b, &mut output, &mut scratch);
});
}
#[bench]
fn mdct_naive_02(b: &mut Bencher) {
bench_mdct_naive(b, 2);
}
#[bench]
fn mdct_naive_04(b: &mut Bencher) {
bench_mdct_naive(b, 4);
}
#[bench]
fn mdct_naive_06(b: &mut Bencher) {
bench_mdct_naive(b, 6);
}
#[bench]
fn mdct_naive_08(b: &mut Bencher) {
bench_mdct_naive(b, 8);
}
#[bench]
fn mdct_naive_10(b: &mut Bencher) {
bench_mdct_naive(b, 10);
}
#[bench]
fn mdct_naive_12(b: &mut Bencher) {
bench_mdct_naive(b, 12);
}
/// Times just the IMDCT execution (not allocation and pre-calculation)
/// for a given length
fn bench_imdct_naive(b: &mut Bencher, len: usize) {
let dct = MdctNaive::new(len, window_fn::mp3);
let input = vec![0_f32; len];
let mut output = vec![0_f32; len * 2];
let (output_a, output_b) = output.split_at_mut(len);
let mut scratch = vec![0_f32; dct.get_scratch_len()];
b.iter(|| {
dct.process_imdct_with_scratch(&input, output_a, output_b, &mut scratch);
});
}
#[bench]
fn imdct_naive_02(b: &mut Bencher) {
bench_imdct_naive(b, 2);
}
#[bench]
fn imdct_naive_04(b: &mut Bencher) {
bench_imdct_naive(b, 4);
}
#[bench]
fn imdct_naive_06(b: &mut Bencher) {
bench_imdct_naive(b, 6);
}
#[bench]
fn imdct_naive_08(b: &mut Bencher) {
bench_imdct_naive(b, 8);
}
#[bench]
fn imdct_naive_10(b: &mut Bencher) {
bench_imdct_naive(b, 10);
}
#[bench]
fn imdct_naive_12(b: &mut Bencher) {
bench_imdct_naive(b, 12);
}
/// Times just the DST6 execution (not allocation and pre-calculation)
/// for a given length
fn bench_dst6_naive(b: &mut Bencher, len: usize) {
let dct = Dst6And7Naive::new(len);
let mut buffer = vec![0_f32; len];
let mut scratch = vec![0_f32; dct.get_scratch_len()];
b.iter(|| {
dct.process_dst6_with_scratch(&mut buffer, &mut scratch);
});
}
#[bench]
fn dst6_even_naive_10(b: &mut Bencher) {
bench_dst6_naive(b, 10);
}
#[bench]
fn dst6_even_naive_11(b: &mut Bencher) {
bench_dst6_naive(b, 11);
}
#[bench]
fn dst6_even_naive_12(b: &mut Bencher) {
bench_dst6_naive(b, 12);
}
#[bench]
fn dst6_even_naive_13(b: &mut Bencher) {
bench_dst6_naive(b, 13);
}
#[bench]
fn dst6_even_naive_14(b: &mut Bencher) {
bench_dst6_naive(b, 14);
}
#[bench]
fn dst6_even_naive_15(b: &mut Bencher) {
bench_dst6_naive(b, 15);
}
#[bench]
fn dst6_even_naive_16(b: &mut Bencher) {
bench_dst6_naive(b, 16);
}
#[bench]
fn dst6_even_naive_17(b: &mut Bencher) {
bench_dst6_naive(b, 17);
}
#[bench]
fn dst6_even_naive_18(b: &mut Bencher) {
bench_dst6_naive(b, 18);
}
#[bench]
fn dst6_even_naive_19(b: &mut Bencher) {
bench_dst6_naive(b, 19);
}
#[bench]
fn dst6_even_naive_20(b: &mut Bencher) {
bench_dst6_naive(b, 20);
}
#[bench]
fn dst6_even_naive_21(b: &mut Bencher) {
bench_dst6_naive(b, 21);
}
#[bench]
fn dst6_even_naive_22(b: &mut Bencher) {
bench_dst6_naive(b, 22);
}
#[bench]
fn dst6_even_naive_23(b: &mut Bencher) {
bench_dst6_naive(b, 23);
}
#[bench]
fn dst6_even_naive_24(b: &mut Bencher) {
bench_dst6_naive(b, 24);
}
#[bench]
fn dst6_even_naive_25(b: &mut Bencher) {
bench_dst6_naive(b, 25);
}
#[bench]
fn dst6_even_naive_26(b: &mut Bencher) {
bench_dst6_naive(b, 26);
}
#[bench]
fn dst6_even_naive_27(b: &mut Bencher) {
bench_dst6_naive(b, 27);
}
#[bench]
fn dst6_even_naive_28(b: &mut Bencher) {
bench_dst6_naive(b, 28);
}
#[bench]
fn dst6_even_naive_29(b: &mut Bencher) {
bench_dst6_naive(b, 29);
}
#[bench]
fn dst6_even_naive_30(b: &mut Bencher) {
bench_dst6_naive(b, 30);
}
#[bench]
fn dst6_even_naive_31(b: &mut Bencher) {
bench_dst6_naive(b, 31);
}
#[bench]
fn dst6_even_naive_32(b: &mut Bencher) {
bench_dst6_naive(b, 32);
}
#[bench]
fn dst6_even_naive_33(b: &mut Bencher) {
bench_dst6_naive(b, 33);
}
#[bench]
fn dst6_even_naive_34(b: &mut Bencher) {
bench_dst6_naive(b, 34);
}
#[bench]
fn dst6_even_naive_35(b: &mut Bencher) {
bench_dst6_naive(b, 35);
}
#[bench]
fn dst6_even_naive_36(b: &mut Bencher) {
bench_dst6_naive(b, 36);
}
#[bench]
fn dst6_even_naive_37(b: &mut Bencher) {
bench_dst6_naive(b, 37);
}
#[bench]
fn dst6_even_naive_38(b: &mut Bencher) {
bench_dst6_naive(b, 38);
}
#[bench]
fn dst6_even_naive_39(b: &mut Bencher) {
bench_dst6_naive(b, 39);
}
/// Times just the DST7 execution (not allocation and pre-calculation)
/// for a given length
fn bench_dst7_naive(b: &mut Bencher, len: usize) {
let dct = Dst6And7Naive::new(len);
let mut buffer = vec![0_f32; len];
let mut scratch = vec![0_f32; dct.get_scratch_len()];
b.iter(|| {
dct.process_dst7_with_scratch(&mut buffer, &mut scratch);
});
}
#[bench]
fn dst7_even_naive_10(b: &mut Bencher) {
bench_dst7_naive(b, 10);
}
#[bench]
fn dst7_even_naive_11(b: &mut Bencher) {
bench_dst7_naive(b, 11);
}
#[bench]
fn dst7_even_naive_12(b: &mut Bencher) {
bench_dst7_naive(b, 12);
}
#[bench]
fn dst7_even_naive_13(b: &mut Bencher) {
bench_dst7_naive(b, 13);
}
#[bench]
fn dst7_even_naive_14(b: &mut Bencher) {
bench_dst7_naive(b, 14);
}
#[bench]
fn dst7_even_naive_15(b: &mut Bencher) {
bench_dst7_naive(b, 15);
}
#[bench]
fn dst7_even_naive_16(b: &mut Bencher) {
bench_dst7_naive(b, 16);
}
#[bench]
fn dst7_even_naive_17(b: &mut Bencher) {
bench_dst7_naive(b, 17);
}
#[bench]
fn dst7_even_naive_18(b: &mut Bencher) {
bench_dst7_naive(b, 18);
}
#[bench]
fn dst7_even_naive_19(b: &mut Bencher) {
bench_dst7_naive(b, 19);
}
#[bench]
fn dst7_even_naive_20(b: &mut Bencher) {
bench_dst7_naive(b, 20);
}
#[bench]
fn dst7_even_naive_21(b: &mut Bencher) {
bench_dst7_naive(b, 21);
}
#[bench]
fn dst7_even_naive_22(b: &mut Bencher) {
bench_dst7_naive(b, 22);
}
#[bench]
fn dst7_even_naive_23(b: &mut Bencher) {
bench_dst7_naive(b, 23);
}
#[bench]
fn dst7_even_naive_24(b: &mut Bencher) {
bench_dst7_naive(b, 24);
}
#[bench]
fn dst7_even_naive_25(b: &mut Bencher) {
bench_dst7_naive(b, 25);
}
#[bench]
fn dst7_even_naive_26(b: &mut Bencher) {
bench_dst7_naive(b, 26);
}
#[bench]
fn dst7_even_naive_27(b: &mut Bencher) {
bench_dst7_naive(b, 27);
}
#[bench]
fn dst7_even_naive_28(b: &mut Bencher) {
bench_dst7_naive(b, 28);
}
#[bench]
fn dst7_even_naive_29(b: &mut Bencher) {
bench_dst7_naive(b, 29);
}
#[bench]
fn dst7_even_naive_30(b: &mut Bencher) {
bench_dst7_naive(b, 30);
}
#[bench]
fn dst7_even_naive_31(b: &mut Bencher) {
bench_dst7_naive(b, 31);
}
#[bench]
fn dst7_even_naive_32(b: &mut Bencher) {
bench_dst7_naive(b, 32);
}
#[bench]
fn dst7_even_naive_33(b: &mut Bencher) {
bench_dst7_naive(b, 33);
}
#[bench]
fn dst7_even_naive_34(b: &mut Bencher) {
bench_dst7_naive(b, 34);
}
#[bench]
fn dst7_even_naive_35(b: &mut Bencher) {
bench_dst7_naive(b, 35);
}
#[bench]
fn dst7_even_naive_36(b: &mut Bencher) {
bench_dst7_naive(b, 36);
}
#[bench]
fn dst7_even_naive_37(b: &mut Bencher) {
bench_dst7_naive(b, 37);
}
#[bench]
fn dst7_even_naive_38(b: &mut Bencher) {
bench_dst7_naive(b, 38);
}
#[bench]
fn dst7_even_naive_39(b: &mut Bencher) {
bench_dst7_naive(b, 39);
}
| 22.033074 | 83 | 0.668344 |
e2e4962cc1160d2017a73b02ba061cf225a05e1e | 6,631 | use super::Cursor;
use crate::msgpack::decode::*;
use crate::msgpack::Marker;
#[test]
fn from_nfix_min() {
let buf = [0xe0];
let mut cur = Cursor::new(&buf[..]);
assert_eq!(-32, read_nfix(&mut cur).unwrap());
assert_eq!(1, cur.position());
}
#[test]
fn from_nfix_max() {
let buf = [0xff];
let mut cur = Cursor::new(&buf[..]);
assert_eq!(-1, read_nfix(&mut cur).unwrap());
assert_eq!(1, cur.position());
}
#[test]
fn from_nfix_type_mismatch() {
let buf = &[0xc0];
let mut cur = Cursor::new(&buf[..]);
match read_nfix(&mut cur) {
Err(ValueReadError::TypeMismatch(..)) => (),
other => panic!("unexpected result: {:?}", other),
}
assert_eq!(1, cur.position());
}
#[test]
fn from_i8_min() {
let buf = [0xd0, 0x80];
let mut cur = Cursor::new(&buf[..]);
assert_eq!(-128, read_i8(&mut cur).unwrap());
assert_eq!(2, cur.position());
}
#[test]
fn from_i8_max() {
let buf = [0xd0, 0x7f];
let mut cur = Cursor::new(&buf[..]);
assert_eq!(127, read_i8(&mut cur).unwrap());
assert_eq!(2, cur.position());
}
#[test]
fn from_i8_type_mismatch() {
let buf = [0xc0, 0x80];
let mut cur = Cursor::new(&buf[..]);
match read_i8(&mut cur) {
Err(ValueReadError::TypeMismatch(Marker::Null)) => (),
other => panic!("unexpected result: {:?}", other),
}
assert_eq!(1, cur.position());
}
#[test]
fn from_i8_unexpected_eof() {
let buf = [0xd0];
let mut cur = Cursor::new(&buf[..]);
read_i8(&mut cur).err().unwrap();
assert_eq!(1, cur.position());
}
#[test]
fn from_i16_min() {
let buf = [0xd1, 0x80, 0x00];
let mut cur = Cursor::new(&buf[..]);
assert_eq!(-32768, read_i16(&mut cur).unwrap());
assert_eq!(3, cur.position());
}
#[test]
fn from_i16_max() {
let buf = [0xd1, 0x7f, 0xff];
let mut cur = Cursor::new(&buf[..]);
assert_eq!(32767, read_i16(&mut cur).unwrap());
assert_eq!(3, cur.position());
}
#[test]
fn from_i16_type_mismatch() {
let buf = [0xc0, 0x80, 0x00];
let mut cur = Cursor::new(&buf[..]);
match read_i16(&mut cur) {
Err(ValueReadError::TypeMismatch(Marker::Null)) => (),
other => panic!("unexpected result: {:?}", other),
}
assert_eq!(1, cur.position());
}
#[test]
fn from_i16_unexpected_eof() {
let buf = [0xd1, 0x7f];
let mut cur = Cursor::new(&buf[..]);
read_i16(&mut cur).err().unwrap();
assert!(cur.position() >= 1);
}
#[test]
fn from_i32_min() {
let buf = [0xd2, 0x80, 0x00, 0x00, 0x00];
let mut cur = Cursor::new(&buf[..]);
assert_eq!(-2147483648, read_i32(&mut cur).unwrap());
assert_eq!(5, cur.position());
}
#[test]
fn from_i32_max() {
let buf = &[0xd2, 0x7f, 0xff, 0xff, 0xff];
let mut cur = Cursor::new(&buf[..]);
assert_eq!(2147483647, read_i32(&mut cur).unwrap());
assert_eq!(5, cur.position());
}
#[test]
fn from_i32_type_mismatch() {
let buf = &[0xc0, 0x80, 0x00, 0x00, 0x00];
let mut cur = Cursor::new(&buf[..]);
match read_i32(&mut cur) {
Err(ValueReadError::TypeMismatch(Marker::Null)) => (),
other => panic!("unexpected result: {:?}", other),
}
assert_eq!(1, cur.position());
}
#[test]
fn from_i32_unexpected_eof() {
let buf = &[0xd2, 0x7f, 0xff, 0xff];
let mut cur = Cursor::new(&buf[..]);
read_i32(&mut cur).err().unwrap();
assert!(cur.position() >= 1);
}
#[test]
fn from_i64_min() {
let buf = [0xd3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
let mut cur = Cursor::new(&buf[..]);
assert_eq!(-9223372036854775808, read_i64(&mut cur).unwrap());
assert_eq!(9, cur.position());
}
#[test]
fn from_i64_max() {
let buf = [0xd3, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
let mut cur = Cursor::new(&buf[..]);
assert_eq!(9223372036854775807, read_i64(&mut cur).unwrap());
assert_eq!(9, cur.position());
}
#[test]
fn from_i64_type_mismatch() {
let buf = [0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
let mut cur = Cursor::new(&buf[..]);
match read_i64(&mut cur) {
Err(ValueReadError::TypeMismatch(Marker::Null)) => (),
other => panic!("unexpected result: {:?}", other),
}
assert_eq!(1, cur.position());
}
#[test]
fn from_i64_unexpected_eof() {
let buf = [0xd3, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
let mut cur = Cursor::new(&buf[..]);
read_i64(&mut cur).err().unwrap();
assert!(cur.position() >= 1);
}
#[test]
fn from_nfix_min_read_int() {
let buf: &[u8] = &[0xe0];
let mut cur = Cursor::new(buf);
assert_eq!(-32, read_int(&mut cur).unwrap());
assert_eq!(1, cur.position());
}
#[test]
fn from_nfix_max_read_int() {
let buf: &[u8] = &[0xff];
let mut cur = Cursor::new(buf);
assert_eq!(-1, read_int(&mut cur).unwrap());
assert_eq!(1, cur.position());
}
#[test]
fn from_i8_min_read_int() {
let buf: &[u8] = &[0xd0, 0x80];
let mut cur = Cursor::new(buf);
assert_eq!(-128, read_int(&mut cur).unwrap());
assert_eq!(2, cur.position());
}
#[test]
fn from_i8_max_read_int() {
let buf: &[u8] = &[0xd0, 0x7f];
let mut cur = Cursor::new(buf);
assert_eq!(127, read_int(&mut cur).unwrap());
assert_eq!(2, cur.position());
}
#[test]
fn from_i16_min_read_int() {
let buf: &[u8] = &[0xd1, 0x80, 0x00];
let mut cur = Cursor::new(buf);
assert_eq!(-32768, read_int(&mut cur).unwrap());
assert_eq!(3, cur.position());
}
#[test]
fn from_i16_max_read_int() {
let buf: &[u8] = &[0xd1, 0x7f, 0xff];
let mut cur = Cursor::new(buf);
assert_eq!(32767, read_int(&mut cur).unwrap());
assert_eq!(3, cur.position());
}
#[test]
fn from_i32_min_read_int() {
let buf: &[u8] = &[0xd2, 0x80, 0x00, 0x00, 0x00];
let mut cur = Cursor::new(buf);
assert_eq!(-2147483648, read_int(&mut cur).unwrap());
assert_eq!(5, cur.position());
}
#[test]
fn from_i32_max_read_int() {
let buf: &[u8] = &[0xd2, 0x7f, 0xff, 0xff, 0xff];
let mut cur = Cursor::new(buf);
assert_eq!(2147483647, read_int(&mut cur).unwrap());
assert_eq!(5, cur.position());
}
#[test]
fn from_i64_min_read_int() {
let buf: &[u8] = &[0xd3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
let mut cur = Cursor::new(buf);
assert_eq!(-9223372036854775808i64, read_int(&mut cur).unwrap());
assert_eq!(9, cur.position());
}
#[test]
fn from_i64_max_read_int() {
let buf: &[u8] = &[0xd3, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
let mut cur = Cursor::new(buf);
assert_eq!(9223372036854775807i64, read_int(&mut cur).unwrap());
assert_eq!(9, cur.position());
}
| 23.597865 | 77 | 0.586639 |
912a62b5b0f6ae46b51c0d1b72005b87dfd5a666 | 1,017 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate collections;
use std::collections::Bitv;
use std::num::Float;
fn main() {
// Generate sieve of Eratosthenes for n up to 1e6
let n = 1000000u;
let mut sieve = Bitv::with_capacity(n+1, true);
let limit: uint = (n as f32).sqrt() as uint;
for i in range(2, limit+1) {
if sieve[i] {
let mut j = 0;
while i*i + j*i <= n {
sieve.set(i*i+j*i, false);
j += 1;
}
}
}
for i in range(2, n+1) {
if sieve[i] {
}
}
}
| 28.25 | 68 | 0.597837 |
f54e606e13caac2b6a212444fcc53bbd06ddae7b | 647 | use std::io;
use failure::Error;
use nexers::nexus::Event;
fn main() -> Result<(), Error> {
use std::fs;
let from = io::BufReader::new(fs::File::open("sample-index")?);
let mut errors = 0;
nexers::nexus::read(from, |event| {
match event {
Event::Doc(d) => {
if d.id.group == "com.google.guava" && d.id.artifact == "guava" {
println!("{:?} {:?}", d.id, d.object_info);
}
}
Event::Error { .. } => errors += 1,
Event::Delete(_) => (),
}
Ok(())
})?;
println!("..and {} errors", errors);
Ok(())
}
| 24.884615 | 81 | 0.435858 |
093f19acf643ff396759068a59df472d5b6efd64 | 4,037 | //! VM memory representation
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use bigint::{U256, M256};
use super::errors::NotSupportedError;
use super::Patch;
#[cfg(feature = "std")] use std::marker::PhantomData;
#[cfg(not(feature = "std"))] use core::marker::PhantomData;
/// Represent a memory in EVM. Read should always succeed. Write can
/// fall.
pub trait Memory {
/// Check whether write on this index would result in an error. If
/// this function returns Ok, then both `write` and `write_raw` on
/// this index should succeed.
fn check_write(&self, index: U256) -> Result<(), NotSupportedError>;
/// Check whether write on the given index range would result in
/// an error. If this function returns Ok, then both `write` and
/// `write_raw` on the given index range should succeed.
fn check_write_range(&self, start: U256, len: U256) -> Result<(), NotSupportedError>;
/// Write value into the index.
fn write(&mut self, index: U256, value: M256) -> Result<(), NotSupportedError>;
/// Write only one byte value into the index.
fn write_raw(&mut self, index: U256, value: u8) -> Result<(), NotSupportedError>;
/// Read value from the index.
fn read(&self, index: U256) -> M256;
/// Read only one byte value from the index.
fn read_raw(&self, index: U256) -> u8;
}
/// A sequencial memory. It uses Rust's `Vec` for internal
/// representation.
pub struct SeqMemory<P: Patch> {
memory: Vec<u8>,
_marker: PhantomData<P>,
}
impl<P: Patch> Default for SeqMemory<P> {
fn default() -> SeqMemory<P> {
SeqMemory {
memory: Vec::new(),
_marker: PhantomData,
}
}
}
impl<P: Patch> SeqMemory<P> {
/// Get the length of the current effective memory range.
#[inline]
pub fn len(&self) -> usize {
self.memory.len()
}
/// Return true if current effective memory range is zero
#[inline]
pub fn is_empty(&self) -> bool { self.len() == 0 }
}
impl<P: Patch> Memory for SeqMemory<P> {
fn check_write(&self, index: U256) -> Result<(), NotSupportedError> {
let end = index + 32.into();
if end > U256::from(P::memory_limit()) {
Err(NotSupportedError::MemoryIndexNotSupported)
} else {
Ok(())
}
}
fn check_write_range(&self, start: U256, len: U256) -> Result<(), NotSupportedError> {
if len == U256::zero() {
return Ok(());
}
if start.saturating_add(len) > U256::from(P::memory_limit()) {
Err(NotSupportedError::MemoryIndexNotSupported)
} else {
self.check_write(start + len - U256::from(1u64))
}
}
fn write(&mut self, index: U256, value: M256) -> Result<(), NotSupportedError> {
let end = M256::from(index) + 32.into();
if end > M256::from(P::memory_limit()) {
return Err(NotSupportedError::MemoryIndexNotSupported);
}
for i in 0..32 {
self.write_raw(index + i.into(), value.index(i)).unwrap();
}
Ok(())
}
fn write_raw(&mut self, index: U256, value: u8) -> Result<(), NotSupportedError> {
if index > U256::from(P::memory_limit()) {
return Err(NotSupportedError::MemoryIndexNotSupported);
}
let index: usize = index.as_usize();
if self.memory.len() <= index {
self.memory.resize(index + 1, 0u8);
}
self.memory[index] = value;
Ok(())
}
fn read(&self, index: U256) -> M256 {
let mut a: [u8; 32] = [0u8; 32];
for (i, item) in a[0..32].iter_mut().enumerate() {
*item = self.read_raw(index + i.into());
}
a.as_ref().into()
}
fn read_raw(&self, index: U256) -> u8 {
if index > U256::from(usize::max_value()) {
return 0u8;
}
let index: usize = index.as_usize();
if self.memory.len() <= index {
return 0u8;
}
self.memory[index]
}
}
| 29.467153 | 90 | 0.576418 |
e554a330e3cd3b98354d8b64e4caaf01c2e07475 | 3,021 | //! # Example
//! ```rust
//! use tantivy::tokenizer::*;
//!
//! let tokenizer = SimpleTokenizer
//! .filter(StopWordFilter::remove(vec!["the".to_string(), "is".to_string()]));
//!
//! let mut stream = tokenizer.token_stream("the fox is crafty");
//! assert_eq!(stream.next().unwrap().text, "fox");
//! assert_eq!(stream.next().unwrap().text, "crafty");
//! assert!(stream.next().is_none());
//! ```
use super::{Token, TokenFilter, TokenStream};
use fnv::FnvHasher;
use std::collections::HashSet;
use std::hash::BuildHasherDefault;
// configure our hashers for SPEED
type StopWordHasher = BuildHasherDefault<FnvHasher>;
type StopWordHashSet = HashSet<String, StopWordHasher>;
/// `TokenFilter` that removes stop words from a token stream
#[derive(Clone)]
pub struct StopWordFilter {
words: StopWordHashSet,
}
impl StopWordFilter {
/// Creates a `StopWordFilter` given a list of words to remove
pub fn remove(words: Vec<String>) -> StopWordFilter {
let mut set = StopWordHashSet::default();
for word in words {
set.insert(word);
}
StopWordFilter { words: set }
}
fn english() -> StopWordFilter {
let words: [&'static str; 33] = [
"a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into",
"is", "it", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then",
"there", "these", "they", "this", "to", "was", "will", "with",
];
StopWordFilter::remove(words.iter().map(|&s| s.to_string()).collect())
}
}
pub struct StopWordFilterStream<TailTokenStream>
where
TailTokenStream: TokenStream,
{
words: StopWordHashSet,
tail: TailTokenStream,
}
impl<TailTokenStream> TokenFilter<TailTokenStream> for StopWordFilter
where
TailTokenStream: TokenStream,
{
type ResultTokenStream = StopWordFilterStream<TailTokenStream>;
fn transform(&self, token_stream: TailTokenStream) -> Self::ResultTokenStream {
StopWordFilterStream::wrap(self.words.clone(), token_stream)
}
}
impl<TailTokenStream> StopWordFilterStream<TailTokenStream>
where
TailTokenStream: TokenStream,
{
fn predicate(&self, token: &Token) -> bool {
!self.words.contains(&token.text)
}
fn wrap(
words: StopWordHashSet,
tail: TailTokenStream,
) -> StopWordFilterStream<TailTokenStream> {
StopWordFilterStream { words, tail }
}
}
impl<TailTokenStream> TokenStream for StopWordFilterStream<TailTokenStream>
where
TailTokenStream: TokenStream,
{
fn token(&self) -> &Token {
self.tail.token()
}
fn token_mut(&mut self) -> &mut Token {
self.tail.token_mut()
}
fn advance(&mut self) -> bool {
while self.tail.advance() {
if self.predicate(self.tail.token()) {
return true;
}
}
false
}
}
impl Default for StopWordFilter {
fn default() -> StopWordFilter {
StopWordFilter::english()
}
}
| 26.734513 | 94 | 0.625952 |
ab8861ca1083392ed16070617b3b0f332181fcff | 1,979 | // Copyright (c) 2019, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use facts_rust as facts;
use hhbc_string_utils_rust::without_xhp_mangling;
use ocamlrep::{bytes_from_ocamlrep, ptr::UnsafeOcamlPtr};
use ocamlrep_ocamlpool::ocaml_ffi;
use oxidized::relative_path::RelativePath;
use facts::facts_parser::*;
ocaml_ffi! {
fn extract_as_json_ffi(
flags: i32,
filename: RelativePath,
text_ptr: UnsafeOcamlPtr,
mangle_xhp: bool,
) -> Option<String> {
// Safety: the OCaml garbage collector must not run as long as text_ptr
// and text_value exist. We don't call into OCaml here, so it won't.
let text_value = unsafe { text_ptr.as_value() };
let text = bytes_from_ocamlrep(text_value).expect("expected string");
extract_as_json_ffi0(
((1 << 0) & flags) != 0, // php5_compat_mode
((1 << 1) & flags) != 0, // hhvm_compat_mode
((1 << 2) & flags) != 0, // allow_new_attribute_syntax
((1 << 3) & flags) != 0, // enable_xhp_class_modifier
((1 << 4) & flags) != 0, // disable_xhp_element_mangling
filename,
text,
mangle_xhp,
)
}
}
fn extract_as_json_ffi0(
php5_compat_mode: bool,
hhvm_compat_mode: bool,
allow_new_attribute_syntax: bool,
enable_xhp_class_modifier: bool,
disable_xhp_element_mangling: bool,
filename: RelativePath,
text: &[u8],
mangle_xhp: bool,
) -> Option<String> {
let opts = ExtractAsJsonOpts {
php5_compat_mode,
hhvm_compat_mode,
allow_new_attribute_syntax,
enable_xhp_class_modifier,
disable_xhp_element_mangling,
filename,
};
if mangle_xhp {
extract_as_json(text, opts)
} else {
without_xhp_mangling(|| extract_as_json(text, opts))
}
}
| 31.412698 | 79 | 0.637696 |
fc9683e840ea1baca48a9229f41b13b36f541ca6 | 7,095 | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::GLUniformType;
use crate::Renderer;
use glib::object::Cast;
use glib::object::IsA;
use glib::translate::*;
use glib::StaticType;
use glib::ToValue;
use std::fmt;
use std::ptr;
glib::wrapper! {
pub struct GLShader(Object<ffi::GskGLShader, ffi::GskGLShaderClass>);
match fn {
get_type => || ffi::gsk_gl_shader_get_type(),
}
}
impl GLShader {
#[doc(alias = "gsk_gl_shader_new_from_bytes")]
pub fn from_bytes(sourcecode: &glib::Bytes) -> GLShader {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::gsk_gl_shader_new_from_bytes(
sourcecode.to_glib_none().0,
))
}
}
#[doc(alias = "gsk_gl_shader_new_from_resource")]
pub fn from_resource(resource_path: &str) -> GLShader {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::gsk_gl_shader_new_from_resource(
resource_path.to_glib_none().0,
))
}
}
#[doc(alias = "gsk_gl_shader_compile")]
pub fn compile<P: IsA<Renderer>>(&self, renderer: &P) -> Result<(), glib::Error> {
unsafe {
let mut error = ptr::null_mut();
let _ = ffi::gsk_gl_shader_compile(
self.to_glib_none().0,
renderer.as_ref().to_glib_none().0,
&mut error,
);
if error.is_null() {
Ok(())
} else {
Err(from_glib_full(error))
}
}
}
#[doc(alias = "gsk_gl_shader_find_uniform_by_name")]
pub fn find_uniform_by_name(&self, name: &str) -> i32 {
unsafe {
ffi::gsk_gl_shader_find_uniform_by_name(self.to_glib_none().0, name.to_glib_none().0)
}
}
//#[doc(alias = "gsk_gl_shader_format_args")]
//pub fn format_args(&self, : /*Unknown conversion*//*Unimplemented*/Fundamental: VarArgs) -> Option<glib::Bytes> {
// unsafe { TODO: call ffi:gsk_gl_shader_format_args() }
//}
#[doc(alias = "gsk_gl_shader_get_arg_bool")]
pub fn get_arg_bool(&self, args: &glib::Bytes, idx: i32) -> bool {
unsafe {
from_glib(ffi::gsk_gl_shader_get_arg_bool(
self.to_glib_none().0,
args.to_glib_none().0,
idx,
))
}
}
#[doc(alias = "gsk_gl_shader_get_arg_float")]
pub fn get_arg_float(&self, args: &glib::Bytes, idx: i32) -> f32 {
unsafe {
ffi::gsk_gl_shader_get_arg_float(self.to_glib_none().0, args.to_glib_none().0, idx)
}
}
#[doc(alias = "gsk_gl_shader_get_arg_int")]
pub fn get_arg_int(&self, args: &glib::Bytes, idx: i32) -> i32 {
unsafe { ffi::gsk_gl_shader_get_arg_int(self.to_glib_none().0, args.to_glib_none().0, idx) }
}
#[doc(alias = "gsk_gl_shader_get_arg_uint")]
pub fn get_arg_uint(&self, args: &glib::Bytes, idx: i32) -> u32 {
unsafe {
ffi::gsk_gl_shader_get_arg_uint(self.to_glib_none().0, args.to_glib_none().0, idx)
}
}
#[doc(alias = "gsk_gl_shader_get_arg_vec2")]
pub fn get_arg_vec2(&self, args: &glib::Bytes, idx: i32, out_value: &mut graphene::Vec2) {
unsafe {
ffi::gsk_gl_shader_get_arg_vec2(
self.to_glib_none().0,
args.to_glib_none().0,
idx,
out_value.to_glib_none_mut().0,
);
}
}
#[doc(alias = "gsk_gl_shader_get_arg_vec3")]
pub fn get_arg_vec3(&self, args: &glib::Bytes, idx: i32, out_value: &mut graphene::Vec3) {
unsafe {
ffi::gsk_gl_shader_get_arg_vec3(
self.to_glib_none().0,
args.to_glib_none().0,
idx,
out_value.to_glib_none_mut().0,
);
}
}
#[doc(alias = "gsk_gl_shader_get_arg_vec4")]
pub fn get_arg_vec4(&self, args: &glib::Bytes, idx: i32, out_value: &mut graphene::Vec4) {
unsafe {
ffi::gsk_gl_shader_get_arg_vec4(
self.to_glib_none().0,
args.to_glib_none().0,
idx,
out_value.to_glib_none_mut().0,
);
}
}
#[doc(alias = "gsk_gl_shader_get_args_size")]
pub fn get_args_size(&self) -> usize {
unsafe { ffi::gsk_gl_shader_get_args_size(self.to_glib_none().0) }
}
#[doc(alias = "gsk_gl_shader_get_n_textures")]
pub fn get_n_textures(&self) -> i32 {
unsafe { ffi::gsk_gl_shader_get_n_textures(self.to_glib_none().0) }
}
#[doc(alias = "gsk_gl_shader_get_n_uniforms")]
pub fn get_n_uniforms(&self) -> i32 {
unsafe { ffi::gsk_gl_shader_get_n_uniforms(self.to_glib_none().0) }
}
#[doc(alias = "gsk_gl_shader_get_resource")]
pub fn get_resource(&self) -> Option<glib::GString> {
unsafe { from_glib_none(ffi::gsk_gl_shader_get_resource(self.to_glib_none().0)) }
}
#[doc(alias = "gsk_gl_shader_get_source")]
pub fn get_source(&self) -> Option<glib::Bytes> {
unsafe { from_glib_none(ffi::gsk_gl_shader_get_source(self.to_glib_none().0)) }
}
#[doc(alias = "gsk_gl_shader_get_uniform_name")]
pub fn get_uniform_name(&self, idx: i32) -> Option<glib::GString> {
unsafe {
from_glib_none(ffi::gsk_gl_shader_get_uniform_name(
self.to_glib_none().0,
idx,
))
}
}
#[doc(alias = "gsk_gl_shader_get_uniform_offset")]
pub fn get_uniform_offset(&self, idx: i32) -> i32 {
unsafe { ffi::gsk_gl_shader_get_uniform_offset(self.to_glib_none().0, idx) }
}
#[doc(alias = "gsk_gl_shader_get_uniform_type")]
pub fn get_uniform_type(&self, idx: i32) -> GLUniformType {
unsafe {
from_glib(ffi::gsk_gl_shader_get_uniform_type(
self.to_glib_none().0,
idx,
))
}
}
}
#[derive(Clone, Default)]
pub struct GLShaderBuilder {
resource: Option<String>,
source: Option<glib::Bytes>,
}
impl GLShaderBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn build(self) -> GLShader {
let mut properties: Vec<(&str, &dyn ToValue)> = vec![];
if let Some(ref resource) = self.resource {
properties.push(("resource", resource));
}
if let Some(ref source) = self.source {
properties.push(("source", source));
}
let ret = glib::Object::new::<GLShader>(&properties).expect("object new");
ret
}
pub fn resource(mut self, resource: &str) -> Self {
self.resource = Some(resource.to_string());
self
}
pub fn source(mut self, source: &glib::Bytes) -> Self {
self.source = Some(source.clone());
self
}
}
impl fmt::Display for GLShader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("GLShader")
}
}
| 30.982533 | 119 | 0.577167 |
1de61b701bd9203cb61fee3099105aefe33762cd | 51,451 | use super::{DeviceMemoryPool, HostMemoryPool, Storage, StorageError, StorageId};
use crate::prelude::*;
use crate::types::{ChunkLayout, DeviceId, GenericAccessor, MemoryKind, UnifiedPtr, MAX_DEVICES};
use crate::worker::memory::copy_engine::CopyEngine;
use by_address::ByAddress;
use crossbeam::channel::Sender;
use lightning_core::util::{TCell, TCellOwner};
use lightning_cuda::prelude::*;
use lru::LruCache;
use rc_borrow::ArcBorrow;
use std::any::Any;
use std::fmt::{self, Debug};
use std::num::NonZeroU32;
use std::ptr;
use std::ptr::NonNull;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Weak};
use std::task::Poll::{self, Pending, Ready};
struct LockMarker;
type Lock = TCellOwner<LockMarker>;
#[derive(Debug)]
pub(crate) enum Event {
MarkValidFile {
chunk: ChunkHandle,
result: Result<StorageId, StorageError>,
},
MarkValidHost {
chunk: ChunkHandle,
result: Result,
},
MarkValidDevice {
chunk: ChunkHandle,
device_id: DeviceId,
result: CudaResult,
},
}
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
enum EntryStatus {
Invalid,
Valid,
}
impl Default for EntryStatus {
fn default() -> Self {
Self::Invalid
}
}
#[derive(Debug)]
struct Entry<T> {
status: EntryStatus,
data: Option<T>,
locks: usize,
}
unsafe impl Send for Entry<HostPtr> {}
unsafe impl Sync for Entry<HostPtr> {}
impl<T> Default for Entry<T> {
fn default() -> Self {
Self {
status: default(),
data: None,
locks: 0,
}
}
}
impl<T> Entry<T> {
fn is_valid(&self) -> bool {
matches!(&self.status, EntryStatus::Valid)
}
}
#[derive(Debug)]
enum FileEntry {
Valid(StorageId),
Error(StorageError),
Invalid,
}
impl FileEntry {
fn is_valid(&self) -> bool {
matches!(self, FileEntry::Valid(_))
}
}
impl Default for FileEntry {
fn default() -> Self {
FileEntry::Invalid
}
}
type HostPtr = NonNull<u8>;
#[derive(Debug)]
struct DataTransfer {
src: MemoryKind,
requests: RequestList,
}
impl DataTransfer {
fn add_request(&mut self, request: RequestRef) {
self.requests.push_back(request);
}
}
#[derive(Default, Debug)]
struct DataTransferList {
to_file: Option<DataTransfer>,
to_host: Option<DataTransfer>,
to_devices: [Option<DataTransfer>; MAX_DEVICES],
}
impl DataTransferList {
fn find_by_src_or_dst(&mut self, mem: MemoryKind) -> Option<&mut DataTransfer> {
if self.to_file.as_ref().map_or(false, |t| t.src == mem) {
return self.to_file.as_mut();
}
if self.to_host.as_ref().map_or(false, |t| t.src == mem) {
return self.to_host.as_mut();
}
if let Some(i) = self.to_devices.iter().flatten().position(|t| t.src == mem) {
return self.to_devices[i].as_mut();
}
self.find_by_dst(mem)
}
fn find_by_dst(&mut self, dst: MemoryKind) -> Option<&mut DataTransfer> {
match dst {
MemoryKind::FileSystem => self.to_file.as_mut(),
MemoryKind::Host => self.to_host.as_mut(),
MemoryKind::Device(i) => self.to_devices[i.get()].as_mut(),
}
}
fn find_any(&mut self) -> Option<&mut DataTransfer> {
if let Some(transfer) = &mut self.to_file {
return Some(transfer);
}
if let Some(transfer) = &mut self.to_host {
return Some(transfer);
}
for device in &mut self.to_devices {
if let Some(transfer) = device {
return Some(transfer);
}
}
None
}
fn insert(&mut self, src: MemoryKind, dst: MemoryKind) -> &mut DataTransfer {
let t = match dst {
MemoryKind::FileSystem => &mut self.to_file,
MemoryKind::Host => &mut self.to_host,
MemoryKind::Device(i) => &mut self.to_devices[i.get()],
};
assert!(t.is_none());
*t = Some(DataTransfer {
src,
requests: RequestList::new(),
});
t.as_mut().unwrap()
}
#[inline]
fn remove_by_dst(&mut self, dst: MemoryKind) -> RequestList {
match dst {
MemoryKind::FileSystem => &mut self.to_file,
MemoryKind::Host => &mut self.to_host,
MemoryKind::Device(i) => &mut self.to_devices[i.get()],
}
.take()
.unwrap()
.requests
}
}
pub(crate) struct ChunkMeta {
layout: ChunkLayout,
size_in_bytes: usize,
state: TCell<LockMarker, ChunkState>,
}
impl ChunkMeta {
pub(crate) fn size_in_bytes(&self) -> usize {
self.size_in_bytes
}
}
impl Debug for ChunkMeta {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ChunkMeta")
.field("layout", &self.layout)
.field("size_in_bytes", &self.size_in_bytes)
.field("state", &"...")
.finish()
}
}
#[derive(Debug)]
struct ChunkState {
status: ChunkStatus,
active_transfers: DataTransferList,
file_entry: FileEntry,
host_entry: Entry<HostPtr>,
device_entries: [Entry<CudaDevicePtr>; MAX_DEVICES],
waiters: RequestList,
refcount: usize,
deletion_planned: bool,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum ChunkStatus {
Available,
Readers(NonZeroU32),
Writer,
Deleted,
}
impl ChunkState {
fn is_valid_anywhere(&self) -> bool {
self.host_entry.is_valid()
|| self.file_entry.is_valid()
|| any(&self.device_entries, |e| e.is_valid())
}
fn is_valid_at(&self, place: MemoryKind) -> bool {
match place {
MemoryKind::FileSystem => self.file_entry.is_valid(),
MemoryKind::Host => self.host_entry.is_valid(),
MemoryKind::Device(i) => self.device_entries[i.get()].is_valid(),
}
}
fn is_valid_only_at(&self, place: MemoryKind) -> bool {
if (place == MemoryKind::Host) ^ self.host_entry.is_valid() {
return false;
}
if (place == MemoryKind::FileSystem) ^ self.file_entry.is_valid() {
return false;
}
for (index, entry) in enumerate(&self.device_entries) {
if (place == MemoryKind::Device(DeviceId::new(index))) ^ entry.is_valid() {
return false;
}
}
true
}
fn is_unlocked(&self) -> bool {
matches!(self.status, ChunkStatus::Available)
}
fn poll_lock(&mut self, request: RequestRef) -> Poll<()> {
match (self.status, request.exclusive) {
(ChunkStatus::Available, _) => Ready(()),
(ChunkStatus::Readers(_), false) => Ready(()),
_ => {
self.waiters.try_push_back(request);
Pending
}
}
}
fn lock(&mut self, request: RequestRef) {
self.status = match (self.status, request.exclusive) {
(ChunkStatus::Available, true) => ChunkStatus::Writer,
(ChunkStatus::Available, false) => ChunkStatus::Readers(NonZeroU32::new(1).unwrap()),
(ChunkStatus::Readers(n), false) => {
ChunkStatus::Readers(NonZeroU32::new(n.get() + 1).unwrap())
}
l => panic!("invalid status, cannot lock {:?}", l),
}
}
fn unlock(&mut self, request: RequestRef, queue: &mut RequestList) {
self.status = match (self.status, request.exclusive) {
(ChunkStatus::Writer, true) => ChunkStatus::Available,
(ChunkStatus::Readers(n), false) => {
if let Some(new_n) = NonZeroU32::new(n.get() - 1) {
ChunkStatus::Readers(new_n)
} else {
ChunkStatus::Available
}
}
l => panic!("invalid status, cannot unlock {:?}", l),
};
queue.extend(&mut self.waiters);
}
fn flag_for_deletion(&mut self) {
self.deletion_planned = true;
}
}
#[derive(Error, Debug)]
pub(crate) enum AllocationError {
#[error("transaction failed, insufficient host memory to satisfy request")]
HostMemoryExhausted,
#[error("transaction failed, insufficient device memory to satisfy request")]
DeviceMemoryExhausted,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
struct TransactionId(usize);
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
enum RequestStatus {
DependenciesPending(usize),
WaitingForLock,
WaitingForSubmission,
Submitted,
AllocateHost,
AllocateDevice(DeviceId),
WaitingForData,
Active,
Terminated,
}
pub(crate) struct Request {
transaction_id: TransactionId,
chunk: ChunkHandle,
exclusive: bool,
parent: RequestParent,
next_in_queue: RequestLink,
state: TCell<LockMarker, RequestState>,
}
impl Debug for Request {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Request")
.field("transaction_id", &self.transaction_id)
.field("chunk", &self.chunk)
.field("exclusive", &self.exclusive)
.field("state", &"...")
.finish()
}
}
struct RequestState {
status: RequestStatus,
place: Option<MemoryKind>,
}
impl Request {
#[inline]
pub(crate) fn parent(&self) -> &RequestParent {
&self.parent
}
#[inline]
pub(crate) fn chunk(&self) -> &ChunkHandle {
&self.chunk
}
#[inline]
fn status(&self, token: &Lock) -> RequestStatus {
self.state.borrow(token).status
}
#[inline]
fn set_status(&self, new_status: RequestStatus, token: &mut Lock) {
/*trace!("request {:?}: {:?} -> {:?}", &self, self.status(token), new_status);*/
self.state.borrow_mut(token).status = new_status;
}
pub(crate) fn get(&self, manager: &Manager) -> GenericAccessor {
let state = self.state.borrow(&manager.token);
assert_eq!(state.status, RequestStatus::Active);
let place = state.place;
let chunk = &self.chunk;
let state = chunk.state.borrow(&manager.token);
let ptr = match place {
Some(MemoryKind::Host) => {
let ptr = state.host_entry.data.unwrap().as_ptr();
match self.exclusive {
true => UnifiedPtr::HostMut(ptr),
false => UnifiedPtr::Host(ptr),
}
}
Some(MemoryKind::Device(i)) => {
let ptr = state.device_entries[i.get()].data.unwrap();
match self.exclusive {
true => UnifiedPtr::DeviceMut(ptr, i),
false => UnifiedPtr::Device(ptr, i),
}
}
_ => unreachable!(),
};
let layout = &chunk.layout;
unsafe { GenericAccessor::new(ptr, layout.strides, layout.size, layout.data_type) }
}
}
pub(crate) type RequestHandle = Arc<Request>;
type RequestRef<'a> = ArcBorrow<'a, Request>;
pub(crate) type RequestParent = Weak<dyn Any + Send + Sync>;
pub(crate) enum RequestEvent {
Ready,
Active,
Abort(anyhow::Error),
}
#[derive(Debug)]
struct RequestList {
head: Option<RequestHandle>,
tail: *const Request,
}
unsafe impl Send for RequestList {}
unsafe impl Sync for RequestList {}
impl RequestList {
fn new() -> Self {
Self {
head: None,
tail: ptr::null(),
}
}
fn is_empty(&self) -> bool {
self.head.is_none()
}
fn push_back(&mut self, handle: RequestRef) {
assert!(self.try_push_back(handle));
}
fn try_push_back(&mut self, handle: RequestRef) -> bool {
if !handle.next_in_queue.try_acquire() {
return false;
}
let old_tail = replace(&mut self.tail, &handle as &Request as *const Request);
let handle = RequestRef::upgrade(handle);
if old_tail.is_null() {
self.head = Some(handle);
} else {
unsafe { (&*old_tail).next_in_queue.set(handle) };
}
true
}
fn pop_front(&mut self) -> Option<RequestHandle> {
if let Some(head) = &self.head {
let next = head.next_in_queue.release();
if next.is_none() {
self.tail = ptr::null();
};
replace(&mut self.head, next)
} else {
None
}
}
fn extend(&mut self, other: &mut RequestList) {
let middle = if let Some(head) = take(&mut other.head) {
head
} else {
return;
};
if self.tail.is_null() {
self.head = Some(middle);
} else {
unsafe { (&*self.tail).next_in_queue.set(middle) };
};
self.tail = other.tail;
other.tail = ptr::null();
}
}
impl Drop for RequestList {
fn drop(&mut self) {
while let Some(_) = self.pop_front() {
//
}
}
}
struct RequestLink {
ptr: AtomicUsize,
}
const FREE_LINK: usize = 0;
const ACQUIRED_LINK: usize = 1;
impl RequestLink {
fn new() -> Self {
Self {
ptr: AtomicUsize::new(FREE_LINK),
}
}
fn try_acquire(&self) -> bool {
self.ptr
.compare_exchange(FREE_LINK, ACQUIRED_LINK, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
}
unsafe fn set(&self, request: RequestHandle) {
let ptr = RequestHandle::into_raw(request) as usize;
self.ptr.store(ptr, Ordering::SeqCst);
}
fn release(&self) -> Option<RequestHandle> {
match self.ptr.swap(FREE_LINK, Ordering::SeqCst) {
x if x == FREE_LINK => panic!("link not locked"),
x if x == ACQUIRED_LINK => None,
ptr => unsafe { Some(Arc::from_raw(ptr as *const Request)) },
}
}
}
pub(crate) type ChunkHandle = Arc<ChunkMeta>;
type ChunkRef<'a> = ArcBorrow<'a, ChunkMeta>;
struct MemoryContext<P> {
memory: P,
lru: LruCache<ByAddress<ChunkHandle>, ()>,
pending_allocations: RequestList,
active_allocation: Option<RequestHandle>,
allocs_per_transaction: HashMap<TransactionId, usize>,
}
trait MemoryOps {
type Ptr;
fn allocate_entry(&mut self, chunk: ChunkRef, token: &mut Lock) -> bool;
fn deallocate_entry(&mut self, chunk: ChunkRef, token: &mut Lock);
fn entry<'a>(&mut self, chunk: ChunkRef<'a>, token: &'a mut Lock) -> &'a mut Entry<Self::Ptr>;
}
impl MemoryOps for HostMemoryPool {
type Ptr = HostPtr;
fn allocate_entry(&mut self, chunk: ChunkRef, token: &mut Lock) -> bool {
let state = chunk.state.borrow_mut(token);
let entry = &mut state.host_entry;
if entry.data.is_none() {
let size_in_bytes = chunk.size_in_bytes;
let alignment = chunk.layout.alignment;
if let Ok(ptr) = self.allocate(size_in_bytes, alignment) {
entry.data = HostPtr::new(ptr);
} else {
return false;
}
}
true
}
fn deallocate_entry(&mut self, chunk: ChunkRef, token: &mut Lock) {
let entry = self.entry(chunk, token);
if let Some(hptr) = entry.data.take() {
self.deallocate(hptr.as_ptr(), chunk.size_in_bytes);
}
}
fn entry<'a>(&mut self, chunk: ChunkRef<'a>, token: &'a mut Lock) -> &'a mut Entry<HostPtr> {
let state = ChunkRef::downgrade(chunk).state.borrow_mut(token);
&mut state.host_entry
}
}
impl MemoryOps for (DeviceId, DeviceMemoryPool) {
type Ptr = CudaDevicePtr;
fn allocate_entry(&mut self, chunk: ChunkRef, token: &mut Lock) -> bool {
let (device_id, memory) = self;
let state = chunk.state.borrow_mut(token);
let entry = &mut state.device_entries[device_id.get()];
if entry.data.is_none() {
let size_in_bytes = chunk.size_in_bytes;
let alignment = chunk.layout.alignment;
if let Ok(ptr) = memory.allocate(size_in_bytes, alignment) {
entry.data = Some(ptr.cast());
} else {
return false;
}
}
true
}
fn deallocate_entry(&mut self, chunk: ChunkRef, token: &mut Lock) {
let entry = self.entry(chunk, token);
if let Some(dptr) = entry.data.take() {
let (_, memory) = self;
memory.deallocate(dptr.cast(), chunk.size_in_bytes);
};
}
fn entry<'a>(
&mut self,
chunk: ChunkRef<'a>,
token: &'a mut Lock,
) -> &'a mut Entry<CudaDevicePtr> {
let (device_id, _) = self;
let state = ChunkRef::downgrade(chunk).state.borrow_mut(token);
&mut state.device_entries[device_id.get()]
}
}
impl<T: MemoryOps> MemoryContext<T> {
fn new(inner: T) -> Self {
Self {
memory: inner,
lru: LruCache::unbounded(),
pending_allocations: RequestList::new(),
active_allocation: None,
allocs_per_transaction: default(),
}
}
fn is_out_of_memory(&mut self, request: RequestRef) -> bool {
let id = request.transaction_id;
self.allocs_per_transaction.len() == 0
|| (self.allocs_per_transaction.len() == 1
&& self.allocs_per_transaction.contains_key(&id))
}
fn try_reserve_allocation(&mut self, request: RequestRef, token: &mut Lock) -> bool {
let chunk = ChunkRef::from(&request.chunk);
if !self.memory.allocate_entry(chunk, token) {
return false;
}
self.reserve_allocation(request, token);
true
}
fn reserve_allocation(&mut self, request: RequestRef, token: &mut Lock) {
let chunk = ChunkRef::from(&request.chunk);
let transaction = request.transaction_id;
let entry = self.memory.entry(chunk, token);
assert!(entry.data.is_some());
if entry.locks == 0 {
self.lru.pop(&ByAddress(ChunkRef::upgrade(chunk)));
}
entry.locks += 1;
*self.allocs_per_transaction.entry(transaction).or_default() += 1;
}
fn unreserve_allocation(&mut self, request: RequestRef, token: &mut Lock) {
let chunk = ChunkRef::from(&request.chunk);
let transaction = request.transaction_id;
use std::collections::hash_map::Entry::Occupied;
if let Occupied(mut e) = self.allocs_per_transaction.entry(transaction) {
if *e.get() > 1 {
*e.get_mut() -= 1;
} else {
e.remove();
}
} else {
panic!();
}
let entry = self.memory.entry(chunk, token);
assert!(entry.data.is_some());
entry.locks -= 1;
if entry.locks == 0 {
self.lru.put(ByAddress(ChunkRef::upgrade(chunk)), ());
}
}
fn deallocate_entry(&mut self, chunk: ChunkRef, token: &mut Lock) {
let entry = self.memory.entry(chunk, token);
assert_eq!(entry.locks, 0);
entry.status = EntryStatus::Invalid;
self.memory.deallocate_entry(chunk, token);
self.lru.pop(&ByAddress(ChunkRef::upgrade(chunk)));
}
}
pub(crate) struct Manager {
sender: Sender<Event>,
chunks: HashSet<ByAddress<ChunkHandle>>,
queue: RequestList,
host: MemoryContext<HostMemoryPool>,
devices: Vec<MemoryContext<(DeviceId, DeviceMemoryPool)>>,
copy_engine: CopyEngine,
storage: Option<Storage>,
token: Lock,
}
impl Manager {
pub(crate) unsafe fn new(
sender: Sender<Event>,
host: HostMemoryPool,
devices: Vec<DeviceMemoryPool>,
copy_engine: CopyEngine,
storage: Option<Storage>,
) -> Self {
let host = MemoryContext::new(host);
let devices = devices
.into_iter()
.enumerate()
.map(|(index, device)| MemoryContext::new((DeviceId::new(index), device)))
.collect_vec();
Self {
sender,
chunks: default(),
queue: RequestList::new(),
host,
devices,
copy_engine,
storage,
token: Lock::new(),
}
}
pub(crate) fn create_chunk(&mut self, layout: ChunkLayout) -> ChunkHandle {
let size_in_bytes = match layout.size_in_bytes() {
Some(s) => s,
None => {
panic!("layout is not contiguous: {:?}", layout);
}
};
let state = ChunkState {
status: ChunkStatus::Available,
active_transfers: default(),
file_entry: default(),
host_entry: default(),
device_entries: default(),
waiters: RequestList::new(),
refcount: 0,
deletion_planned: false,
};
let chunk = Arc::new(ChunkMeta {
layout,
size_in_bytes,
state: TCell::new(state),
});
let by_address = ByAddress(ChunkHandle::clone(&chunk));
let inserted = self.chunks.insert(by_address);
assert_eq!(inserted, true);
chunk
}
pub(crate) fn delete_chunk(&mut self, chunk: &ChunkHandle) {
let state = chunk.state.borrow_mut(&mut self.token);
state.flag_for_deletion();
self.delete_chunk_when_idle(chunk);
}
pub(crate) fn is_idle(&mut self) -> bool {
if !self.queue.is_empty() {
return false;
}
for chunk in &self.chunks {
let state = chunk.state.borrow_mut(&mut self.token);
if let Some(_) = state.active_transfers.find_any() {
return false;
}
}
true
}
fn delete_chunk_when_idle(&mut self, chunk: &ChunkHandle) {
use ChunkStatus::*;
let chunk = ChunkRef::from(chunk);
let state = chunk.state.borrow_mut(&mut self.token);
if !state.deletion_planned || state.refcount != 0 || state.status == Deleted {
return;
}
if let Some(_) = state.active_transfers.find_any() {
eprintln!(
"cannot release buffer {:#?} (state: {:#?}): transfers still in progress",
chunk,
chunk.state.borrow(&self.token),
);
return;
}
assert!(state.is_unlocked());
let by_address = ByAddress(ChunkRef::upgrade(chunk));
let found = self.chunks.remove(&by_address);
assert!(found);
let state = chunk.state.borrow_mut(&mut self.token);
// Make deletion permanent
state.status = Deleted;
// Delete file
if let FileEntry::Valid(id) = take(&mut state.file_entry) {
self.storage.as_ref().unwrap().delete_async(id);
}
self.host.deallocate_entry(chunk, &mut self.token);
self.make_progress_host_allocations();
for index in 0..self.devices.len() {
let device = &mut self.devices[index];
device.deallocate_entry(chunk, &mut self.token);
self.make_progress_device_allocations(DeviceId::new(index));
}
}
pub(crate) fn create_request(
&mut self,
chunk: &ChunkHandle,
parent: RequestParent,
exclusive: bool,
num_dependencies: usize,
) -> RequestHandle {
let transaction_id = TransactionId(parent.as_ptr() as *const () as usize);
let state = chunk.state.borrow_mut(&mut self.token);
assert_eq!(state.deletion_planned, false);
state.refcount += 1;
let request = Arc::new(Request {
state: TCell::new(RequestState {
status: RequestStatus::DependenciesPending(num_dependencies),
place: None,
}),
parent,
chunk: ChunkHandle::clone(chunk),
exclusive,
transaction_id,
next_in_queue: RequestLink::new(),
});
self.queue.push_back(RequestRef::from(&request));
request
}
pub(crate) fn satisfy_dependency(&mut self, request: &RequestHandle) {
let n = match request.status(&self.token) {
RequestStatus::DependenciesPending(n) => n - 1,
other => panic!("invalid status: {:?}", other),
};
request.set_status(RequestStatus::DependenciesPending(n), &mut self.token);
if n == 0 {
self.queue.try_push_back(request.into());
}
}
pub(crate) fn may_submit_request(&mut self, request: &RequestHandle) -> bool {
let request: RequestRef = request.into();
let status = request.status(&self.token);
if status != RequestStatus::WaitingForSubmission {
return false;
}
let state = request.chunk.state.borrow_mut(&mut self.token);
if state.poll_lock(request).is_pending() {
request.set_status(RequestStatus::WaitingForLock, &mut self.token);
return false;
}
true
}
pub(crate) fn submit_request(&mut self, request: &RequestHandle, place: Option<MemoryKind>) {
let request: RequestRef = request.into();
assert_eq!(
request.status(&self.token),
RequestStatus::WaitingForSubmission
);
let state = request.chunk.state.borrow_mut(&mut self.token);
state.lock(request);
let state = request.state.borrow_mut(&mut self.token);
state.place = place;
state.status = RequestStatus::Submitted;
self.queue.push_back(request);
}
pub(crate) unsafe fn finish_request(&mut self, request: &RequestHandle) {
use RequestStatus::*;
let request: RequestRef = request.into();
assert!(matches!(request.status(&self.token), Active | Terminated));
self.release_request_resources(request);
}
pub(crate) fn handle_event(&mut self, event: Event) {
//warn!("event: {:#?}", event);
let (dst, chunk) = match event {
Event::MarkValidFile { chunk, result } => {
let mut state = chunk.state.borrow_mut(&mut self.token);
state.file_entry = match result {
Ok(id) => FileEntry::Valid(id),
Err(e) => FileEntry::Error(e),
};
(MemoryKind::FileSystem, chunk)
}
Event::MarkValidHost { chunk, result } => {
result.expect("???");
let state = chunk.state.borrow_mut(&mut self.token);
let entry = &mut state.host_entry;
entry.status = EntryStatus::Valid;
(MemoryKind::Host, chunk)
}
Event::MarkValidDevice {
chunk,
device_id,
result,
} => {
result.expect("???");
let state = chunk.state.borrow_mut(&mut self.token);
let entry = &mut state.device_entries[device_id.get()];
entry.status = EntryStatus::Valid;
(MemoryKind::Device(device_id), chunk)
}
};
let state = chunk.state.borrow_mut(&mut self.token);
let mut requests = state.active_transfers.remove_by_dst(dst);
self.queue.extend(&mut requests);
self.delete_chunk_when_idle(&chunk);
}
pub(crate) fn poll(&mut self) -> Option<(RequestHandle, RequestEvent)> {
while let Some(request) = self.queue.pop_front() {
if let Some(event) = self.poll_request(RequestRef::from(&request)) {
return Some((request, event));
}
}
None
}
fn release_request_resources(&mut self, request: RequestRef) {
use RequestStatus::*;
let state = request.state.borrow_mut(&mut self.token);
let old_status = replace(&mut state.status, RequestStatus::Terminated);
let place = state.place;
match old_status {
AllocateDevice(_) | WaitingForData | Active => {
self.host.unreserve_allocation(request, &mut self.token);
self.make_progress_host_allocations();
}
AllocateHost
| Terminated
| DependenciesPending(_)
| WaitingForLock
| WaitingForSubmission
| Submitted => {}
}
if let Some(MemoryKind::Device(i)) = place {
match old_status {
WaitingForData | Active => {
let device = &mut self.devices[i.get()];
device.unreserve_allocation(request, &mut self.token);
self.make_progress_device_allocations(i);
}
AllocateHost | AllocateDevice(_) | Terminated => {}
WaitingForLock | WaitingForSubmission | Submitted | DependenciesPending(_) => {}
}
}
match old_status {
AllocateDevice(_) | WaitingForData | Active | AllocateHost => {
let state = request.chunk.state.borrow_mut(&mut self.token);
state.unlock(request, &mut self.queue);
}
Terminated => {}
WaitingForLock | WaitingForSubmission | Submitted | DependenciesPending(_) => {}
}
if old_status != Terminated {
let state = request.chunk.state.borrow_mut(&mut self.token);
state.refcount -= 1;
}
self.delete_chunk_when_idle(&request.chunk);
}
fn abort_request(&mut self, request: RequestRef, error: anyhow::Error) -> Option<RequestEvent> {
self.release_request_resources(request); // Will also update status
Some(RequestEvent::Abort(error))
}
fn poll_request(&mut self, request: RequestRef) -> Option<RequestEvent> {
use RequestStatus::*;
loop {
match request.status(&self.token) {
DependenciesPending(n) => {
if n > 0 {
return None;
}
request.set_status(WaitingForLock, &mut self.token);
}
WaitingForLock => {
let state = request.chunk.state.borrow_mut(&mut self.token);
if state.poll_lock(request).is_pending() {
return None;
}
request.set_status(WaitingForSubmission, &mut self.token);
return Some(RequestEvent::Ready);
}
WaitingForSubmission => {
//
}
Submitted => {
request.set_status(AllocateHost, &mut self.token);
if !self.push_host_allocation(request) {
return None;
}
}
AllocateHost => {
match self.poll_host_allocation(request) {
Ready(Ok(())) => {}
Ready(Err(e)) => {
return self.abort_request(request, e.into());
}
Pending => return None,
}
let place = request.state.borrow(&self.token).place;
match place {
Some(MemoryKind::Device(device_id)) => {
request.set_status(AllocateDevice(device_id), &mut self.token);
if !self.push_device_allocation(device_id, request) {
return None;
}
}
Some(MemoryKind::Host) | None => {
request.set_status(WaitingForData, &mut self.token);
}
_ => {
unimplemented!();
}
}
}
AllocateDevice(device_id) => {
match self.poll_device_allocation(device_id, request) {
Ready(Ok(())) => {}
Ready(Err(e)) => {
return self.abort_request(request, e.into());
}
Pending => return None,
}
request.set_status(WaitingForData, &mut self.token);
}
WaitingForData => {
let place = self.determine_request_place(request);
match self.poll_data(place, request) {
Ready(Ok(())) => {}
Ready(Err(e)) => {
return self.abort_request(request, e.into());
}
Pending => return None,
}
if request.exclusive {
if self.poll_exclusive(place, request).is_pending() {
return None;
}
}
request.set_status(Active, &mut self.token);
return Some(RequestEvent::Active);
}
Active => {}
Terminated => {}
}
}
}
fn determine_request_place(&mut self, request: RequestRef) -> MemoryKind {
let state = request.state.borrow_mut(&mut self.token);
if let Some(place) = state.place {
return place;
}
let chunk = &request.chunk;
let affinity = chunk.layout.affinity;
let state = chunk.state.borrow_mut(&mut self.token);
// Try to find a valid place
// - if buffer is valid at affinity, use affinity
// - otherwise, if buffer is valid at host, use host
// - otherwise, if buffer valid at some device, use that device
// - otherwise, buffer is not valid anywhere, use affinity
// - otherwise, if affinity is None, use host
let mut valid_place = 'a: loop {
if let Some(p) = affinity {
if state.is_valid_at(p) {
break p;
}
}
if state.host_entry.is_valid() {
break MemoryKind::Host;
}
for (i, entry) in enumerate(&mut state.device_entries) {
if entry.is_valid() {
break 'a MemoryKind::Device(DeviceId::new(i));
}
}
if let Some(p) = affinity {
break p;
}
break MemoryKind::Host;
};
if let MemoryKind::Device(i) = valid_place {
let device = &mut self.devices[i.get()];
if !device.try_reserve_allocation(request, &mut self.token) {
valid_place = MemoryKind::Host;
}
}
let state = request.state.borrow_mut(&mut self.token);
state.place = Some(valid_place);
valid_place
}
fn push_host_allocation(&mut self, request: RequestRef) -> bool {
if self.host.active_allocation.is_none() {
self.host.active_allocation = Some(RequestRef::upgrade(request));
true
} else {
self.host.pending_allocations.push_back(request);
false
}
}
fn poll_host_allocation(&mut self, request: RequestRef) -> Poll<Result> {
if !ptr::eq(
RequestRef::into_raw(request),
self.host
.active_allocation
.as_ref()
.map_or(ptr::null(), Arc::as_ptr),
) {
return Pending;
}
let result = loop {
if self.host.try_reserve_allocation(request, &mut self.token) {
break Ok(());
}
match self.evict_host_allocation(request) {
Pending => return Pending,
Ready(Err(e)) => break Err(e),
Ready(Ok(true)) => continue, // Retry
Ready(Ok(false)) => {} //
}
if self.host.is_out_of_memory(request) {
break Err(AllocationError::HostMemoryExhausted.into());
} else {
return Pending;
}
};
self.host.active_allocation = self.host.pending_allocations.pop_front();
if let Some(request) = &self.host.active_allocation {
self.queue.try_push_back(request.into());
}
Ready(result)
}
fn make_progress_host_allocations(&mut self) {
if let Some(request) = &self.host.active_allocation {
self.queue.try_push_back(request.into());
}
}
fn evict_host_allocation(&mut self, request: RequestRef) -> Poll<Result<bool>> {
if self.storage.is_none() {
return Ready(Ok(false));
}
let chunk = match self.host.lru.peek_lru() {
Some((chunk, _)) => ChunkHandle::clone(&chunk),
None => return Ready(Ok(false)),
};
let chunk = ChunkRef::from(&chunk);
match self.poll_file_data(chunk, request) {
Pending => return Pending,
Ready(Ok(())) => {}
Ready(Err(e)) => {
return Ready(match e {
StorageError::CapacityExceeded(_) => Ok(false),
e => {
// TODO: IO error occurred while copying to file. Not sure how to handle this.
error!("IO error while evicting to file: {:?}", e);
Err(e.into())
}
});
}
}
let state = chunk.state.borrow_mut(&mut self.token);
if let Some(transfer) = state.active_transfers.find_any() {
transfer.add_request(request);
return Pending;
}
// Deallocate all device entries.
for device in &mut self.devices {
device.deallocate_entry(chunk, &mut self.token);
}
// Deallocate host entry
self.host.deallocate_entry(chunk, &mut self.token);
Ready(Ok(true))
}
fn push_device_allocation(&mut self, device_id: DeviceId, request: RequestRef) -> bool {
let device = &mut self.devices[device_id.get()];
if device.active_allocation.is_none() {
device.active_allocation = Some(RequestRef::upgrade(request));
true
} else {
device.pending_allocations.push_back(request);
false
}
}
fn make_progress_device_allocations(&mut self, device_id: DeviceId) {
let device = &mut self.devices[device_id.get()];
if let Some(request) = &device.active_allocation {
self.queue.try_push_back(request.into());
}
}
fn poll_device_allocation(
&mut self,
device_id: DeviceId,
request: RequestRef,
) -> Poll<Result<(), AllocationError>> {
let device = &mut self.devices[device_id.get()];
if !ptr::eq(
RequestRef::into_raw(request),
device
.active_allocation
.as_ref()
.map_or(ptr::null(), Arc::as_ptr),
) {
return Pending;
}
let result = loop {
let device = &mut self.devices[device_id.get()];
if device.try_reserve_allocation(request, &mut self.token) {
break Ok(());
}
match self.evict_device_allocation(device_id, request) {
Pending => return Pending,
Ready(true) => continue,
Ready(false) => {}
};
let device = &mut self.devices[device_id.get()];
if device.is_out_of_memory(request) {
break Err(AllocationError::DeviceMemoryExhausted);
} else {
return Pending;
}
};
let device = &mut self.devices[device_id.get()];
device.active_allocation = device.pending_allocations.pop_front();
if let Some(request) = &device.active_allocation {
self.queue.try_push_back(request.into());
}
Ready(result)
}
fn evict_device_allocation(&mut self, device_id: DeviceId, request: RequestRef) -> Poll<bool> {
let device = &mut self.devices[device_id.get()];
let chunk = match device.lru.peek_lru() {
Some((chunk, _)) => ChunkHandle::clone(&chunk),
None => return Ready(false),
};
let state = chunk.state.borrow_mut(&mut self.token);
if let Some(transfer) = state
.active_transfers
.find_by_src_or_dst(MemoryKind::Device(device_id))
{
transfer.add_request(request);
return Pending;
}
let chunk = ChunkRef::from(&chunk);
if state.is_valid_only_at(MemoryKind::Device(device_id)) {
let poll = self.poll_host_data(chunk, request);
assert!(poll.is_pending());
return Pending;
}
device.deallocate_entry(chunk, &mut self.token);
Ready(true)
}
fn poll_data(&mut self, place: MemoryKind, request: RequestRef) -> Poll<Result> {
let chunk = ChunkRef::from(&request.chunk);
match place {
MemoryKind::Host => self.poll_host_data(chunk, request),
MemoryKind::Device(device_id) => self.poll_device_data(device_id, chunk, request),
_ => unreachable!(), // Place must be known by now.
}
}
fn poll_file_data(
&mut self,
chunk: ChunkRef,
request: RequestRef,
) -> Poll<Result<(), StorageError>> {
let state = chunk.state.borrow_mut(&mut self.token);
let entry = &mut state.file_entry;
match take(entry) {
FileEntry::Valid(id) => {
*entry = FileEntry::Valid(id);
return Ready(Ok(()));
}
FileEntry::Error(e) => {
return Ready(Err(e));
}
FileEntry::Invalid => {}
}
if let Some(transfer) = state.active_transfers.find_by_dst(MemoryKind::FileSystem) {
transfer.add_request(request);
return Pending;
}
if self.poll_host_data(chunk, request).is_pending() {
return Pending;
}
let transfer = unsafe { self.copy_host_to_file(chunk) };
transfer.add_request(request);
Pending
}
fn poll_host_data(&mut self, chunk: ChunkRef, request: RequestRef) -> Poll<Result> {
let state = chunk.state.borrow_mut(&mut self.token);
let entry = &state.host_entry;
if entry.is_valid() {
return Ready(Ok(()));
}
if let Some(transfer) = state.active_transfers.find_by_dst(MemoryKind::Host) {
transfer.add_request(request);
return Pending;
}
if let Some(index) = state.device_entries.iter().position(|e| e.is_valid()) {
let device_id = DeviceId::new(index);
let transfer = unsafe { self.copy_device_to_host(device_id, chunk) };
transfer.add_request(request);
return Pending;
}
if state.file_entry.is_valid() {
return match unsafe { self.copy_file_to_host(chunk) } {
Ok(transfer) => {
transfer.add_request(request);
Pending
}
Err(e) => Ready(Err(e)),
};
}
// Data seems to be valid nowhere, set entry to valid.
state.host_entry.status = EntryStatus::Valid;
Ready(Ok(()))
}
fn poll_device_data(
&mut self,
device_id: DeviceId,
chunk: ChunkRef,
request: RequestRef,
) -> Poll<Result> {
let state = chunk.state.borrow_mut(&mut self.token);
let entry = &mut state.device_entries[device_id.get()];
if entry.is_valid() {
return Ready(Ok(()));
}
if let Some(transfer) = state
.active_transfers
.find_by_dst(MemoryKind::Device(device_id))
{
transfer.add_request(request);
return Pending;
}
for i in 0..self.devices.len() {
let src_id = DeviceId::new(i);
if !self.copy_engine.supported_d2d(src_id, device_id) {
continue;
}
if state.device_entries[src_id.get()].is_valid() {
let transfer = unsafe { self.copy_device_to_device(src_id, device_id, chunk) };
transfer.add_request(request);
return Pending;
}
}
if !state.is_valid_anywhere() {
let entry = &mut state.device_entries[device_id.get()];
entry.status = EntryStatus::Valid;
return Ready(Ok(()));
}
if self.poll_host_data(chunk, request).is_pending() {
return Pending;
}
let transfer = unsafe { self.copy_host_to_device(device_id, chunk) };
transfer.add_request(request);
Pending
}
fn poll_exclusive(&mut self, place: MemoryKind, request: RequestRef) -> Poll<()> {
let chunk = &request.chunk;
let state = chunk.state.borrow_mut(&mut self.token);
if let Some(transfer) = state.active_transfers.find_any() {
transfer.add_request(request);
return Pending;
}
// Invalidate host
if place == MemoryKind::Host {
assert_eq!(state.host_entry.status, EntryStatus::Valid);
} else {
state.host_entry.status = EntryStatus::Invalid;
}
// Invalidate devices
for (index, dentry) in enumerate(&mut state.device_entries) {
if place == MemoryKind::Device(DeviceId::new(index)) {
assert_eq!(dentry.status, EntryStatus::Valid);
} else {
dentry.status = EntryStatus::Invalid;
}
}
// Invalidate file
if let FileEntry::Valid(id) = take(&mut state.file_entry) {
self.storage.as_ref().unwrap().delete_async(id);
}
Ready(())
}
unsafe fn copy_device_to_host<'a>(
&'a mut self,
device_id: DeviceId,
chunk_ref: ChunkRef<'a>,
) -> &'a mut DataTransfer {
debug!("COPY D2H");
let sender = self.sender.clone();
let chunk = ChunkRef::upgrade(chunk_ref);
let state = ChunkRef::downgrade(chunk_ref)
.state
.borrow_mut(&mut self.token);
let nbytes = chunk.size_in_bytes;
let src = state.device_entries[device_id.get()].data.unwrap();
let dst = state.host_entry.data.unwrap();
self.copy_engine.copy_d2h(
device_id,
src,
dst.as_ptr() as *mut (),
nbytes,
move |result| {
sender
.send(Event::MarkValidHost {
chunk,
result: result.map_err(|e| e.into()),
})
.unwrap();
},
);
state
.active_transfers
.insert(MemoryKind::Device(device_id), MemoryKind::Host)
}
unsafe fn copy_host_to_device<'a>(
&'a mut self,
device_id: DeviceId,
chunk_ref: ChunkRef<'a>,
) -> &'a mut DataTransfer {
debug!("COPY H2D");
let sender = self.sender.clone();
let chunk = ChunkRef::upgrade(chunk_ref);
let state = ChunkRef::downgrade(chunk_ref)
.state
.borrow_mut(&mut self.token);
let nbytes = chunk.size_in_bytes;
let src = state.host_entry.data.unwrap();
let dst = state.device_entries[device_id.get()].data.unwrap();
self.copy_engine.copy_h2d(
src.as_ptr() as *const (),
device_id,
dst,
nbytes,
move |result| {
sender
.send(Event::MarkValidDevice {
chunk,
device_id,
result,
})
.unwrap();
},
);
state
.active_transfers
.insert(MemoryKind::Host, MemoryKind::Device(device_id))
}
unsafe fn copy_device_to_device<'a>(
&'a mut self,
src_id: DeviceId,
dst_id: DeviceId,
chunk_ref: ChunkRef<'a>,
) -> &'a mut DataTransfer {
let sender = self.sender.clone();
let chunk = ChunkRef::upgrade(chunk_ref);
let state = ChunkRef::downgrade(chunk_ref)
.state
.borrow_mut(&mut self.token);
let nbytes = chunk.size_in_bytes;
let src_ptr = state.device_entries[src_id.get()].data.unwrap();
let dst_ptr = state.device_entries[dst_id.get()].data.unwrap();
self.copy_engine
.copy_d2d(src_id, src_ptr, dst_id, dst_ptr, nbytes, move |result| {
sender
.send(Event::MarkValidDevice {
chunk,
device_id: dst_id,
result,
})
.unwrap();
});
state
.active_transfers
.insert(MemoryKind::Device(src_id), MemoryKind::Device(dst_id))
}
unsafe fn copy_host_to_file<'a>(&'a mut self, chunk_ref: ChunkRef<'a>) -> &'a mut DataTransfer {
let sender = self.sender.clone();
let chunk = ChunkRef::upgrade(chunk_ref);
let state = ChunkRef::downgrade(chunk_ref)
.state
.borrow_mut(&mut self.token);
let hptr = state.host_entry.data.unwrap();
let size_in_bytes = chunk_ref.size_in_bytes;
self.storage
.as_ref()
.unwrap()
.create_async(hptr.as_ptr(), size_in_bytes, move |result| {
sender.send(Event::MarkValidFile { chunk, result }).unwrap();
});
state
.active_transfers
.insert(MemoryKind::Host, MemoryKind::FileSystem)
}
unsafe fn copy_file_to_host<'a>(
&'a mut self,
chunk_ref: ChunkRef<'a>,
) -> Result<&'a mut DataTransfer> {
let sender = self.sender.clone();
let chunk = ChunkRef::upgrade(chunk_ref);
let state = ChunkRef::downgrade(chunk_ref)
.state
.borrow_mut(&mut self.token);
let path = match &state.file_entry {
FileEntry::Valid(id) => *id,
_ => unreachable!(),
};
let hptr = state.host_entry.data.unwrap();
let size_in_bytes = chunk.size_in_bytes;
self.storage.as_ref().unwrap().read_async(
path,
hptr.as_ptr(),
size_in_bytes,
move |result| {
sender
.send(Event::MarkValidHost {
chunk,
result: result.map_err(|e| e.into()),
})
.unwrap();
},
);
let transfer = state
.active_transfers
.insert(MemoryKind::FileSystem, MemoryKind::Host);
Ok(transfer)
}
}
| 29.843968 | 102 | 0.536821 |
8fc2d116af91d0ad31d508c97ecf075ec868f734 | 11,289 | #![cfg(feature = "test-bpf")]
mod program_test;
use {
program_test::{keypair_clone, TestContext, TokenContext},
solana_program_test::{
processor,
tokio::{self, sync::Mutex},
ProgramTest,
},
solana_sdk::{
account_info::{next_account_info, AccountInfo},
entrypoint::ProgramResult,
instruction::{AccountMeta, Instruction, InstructionError},
msg,
program::{get_return_data, invoke},
program_error::ProgramError,
pubkey::Pubkey,
signature::Signer,
signer::keypair::Keypair,
transaction::{Transaction, TransactionError},
transport::TransportError,
},
spl_token_2022::{
error::TokenError,
extension::interest_bearing_mint::InterestBearingConfig,
instruction::{amount_to_ui_amount, ui_amount_to_amount, AuthorityType},
processor::Processor,
},
spl_token_client::token::{ExtensionInitializationParams, TokenError as TokenClientError},
std::{convert::TryInto, sync::Arc},
};
#[tokio::test]
async fn success_initialize() {
for (rate, rate_authority) in [(i16::MIN, None), (i16::MAX, Some(Pubkey::new_unique()))] {
let mut context = TestContext::new().await;
context
.init_token_with_mint(vec![ExtensionInitializationParams::InterestBearingConfig {
rate_authority,
rate,
}])
.await
.unwrap();
let TokenContext { token, .. } = context.token_context.unwrap();
let state = token.get_mint_info().await.unwrap();
let extension = state.get_extension::<InterestBearingConfig>().unwrap();
assert_eq!(
Option::<Pubkey>::from(extension.rate_authority),
rate_authority,
);
assert_eq!(i16::from(extension.current_rate), rate,);
assert_eq!(i16::from(extension.pre_update_average_rate), rate,);
}
}
#[tokio::test]
async fn update_rate() {
let rate_authority = Keypair::new();
let initial_rate = 500;
let mut context = TestContext::new().await;
context
.init_token_with_mint(vec![ExtensionInitializationParams::InterestBearingConfig {
rate_authority: Some(rate_authority.pubkey()),
rate: initial_rate,
}])
.await
.unwrap();
let TokenContext { token, .. } = context.token_context.take().unwrap();
let state = token.get_mint_info().await.unwrap();
let extension = state.get_extension::<InterestBearingConfig>().unwrap();
assert_eq!(i16::from(extension.current_rate), initial_rate);
assert_eq!(i16::from(extension.pre_update_average_rate), initial_rate);
let initialization_timestamp = i64::from(extension.initialization_timestamp);
assert_eq!(
extension.initialization_timestamp,
extension.last_update_timestamp
);
// warp forward, so last update timestamp is advanced during update
let warp_slot = 1_000;
let initial_num_warps = 10;
for i in 1..initial_num_warps {
context
.context
.lock()
.await
.warp_to_slot(i * warp_slot)
.unwrap();
}
// correct
let middle_rate = 1_000;
token
.update_interest_rate(&rate_authority, middle_rate)
.await
.unwrap();
let state = token.get_mint_info().await.unwrap();
let extension = state.get_extension::<InterestBearingConfig>().unwrap();
assert_eq!(i16::from(extension.current_rate), middle_rate);
assert_eq!(i16::from(extension.pre_update_average_rate), initial_rate);
let last_update_timestamp = i64::from(extension.last_update_timestamp);
assert!(last_update_timestamp > initialization_timestamp);
// warp forward
let final_num_warps = 20;
for i in initial_num_warps..final_num_warps {
context
.context
.lock()
.await
.warp_to_slot(i * warp_slot)
.unwrap();
}
// update again, pre_update_average_rate is between the two previous
let new_rate = 2_000;
token
.update_interest_rate(&rate_authority, new_rate)
.await
.unwrap();
let state = token.get_mint_info().await.unwrap();
let extension = state.get_extension::<InterestBearingConfig>().unwrap();
assert_eq!(i16::from(extension.current_rate), new_rate);
let pre_update_average_rate = i16::from(extension.pre_update_average_rate);
assert!(pre_update_average_rate > initial_rate);
assert!(middle_rate > pre_update_average_rate);
let final_update_timestamp = i64::from(extension.last_update_timestamp);
assert!(final_update_timestamp > last_update_timestamp);
// wrong signer
let err = token
.update_interest_rate(&Keypair::new(), 0)
.await
.unwrap_err();
assert_eq!(
err,
TokenClientError::Client(Box::new(TransportError::TransactionError(
TransactionError::InstructionError(
0,
InstructionError::Custom(TokenError::OwnerMismatch as u32)
)
)))
);
}
#[tokio::test]
async fn set_authority() {
let rate_authority = Keypair::new();
let initial_rate = 500;
let mut context = TestContext::new().await;
context
.init_token_with_mint(vec![ExtensionInitializationParams::InterestBearingConfig {
rate_authority: Some(rate_authority.pubkey()),
rate: initial_rate,
}])
.await
.unwrap();
let TokenContext { token, .. } = context.token_context.take().unwrap();
// success
let new_rate_authority = Keypair::new();
token
.set_authority(
token.get_address(),
Some(&new_rate_authority.pubkey()),
AuthorityType::InterestRate,
&rate_authority,
)
.await
.unwrap();
let state = token.get_mint_info().await.unwrap();
let extension = state.get_extension::<InterestBearingConfig>().unwrap();
assert_eq!(
extension.rate_authority,
Some(new_rate_authority.pubkey()).try_into().unwrap(),
);
token
.update_interest_rate(&new_rate_authority, 10)
.await
.unwrap();
let err = token
.update_interest_rate(&rate_authority, 100)
.await
.unwrap_err();
assert_eq!(
err,
TokenClientError::Client(Box::new(TransportError::TransactionError(
TransactionError::InstructionError(
0,
InstructionError::Custom(TokenError::OwnerMismatch as u32)
)
)))
);
// set to none
token
.set_authority(
token.get_address(),
None,
AuthorityType::InterestRate,
&new_rate_authority,
)
.await
.unwrap();
let state = token.get_mint_info().await.unwrap();
let extension = state.get_extension::<InterestBearingConfig>().unwrap();
assert_eq!(extension.rate_authority, None.try_into().unwrap(),);
// now all fail
let err = token
.update_interest_rate(&new_rate_authority, 50)
.await
.unwrap_err();
assert_eq!(
err,
TokenClientError::Client(Box::new(TransportError::TransactionError(
TransactionError::InstructionError(
0,
InstructionError::Custom(TokenError::NoAuthorityExists as u32)
)
)))
);
let err = token
.update_interest_rate(&rate_authority, 5)
.await
.unwrap_err();
assert_eq!(
err,
TokenClientError::Client(Box::new(TransportError::TransactionError(
TransactionError::InstructionError(
0,
InstructionError::Custom(TokenError::NoAuthorityExists as u32)
)
)))
);
}
// test program to CPI into token to get ui amounts
fn process_instruction(
_program_id: &Pubkey,
accounts: &[AccountInfo],
_input: &[u8],
) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
let mint_info = next_account_info(account_info_iter)?;
let token_program = next_account_info(account_info_iter)?;
// 10 tokens, with 9 decimal places
let test_amount = 10_000_000_000;
// "10" as an amount should be smaller than test_amount due to interest
invoke(
&ui_amount_to_amount(token_program.key, mint_info.key, "10")?,
&[mint_info.clone(), token_program.clone()],
)?;
let (_, return_data) = get_return_data().unwrap();
let amount = u64::from_le_bytes(return_data[0..8].try_into().unwrap());
msg!("amount: {}", amount);
if amount >= test_amount {
return Err(ProgramError::InvalidInstructionData);
}
// test_amount as a UI amount should be larger due to interest
invoke(
&amount_to_ui_amount(token_program.key, mint_info.key, test_amount)?,
&[mint_info.clone(), token_program.clone()],
)?;
let (_, return_data) = get_return_data().unwrap();
let ui_amount = String::from_utf8(return_data).unwrap();
msg!("ui amount: {}", ui_amount);
let float_ui_amount = ui_amount.parse::<f64>().unwrap();
if float_ui_amount <= 10.0 {
return Err(ProgramError::InvalidInstructionData);
}
Ok(())
}
#[tokio::test]
async fn amount_conversions() {
let rate_authority = Keypair::new();
let mut program_test = ProgramTest::default();
program_test.prefer_bpf(false);
program_test.add_program(
"spl_token_2022",
spl_token_2022::id(),
processor!(Processor::process),
);
let program_id = Pubkey::new_unique();
program_test.add_program(
"ui_amount_to_amount",
program_id,
processor!(process_instruction),
);
let context = program_test.start_with_context().await;
let payer = keypair_clone(&context.payer);
let last_blockhash = context.last_blockhash;
let context = Arc::new(Mutex::new(context));
let mut context = TestContext {
context,
token_context: None,
};
let initial_rate = i16::MAX;
context
.init_token_with_mint(vec![ExtensionInitializationParams::InterestBearingConfig {
rate_authority: Some(rate_authority.pubkey()),
rate: initial_rate,
}])
.await
.unwrap();
let TokenContext { token, .. } = context.token_context.take().unwrap();
// warp forward, so interest is accrued
let warp_slot = 1_000;
let initial_num_warps = 10;
for i in 1..initial_num_warps {
context
.context
.lock()
.await
.warp_to_slot(i * warp_slot)
.unwrap();
}
let transaction = Transaction::new_signed_with_payer(
&[Instruction {
program_id,
accounts: vec![
AccountMeta::new_readonly(*token.get_address(), false),
AccountMeta::new_readonly(spl_token_2022::id(), false),
],
data: vec![],
}],
Some(&payer.pubkey()),
&[&payer],
last_blockhash,
);
context
.context
.lock()
.await
.banks_client
.process_transaction(transaction)
.await
.unwrap();
}
| 32.439655 | 94 | 0.619275 |
bf7d91077ad391da11c327cc93bfb9afaf312e9a | 116,141 | #[cfg(feature = "std")]
use std::borrow::Cow;
#[cfg(feature = "std")]
use std::ffi::OsStr;
#[cfg(feature = "std")]
use std::path::Path;
use core::cmp;
use core::ops;
use core::ptr;
use core::slice;
use core::str;
use memchr::{memchr, memrchr};
use ascii;
use bstr::BStr;
use byteset;
#[cfg(feature = "std")]
use ext_vec::ByteVec;
use search::{PrefilterState, TwoWay};
#[cfg(feature = "unicode")]
use unicode::{
whitespace_len_fwd, whitespace_len_rev, GraphemeIndices, Graphemes,
SentenceIndices, Sentences, WordIndices, Words, WordsWithBreakIndices,
WordsWithBreaks,
};
use utf8::{self, CharIndices, Chars, Utf8Error};
/// A short-hand constructor for building a `&[u8]`.
///
/// This idiosyncratic constructor is useful for concisely building byte string
/// slices. Its primary utility is in conveniently writing byte string literals
/// in a uniform way. For example, consider this code that does not compile:
///
/// ```ignore
/// let strs = vec![b"a", b"xy"];
/// ```
///
/// The above code doesn't compile because the type of the byte string literal
/// `b"a"` is `&'static [u8; 1]`, and the type of `b"xy"` is
/// `&'static [u8; 2]`. Since their types aren't the same, they can't be stored
/// in the same `Vec`. (This is dissimilar from normal Unicode string slices,
/// where both `"a"` and `"xy"` have the same type of `&'static str`.)
///
/// One way of getting the above code to compile is to convert byte strings to
/// slices. You might try this:
///
/// ```ignore
/// let strs = vec![&b"a", &b"xy"];
/// ```
///
/// But this just creates values with type `& &'static [u8; 1]` and
/// `& &'static [u8; 2]`. Instead, you need to force the issue like so:
///
/// ```
/// let strs = vec![&b"a"[..], &b"xy"[..]];
/// // or
/// let strs = vec![b"a".as_ref(), b"xy".as_ref()];
/// ```
///
/// But neither of these are particularly convenient to type, especially when
/// it's something as common as a string literal. Thus, this constructor
/// permits writing the following instead:
///
/// ```
/// use bstr::B;
///
/// let strs = vec![B("a"), B(b"xy")];
/// ```
///
/// Notice that this also lets you mix and match both string literals and byte
/// string literals. This can be quite convenient!
#[allow(non_snake_case)]
#[inline]
pub fn B<'a, B: ?Sized + AsRef<[u8]>>(bytes: &'a B) -> &'a [u8] {
bytes.as_ref()
}
impl ByteSlice for [u8] {
#[inline]
fn as_bytes(&self) -> &[u8] {
self
}
#[inline]
fn as_bytes_mut(&mut self) -> &mut [u8] {
self
}
}
/// Ensure that callers cannot implement `ByteSlice` by making an
/// umplementable trait its super trait.
pub trait Sealed {}
impl Sealed for [u8] {}
/// A trait that extends `&[u8]` with string oriented methods.
pub trait ByteSlice: Sealed {
/// A method for accessing the raw bytes of this type. This is always a
/// no-op and callers shouldn't care about it. This only exists for making
/// the extension trait work.
#[doc(hidden)]
fn as_bytes(&self) -> &[u8];
/// A method for accessing the raw bytes of this type, mutably. This is
/// always a no-op and callers shouldn't care about it. This only exists
/// for making the extension trait work.
#[doc(hidden)]
fn as_bytes_mut(&mut self) -> &mut [u8];
/// Return this byte slice as a `&BStr`.
///
/// Use `&BStr` is useful because of its `fmt::Debug` representation
/// and various other trait implementations (such as `PartialEq` and
/// `PartialOrd`). In particular, the `Debug` implementation for `BStr`
/// shows its bytes as a normal string. For invalid UTF-8, hex escape
/// sequences are used.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// println!("{:?}", b"foo\xFFbar".as_bstr());
/// ```
fn as_bstr(&self) -> &BStr {
BStr::new(self.as_bytes())
}
/// Return this byte slice as a `&mut BStr`.
///
/// Use `&mut BStr` is useful because of its `fmt::Debug` representation
/// and various other trait implementations (such as `PartialEq` and
/// `PartialOrd`). In particular, the `Debug` implementation for `BStr`
/// shows its bytes as a normal string. For invalid UTF-8, hex escape
/// sequences are used.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let mut bytes = *b"foo\xFFbar";
/// println!("{:?}", &mut bytes.as_bstr_mut());
/// ```
fn as_bstr_mut(&mut self) -> &mut BStr {
BStr::new_mut(self.as_bytes_mut())
}
/// Create an immutable byte string from an OS string slice.
///
/// On Unix, this always succeeds and is zero cost. On non-Unix systems,
/// this returns `None` if the given OS string is not valid UTF-8. (For
/// example, on Windows, file paths are allowed to be a sequence of
/// arbitrary 16-bit integers. Not all such sequences can be transcoded to
/// valid UTF-8.)
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::ffi::OsStr;
///
/// use bstr::{B, ByteSlice};
///
/// let os_str = OsStr::new("foo");
/// let bs = <[u8]>::from_os_str(os_str).expect("should be valid UTF-8");
/// assert_eq!(bs, B("foo"));
/// ```
#[cfg(feature = "std")]
#[inline]
fn from_os_str(os_str: &OsStr) -> Option<&[u8]> {
#[cfg(unix)]
#[inline]
fn imp(os_str: &OsStr) -> Option<&[u8]> {
use std::os::unix::ffi::OsStrExt;
Some(os_str.as_bytes())
}
#[cfg(not(unix))]
#[inline]
fn imp(os_str: &OsStr) -> Option<&[u8]> {
os_str.to_str().map(|s| s.as_bytes())
}
imp(os_str)
}
/// Create an immutable byte string from a file path.
///
/// On Unix, this always succeeds and is zero cost. On non-Unix systems,
/// this returns `None` if the given path is not valid UTF-8. (For example,
/// on Windows, file paths are allowed to be a sequence of arbitrary 16-bit
/// integers. Not all such sequences can be transcoded to valid UTF-8.)
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::path::Path;
///
/// use bstr::{B, ByteSlice};
///
/// let path = Path::new("foo");
/// let bs = <[u8]>::from_path(path).expect("should be valid UTF-8");
/// assert_eq!(bs, B("foo"));
/// ```
#[cfg(feature = "std")]
#[inline]
fn from_path(path: &Path) -> Option<&[u8]> {
Self::from_os_str(path.as_os_str())
}
/// Safely convert this byte string into a `&str` if it's valid UTF-8.
///
/// If this byte string is not valid UTF-8, then an error is returned. The
/// error returned indicates the first invalid byte found and the length
/// of the error.
///
/// In cases where a lossy conversion to `&str` is acceptable, then use one
/// of the [`to_str_lossy`](trait.ByteSlice.html#method.to_str_lossy) or
/// [`to_str_lossy_into`](trait.ByteSlice.html#method.to_str_lossy_into)
/// methods.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice, ByteVec};
///
/// # fn example() -> Result<(), bstr::Utf8Error> {
/// let s = B("☃βツ").to_str()?;
/// assert_eq!("☃βツ", s);
///
/// let mut bstring = <Vec<u8>>::from("☃βツ");
/// bstring.push(b'\xFF');
/// let err = bstring.to_str().unwrap_err();
/// assert_eq!(8, err.valid_up_to());
/// # Ok(()) }; example().unwrap()
/// ```
#[inline]
fn to_str(&self) -> Result<&str, Utf8Error> {
utf8::validate(self.as_bytes()).map(|_| {
// SAFETY: This is safe because of the guarantees provided by
// utf8::validate.
unsafe { str::from_utf8_unchecked(self.as_bytes()) }
})
}
/// Unsafely convert this byte string into a `&str`, without checking for
/// valid UTF-8.
///
/// # Safety
///
/// Callers *must* ensure that this byte string is valid UTF-8 before
/// calling this method. Converting a byte string into a `&str` that is
/// not valid UTF-8 is considered undefined behavior.
///
/// This routine is useful in performance sensitive contexts where the
/// UTF-8 validity of the byte string is already known and it is
/// undesirable to pay the cost of an additional UTF-8 validation check
/// that [`to_str`](trait.ByteSlice.html#method.to_str) performs.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// // SAFETY: This is safe because string literals are guaranteed to be
/// // valid UTF-8 by the Rust compiler.
/// let s = unsafe { B("☃βツ").to_str_unchecked() };
/// assert_eq!("☃βツ", s);
/// ```
unsafe fn to_str_unchecked(&self) -> &str {
str::from_utf8_unchecked(self.as_bytes())
}
/// Convert this byte string to a valid UTF-8 string by replacing invalid
/// UTF-8 bytes with the Unicode replacement codepoint (`U+FFFD`).
///
/// If the byte string is already valid UTF-8, then no copying or
/// allocation is performed and a borrrowed string slice is returned. If
/// the byte string is not valid UTF-8, then an owned string buffer is
/// returned with invalid bytes replaced by the replacement codepoint.
///
/// This method uses the "substitution of maximal subparts" (Unicode
/// Standard, Chapter 3, Section 9) strategy for inserting the replacement
/// codepoint. Specifically, a replacement codepoint is inserted whenever a
/// byte is found that cannot possibly lead to a valid code unit sequence.
/// If there were previous bytes that represented a prefix of a well-formed
/// code unit sequence, then all of those bytes are substituted with a
/// single replacement codepoint. The "substitution of maximal subparts"
/// strategy is the same strategy used by
/// [W3C's Encoding standard](https://www.w3.org/TR/encoding/).
/// For a more precise description of the maximal subpart strategy, see
/// the Unicode Standard, Chapter 3, Section 9. See also
/// [Public Review Issue #121](http://www.unicode.org/review/pr-121.html).
///
/// N.B. Rust's standard library also appears to use the same strategy,
/// but it does not appear to be an API guarantee.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::borrow::Cow;
///
/// use bstr::ByteSlice;
///
/// let mut bstring = <Vec<u8>>::from("☃βツ");
/// assert_eq!(Cow::Borrowed("☃βツ"), bstring.to_str_lossy());
///
/// // Add a byte that makes the sequence invalid.
/// bstring.push(b'\xFF');
/// assert_eq!(Cow::Borrowed("☃βツ\u{FFFD}"), bstring.to_str_lossy());
/// ```
///
/// This demonstrates the "maximal subpart" substitution logic.
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// // \x61 is the ASCII codepoint for 'a'.
/// // \xF1\x80\x80 is a valid 3-byte code unit prefix.
/// // \xE1\x80 is a valid 2-byte code unit prefix.
/// // \xC2 is a valid 1-byte code unit prefix.
/// // \x62 is the ASCII codepoint for 'b'.
/// //
/// // In sum, each of the prefixes is replaced by a single replacement
/// // codepoint since none of the prefixes are properly completed. This
/// // is in contrast to other strategies that might insert a replacement
/// // codepoint for every single byte.
/// let bs = B(b"\x61\xF1\x80\x80\xE1\x80\xC2\x62");
/// assert_eq!("a\u{FFFD}\u{FFFD}\u{FFFD}b", bs.to_str_lossy());
/// ```
#[cfg(feature = "std")]
#[inline]
fn to_str_lossy(&self) -> Cow<str> {
match utf8::validate(self.as_bytes()) {
Ok(()) => {
// SAFETY: This is safe because of the guarantees provided by
// utf8::validate.
unsafe {
Cow::Borrowed(str::from_utf8_unchecked(self.as_bytes()))
}
}
Err(err) => {
let mut lossy = String::with_capacity(self.as_bytes().len());
let (valid, after) =
self.as_bytes().split_at(err.valid_up_to());
// SAFETY: This is safe because utf8::validate guarantees
// that all of `valid` is valid UTF-8.
lossy.push_str(unsafe { str::from_utf8_unchecked(valid) });
lossy.push_str("\u{FFFD}");
if let Some(len) = err.error_len() {
after[len..].to_str_lossy_into(&mut lossy);
}
Cow::Owned(lossy)
}
}
}
/// Copy the contents of this byte string into the given owned string
/// buffer, while replacing invalid UTF-8 code unit sequences with the
/// Unicode replacement codepoint (`U+FFFD`).
///
/// This method uses the same "substitution of maximal subparts" strategy
/// for inserting the replacement codepoint as the
/// [`to_str_lossy`](trait.ByteSlice.html#method.to_str_lossy) method.
///
/// This routine is useful for amortizing allocation. However, unlike
/// `to_str_lossy`, this routine will _always_ copy the contents of this
/// byte string into the destination buffer, even if this byte string is
/// valid UTF-8.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::borrow::Cow;
///
/// use bstr::ByteSlice;
///
/// let mut bstring = <Vec<u8>>::from("☃βツ");
/// // Add a byte that makes the sequence invalid.
/// bstring.push(b'\xFF');
///
/// let mut dest = String::new();
/// bstring.to_str_lossy_into(&mut dest);
/// assert_eq!("☃βツ\u{FFFD}", dest);
/// ```
#[cfg(feature = "std")]
#[inline]
fn to_str_lossy_into(&self, dest: &mut String) {
let mut bytes = self.as_bytes();
dest.reserve(bytes.len());
loop {
match utf8::validate(bytes) {
Ok(()) => {
// SAFETY: This is safe because utf8::validate guarantees
// that all of `bytes` is valid UTF-8.
dest.push_str(unsafe { str::from_utf8_unchecked(bytes) });
break;
}
Err(err) => {
let (valid, after) = bytes.split_at(err.valid_up_to());
// SAFETY: This is safe because utf8::validate guarantees
// that all of `valid` is valid UTF-8.
dest.push_str(unsafe { str::from_utf8_unchecked(valid) });
dest.push_str("\u{FFFD}");
match err.error_len() {
None => break,
Some(len) => bytes = &after[len..],
}
}
}
}
}
/// Create an OS string slice from this byte string.
///
/// On Unix, this always succeeds and is zero cost. On non-Unix systems,
/// this returns a UTF-8 decoding error if this byte string is not valid
/// UTF-8. (For example, on Windows, file paths are allowed to be a
/// sequence of arbitrary 16-bit integers. There is no obvious mapping from
/// an arbitrary sequence of 8-bit integers to an arbitrary sequence of
/// 16-bit integers.)
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let os_str = b"foo".to_os_str().expect("should be valid UTF-8");
/// assert_eq!(os_str, "foo");
/// ```
#[cfg(feature = "std")]
#[inline]
fn to_os_str(&self) -> Result<&OsStr, Utf8Error> {
#[cfg(unix)]
#[inline]
fn imp(bytes: &[u8]) -> Result<&OsStr, Utf8Error> {
use std::os::unix::ffi::OsStrExt;
Ok(OsStr::from_bytes(bytes))
}
#[cfg(not(unix))]
#[inline]
fn imp(bytes: &[u8]) -> Result<&OsStr, Utf8Error> {
bytes.to_str().map(OsStr::new)
}
imp(self.as_bytes())
}
/// Lossily create an OS string slice from this byte string.
///
/// On Unix, this always succeeds and is zero cost. On non-Unix systems,
/// this will perform a UTF-8 check and lossily convert this byte string
/// into valid UTF-8 using the Unicode replacement codepoint.
///
/// Note that this can prevent the correct roundtripping of file paths on
/// non-Unix systems such as Windows, where file paths are an arbitrary
/// sequence of 16-bit integers.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let os_str = b"foo\xFFbar".to_os_str_lossy();
/// assert_eq!(os_str.to_string_lossy(), "foo\u{FFFD}bar");
/// ```
#[cfg(feature = "std")]
#[inline]
fn to_os_str_lossy(&self) -> Cow<OsStr> {
#[cfg(unix)]
#[inline]
fn imp(bytes: &[u8]) -> Cow<OsStr> {
use std::os::unix::ffi::OsStrExt;
Cow::Borrowed(OsStr::from_bytes(bytes))
}
#[cfg(not(unix))]
#[inline]
fn imp(bytes: &[u8]) -> Cow<OsStr> {
use std::ffi::OsString;
match bytes.to_str_lossy() {
Cow::Borrowed(x) => Cow::Borrowed(OsStr::new(x)),
Cow::Owned(x) => Cow::Owned(OsString::from(x)),
}
}
imp(self.as_bytes())
}
/// Create a path slice from this byte string.
///
/// On Unix, this always succeeds and is zero cost. On non-Unix systems,
/// this returns a UTF-8 decoding error if this byte string is not valid
/// UTF-8. (For example, on Windows, file paths are allowed to be a
/// sequence of arbitrary 16-bit integers. There is no obvious mapping from
/// an arbitrary sequence of 8-bit integers to an arbitrary sequence of
/// 16-bit integers.)
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let path = b"foo".to_path().expect("should be valid UTF-8");
/// assert_eq!(path.as_os_str(), "foo");
/// ```
#[cfg(feature = "std")]
#[inline]
fn to_path(&self) -> Result<&Path, Utf8Error> {
self.to_os_str().map(Path::new)
}
/// Lossily create a path slice from this byte string.
///
/// On Unix, this always succeeds and is zero cost. On non-Unix systems,
/// this will perform a UTF-8 check and lossily convert this byte string
/// into valid UTF-8 using the Unicode replacement codepoint.
///
/// Note that this can prevent the correct roundtripping of file paths on
/// non-Unix systems such as Windows, where file paths are an arbitrary
/// sequence of 16-bit integers.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = b"foo\xFFbar";
/// let path = bs.to_path_lossy();
/// assert_eq!(path.to_string_lossy(), "foo\u{FFFD}bar");
/// ```
#[cfg(feature = "std")]
#[inline]
fn to_path_lossy(&self) -> Cow<Path> {
use std::path::PathBuf;
match self.to_os_str_lossy() {
Cow::Borrowed(x) => Cow::Borrowed(Path::new(x)),
Cow::Owned(x) => Cow::Owned(PathBuf::from(x)),
}
}
/// Create a new byte string by repeating this byte string `n` times.
///
/// # Panics
///
/// This function panics if the capacity of the new byte string would
/// overflow.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// assert_eq!(b"foo".repeatn(4), B("foofoofoofoo"));
/// assert_eq!(b"foo".repeatn(0), B(""));
/// ```
#[cfg(feature = "std")]
#[inline]
fn repeatn(&self, n: usize) -> Vec<u8> {
let bs = self.as_bytes();
let mut dst = vec![0; bs.len() * n];
for i in 0..n {
dst[i * bs.len()..(i + 1) * bs.len()].copy_from_slice(bs);
}
dst
}
/// Returns true if and only if this byte string contains the given needle.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert!(b"foo bar".contains_str("foo"));
/// assert!(b"foo bar".contains_str("bar"));
/// assert!(!b"foo".contains_str("foobar"));
/// ```
#[inline]
fn contains_str<B: AsRef<[u8]>>(&self, needle: B) -> bool {
self.find(needle).is_some()
}
/// Returns true if and only if this byte string has the given prefix.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert!(b"foo bar".starts_with_str("foo"));
/// assert!(!b"foo bar".starts_with_str("bar"));
/// assert!(!b"foo".starts_with_str("foobar"));
/// ```
#[inline]
fn starts_with_str<B: AsRef<[u8]>>(&self, prefix: B) -> bool {
self.as_bytes().starts_with(prefix.as_ref())
}
/// Returns true if and only if this byte string has the given suffix.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert!(b"foo bar".ends_with_str("bar"));
/// assert!(!b"foo bar".ends_with_str("foo"));
/// assert!(!b"bar".ends_with_str("foobar"));
/// ```
#[inline]
fn ends_with_str<B: AsRef<[u8]>>(&self, suffix: B) -> bool {
self.as_bytes().ends_with(suffix.as_ref())
}
/// Returns the index of the first occurrence of the given needle.
///
/// The needle may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// Note that if you're are searching for the same needle in many
/// different small haystacks, it may be faster to initialize a
/// [`Finder`](struct.Finder.html) once, and reuse it for each search.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo bar baz";
/// assert_eq!(Some(0), s.find("foo"));
/// assert_eq!(Some(4), s.find("bar"));
/// assert_eq!(None, s.find("quux"));
/// ```
#[inline]
fn find<B: AsRef<[u8]>>(&self, needle: B) -> Option<usize> {
Finder::new(needle.as_ref()).find(self.as_bytes())
}
/// Returns the index of the last occurrence of the given needle.
///
/// The needle may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// Note that if you're are searching for the same needle in many
/// different small haystacks, it may be faster to initialize a
/// [`FinderReverse`](struct.FinderReverse.html) once, and reuse it for
/// each search.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo bar baz";
/// assert_eq!(Some(0), s.rfind("foo"));
/// assert_eq!(Some(4), s.rfind("bar"));
/// assert_eq!(Some(8), s.rfind("ba"));
/// assert_eq!(None, s.rfind("quux"));
/// ```
#[inline]
fn rfind<B: AsRef<[u8]>>(&self, needle: B) -> Option<usize> {
FinderReverse::new(needle.as_ref()).rfind(self.as_bytes())
}
/// Returns an iterator of the non-overlapping occurrences of the given
/// needle. The iterator yields byte offset positions indicating the start
/// of each match.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo bar foo foo quux foo";
/// let matches: Vec<usize> = s.find_iter("foo").collect();
/// assert_eq!(matches, vec![0, 8, 12, 21]);
/// ```
///
/// An empty string matches at every position, including the position
/// immediately following the last byte:
///
/// ```
/// use bstr::ByteSlice;
///
/// let matches: Vec<usize> = b"foo".find_iter("").collect();
/// assert_eq!(matches, vec![0, 1, 2, 3]);
///
/// let matches: Vec<usize> = b"".find_iter("").collect();
/// assert_eq!(matches, vec![0]);
/// ```
#[inline]
fn find_iter<'a, B: ?Sized + AsRef<[u8]>>(
&'a self,
needle: &'a B,
) -> Find<'a> {
Find::new(self.as_bytes(), needle.as_ref())
}
/// Returns an iterator of the non-overlapping occurrences of the given
/// needle in reverse. The iterator yields byte offset positions indicating
/// the start of each match.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo bar foo foo quux foo";
/// let matches: Vec<usize> = s.rfind_iter("foo").collect();
/// assert_eq!(matches, vec![21, 12, 8, 0]);
/// ```
///
/// An empty string matches at every position, including the position
/// immediately following the last byte:
///
/// ```
/// use bstr::ByteSlice;
///
/// let matches: Vec<usize> = b"foo".rfind_iter("").collect();
/// assert_eq!(matches, vec![3, 2, 1, 0]);
///
/// let matches: Vec<usize> = b"".rfind_iter("").collect();
/// assert_eq!(matches, vec![0]);
/// ```
#[inline]
fn rfind_iter<'a, B: ?Sized + AsRef<[u8]>>(
&'a self,
needle: &'a B,
) -> FindReverse<'a> {
FindReverse::new(self.as_bytes(), needle.as_ref())
}
/// Returns the index of the first occurrence of the given byte. If the
/// byte does not occur in this byte string, then `None` is returned.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert_eq!(Some(10), b"foo bar baz".find_byte(b'z'));
/// assert_eq!(None, b"foo bar baz".find_byte(b'y'));
/// ```
#[inline]
fn find_byte(&self, byte: u8) -> Option<usize> {
memchr(byte, self.as_bytes())
}
/// Returns the index of the last occurrence of the given byte. If the
/// byte does not occur in this byte string, then `None` is returned.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert_eq!(Some(10), b"foo bar baz".rfind_byte(b'z'));
/// assert_eq!(None, b"foo bar baz".rfind_byte(b'y'));
/// ```
#[inline]
fn rfind_byte(&self, byte: u8) -> Option<usize> {
memrchr(byte, self.as_bytes())
}
/// Returns the index of the first occurrence of the given codepoint.
/// If the codepoint does not occur in this byte string, then `None` is
/// returned.
///
/// Note that if one searches for the replacement codepoint, `\u{FFFD}`,
/// then only explicit occurrences of that encoding will be found. Invalid
/// UTF-8 sequences will not be matched.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// assert_eq!(Some(10), b"foo bar baz".find_char('z'));
/// assert_eq!(Some(4), B("αβγγδ").find_char('γ'));
/// assert_eq!(None, b"foo bar baz".find_char('y'));
/// ```
#[inline]
fn find_char(&self, ch: char) -> Option<usize> {
self.find(ch.encode_utf8(&mut [0; 4]))
}
/// Returns the index of the last occurrence of the given codepoint.
/// If the codepoint does not occur in this byte string, then `None` is
/// returned.
///
/// Note that if one searches for the replacement codepoint, `\u{FFFD}`,
/// then only explicit occurrences of that encoding will be found. Invalid
/// UTF-8 sequences will not be matched.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// assert_eq!(Some(10), b"foo bar baz".rfind_char('z'));
/// assert_eq!(Some(6), B("αβγγδ").rfind_char('γ'));
/// assert_eq!(None, b"foo bar baz".rfind_char('y'));
/// ```
#[inline]
fn rfind_char(&self, ch: char) -> Option<usize> {
self.rfind(ch.encode_utf8(&mut [0; 4]))
}
/// Returns the index of the first occurrence of any of the bytes in the
/// provided set.
///
/// The `byteset` may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`, but
/// note that passing a `&str` which contains multibyte characters may not
/// behave as you expect: each byte in the `&str` is treated as an
/// individual member of the byte set.
///
/// Note that order is irrelevant for the `byteset` parameter, and
/// duplicate bytes present in its body are ignored.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the set of bytes and the haystack. That is, this
/// runs in `O(byteset.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert_eq!(b"foo bar baz".find_byteset(b"zr"), Some(6));
/// assert_eq!(b"foo baz bar".find_byteset(b"bzr"), Some(4));
/// assert_eq!(None, b"foo baz bar".find_byteset(b"\t\n"));
/// ```
#[inline]
fn find_byteset<B: AsRef<[u8]>>(&self, byteset: B) -> Option<usize> {
byteset::find(self.as_bytes(), byteset.as_ref())
}
/// Returns the index of the first occurrence of a byte that is not a member
/// of the provided set.
///
/// The `byteset` may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`, but
/// note that passing a `&str` which contains multibyte characters may not
/// behave as you expect: each byte in the `&str` is treated as an
/// individual member of the byte set.
///
/// Note that order is irrelevant for the `byteset` parameter, and
/// duplicate bytes present in its body are ignored.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the set of bytes and the haystack. That is, this
/// runs in `O(byteset.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert_eq!(b"foo bar baz".find_not_byteset(b"fo "), Some(4));
/// assert_eq!(b"\t\tbaz bar".find_not_byteset(b" \t\r\n"), Some(2));
/// assert_eq!(b"foo\nbaz\tbar".find_not_byteset(b"\t\n"), Some(0));
/// ```
#[inline]
fn find_not_byteset<B: AsRef<[u8]>>(&self, byteset: B) -> Option<usize> {
byteset::find_not(self.as_bytes(), byteset.as_ref())
}
/// Returns the index of the last occurrence of any of the bytes in the
/// provided set.
///
/// The `byteset` may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`, but
/// note that passing a `&str` which contains multibyte characters may not
/// behave as you expect: each byte in the `&str` is treated as an
/// individual member of the byte set.
///
/// Note that order is irrelevant for the `byteset` parameter, and duplicate
/// bytes present in its body are ignored.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the set of bytes and the haystack. That is, this
/// runs in `O(byteset.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert_eq!(b"foo bar baz".rfind_byteset(b"agb"), Some(9));
/// assert_eq!(b"foo baz bar".rfind_byteset(b"rabz "), Some(10));
/// assert_eq!(b"foo baz bar".rfind_byteset(b"\n123"), None);
/// ```
#[inline]
fn rfind_byteset<B: AsRef<[u8]>>(&self, byteset: B) -> Option<usize> {
byteset::rfind(self.as_bytes(), byteset.as_ref())
}
/// Returns the index of the last occurrence of a byte that is not a member
/// of the provided set.
///
/// The `byteset` may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`, but
/// note that passing a `&str` which contains multibyte characters may not
/// behave as you expect: each byte in the `&str` is treated as an
/// individual member of the byte set.
///
/// Note that order is irrelevant for the `byteset` parameter, and
/// duplicate bytes present in its body are ignored.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the set of bytes and the haystack. That is, this
/// runs in `O(byteset.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert_eq!(b"foo bar baz,\t".rfind_not_byteset(b",\t"), Some(10));
/// assert_eq!(b"foo baz bar".rfind_not_byteset(b"rabz "), Some(2));
/// assert_eq!(None, b"foo baz bar".rfind_not_byteset(b"barfoz "));
/// ```
#[inline]
fn rfind_not_byteset<B: AsRef<[u8]>>(&self, byteset: B) -> Option<usize> {
byteset::rfind_not(self.as_bytes(), byteset.as_ref())
}
/// Returns an iterator over the fields in a byte string, separated by
/// contiguous whitespace.
///
/// # Example
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B(" foo\tbar\t\u{2003}\nquux \n");
/// let fields: Vec<&[u8]> = s.fields().collect();
/// assert_eq!(fields, vec![B("foo"), B("bar"), B("quux")]);
/// ```
///
/// A byte string consisting of just whitespace yields no elements:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// assert_eq!(0, B(" \n\t\u{2003}\n \t").fields().count());
/// ```
#[inline]
fn fields(&self) -> Fields {
Fields::new(self.as_bytes())
}
/// Returns an iterator over the fields in a byte string, separated by
/// contiguous codepoints satisfying the given predicate.
///
/// If this byte string is not valid UTF-8, then the given closure will
/// be called with a Unicode replacement codepoint when invalid UTF-8
/// bytes are seen.
///
/// # Example
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = b"123foo999999bar1quux123456";
/// let fields: Vec<&[u8]> = s.fields_with(|c| c.is_numeric()).collect();
/// assert_eq!(fields, vec![B("foo"), B("bar"), B("quux")]);
/// ```
///
/// A byte string consisting of all codepoints satisfying the predicate
/// yields no elements:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert_eq!(0, b"1911354563".fields_with(|c| c.is_numeric()).count());
/// ```
#[inline]
fn fields_with<F: FnMut(char) -> bool>(&self, f: F) -> FieldsWith<F> {
FieldsWith::new(self.as_bytes(), f)
}
/// Returns an iterator over substrings of this byte string, separated
/// by the given byte string. Each element yielded is guaranteed not to
/// include the splitter substring.
///
/// The splitter may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let x: Vec<&[u8]> = b"Mary had a little lamb".split_str(" ").collect();
/// assert_eq!(x, vec![
/// B("Mary"), B("had"), B("a"), B("little"), B("lamb"),
/// ]);
///
/// let x: Vec<&[u8]> = b"".split_str("X").collect();
/// assert_eq!(x, vec![b""]);
///
/// let x: Vec<&[u8]> = b"lionXXtigerXleopard".split_str("X").collect();
/// assert_eq!(x, vec![B("lion"), B(""), B("tiger"), B("leopard")]);
///
/// let x: Vec<&[u8]> = b"lion::tiger::leopard".split_str("::").collect();
/// assert_eq!(x, vec![B("lion"), B("tiger"), B("leopard")]);
/// ```
///
/// If a string contains multiple contiguous separators, you will end up
/// with empty strings yielded by the iterator:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let x: Vec<&[u8]> = b"||||a||b|c".split_str("|").collect();
/// assert_eq!(x, vec![
/// B(""), B(""), B(""), B(""), B("a"), B(""), B("b"), B("c"),
/// ]);
///
/// let x: Vec<&[u8]> = b"(///)".split_str("/").collect();
/// assert_eq!(x, vec![B("("), B(""), B(""), B(")")]);
/// ```
///
/// Separators at the start or end of a string are neighbored by empty
/// strings.
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let x: Vec<&[u8]> = b"010".split_str("0").collect();
/// assert_eq!(x, vec![B(""), B("1"), B("")]);
/// ```
///
/// When the empty string is used as a separator, it splits every **byte**
/// in the byte string, along with the beginning and end of the byte
/// string.
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let x: Vec<&[u8]> = b"rust".split_str("").collect();
/// assert_eq!(x, vec![
/// B(""), B("r"), B("u"), B("s"), B("t"), B(""),
/// ]);
///
/// // Splitting by an empty string is not UTF-8 aware. Elements yielded
/// // may not be valid UTF-8!
/// let x: Vec<&[u8]> = B("☃").split_str("").collect();
/// assert_eq!(x, vec![
/// B(""), B(b"\xE2"), B(b"\x98"), B(b"\x83"), B(""),
/// ]);
/// ```
///
/// Contiguous separators, especially whitespace, can lead to possibly
/// surprising behavior. For example, this code is correct:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let x: Vec<&[u8]> = b" a b c".split_str(" ").collect();
/// assert_eq!(x, vec![
/// B(""), B(""), B(""), B(""), B("a"), B(""), B("b"), B("c"),
/// ]);
/// ```
///
/// It does *not* give you `["a", "b", "c"]`. For that behavior, use
/// [`fields`](#method.fields) instead.
#[inline]
fn split_str<'a, B: ?Sized + AsRef<[u8]>>(
&'a self,
splitter: &'a B,
) -> Split<'a> {
Split::new(self.as_bytes(), splitter.as_ref())
}
/// Returns an iterator over substrings of this byte string, separated by
/// the given byte string, in reverse. Each element yielded is guaranteed
/// not to include the splitter substring.
///
/// The splitter may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let x: Vec<&[u8]> =
/// b"Mary had a little lamb".rsplit_str(" ").collect();
/// assert_eq!(x, vec![
/// B("lamb"), B("little"), B("a"), B("had"), B("Mary"),
/// ]);
///
/// let x: Vec<&[u8]> = b"".rsplit_str("X").collect();
/// assert_eq!(x, vec![b""]);
///
/// let x: Vec<&[u8]> = b"lionXXtigerXleopard".rsplit_str("X").collect();
/// assert_eq!(x, vec![B("leopard"), B("tiger"), B(""), B("lion")]);
///
/// let x: Vec<&[u8]> = b"lion::tiger::leopard".rsplit_str("::").collect();
/// assert_eq!(x, vec![B("leopard"), B("tiger"), B("lion")]);
/// ```
///
/// If a string contains multiple contiguous separators, you will end up
/// with empty strings yielded by the iterator:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let x: Vec<&[u8]> = b"||||a||b|c".rsplit_str("|").collect();
/// assert_eq!(x, vec![
/// B("c"), B("b"), B(""), B("a"), B(""), B(""), B(""), B(""),
/// ]);
///
/// let x: Vec<&[u8]> = b"(///)".rsplit_str("/").collect();
/// assert_eq!(x, vec![B(")"), B(""), B(""), B("(")]);
/// ```
///
/// Separators at the start or end of a string are neighbored by empty
/// strings.
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let x: Vec<&[u8]> = b"010".rsplit_str("0").collect();
/// assert_eq!(x, vec![B(""), B("1"), B("")]);
/// ```
///
/// When the empty string is used as a separator, it splits every **byte**
/// in the byte string, along with the beginning and end of the byte
/// string.
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let x: Vec<&[u8]> = b"rust".rsplit_str("").collect();
/// assert_eq!(x, vec![
/// B(""), B("t"), B("s"), B("u"), B("r"), B(""),
/// ]);
///
/// // Splitting by an empty string is not UTF-8 aware. Elements yielded
/// // may not be valid UTF-8!
/// let x: Vec<&[u8]> = B("☃").rsplit_str("").collect();
/// assert_eq!(x, vec![B(""), B(b"\x83"), B(b"\x98"), B(b"\xE2"), B("")]);
/// ```
///
/// Contiguous separators, especially whitespace, can lead to possibly
/// surprising behavior. For example, this code is correct:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let x: Vec<&[u8]> = b" a b c".rsplit_str(" ").collect();
/// assert_eq!(x, vec![
/// B("c"), B("b"), B(""), B("a"), B(""), B(""), B(""), B(""),
/// ]);
/// ```
///
/// It does *not* give you `["a", "b", "c"]`.
#[inline]
fn rsplit_str<'a, B: ?Sized + AsRef<[u8]>>(
&'a self,
splitter: &'a B,
) -> SplitReverse<'a> {
SplitReverse::new(self.as_bytes(), splitter.as_ref())
}
/// Returns an iterator of at most `limit` substrings of this byte string,
/// separated by the given byte string. If `limit` substrings are yielded,
/// then the last substring will contain the remainder of this byte string.
///
/// The needle may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let x: Vec<_> = b"Mary had a little lamb".splitn_str(3, " ").collect();
/// assert_eq!(x, vec![B("Mary"), B("had"), B("a little lamb")]);
///
/// let x: Vec<_> = b"".splitn_str(3, "X").collect();
/// assert_eq!(x, vec![b""]);
///
/// let x: Vec<_> = b"lionXXtigerXleopard".splitn_str(3, "X").collect();
/// assert_eq!(x, vec![B("lion"), B(""), B("tigerXleopard")]);
///
/// let x: Vec<_> = b"lion::tiger::leopard".splitn_str(2, "::").collect();
/// assert_eq!(x, vec![B("lion"), B("tiger::leopard")]);
///
/// let x: Vec<_> = b"abcXdef".splitn_str(1, "X").collect();
/// assert_eq!(x, vec![B("abcXdef")]);
///
/// let x: Vec<_> = b"abcXdef".splitn_str(0, "X").collect();
/// assert!(x.is_empty());
/// ```
#[inline]
fn splitn_str<'a, B: ?Sized + AsRef<[u8]>>(
&'a self,
limit: usize,
splitter: &'a B,
) -> SplitN<'a> {
SplitN::new(self.as_bytes(), splitter.as_ref(), limit)
}
/// Returns an iterator of at most `limit` substrings of this byte string,
/// separated by the given byte string, in reverse. If `limit` substrings
/// are yielded, then the last substring will contain the remainder of this
/// byte string.
///
/// The needle may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let x: Vec<_> =
/// b"Mary had a little lamb".rsplitn_str(3, " ").collect();
/// assert_eq!(x, vec![B("lamb"), B("little"), B("Mary had a")]);
///
/// let x: Vec<_> = b"".rsplitn_str(3, "X").collect();
/// assert_eq!(x, vec![b""]);
///
/// let x: Vec<_> = b"lionXXtigerXleopard".rsplitn_str(3, "X").collect();
/// assert_eq!(x, vec![B("leopard"), B("tiger"), B("lionX")]);
///
/// let x: Vec<_> = b"lion::tiger::leopard".rsplitn_str(2, "::").collect();
/// assert_eq!(x, vec![B("leopard"), B("lion::tiger")]);
///
/// let x: Vec<_> = b"abcXdef".rsplitn_str(1, "X").collect();
/// assert_eq!(x, vec![B("abcXdef")]);
///
/// let x: Vec<_> = b"abcXdef".rsplitn_str(0, "X").collect();
/// assert!(x.is_empty());
/// ```
#[inline]
fn rsplitn_str<'a, B: ?Sized + AsRef<[u8]>>(
&'a self,
limit: usize,
splitter: &'a B,
) -> SplitNReverse<'a> {
SplitNReverse::new(self.as_bytes(), splitter.as_ref(), limit)
}
/// Replace all matches of the given needle with the given replacement, and
/// the result as a new `Vec<u8>`.
///
/// This routine is useful as a convenience. If you need to reuse an
/// allocation, use [`replace_into`](#method.replace_into) instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"this is old".replace("old", "new");
/// assert_eq!(s, "this is new".as_bytes());
/// ```
///
/// When the pattern doesn't match:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"this is old".replace("nada nada", "limonada");
/// assert_eq!(s, "this is old".as_bytes());
/// ```
///
/// When the needle is an empty string:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo".replace("", "Z");
/// assert_eq!(s, "ZfZoZoZ".as_bytes());
/// ```
#[cfg(feature = "std")]
#[inline]
fn replace<N: AsRef<[u8]>, R: AsRef<[u8]>>(
&self,
needle: N,
replacement: R,
) -> Vec<u8> {
let mut dest = Vec::with_capacity(self.as_bytes().len());
self.replace_into(needle, replacement, &mut dest);
dest
}
/// Replace up to `limit` matches of the given needle with the given
/// replacement, and the result as a new `Vec<u8>`.
///
/// This routine is useful as a convenience. If you need to reuse an
/// allocation, use [`replacen_into`](#method.replacen_into) instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foofoo".replacen("o", "z", 2);
/// assert_eq!(s, "fzzfoo".as_bytes());
/// ```
///
/// When the pattern doesn't match:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foofoo".replacen("a", "z", 2);
/// assert_eq!(s, "foofoo".as_bytes());
/// ```
///
/// When the needle is an empty string:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo".replacen("", "Z", 2);
/// assert_eq!(s, "ZfZoo".as_bytes());
/// ```
#[cfg(feature = "std")]
#[inline]
fn replacen<N: AsRef<[u8]>, R: AsRef<[u8]>>(
&self,
needle: N,
replacement: R,
limit: usize,
) -> Vec<u8> {
let mut dest = Vec::with_capacity(self.as_bytes().len());
self.replacen_into(needle, replacement, limit, &mut dest);
dest
}
/// Replace all matches of the given needle with the given replacement,
/// and write the result into the provided `Vec<u8>`.
///
/// This does **not** clear `dest` before writing to it.
///
/// This routine is useful for reusing allocation. For a more convenient
/// API, use [`replace`](#method.replace) instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"this is old";
///
/// let mut dest = vec![];
/// s.replace_into("old", "new", &mut dest);
/// assert_eq!(dest, "this is new".as_bytes());
/// ```
///
/// When the pattern doesn't match:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"this is old";
///
/// let mut dest = vec![];
/// s.replace_into("nada nada", "limonada", &mut dest);
/// assert_eq!(dest, "this is old".as_bytes());
/// ```
///
/// When the needle is an empty string:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo";
///
/// let mut dest = vec![];
/// s.replace_into("", "Z", &mut dest);
/// assert_eq!(dest, "ZfZoZoZ".as_bytes());
/// ```
#[cfg(feature = "std")]
#[inline]
fn replace_into<N: AsRef<[u8]>, R: AsRef<[u8]>>(
&self,
needle: N,
replacement: R,
dest: &mut Vec<u8>,
) {
let (needle, replacement) = (needle.as_ref(), replacement.as_ref());
let mut last = 0;
for start in self.find_iter(needle) {
dest.push_str(&self.as_bytes()[last..start]);
dest.push_str(replacement);
last = start + needle.len();
}
dest.push_str(&self.as_bytes()[last..]);
}
/// Replace up to `limit` matches of the given needle with the given
/// replacement, and write the result into the provided `Vec<u8>`.
///
/// This does **not** clear `dest` before writing to it.
///
/// This routine is useful for reusing allocation. For a more convenient
/// API, use [`replacen`](#method.replacen) instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foofoo";
///
/// let mut dest = vec![];
/// s.replacen_into("o", "z", 2, &mut dest);
/// assert_eq!(dest, "fzzfoo".as_bytes());
/// ```
///
/// When the pattern doesn't match:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foofoo";
///
/// let mut dest = vec![];
/// s.replacen_into("a", "z", 2, &mut dest);
/// assert_eq!(dest, "foofoo".as_bytes());
/// ```
///
/// When the needle is an empty string:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo";
///
/// let mut dest = vec![];
/// s.replacen_into("", "Z", 2, &mut dest);
/// assert_eq!(dest, "ZfZoo".as_bytes());
/// ```
#[cfg(feature = "std")]
#[inline]
fn replacen_into<N: AsRef<[u8]>, R: AsRef<[u8]>>(
&self,
needle: N,
replacement: R,
limit: usize,
dest: &mut Vec<u8>,
) {
let (needle, replacement) = (needle.as_ref(), replacement.as_ref());
let mut last = 0;
for start in self.find_iter(needle).take(limit) {
dest.push_str(&self.as_bytes()[last..start]);
dest.push_str(replacement);
last = start + needle.len();
}
dest.push_str(&self.as_bytes()[last..]);
}
/// Returns an iterator over the bytes in this byte string.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = b"foobar";
/// let bytes: Vec<u8> = bs.bytes().collect();
/// assert_eq!(bytes, bs);
/// ```
#[inline]
fn bytes(&self) -> Bytes {
Bytes { it: self.as_bytes().iter() }
}
/// Returns an iterator over the Unicode scalar values in this byte string.
/// If invalid UTF-8 is encountered, then the Unicode replacement codepoint
/// is yielded instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = b"\xE2\x98\x83\xFF\xF0\x9D\x9E\x83\xE2\x98\x61";
/// let chars: Vec<char> = bs.chars().collect();
/// assert_eq!(vec!['☃', '\u{FFFD}', '𝞃', '\u{FFFD}', 'a'], chars);
/// ```
///
/// Codepoints can also be iterated over in reverse:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = b"\xE2\x98\x83\xFF\xF0\x9D\x9E\x83\xE2\x98\x61";
/// let chars: Vec<char> = bs.chars().rev().collect();
/// assert_eq!(vec!['a', '\u{FFFD}', '𝞃', '\u{FFFD}', '☃'], chars);
/// ```
#[inline]
fn chars(&self) -> Chars {
Chars::new(self.as_bytes())
}
/// Returns an iterator over the Unicode scalar values in this byte string
/// along with their starting and ending byte index positions. If invalid
/// UTF-8 is encountered, then the Unicode replacement codepoint is yielded
/// instead.
///
/// Note that this is slightly different from the `CharIndices` iterator
/// provided by the standard library. Aside from working on possibly
/// invalid UTF-8, this iterator provides both the corresponding starting
/// and ending byte indices of each codepoint yielded. The ending position
/// is necessary to slice the original byte string when invalid UTF-8 bytes
/// are converted into a Unicode replacement codepoint, since a single
/// replacement codepoint can substitute anywhere from 1 to 3 invalid bytes
/// (inclusive).
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = b"\xE2\x98\x83\xFF\xF0\x9D\x9E\x83\xE2\x98\x61";
/// let chars: Vec<(usize, usize, char)> = bs.char_indices().collect();
/// assert_eq!(chars, vec![
/// (0, 3, '☃'),
/// (3, 4, '\u{FFFD}'),
/// (4, 8, '𝞃'),
/// (8, 10, '\u{FFFD}'),
/// (10, 11, 'a'),
/// ]);
/// ```
///
/// Codepoints can also be iterated over in reverse:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = b"\xE2\x98\x83\xFF\xF0\x9D\x9E\x83\xE2\x98\x61";
/// let chars: Vec<(usize, usize, char)> = bs
/// .char_indices()
/// .rev()
/// .collect();
/// assert_eq!(chars, vec![
/// (10, 11, 'a'),
/// (8, 10, '\u{FFFD}'),
/// (4, 8, '𝞃'),
/// (3, 4, '\u{FFFD}'),
/// (0, 3, '☃'),
/// ]);
/// ```
#[inline]
fn char_indices(&self) -> CharIndices {
CharIndices::new(self.as_bytes())
}
/// Returns an iterator over the grapheme clusters in this byte string.
/// If invalid UTF-8 is encountered, then the Unicode replacement codepoint
/// is yielded instead.
///
/// # Examples
///
/// This example shows how multiple codepoints can combine to form a
/// single grapheme cluster:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = "a\u{0300}\u{0316}\u{1F1FA}\u{1F1F8}".as_bytes();
/// let graphemes: Vec<&str> = bs.graphemes().collect();
/// assert_eq!(vec!["à̖", "🇺🇸"], graphemes);
/// ```
///
/// This shows that graphemes can be iterated over in reverse:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = "a\u{0300}\u{0316}\u{1F1FA}\u{1F1F8}".as_bytes();
/// let graphemes: Vec<&str> = bs.graphemes().rev().collect();
/// assert_eq!(vec!["🇺🇸", "à̖"], graphemes);
/// ```
#[cfg(feature = "unicode")]
#[inline]
fn graphemes(&self) -> Graphemes {
Graphemes::new(self.as_bytes())
}
/// Returns an iterator over the grapheme clusters in this byte string
/// along with their starting and ending byte index positions. If invalid
/// UTF-8 is encountered, then the Unicode replacement codepoint is yielded
/// instead.
///
/// # Examples
///
/// This example shows how to get the byte offsets of each individual
/// grapheme cluster:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = "a\u{0300}\u{0316}\u{1F1FA}\u{1F1F8}".as_bytes();
/// let graphemes: Vec<(usize, usize, &str)> =
/// bs.grapheme_indices().collect();
/// assert_eq!(vec![(0, 5, "à̖"), (5, 13, "🇺🇸")], graphemes);
/// ```
///
/// This example shows what happens when invalid UTF-8 is enountered. Note
/// that the offsets are valid indices into the original string, and do
/// not necessarily correspond to the length of the `&str` returned!
///
/// ```
/// use bstr::{ByteSlice, ByteVec};
///
/// let mut bytes = vec![];
/// bytes.push_str("a\u{0300}\u{0316}");
/// bytes.push(b'\xFF');
/// bytes.push_str("\u{1F1FA}\u{1F1F8}");
///
/// let graphemes: Vec<(usize, usize, &str)> =
/// bytes.grapheme_indices().collect();
/// assert_eq!(
/// graphemes,
/// vec![(0, 5, "à̖"), (5, 6, "\u{FFFD}"), (6, 14, "🇺🇸")]
/// );
/// ```
#[cfg(feature = "unicode")]
#[inline]
fn grapheme_indices(&self) -> GraphemeIndices {
GraphemeIndices::new(self.as_bytes())
}
/// Returns an iterator over the words in this byte string. If invalid
/// UTF-8 is encountered, then the Unicode replacement codepoint is yielded
/// instead.
///
/// This is similar to
/// [`words_with_breaks`](trait.ByteSlice.html#method.words_with_breaks),
/// except it only returns elements that contain a "word" character. A word
/// character is defined by UTS #18 (Annex C) to be the combination of the
/// `Alphabetic` and `Join_Control` properties, along with the
/// `Decimal_Number`, `Mark` and `Connector_Punctuation` general
/// categories.
///
/// Since words are made up of one or more codepoints, this iterator
/// yields `&str` elements. When invalid UTF-8 is encountered, replacement
/// codepoints are [substituted](index.html#handling-of-invalid-utf-8).
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = br#"The quick ("brown") fox can't jump 32.3 feet, right?"#;
/// let words: Vec<&str> = bs.words().collect();
/// assert_eq!(words, vec![
/// "The", "quick", "brown", "fox", "can't",
/// "jump", "32.3", "feet", "right",
/// ]);
/// ```
#[cfg(feature = "unicode")]
#[inline]
fn words(&self) -> Words {
Words::new(self.as_bytes())
}
/// Returns an iterator over the words in this byte string along with
/// their starting and ending byte index positions.
///
/// This is similar to
/// [`words_with_break_indices`](trait.ByteSlice.html#method.words_with_break_indices),
/// except it only returns elements that contain a "word" character. A word
/// character is defined by UTS #18 (Annex C) to be the combination of the
/// `Alphabetic` and `Join_Control` properties, along with the
/// `Decimal_Number`, `Mark` and `Connector_Punctuation` general
/// categories.
///
/// Since words are made up of one or more codepoints, this iterator
/// yields `&str` elements. When invalid UTF-8 is encountered, replacement
/// codepoints are [substituted](index.html#handling-of-invalid-utf-8).
///
/// # Examples
///
/// This example shows how to get the byte offsets of each individual
/// word:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = b"can't jump 32.3 feet";
/// let words: Vec<(usize, usize, &str)> = bs.word_indices().collect();
/// assert_eq!(words, vec![
/// (0, 5, "can't"),
/// (6, 10, "jump"),
/// (11, 15, "32.3"),
/// (16, 20, "feet"),
/// ]);
/// ```
#[cfg(feature = "unicode")]
#[inline]
fn word_indices(&self) -> WordIndices {
WordIndices::new(self.as_bytes())
}
/// Returns an iterator over the words in this byte string, along with
/// all breaks between the words. Concatenating all elements yielded by
/// the iterator results in the original string (modulo Unicode replacement
/// codepoint substitutions if invalid UTF-8 is encountered).
///
/// Since words are made up of one or more codepoints, this iterator
/// yields `&str` elements. When invalid UTF-8 is encountered, replacement
/// codepoints are [substituted](index.html#handling-of-invalid-utf-8).
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = br#"The quick ("brown") fox can't jump 32.3 feet, right?"#;
/// let words: Vec<&str> = bs.words_with_breaks().collect();
/// assert_eq!(words, vec![
/// "The", " ", "quick", " ", "(", "\"", "brown", "\"", ")",
/// " ", "fox", " ", "can't", " ", "jump", " ", "32.3", " ", "feet",
/// ",", " ", "right", "?",
/// ]);
/// ```
#[cfg(feature = "unicode")]
#[inline]
fn words_with_breaks(&self) -> WordsWithBreaks {
WordsWithBreaks::new(self.as_bytes())
}
/// Returns an iterator over the words and their byte offsets in this
/// byte string, along with all breaks between the words. Concatenating
/// all elements yielded by the iterator results in the original string
/// (modulo Unicode replacement codepoint substitutions if invalid UTF-8 is
/// encountered).
///
/// Since words are made up of one or more codepoints, this iterator
/// yields `&str` elements. When invalid UTF-8 is encountered, replacement
/// codepoints are [substituted](index.html#handling-of-invalid-utf-8).
///
/// # Examples
///
/// This example shows how to get the byte offsets of each individual
/// word:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = b"can't jump 32.3 feet";
/// let words: Vec<(usize, usize, &str)> =
/// bs.words_with_break_indices().collect();
/// assert_eq!(words, vec![
/// (0, 5, "can't"),
/// (5, 6, " "),
/// (6, 10, "jump"),
/// (10, 11, " "),
/// (11, 15, "32.3"),
/// (15, 16, " "),
/// (16, 20, "feet"),
/// ]);
/// ```
#[cfg(feature = "unicode")]
#[inline]
fn words_with_break_indices(&self) -> WordsWithBreakIndices {
WordsWithBreakIndices::new(self.as_bytes())
}
/// Returns an iterator over the sentences in this byte string.
///
/// Typically, a sentence will include its trailing punctuation and
/// whitespace. Concatenating all elements yielded by the iterator
/// results in the original string (modulo Unicode replacement codepoint
/// substitutions if invalid UTF-8 is encountered).
///
/// Since sentences are made up of one or more codepoints, this iterator
/// yields `&str` elements. When invalid UTF-8 is encountered, replacement
/// codepoints are [substituted](index.html#handling-of-invalid-utf-8).
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = b"I want this. Not that. Right now.";
/// let sentences: Vec<&str> = bs.sentences().collect();
/// assert_eq!(sentences, vec![
/// "I want this. ",
/// "Not that. ",
/// "Right now.",
/// ]);
/// ```
#[cfg(feature = "unicode")]
#[inline]
fn sentences(&self) -> Sentences {
Sentences::new(self.as_bytes())
}
/// Returns an iterator over the sentences in this byte string along with
/// their starting and ending byte index positions.
///
/// Typically, a sentence will include its trailing punctuation and
/// whitespace. Concatenating all elements yielded by the iterator
/// results in the original string (modulo Unicode replacement codepoint
/// substitutions if invalid UTF-8 is encountered).
///
/// Since sentences are made up of one or more codepoints, this iterator
/// yields `&str` elements. When invalid UTF-8 is encountered, replacement
/// codepoints are [substituted](index.html#handling-of-invalid-utf-8).
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let bs = b"I want this. Not that. Right now.";
/// let sentences: Vec<(usize, usize, &str)> =
/// bs.sentence_indices().collect();
/// assert_eq!(sentences, vec![
/// (0, 13, "I want this. "),
/// (13, 23, "Not that. "),
/// (23, 33, "Right now."),
/// ]);
/// ```
#[cfg(feature = "unicode")]
#[inline]
fn sentence_indices(&self) -> SentenceIndices {
SentenceIndices::new(self.as_bytes())
}
/// An iterator over all lines in a byte string, without their
/// terminators.
///
/// For this iterator, the only line terminators recognized are `\r\n` and
/// `\n`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = b"\
/// foo
///
/// bar\r
/// baz
///
///
/// quux";
/// let lines: Vec<&[u8]> = s.lines().collect();
/// assert_eq!(lines, vec![
/// B("foo"), B(""), B("bar"), B("baz"), B(""), B(""), B("quux"),
/// ]);
/// ```
#[inline]
fn lines(&self) -> Lines {
Lines::new(self.as_bytes())
}
/// An iterator over all lines in a byte string, including their
/// terminators.
///
/// For this iterator, the only line terminator recognized is `\n`. (Since
/// line terminators are included, this also handles `\r\n` line endings.)
///
/// Line terminators are only included if they are present in the original
/// byte string. For example, the last line in a byte string may not end
/// with a line terminator.
///
/// Concatenating all elements yielded by this iterator is guaranteed to
/// yield the original byte string.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = b"\
/// foo
///
/// bar\r
/// baz
///
///
/// quux";
/// let lines: Vec<&[u8]> = s.lines_with_terminator().collect();
/// assert_eq!(lines, vec![
/// B("foo\n"),
/// B("\n"),
/// B("bar\r\n"),
/// B("baz\n"),
/// B("\n"),
/// B("\n"),
/// B("quux"),
/// ]);
/// ```
#[inline]
fn lines_with_terminator(&self) -> LinesWithTerminator {
LinesWithTerminator::new(self.as_bytes())
}
/// Return a byte string slice with leading and trailing whitespace
/// removed.
///
/// Whitespace is defined according to the terms of the `White_Space`
/// Unicode property.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B(" foo\tbar\t\u{2003}\n");
/// assert_eq!(s.trim(), B("foo\tbar"));
/// ```
#[cfg(feature = "unicode")]
#[inline]
fn trim(&self) -> &[u8] {
self.trim_start().trim_end()
}
/// Return a byte string slice with leading whitespace removed.
///
/// Whitespace is defined according to the terms of the `White_Space`
/// Unicode property.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B(" foo\tbar\t\u{2003}\n");
/// assert_eq!(s.trim_start(), B("foo\tbar\t\u{2003}\n"));
/// ```
#[cfg(feature = "unicode")]
#[inline]
fn trim_start(&self) -> &[u8] {
let start = whitespace_len_fwd(self.as_bytes());
&self.as_bytes()[start..]
}
/// Return a byte string slice with trailing whitespace removed.
///
/// Whitespace is defined according to the terms of the `White_Space`
/// Unicode property.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B(" foo\tbar\t\u{2003}\n");
/// assert_eq!(s.trim_end(), B(" foo\tbar"));
/// ```
#[cfg(feature = "unicode")]
#[inline]
fn trim_end(&self) -> &[u8] {
let end = whitespace_len_rev(self.as_bytes());
&self.as_bytes()[..end]
}
/// Return a byte string slice with leading and trailing characters
/// satisfying the given predicate removed.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = b"123foo5bar789";
/// assert_eq!(s.trim_with(|c| c.is_numeric()), B("foo5bar"));
/// ```
#[inline]
fn trim_with<F: FnMut(char) -> bool>(&self, mut trim: F) -> &[u8] {
self.trim_start_with(&mut trim).trim_end_with(&mut trim)
}
/// Return a byte string slice with leading characters satisfying the given
/// predicate removed.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = b"123foo5bar789";
/// assert_eq!(s.trim_start_with(|c| c.is_numeric()), B("foo5bar789"));
/// ```
#[inline]
fn trim_start_with<F: FnMut(char) -> bool>(&self, mut trim: F) -> &[u8] {
for (s, _, ch) in self.char_indices() {
if !trim(ch) {
return &self.as_bytes()[s..];
}
}
b""
}
/// Return a byte string slice with trailing characters satisfying the
/// given predicate removed.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = b"123foo5bar";
/// assert_eq!(s.trim_end_with(|c| c.is_numeric()), B("123foo5bar"));
/// ```
#[inline]
fn trim_end_with<F: FnMut(char) -> bool>(&self, mut trim: F) -> &[u8] {
for (_, e, ch) in self.char_indices().rev() {
if !trim(ch) {
return &self.as_bytes()[..e];
}
}
b""
}
/// Returns a new `Vec<u8>` containing the lowercase equivalent of this
/// byte string.
///
/// In this case, lowercase is defined according to the `Lowercase` Unicode
/// property.
///
/// If invalid UTF-8 is seen, or if a character has no lowercase variant,
/// then it is written to the given buffer unchanged.
///
/// Note that some characters in this byte string may expand into multiple
/// characters when changing the case, so the number of bytes written to
/// the given byte string may not be equivalent to the number of bytes in
/// this byte string.
///
/// If you'd like to reuse an allocation for performance reasons, then use
/// [`to_lowercase_into`](#method.to_lowercase_into) instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B("HELLO Β");
/// assert_eq!("hello β".as_bytes(), s.to_lowercase().as_bytes());
/// ```
///
/// Scripts without case are not changed:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B("农历新年");
/// assert_eq!("农历新年".as_bytes(), s.to_lowercase().as_bytes());
/// ```
///
/// Invalid UTF-8 remains as is:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B(b"FOO\xFFBAR\xE2\x98BAZ");
/// assert_eq!(B(b"foo\xFFbar\xE2\x98baz"), s.to_lowercase().as_bytes());
/// ```
#[cfg(all(feature = "std", feature = "unicode"))]
#[inline]
fn to_lowercase(&self) -> Vec<u8> {
let mut buf = vec![];
self.to_lowercase_into(&mut buf);
buf
}
/// Writes the lowercase equivalent of this byte string into the given
/// buffer. The buffer is not cleared before written to.
///
/// In this case, lowercase is defined according to the `Lowercase`
/// Unicode property.
///
/// If invalid UTF-8 is seen, or if a character has no lowercase variant,
/// then it is written to the given buffer unchanged.
///
/// Note that some characters in this byte string may expand into multiple
/// characters when changing the case, so the number of bytes written to
/// the given byte string may not be equivalent to the number of bytes in
/// this byte string.
///
/// If you don't need to amortize allocation and instead prefer
/// convenience, then use [`to_lowercase`](#method.to_lowercase) instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B("HELLO Β");
///
/// let mut buf = vec![];
/// s.to_lowercase_into(&mut buf);
/// assert_eq!("hello β".as_bytes(), buf.as_bytes());
/// ```
///
/// Scripts without case are not changed:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B("农历新年");
///
/// let mut buf = vec![];
/// s.to_lowercase_into(&mut buf);
/// assert_eq!("农历新年".as_bytes(), buf.as_bytes());
/// ```
///
/// Invalid UTF-8 remains as is:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B(b"FOO\xFFBAR\xE2\x98BAZ");
///
/// let mut buf = vec![];
/// s.to_lowercase_into(&mut buf);
/// assert_eq!(B(b"foo\xFFbar\xE2\x98baz"), buf.as_bytes());
/// ```
#[cfg(all(feature = "std", feature = "unicode"))]
#[inline]
fn to_lowercase_into(&self, buf: &mut Vec<u8>) {
// TODO: This is the best we can do given what std exposes I think.
// If we roll our own case handling, then we might be able to do this
// a bit faster. We shouldn't roll our own case handling unless we
// need to, e.g., for doing caseless matching or case folding.
// TODO(BUG): This doesn't handle any special casing rules.
buf.reserve(self.as_bytes().len());
for (s, e, ch) in self.char_indices() {
if ch == '\u{FFFD}' {
buf.push_str(&self.as_bytes()[s..e]);
} else if ch.is_ascii() {
buf.push_char(ch.to_ascii_lowercase());
} else {
for upper in ch.to_lowercase() {
buf.push_char(upper);
}
}
}
}
/// Returns a new `Vec<u8>` containing the ASCII lowercase equivalent of
/// this byte string.
///
/// In this case, lowercase is only defined in ASCII letters. Namely, the
/// letters `A-Z` are converted to `a-z`. All other bytes remain unchanged.
/// In particular, the length of the byte string returned is always
/// equivalent to the length of this byte string.
///
/// If you'd like to reuse an allocation for performance reasons, then use
/// [`make_ascii_lowercase`](#method.make_ascii_lowercase) to perform
/// the conversion in place.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B("HELLO Β");
/// assert_eq!("hello Β".as_bytes(), s.to_ascii_lowercase().as_bytes());
/// ```
///
/// Invalid UTF-8 remains as is:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B(b"FOO\xFFBAR\xE2\x98BAZ");
/// assert_eq!(s.to_ascii_lowercase(), B(b"foo\xFFbar\xE2\x98baz"));
/// ```
#[cfg(feature = "std")]
#[inline]
fn to_ascii_lowercase(&self) -> Vec<u8> {
self.as_bytes().to_ascii_lowercase()
}
/// Convert this byte string to its lowercase ASCII equivalent in place.
///
/// In this case, lowercase is only defined in ASCII letters. Namely, the
/// letters `A-Z` are converted to `a-z`. All other bytes remain unchanged.
///
/// If you don't need to do the conversion in
/// place and instead prefer convenience, then use
/// [`to_ascii_lowercase`](#method.to_ascii_lowercase) instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let mut s = <Vec<u8>>::from("HELLO Β");
/// s.make_ascii_lowercase();
/// assert_eq!(s, "hello Β".as_bytes());
/// ```
///
/// Invalid UTF-8 remains as is:
///
/// ```
/// use bstr::{B, ByteSlice, ByteVec};
///
/// let mut s = <Vec<u8>>::from_slice(b"FOO\xFFBAR\xE2\x98BAZ");
/// s.make_ascii_lowercase();
/// assert_eq!(s, B(b"foo\xFFbar\xE2\x98baz"));
/// ```
#[inline]
fn make_ascii_lowercase(&mut self) {
self.as_bytes_mut().make_ascii_lowercase();
}
/// Returns a new `Vec<u8>` containing the uppercase equivalent of this
/// byte string.
///
/// In this case, uppercase is defined according to the `Uppercase`
/// Unicode property.
///
/// If invalid UTF-8 is seen, or if a character has no uppercase variant,
/// then it is written to the given buffer unchanged.
///
/// Note that some characters in this byte string may expand into multiple
/// characters when changing the case, so the number of bytes written to
/// the given byte string may not be equivalent to the number of bytes in
/// this byte string.
///
/// If you'd like to reuse an allocation for performance reasons, then use
/// [`to_uppercase_into`](#method.to_uppercase_into) instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B("hello β");
/// assert_eq!(s.to_uppercase(), B("HELLO Β"));
/// ```
///
/// Scripts without case are not changed:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B("农历新年");
/// assert_eq!(s.to_uppercase(), B("农历新年"));
/// ```
///
/// Invalid UTF-8 remains as is:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B(b"foo\xFFbar\xE2\x98baz");
/// assert_eq!(s.to_uppercase(), B(b"FOO\xFFBAR\xE2\x98BAZ"));
/// ```
#[cfg(all(feature = "std", feature = "unicode"))]
#[inline]
fn to_uppercase(&self) -> Vec<u8> {
let mut buf = vec![];
self.to_uppercase_into(&mut buf);
buf
}
/// Writes the uppercase equivalent of this byte string into the given
/// buffer. The buffer is not cleared before written to.
///
/// In this case, uppercase is defined according to the `Uppercase`
/// Unicode property.
///
/// If invalid UTF-8 is seen, or if a character has no uppercase variant,
/// then it is written to the given buffer unchanged.
///
/// Note that some characters in this byte string may expand into multiple
/// characters when changing the case, so the number of bytes written to
/// the given byte string may not be equivalent to the number of bytes in
/// this byte string.
///
/// If you don't need to amortize allocation and instead prefer
/// convenience, then use [`to_uppercase`](#method.to_uppercase) instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B("hello β");
///
/// let mut buf = vec![];
/// s.to_uppercase_into(&mut buf);
/// assert_eq!(buf, B("HELLO Β"));
/// ```
///
/// Scripts without case are not changed:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B("农历新年");
///
/// let mut buf = vec![];
/// s.to_uppercase_into(&mut buf);
/// assert_eq!(buf, B("农历新年"));
/// ```
///
/// Invalid UTF-8 remains as is:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B(b"foo\xFFbar\xE2\x98baz");
///
/// let mut buf = vec![];
/// s.to_uppercase_into(&mut buf);
/// assert_eq!(buf, B(b"FOO\xFFBAR\xE2\x98BAZ"));
/// ```
#[cfg(all(feature = "std", feature = "unicode"))]
#[inline]
fn to_uppercase_into(&self, buf: &mut Vec<u8>) {
// TODO: This is the best we can do given what std exposes I think.
// If we roll our own case handling, then we might be able to do this
// a bit faster. We shouldn't roll our own case handling unless we
// need to, e.g., for doing caseless matching or case folding.
buf.reserve(self.as_bytes().len());
for (s, e, ch) in self.char_indices() {
if ch == '\u{FFFD}' {
buf.push_str(&self.as_bytes()[s..e]);
} else if ch.is_ascii() {
buf.push_char(ch.to_ascii_uppercase());
} else {
for upper in ch.to_uppercase() {
buf.push_char(upper);
}
}
}
}
/// Returns a new `Vec<u8>` containing the ASCII uppercase equivalent of
/// this byte string.
///
/// In this case, uppercase is only defined in ASCII letters. Namely, the
/// letters `a-z` are converted to `A-Z`. All other bytes remain unchanged.
/// In particular, the length of the byte string returned is always
/// equivalent to the length of this byte string.
///
/// If you'd like to reuse an allocation for performance reasons, then use
/// [`make_ascii_uppercase`](#method.make_ascii_uppercase) to perform
/// the conversion in place.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B("hello β");
/// assert_eq!(s.to_ascii_uppercase(), B("HELLO β"));
/// ```
///
/// Invalid UTF-8 remains as is:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let s = B(b"foo\xFFbar\xE2\x98baz");
/// assert_eq!(s.to_ascii_uppercase(), B(b"FOO\xFFBAR\xE2\x98BAZ"));
/// ```
#[cfg(feature = "std")]
#[inline]
fn to_ascii_uppercase(&self) -> Vec<u8> {
self.as_bytes().to_ascii_uppercase()
}
/// Convert this byte string to its uppercase ASCII equivalent in place.
///
/// In this case, uppercase is only defined in ASCII letters. Namely, the
/// letters `a-z` are converted to `A-Z`. All other bytes remain unchanged.
///
/// If you don't need to do the conversion in
/// place and instead prefer convenience, then use
/// [`to_ascii_uppercase`](#method.to_ascii_uppercase) instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let mut s = <Vec<u8>>::from("hello β");
/// s.make_ascii_uppercase();
/// assert_eq!(s, B("HELLO β"));
/// ```
///
/// Invalid UTF-8 remains as is:
///
/// ```
/// use bstr::{B, ByteSlice, ByteVec};
///
/// let mut s = <Vec<u8>>::from_slice(b"foo\xFFbar\xE2\x98baz");
/// s.make_ascii_uppercase();
/// assert_eq!(s, B(b"FOO\xFFBAR\xE2\x98BAZ"));
/// ```
#[inline]
fn make_ascii_uppercase(&mut self) {
self.as_bytes_mut().make_ascii_uppercase();
}
/// Reverse the bytes in this string, in place.
///
/// This is not necessarily a well formed operation! For example, if this
/// byte string contains valid UTF-8 that isn't ASCII, then reversing the
/// string will likely result in invalid UTF-8 and otherwise non-sensical
/// content.
///
/// Note that this is equivalent to the generic `[u8]::reverse` method.
/// This method is provided to permit callers to explicitly differentiate
/// between reversing bytes, codepoints and graphemes.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let mut s = <Vec<u8>>::from("hello");
/// s.reverse_bytes();
/// assert_eq!(s, "olleh".as_bytes());
/// ```
#[inline]
fn reverse_bytes(&mut self) {
self.as_bytes_mut().reverse();
}
/// Reverse the codepoints in this string, in place.
///
/// If this byte string is valid UTF-8, then its reversal by codepoint
/// is also guaranteed to be valid UTF-8.
///
/// This operation is equivalent to the following, but without allocating:
///
/// ```
/// use bstr::ByteSlice;
///
/// let mut s = <Vec<u8>>::from("foo☃bar");
///
/// let mut chars: Vec<char> = s.chars().collect();
/// chars.reverse();
///
/// let reversed: String = chars.into_iter().collect();
/// assert_eq!(reversed, "rab☃oof");
/// ```
///
/// Note that this is not necessarily a well formed operation. For example,
/// if this byte string contains grapheme clusters with more than one
/// codepoint, then those grapheme clusters will not necessarily be
/// preserved. If you'd like to preserve grapheme clusters, then use
/// [`reverse_graphemes`](#method.reverse_graphemes) instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let mut s = <Vec<u8>>::from("foo☃bar");
/// s.reverse_chars();
/// assert_eq!(s, "rab☃oof".as_bytes());
/// ```
///
/// This example shows that not all reversals lead to a well formed string.
/// For example, in this case, combining marks are used to put accents over
/// some letters, and those accent marks must appear after the codepoints
/// they modify.
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let mut s = <Vec<u8>>::from("résumé");
/// s.reverse_chars();
/// assert_eq!(s, B(b"\xCC\x81emus\xCC\x81er"));
/// ```
///
/// A word of warning: the above example relies on the fact that
/// `résumé` is in decomposed normal form, which means there are separate
/// codepoints for the accents above `e`. If it is instead in composed
/// normal form, then the example works:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let mut s = <Vec<u8>>::from("résumé");
/// s.reverse_chars();
/// assert_eq!(s, B("émusér"));
/// ```
///
/// The point here is to be cautious and not assume that just because
/// `reverse_chars` works in one case, that it therefore works in all
/// cases.
#[inline]
fn reverse_chars(&mut self) {
let mut i = 0;
loop {
let (_, size) = utf8::decode(&self.as_bytes()[i..]);
if size == 0 {
break;
}
if size > 1 {
self.as_bytes_mut()[i..i + size].reverse_bytes();
}
i += size;
}
self.reverse_bytes();
}
/// Reverse the graphemes in this string, in place.
///
/// If this byte string is valid UTF-8, then its reversal by grapheme
/// is also guaranteed to be valid UTF-8.
///
/// This operation is equivalent to the following, but without allocating:
///
/// ```
/// use bstr::ByteSlice;
///
/// let mut s = <Vec<u8>>::from("foo☃bar");
///
/// let mut graphemes: Vec<&str> = s.graphemes().collect();
/// graphemes.reverse();
///
/// let reversed = graphemes.concat();
/// assert_eq!(reversed, "rab☃oof");
/// ```
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let mut s = <Vec<u8>>::from("foo☃bar");
/// s.reverse_graphemes();
/// assert_eq!(s, "rab☃oof".as_bytes());
/// ```
///
/// This example shows how this correctly handles grapheme clusters,
/// unlike `reverse_chars`.
///
/// ```
/// use bstr::ByteSlice;
///
/// let mut s = <Vec<u8>>::from("résumé");
/// s.reverse_graphemes();
/// assert_eq!(s, "émusér".as_bytes());
/// ```
#[cfg(feature = "unicode")]
#[inline]
fn reverse_graphemes(&mut self) {
use unicode::decode_grapheme;
let mut i = 0;
loop {
let (_, size) = decode_grapheme(&self.as_bytes()[i..]);
if size == 0 {
break;
}
if size > 1 {
self.as_bytes_mut()[i..i + size].reverse_bytes();
}
i += size;
}
self.reverse_bytes();
}
/// Returns true if and only if every byte in this byte string is ASCII.
///
/// ASCII is an encoding that defines 128 codepoints. A byte corresponds to
/// an ASCII codepoint if and only if it is in the inclusive range
/// `[0, 127]`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// assert!(B("abc").is_ascii());
/// assert!(!B("☃βツ").is_ascii());
/// assert!(!B(b"\xFF").is_ascii());
/// ```
#[inline]
fn is_ascii(&self) -> bool {
ascii::first_non_ascii_byte(self.as_bytes()) == self.as_bytes().len()
}
/// Returns true if and only if the entire byte string is valid UTF-8.
///
/// If you need location information about where a byte string's first
/// invalid UTF-8 byte is, then use the [`to_str`](#method.to_str) method.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// assert!(B("abc").is_utf8());
/// assert!(B("☃βツ").is_utf8());
/// // invalid bytes
/// assert!(!B(b"abc\xFF").is_utf8());
/// // surrogate encoding
/// assert!(!B(b"\xED\xA0\x80").is_utf8());
/// // incomplete sequence
/// assert!(!B(b"\xF0\x9D\x9Ca").is_utf8());
/// // overlong sequence
/// assert!(!B(b"\xF0\x82\x82\xAC").is_utf8());
/// ```
#[inline]
fn is_utf8(&self) -> bool {
utf8::validate(self.as_bytes()).is_ok()
}
/// Returns the last byte in this byte string, if it's non-empty. If this
/// byte string is empty, this returns `None`.
///
/// Note that this is like the generic `[u8]::last`, except this returns
/// the byte by value instead of a reference to the byte.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert_eq!(Some(b'z'), b"baz".last_byte());
/// assert_eq!(None, b"".last_byte());
/// ```
#[inline]
fn last_byte(&self) -> Option<u8> {
let bytes = self.as_bytes();
bytes.get(bytes.len().saturating_sub(1)).map(|&b| b)
}
/// Returns the index of the first non-ASCII byte in this byte string (if
/// any such indices exist). Specifically, it returns the index of the
/// first byte with a value greater than or equal to `0x80`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::{ByteSlice, B};
///
/// assert_eq!(Some(3), b"abc\xff".find_non_ascii_byte());
/// assert_eq!(None, b"abcde".find_non_ascii_byte());
/// assert_eq!(Some(0), B("😀").find_non_ascii_byte());
/// ```
#[inline]
fn find_non_ascii_byte(&self) -> Option<usize> {
let index = ascii::first_non_ascii_byte(self.as_bytes());
if index == self.as_bytes().len() {
None
} else {
Some(index)
}
}
/// Copies elements from one part of the slice to another part of itself,
/// where the parts may be overlapping.
///
/// `src` is the range within this byte string to copy from, while `dest`
/// is the starting index of the range within this byte string to copy to.
/// The length indicated by `src` must be less than or equal to the number
/// of bytes from `dest` to the end of the byte string.
///
/// # Panics
///
/// Panics if either range is out of bounds, or if `src` is too big to fit
/// into `dest`, or if the end of `src` is before the start.
///
/// # Examples
///
/// Copying four bytes within a byte string:
///
/// ```
/// use bstr::{B, ByteSlice};
///
/// let mut buf = *b"Hello, World!";
/// let s = &mut buf;
/// s.copy_within_str(1..5, 8);
/// assert_eq!(s, B("Hello, Wello!"));
/// ```
#[inline]
fn copy_within_str<R>(&mut self, src: R, dest: usize)
where
R: ops::RangeBounds<usize>,
{
// TODO: Deprecate this once slice::copy_within stabilizes.
let src_start = match src.start_bound() {
ops::Bound::Included(&n) => n,
ops::Bound::Excluded(&n) => {
n.checked_add(1).expect("attempted to index slice beyond max")
}
ops::Bound::Unbounded => 0,
};
let src_end = match src.end_bound() {
ops::Bound::Included(&n) => {
n.checked_add(1).expect("attempted to index slice beyond max")
}
ops::Bound::Excluded(&n) => n,
ops::Bound::Unbounded => self.as_bytes().len(),
};
assert!(src_start <= src_end, "src end is before src start");
assert!(src_end <= self.as_bytes().len(), "src is out of bounds");
let count = src_end - src_start;
assert!(
dest <= self.as_bytes().len() - count,
"dest is out of bounds",
);
// SAFETY: This is safe because we use ptr::copy to handle overlapping
// copies, and is also safe because we've checked all the bounds above.
// Finally, we are only dealing with u8 data, which is Copy, which
// means we can copy without worrying about ownership/destructors.
unsafe {
ptr::copy(
self.as_bytes().get_unchecked(src_start),
self.as_bytes_mut().get_unchecked_mut(dest),
count,
);
}
}
}
/// A single substring searcher fixed to a particular needle.
///
/// The purpose of this type is to permit callers to construct a substring
/// searcher that can be used to search haystacks without the overhead of
/// constructing the searcher in the first place. This is a somewhat niche
/// concern when it's necessary to re-use the same needle to search multiple
/// different haystacks with as little overhead as possible. In general, using
/// [`ByteSlice::find`](trait.ByteSlice.html#method.find)
/// or
/// [`ByteSlice::find_iter`](trait.ByteSlice.html#method.find_iter)
/// is good enough, but `Finder` is useful when you can meaningfully observe
/// searcher construction time in a profile.
///
/// When the `std` feature is enabled, then this type has an `into_owned`
/// version which permits building a `Finder` that is not connected to the
/// lifetime of its needle.
#[derive(Clone, Debug)]
pub struct Finder<'a> {
searcher: TwoWay<'a>,
}
impl<'a> Finder<'a> {
/// Create a new finder for the given needle.
#[inline]
pub fn new<B: ?Sized + AsRef<[u8]>>(needle: &'a B) -> Finder<'a> {
Finder { searcher: TwoWay::forward(needle.as_ref()) }
}
/// Convert this finder into its owned variant, such that it no longer
/// borrows the needle.
///
/// If this is already an owned finder, then this is a no-op. Otherwise,
/// this copies the needle.
///
/// This is only available when the `std` feature is enabled.
#[cfg(feature = "std")]
#[inline]
pub fn into_owned(self) -> Finder<'static> {
Finder { searcher: self.searcher.into_owned() }
}
/// Returns the needle that this finder searches for.
///
/// Note that the lifetime of the needle returned is tied to the lifetime
/// of the finder, and may be shorter than the `'a` lifetime. Namely, a
/// finder's needle can be either borrowed or owned, so the lifetime of the
/// needle returned must necessarily be the shorter of the two.
#[inline]
pub fn needle(&self) -> &[u8] {
self.searcher.needle()
}
/// Returns the index of the first occurrence of this needle in the given
/// haystack.
///
/// The haystack may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::Finder;
///
/// let haystack = "foo bar baz";
/// assert_eq!(Some(0), Finder::new("foo").find(haystack));
/// assert_eq!(Some(4), Finder::new("bar").find(haystack));
/// assert_eq!(None, Finder::new("quux").find(haystack));
/// ```
#[inline]
pub fn find<B: AsRef<[u8]>>(&self, haystack: B) -> Option<usize> {
self.searcher.find(haystack.as_ref())
}
}
/// A single substring reverse searcher fixed to a particular needle.
///
/// The purpose of this type is to permit callers to construct a substring
/// searcher that can be used to search haystacks without the overhead of
/// constructing the searcher in the first place. This is a somewhat niche
/// concern when it's necessary to re-use the same needle to search multiple
/// different haystacks with as little overhead as possible. In general, using
/// [`ByteSlice::rfind`](trait.ByteSlice.html#method.rfind)
/// or
/// [`ByteSlice::rfind_iter`](trait.ByteSlice.html#method.rfind_iter)
/// is good enough, but `FinderReverse` is useful when you can meaningfully
/// observe searcher construction time in a profile.
///
/// When the `std` feature is enabled, then this type has an `into_owned`
/// version which permits building a `FinderReverse` that is not connected to
/// the lifetime of its needle.
#[derive(Clone, Debug)]
pub struct FinderReverse<'a> {
searcher: TwoWay<'a>,
}
impl<'a> FinderReverse<'a> {
/// Create a new reverse finder for the given needle.
#[inline]
pub fn new<B: ?Sized + AsRef<[u8]>>(needle: &'a B) -> FinderReverse<'a> {
FinderReverse { searcher: TwoWay::reverse(needle.as_ref()) }
}
/// Convert this finder into its owned variant, such that it no longer
/// borrows the needle.
///
/// If this is already an owned finder, then this is a no-op. Otherwise,
/// this copies the needle.
///
/// This is only available when the `std` feature is enabled.
#[cfg(feature = "std")]
#[inline]
pub fn into_owned(self) -> FinderReverse<'static> {
FinderReverse { searcher: self.searcher.into_owned() }
}
/// Returns the needle that this finder searches for.
///
/// Note that the lifetime of the needle returned is tied to the lifetime
/// of this finder, and may be shorter than the `'a` lifetime. Namely,
/// a finder's needle can be either borrowed or owned, so the lifetime of
/// the needle returned must necessarily be the shorter of the two.
#[inline]
pub fn needle(&self) -> &[u8] {
self.searcher.needle()
}
/// Returns the index of the last occurrence of this needle in the given
/// haystack.
///
/// The haystack may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::FinderReverse;
///
/// let haystack = "foo bar baz";
/// assert_eq!(Some(0), FinderReverse::new("foo").rfind(haystack));
/// assert_eq!(Some(4), FinderReverse::new("bar").rfind(haystack));
/// assert_eq!(None, FinderReverse::new("quux").rfind(haystack));
/// ```
#[inline]
pub fn rfind<B: AsRef<[u8]>>(&self, haystack: B) -> Option<usize> {
self.searcher.rfind(haystack.as_ref())
}
}
/// An iterator over non-overlapping substring matches.
///
/// Matches are reported by the byte offset at which they begin.
///
/// `'a` is the shorter of two lifetimes: the byte string being searched or the
/// byte string being looked for.
#[derive(Debug)]
pub struct Find<'a> {
haystack: &'a [u8],
prestate: PrefilterState,
searcher: TwoWay<'a>,
pos: usize,
}
impl<'a> Find<'a> {
fn new(haystack: &'a [u8], needle: &'a [u8]) -> Find<'a> {
let searcher = TwoWay::forward(needle);
let prestate = searcher.prefilter_state();
Find { haystack, prestate, searcher, pos: 0 }
}
}
impl<'a> Iterator for Find<'a> {
type Item = usize;
#[inline]
fn next(&mut self) -> Option<usize> {
if self.pos > self.haystack.len() {
return None;
}
let result = self
.searcher
.find_with(&mut self.prestate, &self.haystack[self.pos..]);
match result {
None => None,
Some(i) => {
let pos = self.pos + i;
self.pos = pos + cmp::max(1, self.searcher.needle().len());
Some(pos)
}
}
}
}
/// An iterator over non-overlapping substring matches in reverse.
///
/// Matches are reported by the byte offset at which they begin.
///
/// `'a` is the shorter of two lifetimes: the byte string being searched or the
/// byte string being looked for.
#[derive(Debug)]
pub struct FindReverse<'a> {
haystack: &'a [u8],
prestate: PrefilterState,
searcher: TwoWay<'a>,
/// When searching with an empty needle, this gets set to `None` after
/// we've yielded the last element at `0`.
pos: Option<usize>,
}
impl<'a> FindReverse<'a> {
fn new(haystack: &'a [u8], needle: &'a [u8]) -> FindReverse<'a> {
let searcher = TwoWay::reverse(needle);
let prestate = searcher.prefilter_state();
let pos = Some(haystack.len());
FindReverse { haystack, prestate, searcher, pos }
}
fn haystack(&self) -> &'a [u8] {
self.haystack
}
fn needle(&self) -> &[u8] {
self.searcher.needle()
}
}
impl<'a> Iterator for FindReverse<'a> {
type Item = usize;
#[inline]
fn next(&mut self) -> Option<usize> {
let pos = match self.pos {
None => return None,
Some(pos) => pos,
};
let result = self
.searcher
.rfind_with(&mut self.prestate, &self.haystack[..pos]);
match result {
None => None,
Some(i) => {
if pos == i {
self.pos = pos.checked_sub(1);
} else {
self.pos = Some(i);
}
Some(i)
}
}
}
}
/// An iterator over the bytes in a byte string.
///
/// `'a` is the lifetime of the byte string being traversed.
#[derive(Clone, Debug)]
pub struct Bytes<'a> {
it: slice::Iter<'a, u8>,
}
impl<'a> Iterator for Bytes<'a> {
type Item = u8;
#[inline]
fn next(&mut self) -> Option<u8> {
self.it.next().map(|&b| b)
}
}
impl<'a> DoubleEndedIterator for Bytes<'a> {
#[inline]
fn next_back(&mut self) -> Option<u8> {
self.it.next_back().map(|&b| b)
}
}
impl<'a> ExactSizeIterator for Bytes<'a> {
#[inline]
fn len(&self) -> usize {
self.it.len()
}
}
/// An iterator over the fields in a byte string, separated by whitespace.
///
/// This iterator splits on contiguous runs of whitespace, such that the fields
/// in `foo\t\t\n \nbar` are `foo` and `bar`.
///
/// `'a` is the lifetime of the byte string being split.
#[derive(Debug)]
pub struct Fields<'a> {
it: FieldsWith<'a, fn(char) -> bool>,
}
impl<'a> Fields<'a> {
fn new(bytes: &'a [u8]) -> Fields<'a> {
Fields { it: bytes.fields_with(|ch| ch.is_whitespace()) }
}
}
impl<'a> Iterator for Fields<'a> {
type Item = &'a [u8];
#[inline]
fn next(&mut self) -> Option<&'a [u8]> {
self.it.next()
}
}
/// An iterator over fields in the byte string, separated by a predicate over
/// codepoints.
///
/// This iterator splits a byte string based on its predicate function such
/// that the elements returned are separated by contiguous runs of codepoints
/// for which the predicate returns true.
///
/// `'a` is the lifetime of the byte string being split, while `F` is the type
/// of the predicate, i.e., `FnMut(char) -> bool`.
#[derive(Debug)]
pub struct FieldsWith<'a, F> {
f: F,
bytes: &'a [u8],
chars: CharIndices<'a>,
}
impl<'a, F: FnMut(char) -> bool> FieldsWith<'a, F> {
fn new(bytes: &'a [u8], f: F) -> FieldsWith<'a, F> {
FieldsWith { f, bytes, chars: bytes.char_indices() }
}
}
impl<'a, F: FnMut(char) -> bool> Iterator for FieldsWith<'a, F> {
type Item = &'a [u8];
#[inline]
fn next(&mut self) -> Option<&'a [u8]> {
let (start, mut end);
loop {
match self.chars.next() {
None => return None,
Some((s, e, ch)) => {
if !(self.f)(ch) {
start = s;
end = e;
break;
}
}
}
}
while let Some((_, e, ch)) = self.chars.next() {
if (self.f)(ch) {
break;
}
end = e;
}
Some(&self.bytes[start..end])
}
}
/// An iterator over substrings in a byte string, split by a separator.
///
/// `'a` is the lifetime of the byte string being split.
#[derive(Debug)]
pub struct Split<'a> {
finder: Find<'a>,
/// The end position of the previous match of our splitter. The element
/// we yield corresponds to the substring starting at `last` up to the
/// beginning of the next match of the splitter.
last: usize,
/// Only set when iteration is complete. A corner case here is when a
/// splitter is matched at the end of the haystack. At that point, we still
/// need to yield an empty string following it.
done: bool,
}
impl<'a> Split<'a> {
fn new(haystack: &'a [u8], splitter: &'a [u8]) -> Split<'a> {
let finder = haystack.find_iter(splitter);
Split { finder, last: 0, done: false }
}
}
impl<'a> Iterator for Split<'a> {
type Item = &'a [u8];
#[inline]
fn next(&mut self) -> Option<&'a [u8]> {
let haystack = self.finder.haystack;
match self.finder.next() {
Some(start) => {
let next = &haystack[self.last..start];
self.last = start + self.finder.searcher.needle().len();
Some(next)
}
None => {
if self.last >= haystack.len() {
if !self.done {
self.done = true;
Some(b"")
} else {
None
}
} else {
let s = &haystack[self.last..];
self.last = haystack.len();
self.done = true;
Some(s)
}
}
}
}
}
/// An iterator over substrings in a byte string, split by a separator, in
/// reverse.
///
/// `'a` is the lifetime of the byte string being split, while `F` is the type
/// of the predicate, i.e., `FnMut(char) -> bool`.
#[derive(Debug)]
pub struct SplitReverse<'a> {
finder: FindReverse<'a>,
/// The end position of the previous match of our splitter. The element
/// we yield corresponds to the substring starting at `last` up to the
/// beginning of the next match of the splitter.
last: usize,
/// Only set when iteration is complete. A corner case here is when a
/// splitter is matched at the end of the haystack. At that point, we still
/// need to yield an empty string following it.
done: bool,
}
impl<'a> SplitReverse<'a> {
fn new(haystack: &'a [u8], splitter: &'a [u8]) -> SplitReverse<'a> {
let finder = haystack.rfind_iter(splitter);
SplitReverse { finder, last: haystack.len(), done: false }
}
}
impl<'a> Iterator for SplitReverse<'a> {
type Item = &'a [u8];
#[inline]
fn next(&mut self) -> Option<&'a [u8]> {
let haystack = self.finder.haystack();
match self.finder.next() {
Some(start) => {
let nlen = self.finder.needle().len();
let next = &haystack[start + nlen..self.last];
self.last = start;
Some(next)
}
None => {
if self.last == 0 {
if !self.done {
self.done = true;
Some(b"")
} else {
None
}
} else {
let s = &haystack[..self.last];
self.last = 0;
self.done = true;
Some(s)
}
}
}
}
}
/// An iterator over at most `n` substrings in a byte string, split by a
/// separator.
///
/// `'a` is the lifetime of the byte string being split, while `F` is the type
/// of the predicate, i.e., `FnMut(char) -> bool`.
#[derive(Debug)]
pub struct SplitN<'a> {
split: Split<'a>,
limit: usize,
count: usize,
}
impl<'a> SplitN<'a> {
fn new(
haystack: &'a [u8],
splitter: &'a [u8],
limit: usize,
) -> SplitN<'a> {
let split = haystack.split_str(splitter);
SplitN { split, limit, count: 0 }
}
}
impl<'a> Iterator for SplitN<'a> {
type Item = &'a [u8];
#[inline]
fn next(&mut self) -> Option<&'a [u8]> {
self.count += 1;
if self.count > self.limit {
None
} else if self.count == self.limit {
Some(&self.split.finder.haystack[self.split.last..])
} else {
self.split.next()
}
}
}
/// An iterator over at most `n` substrings in a byte string, split by a
/// separator, in reverse.
///
/// `'a` is the lifetime of the byte string being split, while `F` is the type
/// of the predicate, i.e., `FnMut(char) -> bool`.
#[derive(Debug)]
pub struct SplitNReverse<'a> {
split: SplitReverse<'a>,
limit: usize,
count: usize,
}
impl<'a> SplitNReverse<'a> {
fn new(
haystack: &'a [u8],
splitter: &'a [u8],
limit: usize,
) -> SplitNReverse<'a> {
let split = haystack.rsplit_str(splitter);
SplitNReverse { split, limit, count: 0 }
}
}
impl<'a> Iterator for SplitNReverse<'a> {
type Item = &'a [u8];
#[inline]
fn next(&mut self) -> Option<&'a [u8]> {
self.count += 1;
if self.count > self.limit {
None
} else if self.count == self.limit {
Some(&self.split.finder.haystack()[..self.split.last])
} else {
self.split.next()
}
}
}
/// An iterator over all lines in a byte string, without their terminators.
///
/// For this iterator, the only line terminators recognized are `\r\n` and
/// `\n`.
///
/// `'a` is the lifetime of the byte string being iterated over.
pub struct Lines<'a> {
it: LinesWithTerminator<'a>,
}
impl<'a> Lines<'a> {
fn new(bytes: &'a [u8]) -> Lines<'a> {
Lines { it: LinesWithTerminator::new(bytes) }
}
}
impl<'a> Iterator for Lines<'a> {
type Item = &'a [u8];
#[inline]
fn next(&mut self) -> Option<&'a [u8]> {
let mut line = self.it.next()?;
if line.last_byte() == Some(b'\n') {
line = &line[..line.len() - 1];
if line.last_byte() == Some(b'\r') {
line = &line[..line.len() - 1];
}
}
Some(line)
}
}
/// An iterator over all lines in a byte string, including their terminators.
///
/// For this iterator, the only line terminator recognized is `\n`. (Since
/// line terminators are included, this also handles `\r\n` line endings.)
///
/// Line terminators are only included if they are present in the original
/// byte string. For example, the last line in a byte string may not end with
/// a line terminator.
///
/// Concatenating all elements yielded by this iterator is guaranteed to yield
/// the original byte string.
///
/// `'a` is the lifetime of the byte string being iterated over.
pub struct LinesWithTerminator<'a> {
bytes: &'a [u8],
}
impl<'a> LinesWithTerminator<'a> {
fn new(bytes: &'a [u8]) -> LinesWithTerminator<'a> {
LinesWithTerminator { bytes }
}
}
impl<'a> Iterator for LinesWithTerminator<'a> {
type Item = &'a [u8];
#[inline]
fn next(&mut self) -> Option<&'a [u8]> {
match self.bytes.find_byte(b'\n') {
None if self.bytes.is_empty() => None,
None => {
let line = self.bytes;
self.bytes = b"";
Some(line)
}
Some(end) => {
let line = &self.bytes[..end + 1];
self.bytes = &self.bytes[end + 1..];
Some(line)
}
}
}
}
#[cfg(test)]
mod tests {
use ext_slice::{ByteSlice, B};
use tests::LOSSY_TESTS;
#[test]
fn to_str_lossy() {
for (i, &(expected, input)) in LOSSY_TESTS.iter().enumerate() {
let got = B(input).to_str_lossy();
assert_eq!(
expected.as_bytes(),
got.as_bytes(),
"to_str_lossy(ith: {:?}, given: {:?})",
i,
input,
);
let mut got = String::new();
B(input).to_str_lossy_into(&mut got);
assert_eq!(
expected.as_bytes(),
got.as_bytes(),
"to_str_lossy_into",
);
let got = String::from_utf8_lossy(input);
assert_eq!(expected.as_bytes(), got.as_bytes(), "std");
}
}
#[test]
#[should_panic]
fn copy_within_fail1() {
let mut buf = *b"foobar";
let s = &mut buf;
s.copy_within_str(0..2, 5);
}
#[test]
#[should_panic]
fn copy_within_fail2() {
let mut buf = *b"foobar";
let s = &mut buf;
s.copy_within_str(3..2, 0);
}
#[test]
#[should_panic]
fn copy_within_fail3() {
let mut buf = *b"foobar";
let s = &mut buf;
s.copy_within_str(5..7, 0);
}
#[test]
#[should_panic]
fn copy_within_fail4() {
let mut buf = *b"foobar";
let s = &mut buf;
s.copy_within_str(0..1, 6);
}
}
| 31.924409 | 91 | 0.540963 |
012770fff1ee018ac2614b388b30ce9d5f995c8e | 13,187 | //! A collection of traits abstracting over Listeners and Streams.
use std::io::{self, Read, Write};
use std::net::{SocketAddr, ToSocketAddrs};
use mio::tcp::{TcpStream, TcpListener};
use mio::{Selector, Token, Evented, EventSet, PollOpt, TryAccept};
#[cfg(feature = "openssl")]
pub use self::openssl::Openssl;
#[cfg(not(windows))]
pub trait Transport: Read + Write + Evented + ::vecio::Writev {}
#[cfg(not(windows))]
impl<T: Read + Write + Evented + ::vecio::Writev> Transport for T {}
#[cfg(windows)]
pub trait Transport: Read + Write + Evented {}
#[cfg(windows)]
impl<T: Read + Write + Evented> Transport for T {}
/// A connector creates a NetworkStream.
pub trait Connect {
/// Type of Stream to create
type Output: Transport;
/// Connect to a remote address.
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Output>;
}
/// An alias to `mio::tcp::TcpStream`.
#[derive(Debug)]
pub struct HttpStream(pub TcpStream);
impl Read for HttpStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
}
impl Write for HttpStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
impl Evented for HttpStream {
#[inline]
fn register(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> {
self.0.register(selector, token, interest, opts)
}
#[inline]
fn reregister(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> {
self.0.reregister(selector, token, interest, opts)
}
#[inline]
fn deregister(&self, selector: &mut Selector) -> io::Result<()> {
self.0.deregister(selector)
}
}
impl ::vecio::Writev for HttpStream {
fn writev(&mut self, bufs: &[&[u8]]) -> io::Result<usize> {
use ::vecio::Rawv;
self.0.writev(bufs)
}
}
/// An alias to `mio::tcp::TcpListener`.
pub struct HttpListener(pub TcpListener);
impl TryAccept for HttpListener {
type Output = HttpStream;
#[inline]
fn accept(&self) -> io::Result<Option<HttpStream>> {
TryAccept::accept(&self.0).map(|ok| ok.map(HttpStream))
}
}
impl Evented for HttpListener {
#[inline]
fn register(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> {
self.0.register(selector, token, interest, opts)
}
#[inline]
fn reregister(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> {
self.0.reregister(selector, token, interest, opts)
}
#[inline]
fn deregister(&self, selector: &mut Selector) -> io::Result<()> {
self.0.deregister(selector)
}
}
/// A connector that will produce HttpStreams.
#[derive(Debug, Clone, Default)]
pub struct HttpConnector;
impl Connect for HttpConnector {
type Output = HttpStream;
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<HttpStream> {
let addr = (host, port).to_socket_addrs().unwrap().next().unwrap();
Ok(try!(match scheme {
"http" => {
debug!("http scheme");
Ok(HttpStream(try!(TcpStream::connect(&addr))))
},
_ => {
Err(io::Error::new(io::ErrorKind::InvalidInput,
"Invalid scheme for Http"))
}
}))
}
}
/// A closure as a connector used to generate TcpStreams per request
///
/// # Example
///
/// Basic example:
///
/// ```norun
/// Client::with_connector(|addr: &str, port: u16, scheme: &str| {
/// TcpStream::connect(&(addr, port))
/// });
/// ```
///
/// Example using TcpBuilder from the net2 crate if you want to configure your source socket:
///
/// ```norun
/// Client::with_connector(|addr: &str, port: u16, scheme: &str| {
/// let b = try!(TcpBuilder::new_v4());
/// try!(b.bind("127.0.0.1:0"));
/// b.connect(&(addr, port))
/// });
/// ```
impl<F> Connect for F where F: Fn(&str, u16, &str) -> io::Result<TcpStream> {
type Output = HttpStream;
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<HttpStream> {
Ok(HttpStream(try!((*self)(host, port, scheme))))
}
}
/// An abstraction to allow any SSL implementation to be used with HttpsStreams.
pub trait Ssl {
/// The protected stream.
type Stream: Transport;
/// Wrap a client stream with SSL.
fn wrap_client(&self, stream: TcpStream, host: &str) -> ::Result<Self::Stream>;
/// Wrap a server stream with SSL.
fn wrap_server(&self, stream: TcpStream) -> ::Result<Self::Stream>;
}
/// A stream over the HTTP protocol, possibly protected by SSL.
#[derive(Debug)]
pub enum HttpsStream<S: Transport> {
/// A plain text stream.
Http(HttpStream),
/// A stream protected by SSL.
Https(S)
}
impl<S: Transport> Read for HttpsStream<S> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self {
HttpsStream::Http(ref mut s) => s.read(buf),
HttpsStream::Https(ref mut s) => s.read(buf)
}
}
}
impl<S: Transport> Write for HttpsStream<S> {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
match *self {
HttpsStream::Http(ref mut s) => s.write(msg),
HttpsStream::Https(ref mut s) => s.write(msg)
}
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
match *self {
HttpsStream::Http(ref mut s) => s.flush(),
HttpsStream::Https(ref mut s) => s.flush()
}
}
}
impl<S: Transport> ::vecio::Writev for HttpsStream<S> {
fn writev(&mut self, bufs: &[&[u8]]) -> io::Result<usize> {
match *self {
HttpsStream::Http(ref mut s) => s.writev(bufs),
HttpsStream::Https(ref mut s) => s.writev(bufs)
}
}
}
#[cfg(unix)]
impl ::std::os::unix::io::AsRawFd for HttpStream {
fn as_raw_fd(&self) -> ::std::os::unix::io::RawFd {
self.0.as_raw_fd()
}
}
#[cfg(unix)]
impl<S: Transport + ::std::os::unix::io::AsRawFd> ::std::os::unix::io::AsRawFd for HttpsStream<S> {
fn as_raw_fd(&self) -> ::std::os::unix::io::RawFd {
match *self {
HttpsStream::Http(ref s) => s.as_raw_fd(),
HttpsStream::Https(ref s) => s.as_raw_fd(),
}
}
}
impl<S: Transport> Evented for HttpsStream<S> {
#[inline]
fn register(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> {
match *self {
HttpsStream::Http(ref s) => s.register(selector, token, interest, opts),
HttpsStream::Https(ref s) => s.register(selector, token, interest, opts),
}
}
#[inline]
fn reregister(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> {
match *self {
HttpsStream::Http(ref s) => s.reregister(selector, token, interest, opts),
HttpsStream::Https(ref s) => s.reregister(selector, token, interest, opts),
}
}
#[inline]
fn deregister(&self, selector: &mut Selector) -> io::Result<()> {
match *self {
HttpsStream::Http(ref s) => s.deregister(selector),
HttpsStream::Https(ref s) => s.deregister(selector),
}
}
}
/// A Http Listener over SSL.
pub struct HttpsListener<S: Ssl> {
listener: TcpListener,
ssl: S,
}
impl<S: Ssl> HttpsListener<S> {
/// Start listening to an address over HTTPS.
#[inline]
pub fn new/*<To: ToSocketAddrs>(addr: To,*/(addr: &SocketAddr, ssl: S) -> io::Result<HttpsListener<S>> {
TcpListener::bind(addr).map(|l| HttpsListener {
listener: l,
ssl: ssl
})
}
/// Construct an HttpsListener from a bound `TcpListener`.
pub fn with_listener(listener: TcpListener, ssl: S) -> HttpsListener<S> {
HttpsListener {
listener: listener,
ssl: ssl
}
}
}
impl<S: Ssl> TryAccept for HttpsListener<S> {
type Output = S::Stream;
#[inline]
fn accept(&self) -> io::Result<Option<S::Stream>> {
self.listener.accept().and_then(|s| match s {
Some((s, _)) => self.ssl.wrap_server(s).map(Some).map_err(|e| {
match e {
::Error::Io(e) => e,
_ => io::Error::new(io::ErrorKind::Other, e),
}
}),
None => Ok(None),
})
}
}
impl<S: Ssl> Evented for HttpsListener<S> {
#[inline]
fn register(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> {
self.listener.register(selector, token, interest, opts)
}
#[inline]
fn reregister(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> {
self.listener.reregister(selector, token, interest, opts)
}
#[inline]
fn deregister(&self, selector: &mut Selector) -> io::Result<()> {
self.listener.deregister(selector)
}
}
/// A connector that can protect HTTP streams using SSL.
#[derive(Debug, Default)]
pub struct HttpsConnector<S: Ssl> {
ssl: S
}
impl<S: Ssl> HttpsConnector<S> {
/// Create a new connector using the provided SSL implementation.
pub fn new(s: S) -> HttpsConnector<S> {
HttpsConnector { ssl: s }
}
}
fn _assert_transport() {
fn _assert<T: Transport>() {}
_assert::<HttpsStream<HttpStream>>();
}
/*
impl<S: Ssl> Connect for HttpsConnector<S> {
type Stream = HttpsStream<<S as Ssl>::Stream>;
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream> {
let addr = (host, port).to_socket_addrs().unwrap().next().unwrap();
if scheme == "https" {
debug!("https scheme");
let stream = try!(TcpStream::connect(&addr));
self.ssl.wrap_client(stream, host).map(HttpsStream::Https)
} else {
HttpConnector.connect(host, port, scheme).map(HttpsStream::Http)
}
}
}
*/
#[cfg(not(feature = "openssl"))]
#[doc(hidden)]
pub type DefaultConnector = HttpConnector;
#[cfg(feature = "openssl")]
#[doc(hidden)]
pub type DefaultConnector = HttpsConnector<self::openssl::Openssl>;
#[cfg(feature = "openssl")]
mod openssl {
use std::io;
use std::net::{SocketAddr, Shutdown};
use std::path::Path;
use std::sync::Arc;
use mio::tcp::TcpStream;
use openssl::ssl::{Ssl, SslContext, SslStream, SslMethod, SSL_VERIFY_NONE};
use openssl::ssl::error::StreamError as SslIoError;
use openssl::ssl::error::SslError;
use openssl::x509::X509FileType;
/// An implementation of `Ssl` for OpenSSL.
///
/// # Example
///
/// ```no_run
/// use hyper::Server;
/// use hyper::net::Openssl;
///
/// let ssl = Openssl::with_cert_and_key("/home/foo/cert", "/home/foo/key").unwrap();
/// Server::https("0.0.0.0:443", ssl).unwrap();
/// ```
///
/// For complete control, create a `SslContext` with the options you desire
/// and then create `Openssl { context: ctx }
#[derive(Debug, Clone)]
pub struct Openssl {
/// The `SslContext` from openssl crate.
pub context: Arc<SslContext>
}
impl Default for Openssl {
fn default() -> Openssl {
Openssl {
context: Arc::new(SslContext::new(SslMethod::Sslv23).unwrap_or_else(|e| {
// if we cannot create a SslContext, that's because of a
// serious problem. just crash.
panic!("{}", e)
}))
}
}
}
impl Openssl {
/// Ease creating an `Openssl` with a certificate and key.
pub fn with_cert_and_key<C, K>(cert: C, key: K) -> Result<Openssl, SslError>
where C: AsRef<Path>, K: AsRef<Path> {
let mut ctx = try!(SslContext::new(SslMethod::Sslv23));
try!(ctx.set_cipher_list("DEFAULT"));
try!(ctx.set_certificate_file(cert.as_ref(), X509FileType::PEM));
try!(ctx.set_private_key_file(key.as_ref(), X509FileType::PEM));
ctx.set_verify(SSL_VERIFY_NONE, None);
Ok(Openssl { context: Arc::new(ctx) })
}
}
impl super::Ssl for Openssl {
type Stream = SslStream<TcpStream>;
fn wrap_client(&self, stream: TcpStream, host: &str) -> ::Result<Self::Stream> {
let ssl = try!(Ssl::new(&self.context));
try!(ssl.set_hostname(host));
SslStream::connect(ssl, stream).map_err(From::from)
}
fn wrap_server(&self, stream: TcpStream) -> ::Result<Self::Stream> {
match SslStream::accept(&*self.context, stream) {
Ok(ssl_stream) => Ok(ssl_stream),
Err(SslIoError(e)) => {
Err(io::Error::new(io::ErrorKind::ConnectionAborted, e).into())
},
Err(e) => Err(e.into())
}
}
}
}
| 29.902494 | 118 | 0.577235 |
6a80c5d5c7ff2624f17b79c131b08937e61537c6 | 8,792 | #![deny(missing_debug_implementations)]
use datasets::Dataset;
use rand::distributions::{Bernoulli, Distribution};
use rand::{thread_rng, Rng};
use rulinalg::matrix::{BaseMatrix, BaseMatrixMut, Matrix as RulinalgMatrix};
pub mod activations;
pub mod layers;
pub mod losses;
pub mod optimizers;
pub mod tensor;
pub type Vector = Vec<f64>;
pub type Matrix = Vec<Vec<f64>>;
#[allow(clippy::ptr_arg)]
pub fn elementwise_multiplication(vec_a: &Vector, vec_b: &Vector) -> Vector {
vec_a.iter().zip(vec_b.iter()).map(|(a, b)| a * b).collect()
}
pub fn argmax(vec: &[f64]) -> usize {
let mut max = vec[0];
let mut ans = 0;
for (i, x) in vec.iter().enumerate().skip(1) {
if x > &max {
max = *x;
ans = i;
}
}
ans
}
pub fn vector_sum(vec: Vector) -> f64 {
vec.iter().sum()
}
#[allow(clippy::ptr_arg)]
pub fn dot(vec_a: &Vector, vec_b: &Vector) -> f64 {
vec_a.iter().zip(vec_b.iter()).map(|(a, b)| a * b).sum()
}
#[allow(clippy::ptr_arg)]
pub fn elementwise_scalar_multiplication(vec: &Vector, n: f64) -> Vector {
vec.iter().map(|x| x * n).collect()
}
#[allow(clippy::ptr_arg)]
pub fn elementwise_addition(vec_a: &Vector, vec_b: &Vector) -> Vector {
vec_a.iter().zip(vec_b.iter()).map(|(a, b)| a + b).collect()
}
#[allow(clippy::ptr_arg)]
pub fn vector_average(vec: &Vector) -> f64 {
let len = vec.len() as f64;
vec.iter().sum::<f64>() / len
}
#[allow(clippy::ptr_arg)]
pub fn vector_vector_subtraction(v1: &Vector, v2: &Vector) -> Vector {
v1.iter().zip(v2.iter()).map(|(a, b)| a - b).collect()
}
#[allow(clippy::ptr_arg)]
pub fn vector_vector_multiplication(v1: &Vector, v2: &Vector) -> Vector {
v1.iter().zip(v2.iter()).map(|(a, b)| a * b).collect()
}
#[allow(clippy::ptr_arg)]
pub fn vector_vector_dot(vec1: &Vector, vec2: &Vector) -> Matrix {
vec1.iter()
.map(|i| vec2.iter().map(|j| i * j).collect())
.collect()
}
#[allow(clippy::ptr_arg)]
pub fn vector_matrix_dot(vec: &Vector, mat: &Matrix) -> Vector {
matrix_vector_dot(&transpose(mat), vec)
}
#[allow(clippy::ptr_arg)]
pub fn matrix_vector_dot(mat: &Matrix, vec: &Vector) -> Vector {
mat.iter().map(|w| dot(w, vec)).collect()
}
#[allow(clippy::ptr_arg)]
pub fn matrix_matrix_subtraction(mat1: &Matrix, mat2: &Matrix) -> Matrix {
mat1.iter()
.zip(mat2.iter())
.map(|(v1, v2)| vector_vector_subtraction(v1, v2))
.collect()
}
#[allow(clippy::ptr_arg)]
pub fn matrix_matrix_multiplication(mat1: &Matrix, mat2: &Matrix) -> Matrix {
mat1.iter()
.zip(mat2.iter())
.map(|(v1, v2)| vector_vector_multiplication(v1, v2))
.collect()
}
#[allow(clippy::ptr_arg, clippy::needless_range_loop)]
pub fn matrix_matrix_dot(mat1: &Matrix, mat2: &Matrix) -> Matrix {
assert_eq!(mat1[0].len(), mat2.len());
let mut ans = vec![vec![0.0; mat2[0].len()]; mat1.len()];
for i in 0..mat1.len() {
for j in 0..mat2[0].len() {
for k in 0..mat2.len() {
ans[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
ans
}
pub fn relu_vector(v: Vector) -> Vector {
v.into_iter()
.map(|a| if a > 0.0 { a } else { 0.0 })
.collect()
}
pub fn relu_vector_derivative(v: Vector) -> Vector {
v.into_iter()
.map(|a| if a > 0.0 { 1.0 } else { 0.0 })
.collect()
}
pub fn relu_matrix(m: Matrix) -> Matrix {
m.into_iter().map(relu_vector).collect()
}
pub fn relu_matrix_derivative(m: Matrix) -> Matrix {
m.into_iter().map(relu_vector_derivative).collect()
}
#[allow(clippy::ptr_arg, clippy::needless_range_loop)]
pub fn transpose(m: &Matrix) -> Matrix {
let mut ans = vec![vec![0.0; m.len()]; m[0].len()];
for i in 0..m.len() {
for j in 0..m[0].len() {
ans[j][i] = m[i][j];
}
}
ans
}
pub fn generate_random_vector(
size: usize,
scale_factor: f64,
add_factor: f64,
dist: &impl Distribution<f64>,
) -> Vec<f64> {
let mut rng = thread_rng();
(0..size)
.map(|_| scale_factor * rng.sample(dist) + add_factor)
.collect()
}
pub fn process_mnist_batch_dataset(
dataset: impl Dataset<Item = (Vec<u8>, u8)>,
dataset_size: usize,
batch_size: usize,
) -> (Vec<Vec<f64>>, Vec<Vec<f64>>) {
let normalize_image = |img: Vec<u8>| img.iter().map(|v| f64::from(*v) / 255.0).collect();
let encode_label = |l| {
let mut v = vec![0.0; 10];
v[l as usize] = 1.0;
v
};
let (images, labels): (Vec<_>, Vec<_>) = dataset
.take(dataset_size)
.map(|(i, l)| (normalize_image(i), encode_label(l)))
.unzip();
let images = images
.into_iter()
.batch(batch_size, false)
.map(|v| {
v.into_iter()
.fold(Vec::with_capacity(batch_size * 784), |mut acc, mut img| {
acc.append(&mut img);
acc
})
})
.collect();
let labels = labels
.into_iter()
.batch(batch_size, false)
.map(|v| {
v.into_iter()
.fold(Vec::with_capacity(batch_size * 10), |mut acc, mut l| {
acc.append(&mut l);
acc
})
})
.collect();
(images, labels)
}
pub fn sample_bernoulli_trials(p: f64, length: usize) -> Vec<f64> {
let dist = Bernoulli::new(p);
thread_rng()
.sample_iter(&dist)
.take(length)
.map(|v| if v { 1.0 } else { 0.0 })
.collect()
}
pub fn relu_mut(m: &mut RulinalgMatrix<f64>) {
for x in m.iter_mut() {
*x = if (*x) > 0.0 { *x } else { 0.0 };
}
}
pub fn relu_derivative(m: &RulinalgMatrix<f64>) -> RulinalgMatrix<f64> {
let mut ans = RulinalgMatrix::zeros(m.rows(), m.cols());
for i in 0..m.rows() {
for j in 0..m.cols() {
if m[[i, j]] >= 0.0 {
ans[[i, j]] = 1.0;
}
}
}
ans
}
pub fn sigmoid_mut(m: &mut RulinalgMatrix<f64>) {
for x in m.iter_mut() {
*x = 1.0 / (1.0 + (-(*x)).exp());
}
}
pub fn tanh_mut(m: &mut RulinalgMatrix<f64>) {
for x in m.iter_mut() {
*x = (*x).tanh();
}
}
pub fn tanh_derivative(m: &RulinalgMatrix<f64>) -> RulinalgMatrix<f64> {
let mut ans = RulinalgMatrix::zeros(m.rows(), m.cols());
for i in 0..m.rows() {
for j in 0..m.cols() {
ans[[i, j]] = 1.0 - (m[[i, j]] * m[[i, j]]);
}
}
ans
}
pub fn softmax_mut(m: &mut RulinalgMatrix<f64>) {
for i in 0..m.rows() {
let mut s = 0.0;
for j in 0..m.cols() {
m[[i, j]] = m[[i, j]].exp();
s += m[[i, j]];
}
for j in 0..m.cols() {
m[[i, j]] /= s;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_elementwise_multiplication() {
assert_eq!(
vec![6.0, 14.0, 24.0, 36.0, 0.0],
elementwise_multiplication(
&vec![1.0, 2.0, 3.0, 4.0, 5.0],
&vec![6.0, 7.0, 8.0, 9.0, 0.0],
),
);
}
#[test]
fn test_vector_sum() {
assert_eq!(15.0, vector_sum(vec![1.0, 2.0, 3.0, 4.0, 5.0]));
}
#[test]
fn test_elementwise_addition() {
assert_eq!(
vec![7.0, 9.0, 11.0, 13.0, 5.0],
elementwise_addition(
&vec![1.0, 2.0, 3.0, 4.0, 5.0],
&vec![6.0, 7.0, 8.0, 9.0, 0.0],
),
)
}
#[test]
fn test_vector_average() {
assert_eq!(3.0, vector_average(&vec![1.0, 2.0, 3.0, 4.0, 5.0]));
}
#[test]
fn test_dot() {
assert_eq!(
80.0,
dot(
&vec![1.0, 2.0, 3.0, 4.0, 5.0],
&vec![6.0, 7.0, 8.0, 9.0, 0.0],
),
);
}
#[test]
fn test_elementwise_scalar_multiplication() {
assert_eq!(
vec![2.0, 4.0, 6.0, 8.0, 10.0],
elementwise_scalar_multiplication(&vec![1.0, 2.0, 3.0, 4.0, 5.0], 2.0,)
)
}
#[test]
fn test_matrix_vector_dot() {
assert_eq!(
vec![55.0, 45.0, 40.0, 40.0, 35.0],
matrix_vector_dot(
&vec![
vec![1.0, 2.0, 3.0, 4.0, 5.0],
vec![2.0, 3.0, 4.0, 5.0, 1.0],
vec![3.0, 4.0, 5.0, 1.0, 2.0],
vec![4.0, 5.0, 1.0, 2.0, 3.0],
vec![5.0, 4.0, 3.0, 2.0, 1.0],
],
&vec![1.0, 2.0, 3.0, 4.0, 5.0],
),
);
}
#[test]
fn test_relu_vector() {
assert_eq!(
vec![1.0, 0.0, 2.0, 0.0, 4.0],
relu_vector(vec![1.0, -1.0, 2.0, -2.0, 4.0]),
);
}
}
| 24.766197 | 93 | 0.502047 |
f4ed2f119125e0bbfe047a5b68ec938e2cfd6206 | 2,423 | // Implements http://rosettacode.org/wiki/LZW_compression
use std::collections::hashmap::HashMap;
// Compress using LZW
fn compress(original_str: &str) -> Vec<int> {
let original = original_str.as_bytes();
let mut dict_size = 256;
let mut dictionary = HashMap::new();
for i in range(0i, dict_size) {
dictionary.insert(vec!(i as u8), i);
}
let mut result = vec!();
let mut w = vec!();
for &c in original.iter() {
let mut wc = w.clone();
wc.push(c);
match dictionary.find(&wc) {
Some(_) => w = wc,
None => {
result.push(dictionary[w]);
dictionary.insert(wc, dict_size);
dict_size += 1;
w = vec!(c);
}
}
}
if w.len() > 0 {
result.push(dictionary[w]);
}
result
}
// Decompress using LZW
fn decompress(compressed: &Vec<int>) -> String {
let mut dict_size = 256;
let mut dictionary = HashMap::new();
for i in range(0i, dict_size) {
dictionary.insert(i, vec!(i as u8));
}
let mut w = vec!(compressed[0].clone() as u8);
let compressed = compressed.slice_from(1);
let mut result = w.clone();
for &k in compressed.iter() {
let entry = match dictionary.find(&k) {
Some(v) => v.clone(),
None if k == dict_size => { let mut new = w.clone(); new.push(w[0].clone()); new }
None => fail!("Invalid compressed string")
};
result.extend(entry.iter().map(|&x| x.clone()));
w.push(entry[0].clone());
dictionary.insert(dict_size, w);
dict_size += 1;
w = entry;
}
String::from_utf8(result).unwrap()
}
#[cfg(not(test))]
fn main() {
// Show original
let original = "TOBEORNOTTOBEORTOBEORNOT";
println!("Original: {}", original);
// Show compressed
let compressed = compress(original);
println!("Compressed: {}", compressed);
// Show decompressed
let decompressed = decompress(&compressed);
println!("Decompressed: {}", decompressed);
}
#[test]
fn test_coherence() {
for s in range(50000i, 50100).map(|n| n.to_string()) {
assert_eq!(decompress(&compress(s.as_slice())), s);
}
}
#[test]
fn test_example() {
let original = "TOBEORNOTTOBEORTOBEORNOT";
assert_eq!(compress(original).as_slice(), &[84i, 79, 66, 69, 79, 82, 78, 79, 84,
256, 258, 260, 265, 259, 261, 263]);
}
| 25.239583 | 92 | 0.568304 |
7291ee583ab4d5e585c5ef4f20839e3b0767917b | 13,133 | #![allow(clippy::module_inception)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::ptr_arg)]
#![allow(clippy::large_enum_variant)]
#![doc = "generated by AutoRust"]
#[cfg(feature = "package-2021-05")]
pub mod package_2021_05;
#[cfg(all(feature = "package-2021-05", not(feature = "no-default-version")))]
pub use package_2021_05::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2021-03")]
pub mod package_2021_03;
#[cfg(all(feature = "package-2021-03", not(feature = "no-default-version")))]
pub use package_2021_03::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2021-02")]
pub mod package_2021_02;
#[cfg(all(feature = "package-2021-02", not(feature = "no-default-version")))]
pub use package_2021_02::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2020-11")]
pub mod package_2020_11;
#[cfg(all(feature = "package-2020-11", not(feature = "no-default-version")))]
pub use package_2020_11::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2021-02-preview-only")]
pub mod package_2021_02_preview_only;
#[cfg(all(feature = "package-2021-02-preview-only", not(feature = "no-default-version")))]
pub use package_2021_02_preview_only::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2021-02-preview")]
pub mod package_2021_02_preview;
#[cfg(all(feature = "package-2021-02-preview", not(feature = "no-default-version")))]
pub use package_2021_02_preview::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2021-03-preview")]
pub mod package_2021_03_preview;
#[cfg(all(feature = "package-2021-03-preview", not(feature = "no-default-version")))]
pub use package_2021_03_preview::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2020-08")]
pub mod package_2020_08;
#[cfg(all(feature = "package-2020-08", not(feature = "no-default-version")))]
pub use package_2020_08::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2020-07")]
pub mod package_2020_07;
#[cfg(all(feature = "package-2020-07", not(feature = "no-default-version")))]
pub use package_2020_07::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2020-06")]
pub mod package_2020_06;
#[cfg(all(feature = "package-2020-06", not(feature = "no-default-version")))]
pub use package_2020_06::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2020-05")]
pub mod package_2020_05;
#[cfg(all(feature = "package-2020-05", not(feature = "no-default-version")))]
pub use package_2020_05::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2020-04")]
pub mod package_2020_04;
#[cfg(all(feature = "package-2020-04", not(feature = "no-default-version")))]
pub use package_2020_04::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2020-03")]
pub mod package_2020_03;
#[cfg(all(feature = "package-2020-03", not(feature = "no-default-version")))]
pub use package_2020_03::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2019-12")]
pub mod package_2019_12;
#[cfg(all(feature = "package-2019-12", not(feature = "no-default-version")))]
pub use package_2019_12::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2019-11")]
pub mod package_2019_11;
#[cfg(all(feature = "package-2019-11", not(feature = "no-default-version")))]
pub use package_2019_11::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2019-09")]
pub mod package_2019_09;
#[cfg(all(feature = "package-2019-09", not(feature = "no-default-version")))]
pub use package_2019_09::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2019-08")]
pub mod package_2019_08;
#[cfg(all(feature = "package-2019-08", not(feature = "no-default-version")))]
pub use package_2019_08::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2019-07")]
pub mod package_2019_07;
#[cfg(all(feature = "package-2019-07", not(feature = "no-default-version")))]
pub use package_2019_07::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2019-06")]
pub mod package_2019_06;
#[cfg(all(feature = "package-2019-06", not(feature = "no-default-version")))]
pub use package_2019_06::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2019-04")]
pub mod package_2019_04;
#[cfg(all(feature = "package-2019-04", not(feature = "no-default-version")))]
pub use package_2019_04::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2019-02")]
pub mod package_2019_02;
#[cfg(all(feature = "package-2019-02", not(feature = "no-default-version")))]
pub use package_2019_02::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2018-12")]
pub mod package_2018_12;
#[cfg(all(feature = "package-2018-12", not(feature = "no-default-version")))]
pub use package_2018_12::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2018-12-only")]
pub mod package_2018_12_only;
#[cfg(all(feature = "package-2018-12-only", not(feature = "no-default-version")))]
pub use package_2018_12_only::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2018-11")]
pub mod package_2018_11;
#[cfg(all(feature = "package-2018-11", not(feature = "no-default-version")))]
pub use package_2018_11::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2018-10")]
pub mod package_2018_10;
#[cfg(all(feature = "package-2018-10", not(feature = "no-default-version")))]
pub use package_2018_10::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2018-08")]
pub mod package_2018_08;
#[cfg(all(feature = "package-2018-08", not(feature = "no-default-version")))]
pub use package_2018_08::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2018-07")]
pub mod package_2018_07;
#[cfg(all(feature = "package-2018-07", not(feature = "no-default-version")))]
pub use package_2018_07::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2018-06")]
pub mod package_2018_06;
#[cfg(all(feature = "package-2018-06", not(feature = "no-default-version")))]
pub use package_2018_06::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2018-04")]
pub mod package_2018_04;
#[cfg(all(feature = "package-2018-04", not(feature = "no-default-version")))]
pub use package_2018_04::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2018-02")]
pub mod package_2018_02;
#[cfg(all(feature = "package-2018-02", not(feature = "no-default-version")))]
pub use package_2018_02::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2018-01")]
pub mod package_2018_01;
#[cfg(all(feature = "package-2018-01", not(feature = "no-default-version")))]
pub use package_2018_01::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2018-01-only")]
pub mod package_2018_01_only;
#[cfg(all(feature = "package-2018-01-only", not(feature = "no-default-version")))]
pub use package_2018_01_only::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2017-11")]
pub mod package_2017_11;
#[cfg(all(feature = "package-2017-11", not(feature = "no-default-version")))]
pub use package_2017_11::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2017-11-only")]
pub mod package_2017_11_only;
#[cfg(all(feature = "package-2017-11-only", not(feature = "no-default-version")))]
pub use package_2017_11_only::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2017-10")]
pub mod package_2017_10;
#[cfg(all(feature = "package-2017-10", not(feature = "no-default-version")))]
pub use package_2017_10::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2017-10-only")]
pub mod package_2017_10_only;
#[cfg(all(feature = "package-2017-10-only", not(feature = "no-default-version")))]
pub use package_2017_10_only::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2017-09")]
pub mod package_2017_09;
#[cfg(all(feature = "package-2017-09", not(feature = "no-default-version")))]
pub use package_2017_09::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2017-09-only")]
pub mod package_2017_09_only;
#[cfg(all(feature = "package-2017-09-only", not(feature = "no-default-version")))]
pub use package_2017_09_only::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2017-08")]
pub mod package_2017_08;
#[cfg(all(feature = "package-2017-08", not(feature = "no-default-version")))]
pub use package_2017_08::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2017-06")]
pub mod package_2017_06;
#[cfg(all(feature = "package-2017-06", not(feature = "no-default-version")))]
pub use package_2017_06::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2017-03")]
pub mod package_2017_03;
#[cfg(all(feature = "package-2017-03", not(feature = "no-default-version")))]
pub use package_2017_03::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2017-03-only")]
pub mod package_2017_03_only;
#[cfg(all(feature = "package-2017-03-only", not(feature = "no-default-version")))]
pub use package_2017_03_only::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2017-03-30-only")]
pub mod package_2017_03_30_only;
#[cfg(all(feature = "package-2017-03-30-only", not(feature = "no-default-version")))]
pub use package_2017_03_30_only::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2016-12")]
pub mod package_2016_12;
#[cfg(all(feature = "package-2016-12", not(feature = "no-default-version")))]
pub use package_2016_12::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2016-09")]
pub mod package_2016_09;
#[cfg(all(feature = "package-2016-09", not(feature = "no-default-version")))]
pub use package_2016_09::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2016-06")]
pub mod package_2016_06;
#[cfg(all(feature = "package-2016-06", not(feature = "no-default-version")))]
pub use package_2016_06::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2016-03")]
pub mod package_2016_03;
#[cfg(all(feature = "package-2016-03", not(feature = "no-default-version")))]
pub use package_2016_03::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2015-06split")]
pub mod package_2015_06split;
#[cfg(all(feature = "package-2015-06split", not(feature = "no-default-version")))]
pub use package_2015_06split::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "package-2015-05-preview")]
pub mod package_2015_05_preview;
#[cfg(all(feature = "package-2015-05-preview", not(feature = "no-default-version")))]
pub use package_2015_05_preview::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
#[cfg(feature = "profile-hybrid-2020-09-01")]
pub mod profile_hybrid_2020_09_01;
#[cfg(all(feature = "profile-hybrid-2020-09-01", not(feature = "no-default-version")))]
pub use profile_hybrid_2020_09_01::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
| 63.752427 | 125 | 0.746593 |
673471d432f277d7c5e99102c04d055e65b948d8 | 230,209 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[allow(clippy::unnecessary_wraps)]
pub fn parse_batch_update_cluster_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::BatchUpdateClusterOutput,
crate::error::BatchUpdateClusterError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::BatchUpdateClusterError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::BatchUpdateClusterError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterValueException" => crate::error::BatchUpdateClusterError {
meta: generic,
kind: crate::error::BatchUpdateClusterErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::BatchUpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceUpdateNotFoundFault" => {
crate::error::BatchUpdateClusterError {
meta: generic,
kind: crate::error::BatchUpdateClusterErrorKind::ServiceUpdateNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_update_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_update_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::BatchUpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
_ => crate::error::BatchUpdateClusterError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_batch_update_cluster_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::BatchUpdateClusterOutput,
crate::error::BatchUpdateClusterError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::batch_update_cluster_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_batch_update_cluster(
response.body().as_ref(),
output,
)
.map_err(crate::error::BatchUpdateClusterError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_copy_snapshot_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CopySnapshotOutput, crate::error::CopySnapshotError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CopySnapshotError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CopySnapshotError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => crate::error::CopySnapshotError {
meta: generic,
kind: crate::error::CopySnapshotErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CopySnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::CopySnapshotError {
meta: generic,
kind: crate::error::CopySnapshotErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CopySnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidSnapshotStateFault" => {
crate::error::CopySnapshotError {
meta: generic,
kind: crate::error::CopySnapshotErrorKind::InvalidSnapshotStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_snapshot_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_snapshot_state_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CopySnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ServiceLinkedRoleNotFoundFault" => crate::error::CopySnapshotError {
meta: generic,
kind: crate::error::CopySnapshotErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CopySnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SnapshotAlreadyExistsFault" => {
crate::error::CopySnapshotError {
meta: generic,
kind: crate::error::CopySnapshotErrorKind::SnapshotAlreadyExistsFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::snapshot_already_exists_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_snapshot_already_exists_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CopySnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"SnapshotNotFoundFault" => crate::error::CopySnapshotError {
meta: generic,
kind: crate::error::CopySnapshotErrorKind::SnapshotNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::snapshot_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_snapshot_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CopySnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SnapshotQuotaExceededFault" => {
crate::error::CopySnapshotError {
meta: generic,
kind: crate::error::CopySnapshotErrorKind::SnapshotQuotaExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::snapshot_quota_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_snapshot_quota_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CopySnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"TagQuotaPerResourceExceeded" => {
crate::error::CopySnapshotError {
meta: generic,
kind: crate::error::CopySnapshotErrorKind::TagQuotaPerResourceExceeded({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::tag_quota_per_resource_exceeded::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_tag_quota_per_resource_exceededjson_err(response.body().as_ref(), output).map_err(crate::error::CopySnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
_ => crate::error::CopySnapshotError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_copy_snapshot_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CopySnapshotOutput, crate::error::CopySnapshotError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::copy_snapshot_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_copy_snapshot(response.body().as_ref(), output)
.map_err(crate::error::CopySnapshotError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_acl_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateAclOutput, crate::error::CreateACLError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CreateACLError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CreateACLError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ACLAlreadyExistsFault" => crate::error::CreateACLError {
meta: generic,
kind: crate::error::CreateACLErrorKind::AclAlreadyExistsFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::acl_already_exists_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_acl_already_exists_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ACLQuotaExceededFault" => crate::error::CreateACLError {
meta: generic,
kind: crate::error::CreateACLErrorKind::AclQuotaExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::acl_quota_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_acl_quota_exceeded_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"DefaultUserRequired" => crate::error::CreateACLError {
meta: generic,
kind: crate::error::CreateACLErrorKind::DefaultUserRequired({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::default_user_required::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_default_user_requiredjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"DuplicateUserNameFault" => crate::error::CreateACLError {
meta: generic,
kind: crate::error::CreateACLErrorKind::DuplicateUserNameFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::duplicate_user_name_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_duplicate_user_name_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::CreateACLError {
meta: generic,
kind: crate::error::CreateACLErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CreateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TagQuotaPerResourceExceeded" => {
crate::error::CreateACLError {
meta: generic,
kind: crate::error::CreateACLErrorKind::TagQuotaPerResourceExceeded({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::tag_quota_per_resource_exceeded::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_tag_quota_per_resource_exceededjson_err(response.body().as_ref(), output).map_err(crate::error::CreateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"UserNotFoundFault" => crate::error::CreateACLError {
meta: generic,
kind: crate::error::CreateACLErrorKind::UserNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::user_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_user_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::CreateACLError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_acl_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateAclOutput, crate::error::CreateACLError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::create_acl_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_create_acl(response.body().as_ref(), output)
.map_err(crate::error::CreateACLError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_cluster_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateClusterOutput, crate::error::CreateClusterError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CreateClusterError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CreateClusterError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ACLNotFoundFault" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::AclNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::acl_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_acl_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ClusterAlreadyExistsFault" => {
crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::ClusterAlreadyExistsFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::cluster_already_exists_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_cluster_already_exists_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ClusterQuotaForCustomerExceededFault" => {
crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::ClusterQuotaForCustomerExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]let mut output = crate::error::cluster_quota_for_customer_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_cluster_quota_for_customer_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InsufficientClusterCapacityFault" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::InsufficientClusterCapacityFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::insufficient_cluster_capacity_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_insufficient_cluster_capacity_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidACLStateFault" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::InvalidAclStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_acl_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_acl_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidCredentialsException" => {
crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::InvalidCredentialsException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_credentials_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_credentials_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InvalidParameterCombinationException" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidVPCNetworkStateFault" => {
crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::InvalidVpcNetworkStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_vpc_network_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_vpc_network_state_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"NodeQuotaForClusterExceededFault" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::NodeQuotaForClusterExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::node_quota_for_cluster_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_node_quota_for_cluster_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"NodeQuotaForCustomerExceededFault" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::NodeQuotaForCustomerExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::node_quota_for_customer_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_node_quota_for_customer_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ParameterGroupNotFoundFault" => {
crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::ParameterGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::parameter_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_parameter_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ServiceLinkedRoleNotFoundFault" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ShardsPerClusterQuotaExceededFault" => crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::ShardsPerClusterQuotaExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::shards_per_cluster_quota_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_shards_per_cluster_quota_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetGroupNotFoundFault" => {
crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::SubnetGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::subnet_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"TagQuotaPerResourceExceeded" => {
crate::error::CreateClusterError {
meta: generic,
kind: crate::error::CreateClusterErrorKind::TagQuotaPerResourceExceeded({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::tag_quota_per_resource_exceeded::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_tag_quota_per_resource_exceededjson_err(response.body().as_ref(), output).map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
_ => crate::error::CreateClusterError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_cluster_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateClusterOutput, crate::error::CreateClusterError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::create_cluster_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_create_cluster(response.body().as_ref(), output)
.map_err(crate::error::CreateClusterError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_parameter_group_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::CreateParameterGroupOutput,
crate::error::CreateParameterGroupError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CreateParameterGroupError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CreateParameterGroupError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => crate::error::CreateParameterGroupError {
meta: generic,
kind: crate::error::CreateParameterGroupErrorKind::InvalidParameterCombinationException(
{
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default(
);
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CreateParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
},
),
},
"InvalidParameterGroupStateFault" => crate::error::CreateParameterGroupError {
meta: generic,
kind: crate::error::CreateParameterGroupErrorKind::InvalidParameterGroupStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_group_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_group_state_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::CreateParameterGroupError {
meta: generic,
kind: crate::error::CreateParameterGroupErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CreateParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ParameterGroupAlreadyExistsFault" => crate::error::CreateParameterGroupError {
meta: generic,
kind: crate::error::CreateParameterGroupErrorKind::ParameterGroupAlreadyExistsFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::parameter_group_already_exists_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_parameter_group_already_exists_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ParameterGroupQuotaExceededFault" => crate::error::CreateParameterGroupError {
meta: generic,
kind: crate::error::CreateParameterGroupErrorKind::ParameterGroupQuotaExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::parameter_group_quota_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_parameter_group_quota_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceLinkedRoleNotFoundFault" => crate::error::CreateParameterGroupError {
meta: generic,
kind: crate::error::CreateParameterGroupErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TagQuotaPerResourceExceeded" => {
crate::error::CreateParameterGroupError {
meta: generic,
kind: crate::error::CreateParameterGroupErrorKind::TagQuotaPerResourceExceeded({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::tag_quota_per_resource_exceeded::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_tag_quota_per_resource_exceededjson_err(response.body().as_ref(), output).map_err(crate::error::CreateParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
_ => crate::error::CreateParameterGroupError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_parameter_group_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::CreateParameterGroupOutput,
crate::error::CreateParameterGroupError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::create_parameter_group_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_create_parameter_group(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateParameterGroupError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_snapshot_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateSnapshotOutput, crate::error::CreateSnapshotError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CreateSnapshotError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CreateSnapshotError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ClusterNotFoundFault" => crate::error::CreateSnapshotError {
meta: generic,
kind: crate::error::CreateSnapshotErrorKind::ClusterNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::cluster_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_cluster_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidClusterStateFault" => crate::error::CreateSnapshotError {
meta: generic,
kind: crate::error::CreateSnapshotErrorKind::InvalidClusterStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_cluster_state_fault::Builder::default();
let _ = response;
output =
crate::json_deser::deser_structure_invalid_cluster_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterCombinationException" => crate::error::CreateSnapshotError {
meta: generic,
kind: crate::error::CreateSnapshotErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CreateSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::CreateSnapshotError {
meta: generic,
kind: crate::error::CreateSnapshotErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CreateSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceLinkedRoleNotFoundFault" => crate::error::CreateSnapshotError {
meta: generic,
kind: crate::error::CreateSnapshotErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SnapshotAlreadyExistsFault" => {
crate::error::CreateSnapshotError {
meta: generic,
kind: crate::error::CreateSnapshotErrorKind::SnapshotAlreadyExistsFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::snapshot_already_exists_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_snapshot_already_exists_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"SnapshotQuotaExceededFault" => {
crate::error::CreateSnapshotError {
meta: generic,
kind: crate::error::CreateSnapshotErrorKind::SnapshotQuotaExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::snapshot_quota_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_snapshot_quota_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"TagQuotaPerResourceExceeded" => {
crate::error::CreateSnapshotError {
meta: generic,
kind: crate::error::CreateSnapshotErrorKind::TagQuotaPerResourceExceeded({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::tag_quota_per_resource_exceeded::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_tag_quota_per_resource_exceededjson_err(response.body().as_ref(), output).map_err(crate::error::CreateSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
_ => crate::error::CreateSnapshotError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_snapshot_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateSnapshotOutput, crate::error::CreateSnapshotError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::create_snapshot_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_create_snapshot(response.body().as_ref(), output)
.map_err(crate::error::CreateSnapshotError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_subnet_group_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateSubnetGroupOutput, crate::error::CreateSubnetGroupError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CreateSubnetGroupError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CreateSubnetGroupError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidSubnet" => crate::error::CreateSubnetGroupError {
meta: generic,
kind: crate::error::CreateSubnetGroupErrorKind::InvalidSubnet({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_subnet::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_subnetjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceLinkedRoleNotFoundFault" => crate::error::CreateSubnetGroupError {
meta: generic,
kind: crate::error::CreateSubnetGroupErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetGroupAlreadyExistsFault" => crate::error::CreateSubnetGroupError {
meta: generic,
kind: crate::error::CreateSubnetGroupErrorKind::SubnetGroupAlreadyExistsFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::subnet_group_already_exists_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_group_already_exists_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetGroupQuotaExceededFault" => crate::error::CreateSubnetGroupError {
meta: generic,
kind: crate::error::CreateSubnetGroupErrorKind::SubnetGroupQuotaExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::subnet_group_quota_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_group_quota_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::CreateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetNotAllowedFault" => crate::error::CreateSubnetGroupError {
meta: generic,
kind: crate::error::CreateSubnetGroupErrorKind::SubnetNotAllowedFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::subnet_not_allowed_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_not_allowed_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetQuotaExceededFault" => crate::error::CreateSubnetGroupError {
meta: generic,
kind: crate::error::CreateSubnetGroupErrorKind::SubnetQuotaExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::subnet_quota_exceeded_fault::Builder::default();
let _ = response;
output =
crate::json_deser::deser_structure_subnet_quota_exceeded_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TagQuotaPerResourceExceeded" => {
crate::error::CreateSubnetGroupError {
meta: generic,
kind: crate::error::CreateSubnetGroupErrorKind::TagQuotaPerResourceExceeded({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::tag_quota_per_resource_exceeded::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_tag_quota_per_resource_exceededjson_err(response.body().as_ref(), output).map_err(crate::error::CreateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
_ => crate::error::CreateSubnetGroupError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_subnet_group_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateSubnetGroupOutput, crate::error::CreateSubnetGroupError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::create_subnet_group_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_create_subnet_group(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateSubnetGroupError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_user_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateUserOutput, crate::error::CreateUserError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CreateUserError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CreateUserError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"DuplicateUserNameFault" => crate::error::CreateUserError {
meta: generic,
kind: crate::error::CreateUserErrorKind::DuplicateUserNameFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::duplicate_user_name_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_duplicate_user_name_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterCombinationException" => crate::error::CreateUserError {
meta: generic,
kind: crate::error::CreateUserErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CreateUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::CreateUserError {
meta: generic,
kind: crate::error::CreateUserErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CreateUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TagQuotaPerResourceExceeded" => {
crate::error::CreateUserError {
meta: generic,
kind: crate::error::CreateUserErrorKind::TagQuotaPerResourceExceeded({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::tag_quota_per_resource_exceeded::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_tag_quota_per_resource_exceededjson_err(response.body().as_ref(), output).map_err(crate::error::CreateUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"UserAlreadyExistsFault" => crate::error::CreateUserError {
meta: generic,
kind: crate::error::CreateUserErrorKind::UserAlreadyExistsFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::user_already_exists_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_user_already_exists_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"UserQuotaExceededFault" => crate::error::CreateUserError {
meta: generic,
kind: crate::error::CreateUserErrorKind::UserQuotaExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::user_quota_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_user_quota_exceeded_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::CreateUserError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_user_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateUserOutput, crate::error::CreateUserError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::create_user_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_create_user(response.body().as_ref(), output)
.map_err(crate::error::CreateUserError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_acl_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteAclOutput, crate::error::DeleteACLError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DeleteACLError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DeleteACLError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ACLNotFoundFault" => crate::error::DeleteACLError {
meta: generic,
kind: crate::error::DeleteACLErrorKind::AclNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::acl_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_acl_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DeleteACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidACLStateFault" => crate::error::DeleteACLError {
meta: generic,
kind: crate::error::DeleteACLErrorKind::InvalidAclStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_acl_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_acl_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DeleteACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::DeleteACLError {
meta: generic,
kind: crate::error::DeleteACLErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DeleteACLError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_acl_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteAclOutput, crate::error::DeleteACLError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::delete_acl_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_delete_acl(response.body().as_ref(), output)
.map_err(crate::error::DeleteACLError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_cluster_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteClusterOutput, crate::error::DeleteClusterError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DeleteClusterError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DeleteClusterError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ClusterNotFoundFault" => crate::error::DeleteClusterError {
meta: generic,
kind: crate::error::DeleteClusterErrorKind::ClusterNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::cluster_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_cluster_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidClusterStateFault" => crate::error::DeleteClusterError {
meta: generic,
kind: crate::error::DeleteClusterErrorKind::InvalidClusterStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_cluster_state_fault::Builder::default();
let _ = response;
output =
crate::json_deser::deser_structure_invalid_cluster_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterCombinationException" => crate::error::DeleteClusterError {
meta: generic,
kind: crate::error::DeleteClusterErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::DeleteClusterError {
meta: generic,
kind: crate::error::DeleteClusterErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceLinkedRoleNotFoundFault" => crate::error::DeleteClusterError {
meta: generic,
kind: crate::error::DeleteClusterErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SnapshotAlreadyExistsFault" => {
crate::error::DeleteClusterError {
meta: generic,
kind: crate::error::DeleteClusterErrorKind::SnapshotAlreadyExistsFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::snapshot_already_exists_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_snapshot_already_exists_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
_ => crate::error::DeleteClusterError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_cluster_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteClusterOutput, crate::error::DeleteClusterError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::delete_cluster_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_delete_cluster(response.body().as_ref(), output)
.map_err(crate::error::DeleteClusterError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_parameter_group_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DeleteParameterGroupOutput,
crate::error::DeleteParameterGroupError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DeleteParameterGroupError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DeleteParameterGroupError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => crate::error::DeleteParameterGroupError {
meta: generic,
kind: crate::error::DeleteParameterGroupErrorKind::InvalidParameterCombinationException(
{
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default(
);
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
},
),
},
"InvalidParameterGroupStateFault" => crate::error::DeleteParameterGroupError {
meta: generic,
kind: crate::error::DeleteParameterGroupErrorKind::InvalidParameterGroupStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_group_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_group_state_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::DeleteParameterGroupError {
meta: generic,
kind: crate::error::DeleteParameterGroupErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ParameterGroupNotFoundFault" => {
crate::error::DeleteParameterGroupError {
meta: generic,
kind: crate::error::DeleteParameterGroupErrorKind::ParameterGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::parameter_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_parameter_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ServiceLinkedRoleNotFoundFault" => crate::error::DeleteParameterGroupError {
meta: generic,
kind: crate::error::DeleteParameterGroupErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DeleteParameterGroupError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_parameter_group_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DeleteParameterGroupOutput,
crate::error::DeleteParameterGroupError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::delete_parameter_group_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_delete_parameter_group(
response.body().as_ref(),
output,
)
.map_err(crate::error::DeleteParameterGroupError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_snapshot_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteSnapshotOutput, crate::error::DeleteSnapshotError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DeleteSnapshotError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DeleteSnapshotError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => crate::error::DeleteSnapshotError {
meta: generic,
kind: crate::error::DeleteSnapshotErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::DeleteSnapshotError {
meta: generic,
kind: crate::error::DeleteSnapshotErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidSnapshotStateFault" => {
crate::error::DeleteSnapshotError {
meta: generic,
kind: crate::error::DeleteSnapshotErrorKind::InvalidSnapshotStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_snapshot_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_snapshot_state_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ServiceLinkedRoleNotFoundFault" => crate::error::DeleteSnapshotError {
meta: generic,
kind: crate::error::DeleteSnapshotErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SnapshotNotFoundFault" => crate::error::DeleteSnapshotError {
meta: generic,
kind: crate::error::DeleteSnapshotErrorKind::SnapshotNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::snapshot_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_snapshot_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DeleteSnapshotError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DeleteSnapshotError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_snapshot_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteSnapshotOutput, crate::error::DeleteSnapshotError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::delete_snapshot_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_delete_snapshot(response.body().as_ref(), output)
.map_err(crate::error::DeleteSnapshotError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_subnet_group_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteSubnetGroupOutput, crate::error::DeleteSubnetGroupError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DeleteSubnetGroupError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DeleteSubnetGroupError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ServiceLinkedRoleNotFoundFault" => crate::error::DeleteSubnetGroupError {
meta: generic,
kind: crate::error::DeleteSubnetGroupErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetGroupInUseFault" => crate::error::DeleteSubnetGroupError {
meta: generic,
kind: crate::error::DeleteSubnetGroupErrorKind::SubnetGroupInUseFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::subnet_group_in_use_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_group_in_use_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DeleteSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetGroupNotFoundFault" => {
crate::error::DeleteSubnetGroupError {
meta: generic,
kind: crate::error::DeleteSubnetGroupErrorKind::SubnetGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::subnet_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
_ => crate::error::DeleteSubnetGroupError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_subnet_group_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteSubnetGroupOutput, crate::error::DeleteSubnetGroupError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::delete_subnet_group_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_delete_subnet_group(
response.body().as_ref(),
output,
)
.map_err(crate::error::DeleteSubnetGroupError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_user_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteUserOutput, crate::error::DeleteUserError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DeleteUserError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DeleteUserError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterValueException" => crate::error::DeleteUserError {
meta: generic,
kind: crate::error::DeleteUserErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DeleteUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidUserStateFault" => crate::error::DeleteUserError {
meta: generic,
kind: crate::error::DeleteUserErrorKind::InvalidUserStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_user_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_user_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DeleteUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"UserNotFoundFault" => crate::error::DeleteUserError {
meta: generic,
kind: crate::error::DeleteUserErrorKind::UserNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::user_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_user_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DeleteUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DeleteUserError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_user_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteUserOutput, crate::error::DeleteUserError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::delete_user_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_delete_user(response.body().as_ref(), output)
.map_err(crate::error::DeleteUserError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_ac_ls_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeAcLsOutput, crate::error::DescribeACLsError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeACLsError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeACLsError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ACLNotFoundFault" => crate::error::DescribeACLsError {
meta: generic,
kind: crate::error::DescribeACLsErrorKind::AclNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::acl_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_acl_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeACLsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterCombinationException" => crate::error::DescribeACLsError {
meta: generic,
kind: crate::error::DescribeACLsErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeACLsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeACLsError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_ac_ls_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeAcLsOutput, crate::error::DescribeACLsError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_ac_ls_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_describe_ac_ls(response.body().as_ref(), output)
.map_err(crate::error::DescribeACLsError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_clusters_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeClustersOutput, crate::error::DescribeClustersError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeClustersError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeClustersError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ClusterNotFoundFault" => crate::error::DescribeClustersError {
meta: generic,
kind: crate::error::DescribeClustersErrorKind::ClusterNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::cluster_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_cluster_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeClustersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterCombinationException" => crate::error::DescribeClustersError {
meta: generic,
kind: crate::error::DescribeClustersErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeClustersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::DescribeClustersError {
meta: generic,
kind: crate::error::DescribeClustersErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeClustersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceLinkedRoleNotFoundFault" => crate::error::DescribeClustersError {
meta: generic,
kind: crate::error::DescribeClustersErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeClustersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeClustersError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_clusters_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeClustersOutput, crate::error::DescribeClustersError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_clusters_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_describe_clusters(response.body().as_ref(), output)
.map_err(crate::error::DescribeClustersError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_engine_versions_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeEngineVersionsOutput,
crate::error::DescribeEngineVersionsError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeEngineVersionsError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => {
return Err(crate::error::DescribeEngineVersionsError::unhandled(
generic,
))
}
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => crate::error::DescribeEngineVersionsError {
meta: generic,
kind:
crate::error::DescribeEngineVersionsErrorKind::InvalidParameterCombinationException(
{
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]let mut output = crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeEngineVersionsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
},
),
},
"InvalidParameterValueException" => crate::error::DescribeEngineVersionsError {
meta: generic,
kind: crate::error::DescribeEngineVersionsErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeEngineVersionsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceLinkedRoleNotFoundFault" => crate::error::DescribeEngineVersionsError {
meta: generic,
kind: crate::error::DescribeEngineVersionsErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeEngineVersionsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeEngineVersionsError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_engine_versions_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeEngineVersionsOutput,
crate::error::DescribeEngineVersionsError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_engine_versions_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_describe_engine_versions(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeEngineVersionsError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_events_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeEventsOutput, crate::error::DescribeEventsError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeEventsError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeEventsError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => crate::error::DescribeEventsError {
meta: generic,
kind: crate::error::DescribeEventsErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeEventsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::DescribeEventsError {
meta: generic,
kind: crate::error::DescribeEventsErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeEventsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceLinkedRoleNotFoundFault" => crate::error::DescribeEventsError {
meta: generic,
kind: crate::error::DescribeEventsErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeEventsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeEventsError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_events_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeEventsOutput, crate::error::DescribeEventsError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_events_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_describe_events(response.body().as_ref(), output)
.map_err(crate::error::DescribeEventsError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_parameter_groups_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeParameterGroupsOutput,
crate::error::DescribeParameterGroupsError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeParameterGroupsError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => {
return Err(crate::error::DescribeParameterGroupsError::unhandled(
generic,
))
}
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => crate::error::DescribeParameterGroupsError {
meta: generic,
kind:
crate::error::DescribeParameterGroupsErrorKind::InvalidParameterCombinationException(
{
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]let mut output = crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeParameterGroupsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
},
),
},
"InvalidParameterValueException" => crate::error::DescribeParameterGroupsError {
meta: generic,
kind: crate::error::DescribeParameterGroupsErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeParameterGroupsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ParameterGroupNotFoundFault" => {
crate::error::DescribeParameterGroupsError {
meta: generic,
kind: crate::error::DescribeParameterGroupsErrorKind::ParameterGroupNotFoundFault(
{
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::parameter_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_parameter_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeParameterGroupsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
},
),
}
}
"ServiceLinkedRoleNotFoundFault" => crate::error::DescribeParameterGroupsError {
meta: generic,
kind: crate::error::DescribeParameterGroupsErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeParameterGroupsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeParameterGroupsError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_parameter_groups_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeParameterGroupsOutput,
crate::error::DescribeParameterGroupsError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_parameter_groups_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_describe_parameter_groups(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeParameterGroupsError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_parameters_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeParametersOutput,
crate::error::DescribeParametersError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeParametersError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeParametersError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => {
crate::error::DescribeParametersError {
meta: generic,
kind:
crate::error::DescribeParametersErrorKind::InvalidParameterCombinationException(
{
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]let mut output = crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeParametersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
},
),
}
}
"InvalidParameterValueException" => crate::error::DescribeParametersError {
meta: generic,
kind: crate::error::DescribeParametersErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeParametersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ParameterGroupNotFoundFault" => {
crate::error::DescribeParametersError {
meta: generic,
kind: crate::error::DescribeParametersErrorKind::ParameterGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::parameter_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_parameter_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeParametersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ServiceLinkedRoleNotFoundFault" => crate::error::DescribeParametersError {
meta: generic,
kind: crate::error::DescribeParametersErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeParametersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeParametersError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_parameters_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeParametersOutput,
crate::error::DescribeParametersError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_parameters_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_describe_parameters(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeParametersError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_service_updates_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeServiceUpdatesOutput,
crate::error::DescribeServiceUpdatesError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeServiceUpdatesError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => {
return Err(crate::error::DescribeServiceUpdatesError::unhandled(
generic,
))
}
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => crate::error::DescribeServiceUpdatesError {
meta: generic,
kind:
crate::error::DescribeServiceUpdatesErrorKind::InvalidParameterCombinationException(
{
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]let mut output = crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeServiceUpdatesError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
},
),
},
"InvalidParameterValueException" => crate::error::DescribeServiceUpdatesError {
meta: generic,
kind: crate::error::DescribeServiceUpdatesErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeServiceUpdatesError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeServiceUpdatesError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_service_updates_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeServiceUpdatesOutput,
crate::error::DescribeServiceUpdatesError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_service_updates_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_describe_service_updates(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeServiceUpdatesError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_snapshots_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeSnapshotsOutput, crate::error::DescribeSnapshotsError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeSnapshotsError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeSnapshotsError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => crate::error::DescribeSnapshotsError {
meta: generic,
kind: crate::error::DescribeSnapshotsErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeSnapshotsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::DescribeSnapshotsError {
meta: generic,
kind: crate::error::DescribeSnapshotsErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeSnapshotsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceLinkedRoleNotFoundFault" => crate::error::DescribeSnapshotsError {
meta: generic,
kind: crate::error::DescribeSnapshotsErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeSnapshotsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SnapshotNotFoundFault" => crate::error::DescribeSnapshotsError {
meta: generic,
kind: crate::error::DescribeSnapshotsErrorKind::SnapshotNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::snapshot_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_snapshot_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeSnapshotsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeSnapshotsError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_snapshots_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeSnapshotsOutput, crate::error::DescribeSnapshotsError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_snapshots_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_describe_snapshots(response.body().as_ref(), output)
.map_err(crate::error::DescribeSnapshotsError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_subnet_groups_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeSubnetGroupsOutput,
crate::error::DescribeSubnetGroupsError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeSubnetGroupsError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeSubnetGroupsError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ServiceLinkedRoleNotFoundFault" => crate::error::DescribeSubnetGroupsError {
meta: generic,
kind: crate::error::DescribeSubnetGroupsErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeSubnetGroupsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetGroupNotFoundFault" => {
crate::error::DescribeSubnetGroupsError {
meta: generic,
kind: crate::error::DescribeSubnetGroupsErrorKind::SubnetGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::subnet_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeSubnetGroupsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
_ => crate::error::DescribeSubnetGroupsError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_subnet_groups_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeSubnetGroupsOutput,
crate::error::DescribeSubnetGroupsError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_subnet_groups_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_describe_subnet_groups(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeSubnetGroupsError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_users_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeUsersOutput, crate::error::DescribeUsersError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeUsersError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeUsersError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => crate::error::DescribeUsersError {
meta: generic,
kind: crate::error::DescribeUsersErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeUsersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"UserNotFoundFault" => crate::error::DescribeUsersError {
meta: generic,
kind: crate::error::DescribeUsersErrorKind::UserNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::user_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_user_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeUsersError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeUsersError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_users_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeUsersOutput, crate::error::DescribeUsersError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_users_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_describe_users(response.body().as_ref(), output)
.map_err(crate::error::DescribeUsersError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_failover_shard_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::FailoverShardOutput, crate::error::FailoverShardError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::FailoverShardError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::FailoverShardError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"APICallRateForCustomerExceededFault" => {
crate::error::FailoverShardError {
meta: generic,
kind: crate::error::FailoverShardErrorKind::ApiCallRateForCustomerExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]let mut output = crate::error::api_call_rate_for_customer_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_api_call_rate_for_customer_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::FailoverShardError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ClusterNotFoundFault" => crate::error::FailoverShardError {
meta: generic,
kind: crate::error::FailoverShardErrorKind::ClusterNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::cluster_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_cluster_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::FailoverShardError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidClusterStateFault" => crate::error::FailoverShardError {
meta: generic,
kind: crate::error::FailoverShardErrorKind::InvalidClusterStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_cluster_state_fault::Builder::default();
let _ = response;
output =
crate::json_deser::deser_structure_invalid_cluster_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::FailoverShardError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidKMSKeyFault" => crate::error::FailoverShardError {
meta: generic,
kind: crate::error::FailoverShardErrorKind::InvalidKmsKeyFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_kms_key_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_kms_key_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::FailoverShardError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterCombinationException" => crate::error::FailoverShardError {
meta: generic,
kind: crate::error::FailoverShardErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::FailoverShardError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::FailoverShardError {
meta: generic,
kind: crate::error::FailoverShardErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::FailoverShardError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ShardNotFoundFault" => crate::error::FailoverShardError {
meta: generic,
kind: crate::error::FailoverShardErrorKind::ShardNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::shard_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_shard_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::FailoverShardError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TestFailoverNotAvailableFault" => crate::error::FailoverShardError {
meta: generic,
kind: crate::error::FailoverShardErrorKind::TestFailoverNotAvailableFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::test_failover_not_available_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_test_failover_not_available_faultjson_err(response.body().as_ref(), output).map_err(crate::error::FailoverShardError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::FailoverShardError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_failover_shard_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::FailoverShardOutput, crate::error::FailoverShardError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::failover_shard_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_failover_shard(response.body().as_ref(), output)
.map_err(crate::error::FailoverShardError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_allowed_node_type_updates_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::ListAllowedNodeTypeUpdatesOutput,
crate::error::ListAllowedNodeTypeUpdatesError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::ListAllowedNodeTypeUpdatesError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => {
return Err(crate::error::ListAllowedNodeTypeUpdatesError::unhandled(
generic,
))
}
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ClusterNotFoundFault" => crate::error::ListAllowedNodeTypeUpdatesError { meta: generic, kind: crate::error::ListAllowedNodeTypeUpdatesErrorKind::ClusterNotFoundFault({
#[allow(unused_mut)]let mut tmp =
{
#[allow(unused_mut)]let mut output = crate::error::cluster_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_cluster_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::ListAllowedNodeTypeUpdatesError::unhandled)?;
output.build()
}
;
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
})},
"InvalidParameterCombinationException" => crate::error::ListAllowedNodeTypeUpdatesError { meta: generic, kind: crate::error::ListAllowedNodeTypeUpdatesErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]let mut tmp =
{
#[allow(unused_mut)]let mut output = crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::ListAllowedNodeTypeUpdatesError::unhandled)?;
output.build()
}
;
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
})},
"InvalidParameterValueException" => crate::error::ListAllowedNodeTypeUpdatesError { meta: generic, kind: crate::error::ListAllowedNodeTypeUpdatesErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]let mut tmp =
{
#[allow(unused_mut)]let mut output = crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::ListAllowedNodeTypeUpdatesError::unhandled)?;
output.build()
}
;
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
})},
"ServiceLinkedRoleNotFoundFault" => crate::error::ListAllowedNodeTypeUpdatesError { meta: generic, kind: crate::error::ListAllowedNodeTypeUpdatesErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]let mut tmp =
{
#[allow(unused_mut)]let mut output = crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::ListAllowedNodeTypeUpdatesError::unhandled)?;
output.build()
}
;
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
})},
_ => crate::error::ListAllowedNodeTypeUpdatesError::generic(generic)
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_allowed_node_type_updates_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::ListAllowedNodeTypeUpdatesOutput,
crate::error::ListAllowedNodeTypeUpdatesError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::list_allowed_node_type_updates_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_list_allowed_node_type_updates(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListAllowedNodeTypeUpdatesError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_tags_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListTagsOutput, crate::error::ListTagsError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::ListTagsError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::ListTagsError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ACLNotFoundFault" => crate::error::ListTagsError {
meta: generic,
kind: crate::error::ListTagsErrorKind::AclNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::acl_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_acl_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListTagsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ClusterNotFoundFault" => crate::error::ListTagsError {
meta: generic,
kind: crate::error::ListTagsErrorKind::ClusterNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::cluster_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_cluster_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListTagsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidARNFault" => crate::error::ListTagsError {
meta: generic,
kind: crate::error::ListTagsErrorKind::InvalidArnFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arn_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListTagsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidClusterStateFault" => crate::error::ListTagsError {
meta: generic,
kind: crate::error::ListTagsErrorKind::InvalidClusterStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_cluster_state_fault::Builder::default();
let _ = response;
output =
crate::json_deser::deser_structure_invalid_cluster_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListTagsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ParameterGroupNotFoundFault" => {
crate::error::ListTagsError {
meta: generic,
kind: crate::error::ListTagsErrorKind::ParameterGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::parameter_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_parameter_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::ListTagsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ServiceLinkedRoleNotFoundFault" => crate::error::ListTagsError {
meta: generic,
kind: crate::error::ListTagsErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::ListTagsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SnapshotNotFoundFault" => crate::error::ListTagsError {
meta: generic,
kind: crate::error::ListTagsErrorKind::SnapshotNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::snapshot_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_snapshot_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListTagsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetGroupNotFoundFault" => {
crate::error::ListTagsError {
meta: generic,
kind: crate::error::ListTagsErrorKind::SubnetGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::subnet_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::ListTagsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"UserNotFoundFault" => crate::error::ListTagsError {
meta: generic,
kind: crate::error::ListTagsErrorKind::UserNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::user_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_user_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListTagsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::ListTagsError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_tags_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListTagsOutput, crate::error::ListTagsError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::list_tags_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_list_tags(response.body().as_ref(), output)
.map_err(crate::error::ListTagsError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_reset_parameter_group_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::ResetParameterGroupOutput,
crate::error::ResetParameterGroupError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::ResetParameterGroupError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::ResetParameterGroupError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => {
crate::error::ResetParameterGroupError {
meta: generic,
kind:
crate::error::ResetParameterGroupErrorKind::InvalidParameterCombinationException(
{
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]let mut output = crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::ResetParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
},
),
}
}
"InvalidParameterGroupStateFault" => crate::error::ResetParameterGroupError {
meta: generic,
kind: crate::error::ResetParameterGroupErrorKind::InvalidParameterGroupStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_group_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_group_state_faultjson_err(response.body().as_ref(), output).map_err(crate::error::ResetParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::ResetParameterGroupError {
meta: generic,
kind: crate::error::ResetParameterGroupErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::ResetParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ParameterGroupNotFoundFault" => {
crate::error::ResetParameterGroupError {
meta: generic,
kind: crate::error::ResetParameterGroupErrorKind::ParameterGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::parameter_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_parameter_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::ResetParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ServiceLinkedRoleNotFoundFault" => crate::error::ResetParameterGroupError {
meta: generic,
kind: crate::error::ResetParameterGroupErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::ResetParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::ResetParameterGroupError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_reset_parameter_group_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::ResetParameterGroupOutput,
crate::error::ResetParameterGroupError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::reset_parameter_group_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_reset_parameter_group(
response.body().as_ref(),
output,
)
.map_err(crate::error::ResetParameterGroupError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_tag_resource_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::TagResourceOutput, crate::error::TagResourceError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::TagResourceError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::TagResourceError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ACLNotFoundFault" => crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::AclNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::acl_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_acl_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ClusterNotFoundFault" => crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::ClusterNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::cluster_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_cluster_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidARNFault" => crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::InvalidArnFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arn_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidClusterStateFault" => crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::InvalidClusterStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_cluster_state_fault::Builder::default();
let _ = response;
output =
crate::json_deser::deser_structure_invalid_cluster_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ParameterGroupNotFoundFault" => {
crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::ParameterGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::parameter_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_parameter_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ServiceLinkedRoleNotFoundFault" => crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SnapshotNotFoundFault" => crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::SnapshotNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::snapshot_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_snapshot_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetGroupNotFoundFault" => {
crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::SubnetGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::subnet_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"TagQuotaPerResourceExceeded" => {
crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::TagQuotaPerResourceExceeded({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::tag_quota_per_resource_exceeded::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_tag_quota_per_resource_exceededjson_err(response.body().as_ref(), output).map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"UserNotFoundFault" => crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::UserNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::user_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_user_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::TagResourceError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_tag_resource_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::TagResourceOutput, crate::error::TagResourceError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::tag_resource_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_tag_resource(response.body().as_ref(), output)
.map_err(crate::error::TagResourceError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_untag_resource_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UntagResourceOutput, crate::error::UntagResourceError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::UntagResourceError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::UntagResourceError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ACLNotFoundFault" => crate::error::UntagResourceError {
meta: generic,
kind: crate::error::UntagResourceErrorKind::AclNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::acl_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_acl_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ClusterNotFoundFault" => crate::error::UntagResourceError {
meta: generic,
kind: crate::error::UntagResourceErrorKind::ClusterNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::cluster_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_cluster_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidARNFault" => crate::error::UntagResourceError {
meta: generic,
kind: crate::error::UntagResourceErrorKind::InvalidArnFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arn_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidClusterStateFault" => crate::error::UntagResourceError {
meta: generic,
kind: crate::error::UntagResourceErrorKind::InvalidClusterStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_cluster_state_fault::Builder::default();
let _ = response;
output =
crate::json_deser::deser_structure_invalid_cluster_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ParameterGroupNotFoundFault" => {
crate::error::UntagResourceError {
meta: generic,
kind: crate::error::UntagResourceErrorKind::ParameterGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::parameter_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_parameter_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ServiceLinkedRoleNotFoundFault" => crate::error::UntagResourceError {
meta: generic,
kind: crate::error::UntagResourceErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SnapshotNotFoundFault" => crate::error::UntagResourceError {
meta: generic,
kind: crate::error::UntagResourceErrorKind::SnapshotNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::snapshot_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_snapshot_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetGroupNotFoundFault" => {
crate::error::UntagResourceError {
meta: generic,
kind: crate::error::UntagResourceErrorKind::SubnetGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::subnet_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"TagNotFoundFault" => crate::error::UntagResourceError {
meta: generic,
kind: crate::error::UntagResourceErrorKind::TagNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::tag_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_tag_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"UserNotFoundFault" => crate::error::UntagResourceError {
meta: generic,
kind: crate::error::UntagResourceErrorKind::UserNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::user_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_user_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::UntagResourceError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_untag_resource_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UntagResourceOutput, crate::error::UntagResourceError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::untag_resource_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_untag_resource(response.body().as_ref(), output)
.map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_acl_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UpdateAclOutput, crate::error::UpdateACLError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::UpdateACLError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::UpdateACLError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ACLNotFoundFault" => crate::error::UpdateACLError {
meta: generic,
kind: crate::error::UpdateACLErrorKind::AclNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::acl_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_acl_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"DefaultUserRequired" => crate::error::UpdateACLError {
meta: generic,
kind: crate::error::UpdateACLErrorKind::DefaultUserRequired({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::default_user_required::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_default_user_requiredjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"DuplicateUserNameFault" => crate::error::UpdateACLError {
meta: generic,
kind: crate::error::UpdateACLErrorKind::DuplicateUserNameFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::duplicate_user_name_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_duplicate_user_name_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidACLStateFault" => crate::error::UpdateACLError {
meta: generic,
kind: crate::error::UpdateACLErrorKind::InvalidAclStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_acl_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_acl_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterCombinationException" => crate::error::UpdateACLError {
meta: generic,
kind: crate::error::UpdateACLErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::UpdateACLError {
meta: generic,
kind: crate::error::UpdateACLErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"UserNotFoundFault" => crate::error::UpdateACLError {
meta: generic,
kind: crate::error::UpdateACLErrorKind::UserNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::user_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_user_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateACLError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::UpdateACLError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_acl_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UpdateAclOutput, crate::error::UpdateACLError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::update_acl_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_update_acl(response.body().as_ref(), output)
.map_err(crate::error::UpdateACLError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_cluster_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UpdateClusterOutput, crate::error::UpdateClusterError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::UpdateClusterError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::UpdateClusterError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ACLNotFoundFault" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::AclNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::acl_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_acl_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ClusterNotFoundFault" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::ClusterNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::cluster_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_cluster_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ClusterQuotaForCustomerExceededFault" => {
crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::ClusterQuotaForCustomerExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]let mut output = crate::error::cluster_quota_for_customer_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_cluster_quota_for_customer_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InvalidACLStateFault" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::InvalidAclStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_acl_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_acl_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidClusterStateFault" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::InvalidClusterStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_cluster_state_fault::Builder::default();
let _ = response;
output =
crate::json_deser::deser_structure_invalid_cluster_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidKMSKeyFault" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::InvalidKmsKeyFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_kms_key_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_kms_key_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidNodeStateFault" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::InvalidNodeStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_node_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_node_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterCombinationException" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidVPCNetworkStateFault" => {
crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::InvalidVpcNetworkStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_vpc_network_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_vpc_network_state_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"NodeQuotaForClusterExceededFault" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::NodeQuotaForClusterExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::node_quota_for_cluster_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_node_quota_for_cluster_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"NodeQuotaForCustomerExceededFault" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::NodeQuotaForCustomerExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::node_quota_for_customer_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_node_quota_for_customer_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"NoOperationFault" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::NoOperationFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::no_operation_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_no_operation_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ParameterGroupNotFoundFault" => {
crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::ParameterGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::parameter_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_parameter_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ServiceLinkedRoleNotFoundFault" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ShardsPerClusterQuotaExceededFault" => crate::error::UpdateClusterError {
meta: generic,
kind: crate::error::UpdateClusterErrorKind::ShardsPerClusterQuotaExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::shards_per_cluster_quota_exceeded_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_shards_per_cluster_quota_exceeded_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::UpdateClusterError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_cluster_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UpdateClusterOutput, crate::error::UpdateClusterError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::update_cluster_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_update_cluster(response.body().as_ref(), output)
.map_err(crate::error::UpdateClusterError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_parameter_group_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::UpdateParameterGroupOutput,
crate::error::UpdateParameterGroupError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::UpdateParameterGroupError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::UpdateParameterGroupError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => crate::error::UpdateParameterGroupError {
meta: generic,
kind: crate::error::UpdateParameterGroupErrorKind::InvalidParameterCombinationException(
{
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default(
);
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
},
),
},
"InvalidParameterGroupStateFault" => crate::error::UpdateParameterGroupError {
meta: generic,
kind: crate::error::UpdateParameterGroupErrorKind::InvalidParameterGroupStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_group_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_group_state_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::UpdateParameterGroupError {
meta: generic,
kind: crate::error::UpdateParameterGroupErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ParameterGroupNotFoundFault" => {
crate::error::UpdateParameterGroupError {
meta: generic,
kind: crate::error::UpdateParameterGroupErrorKind::ParameterGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::parameter_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_parameter_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"ServiceLinkedRoleNotFoundFault" => crate::error::UpdateParameterGroupError {
meta: generic,
kind: crate::error::UpdateParameterGroupErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateParameterGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::UpdateParameterGroupError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_parameter_group_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::UpdateParameterGroupOutput,
crate::error::UpdateParameterGroupError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::update_parameter_group_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_update_parameter_group(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateParameterGroupError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_subnet_group_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UpdateSubnetGroupOutput, crate::error::UpdateSubnetGroupError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::UpdateSubnetGroupError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::UpdateSubnetGroupError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidSubnet" => crate::error::UpdateSubnetGroupError {
meta: generic,
kind: crate::error::UpdateSubnetGroupErrorKind::InvalidSubnet({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_subnet::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_subnetjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ServiceLinkedRoleNotFoundFault" => crate::error::UpdateSubnetGroupError {
meta: generic,
kind: crate::error::UpdateSubnetGroupErrorKind::ServiceLinkedRoleNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::service_linked_role_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_service_linked_role_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetGroupNotFoundFault" => {
crate::error::UpdateSubnetGroupError {
meta: generic,
kind: crate::error::UpdateSubnetGroupErrorKind::SubnetGroupNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::subnet_group_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_group_not_found_faultjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"SubnetInUse" => crate::error::UpdateSubnetGroupError {
meta: generic,
kind: crate::error::UpdateSubnetGroupErrorKind::SubnetInUse({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::subnet_in_use::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_in_usejson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetNotAllowedFault" => crate::error::UpdateSubnetGroupError {
meta: generic,
kind: crate::error::UpdateSubnetGroupErrorKind::SubnetNotAllowedFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::subnet_not_allowed_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_subnet_not_allowed_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"SubnetQuotaExceededFault" => crate::error::UpdateSubnetGroupError {
meta: generic,
kind: crate::error::UpdateSubnetGroupErrorKind::SubnetQuotaExceededFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::subnet_quota_exceeded_fault::Builder::default();
let _ = response;
output =
crate::json_deser::deser_structure_subnet_quota_exceeded_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateSubnetGroupError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::UpdateSubnetGroupError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_subnet_group_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UpdateSubnetGroupOutput, crate::error::UpdateSubnetGroupError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::update_subnet_group_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_update_subnet_group(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateSubnetGroupError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_user_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UpdateUserOutput, crate::error::UpdateUserError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::UpdateUserError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::UpdateUserError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidParameterCombinationException" => crate::error::UpdateUserError {
meta: generic,
kind: crate::error::UpdateUserErrorKind::InvalidParameterCombinationException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_combination_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_combination_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidParameterValueException" => crate::error::UpdateUserError {
meta: generic,
kind: crate::error::UpdateUserErrorKind::InvalidParameterValueException({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_parameter_value_exception::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_parameter_value_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidUserStateFault" => crate::error::UpdateUserError {
meta: generic,
kind: crate::error::UpdateUserErrorKind::InvalidUserStateFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_user_state_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_user_state_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"UserNotFoundFault" => crate::error::UpdateUserError {
meta: generic,
kind: crate::error::UpdateUserErrorKind::UserNotFoundFault({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::user_not_found_fault::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_user_not_found_faultjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateUserError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::UpdateUserError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_user_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UpdateUserOutput, crate::error::UpdateUserError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::update_user_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_update_user(response.body().as_ref(), output)
.map_err(crate::error::UpdateUserError::unhandled)?;
output.build()
})
}
| 44.910066 | 218 | 0.523841 |
6a25d2df1296173435e159af4cb8bb49d8e01f27 | 1,926 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
extern crate arrow;
use arrow::array::{Float64Array, StringArray};
use arrow::csv;
use std::fs::File;
fn main() {
let file = File::open("test/data/uk_cities_with_headers.csv").unwrap();
let builder = csv::ReaderBuilder::new()
.has_headers(true)
.infer_schema(Some(100));
let mut csv = builder.build(file).unwrap();
let batch = csv.next().unwrap().unwrap();
println!(
"Loaded {} rows containing {} columns",
batch.num_rows(),
batch.num_columns()
);
println!("Inferred schema: {:?}", batch.schema());
let city = batch
.column(0)
.as_any()
.downcast_ref::<StringArray>()
.unwrap();
let lat = batch
.column(1)
.as_any()
.downcast_ref::<Float64Array>()
.unwrap();
let lng = batch
.column(2)
.as_any()
.downcast_ref::<Float64Array>()
.unwrap();
for i in 0..batch.num_rows() {
println!(
"City: {}, Latitude: {}, Longitude: {}",
city.value(i),
lat.value(i),
lng.value(i)
);
}
}
| 29.630769 | 75 | 0.620976 |
2617621dee1c12a9792b1ab0cddd324eff9a19de | 103,689 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
/// Operation shape for `AssignInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`assign_instance`](crate::client::Client::assign_instance).
///
/// See [`crate::client::fluent_builders::AssignInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct AssignInstance {
_private: (),
}
impl AssignInstance {
/// Creates a new builder-style object to manufacture [`AssignInstanceInput`](crate::input::AssignInstanceInput)
pub fn builder() -> crate::input::assign_instance_input::Builder {
crate::input::assign_instance_input::Builder::default()
}
/// Creates a new `AssignInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for AssignInstance {
type Output =
std::result::Result<crate::output::AssignInstanceOutput, crate::error::AssignInstanceError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_assign_instance_error(response)
} else {
crate::operation_deser::parse_assign_instance_response(response)
}
}
}
/// Operation shape for `AssignVolume`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`assign_volume`](crate::client::Client::assign_volume).
///
/// See [`crate::client::fluent_builders::AssignVolume`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct AssignVolume {
_private: (),
}
impl AssignVolume {
/// Creates a new builder-style object to manufacture [`AssignVolumeInput`](crate::input::AssignVolumeInput)
pub fn builder() -> crate::input::assign_volume_input::Builder {
crate::input::assign_volume_input::Builder::default()
}
/// Creates a new `AssignVolume` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for AssignVolume {
type Output =
std::result::Result<crate::output::AssignVolumeOutput, crate::error::AssignVolumeError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_assign_volume_error(response)
} else {
crate::operation_deser::parse_assign_volume_response(response)
}
}
}
/// Operation shape for `AssociateElasticIp`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`associate_elastic_ip`](crate::client::Client::associate_elastic_ip).
///
/// See [`crate::client::fluent_builders::AssociateElasticIp`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct AssociateElasticIp {
_private: (),
}
impl AssociateElasticIp {
/// Creates a new builder-style object to manufacture [`AssociateElasticIpInput`](crate::input::AssociateElasticIpInput)
pub fn builder() -> crate::input::associate_elastic_ip_input::Builder {
crate::input::associate_elastic_ip_input::Builder::default()
}
/// Creates a new `AssociateElasticIp` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for AssociateElasticIp {
type Output = std::result::Result<
crate::output::AssociateElasticIpOutput,
crate::error::AssociateElasticIpError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_associate_elastic_ip_error(response)
} else {
crate::operation_deser::parse_associate_elastic_ip_response(response)
}
}
}
/// Operation shape for `AttachElasticLoadBalancer`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`attach_elastic_load_balancer`](crate::client::Client::attach_elastic_load_balancer).
///
/// See [`crate::client::fluent_builders::AttachElasticLoadBalancer`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct AttachElasticLoadBalancer {
_private: (),
}
impl AttachElasticLoadBalancer {
/// Creates a new builder-style object to manufacture [`AttachElasticLoadBalancerInput`](crate::input::AttachElasticLoadBalancerInput)
pub fn builder() -> crate::input::attach_elastic_load_balancer_input::Builder {
crate::input::attach_elastic_load_balancer_input::Builder::default()
}
/// Creates a new `AttachElasticLoadBalancer` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for AttachElasticLoadBalancer {
type Output = std::result::Result<
crate::output::AttachElasticLoadBalancerOutput,
crate::error::AttachElasticLoadBalancerError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_attach_elastic_load_balancer_error(response)
} else {
crate::operation_deser::parse_attach_elastic_load_balancer_response(response)
}
}
}
/// Operation shape for `CloneStack`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`clone_stack`](crate::client::Client::clone_stack).
///
/// See [`crate::client::fluent_builders::CloneStack`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct CloneStack {
_private: (),
}
impl CloneStack {
/// Creates a new builder-style object to manufacture [`CloneStackInput`](crate::input::CloneStackInput)
pub fn builder() -> crate::input::clone_stack_input::Builder {
crate::input::clone_stack_input::Builder::default()
}
/// Creates a new `CloneStack` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for CloneStack {
type Output =
std::result::Result<crate::output::CloneStackOutput, crate::error::CloneStackError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_clone_stack_error(response)
} else {
crate::operation_deser::parse_clone_stack_response(response)
}
}
}
/// Operation shape for `CreateApp`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`create_app`](crate::client::Client::create_app).
///
/// See [`crate::client::fluent_builders::CreateApp`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct CreateApp {
_private: (),
}
impl CreateApp {
/// Creates a new builder-style object to manufacture [`CreateAppInput`](crate::input::CreateAppInput)
pub fn builder() -> crate::input::create_app_input::Builder {
crate::input::create_app_input::Builder::default()
}
/// Creates a new `CreateApp` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for CreateApp {
type Output = std::result::Result<crate::output::CreateAppOutput, crate::error::CreateAppError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_create_app_error(response)
} else {
crate::operation_deser::parse_create_app_response(response)
}
}
}
/// Operation shape for `CreateDeployment`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`create_deployment`](crate::client::Client::create_deployment).
///
/// See [`crate::client::fluent_builders::CreateDeployment`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct CreateDeployment {
_private: (),
}
impl CreateDeployment {
/// Creates a new builder-style object to manufacture [`CreateDeploymentInput`](crate::input::CreateDeploymentInput)
pub fn builder() -> crate::input::create_deployment_input::Builder {
crate::input::create_deployment_input::Builder::default()
}
/// Creates a new `CreateDeployment` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for CreateDeployment {
type Output = std::result::Result<
crate::output::CreateDeploymentOutput,
crate::error::CreateDeploymentError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_create_deployment_error(response)
} else {
crate::operation_deser::parse_create_deployment_response(response)
}
}
}
/// Operation shape for `CreateInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`create_instance`](crate::client::Client::create_instance).
///
/// See [`crate::client::fluent_builders::CreateInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct CreateInstance {
_private: (),
}
impl CreateInstance {
/// Creates a new builder-style object to manufacture [`CreateInstanceInput`](crate::input::CreateInstanceInput)
pub fn builder() -> crate::input::create_instance_input::Builder {
crate::input::create_instance_input::Builder::default()
}
/// Creates a new `CreateInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for CreateInstance {
type Output =
std::result::Result<crate::output::CreateInstanceOutput, crate::error::CreateInstanceError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_create_instance_error(response)
} else {
crate::operation_deser::parse_create_instance_response(response)
}
}
}
/// Operation shape for `CreateLayer`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`create_layer`](crate::client::Client::create_layer).
///
/// See [`crate::client::fluent_builders::CreateLayer`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct CreateLayer {
_private: (),
}
impl CreateLayer {
/// Creates a new builder-style object to manufacture [`CreateLayerInput`](crate::input::CreateLayerInput)
pub fn builder() -> crate::input::create_layer_input::Builder {
crate::input::create_layer_input::Builder::default()
}
/// Creates a new `CreateLayer` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for CreateLayer {
type Output =
std::result::Result<crate::output::CreateLayerOutput, crate::error::CreateLayerError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_create_layer_error(response)
} else {
crate::operation_deser::parse_create_layer_response(response)
}
}
}
/// Operation shape for `CreateStack`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`create_stack`](crate::client::Client::create_stack).
///
/// See [`crate::client::fluent_builders::CreateStack`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct CreateStack {
_private: (),
}
impl CreateStack {
/// Creates a new builder-style object to manufacture [`CreateStackInput`](crate::input::CreateStackInput)
pub fn builder() -> crate::input::create_stack_input::Builder {
crate::input::create_stack_input::Builder::default()
}
/// Creates a new `CreateStack` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for CreateStack {
type Output =
std::result::Result<crate::output::CreateStackOutput, crate::error::CreateStackError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_create_stack_error(response)
} else {
crate::operation_deser::parse_create_stack_response(response)
}
}
}
/// Operation shape for `CreateUserProfile`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`create_user_profile`](crate::client::Client::create_user_profile).
///
/// See [`crate::client::fluent_builders::CreateUserProfile`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct CreateUserProfile {
_private: (),
}
impl CreateUserProfile {
/// Creates a new builder-style object to manufacture [`CreateUserProfileInput`](crate::input::CreateUserProfileInput)
pub fn builder() -> crate::input::create_user_profile_input::Builder {
crate::input::create_user_profile_input::Builder::default()
}
/// Creates a new `CreateUserProfile` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for CreateUserProfile {
type Output = std::result::Result<
crate::output::CreateUserProfileOutput,
crate::error::CreateUserProfileError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_create_user_profile_error(response)
} else {
crate::operation_deser::parse_create_user_profile_response(response)
}
}
}
/// Operation shape for `DeleteApp`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`delete_app`](crate::client::Client::delete_app).
///
/// See [`crate::client::fluent_builders::DeleteApp`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DeleteApp {
_private: (),
}
impl DeleteApp {
/// Creates a new builder-style object to manufacture [`DeleteAppInput`](crate::input::DeleteAppInput)
pub fn builder() -> crate::input::delete_app_input::Builder {
crate::input::delete_app_input::Builder::default()
}
/// Creates a new `DeleteApp` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DeleteApp {
type Output = std::result::Result<crate::output::DeleteAppOutput, crate::error::DeleteAppError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_delete_app_error(response)
} else {
crate::operation_deser::parse_delete_app_response(response)
}
}
}
/// Operation shape for `DeleteInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`delete_instance`](crate::client::Client::delete_instance).
///
/// See [`crate::client::fluent_builders::DeleteInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DeleteInstance {
_private: (),
}
impl DeleteInstance {
/// Creates a new builder-style object to manufacture [`DeleteInstanceInput`](crate::input::DeleteInstanceInput)
pub fn builder() -> crate::input::delete_instance_input::Builder {
crate::input::delete_instance_input::Builder::default()
}
/// Creates a new `DeleteInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DeleteInstance {
type Output =
std::result::Result<crate::output::DeleteInstanceOutput, crate::error::DeleteInstanceError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_delete_instance_error(response)
} else {
crate::operation_deser::parse_delete_instance_response(response)
}
}
}
/// Operation shape for `DeleteLayer`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`delete_layer`](crate::client::Client::delete_layer).
///
/// See [`crate::client::fluent_builders::DeleteLayer`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DeleteLayer {
_private: (),
}
impl DeleteLayer {
/// Creates a new builder-style object to manufacture [`DeleteLayerInput`](crate::input::DeleteLayerInput)
pub fn builder() -> crate::input::delete_layer_input::Builder {
crate::input::delete_layer_input::Builder::default()
}
/// Creates a new `DeleteLayer` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DeleteLayer {
type Output =
std::result::Result<crate::output::DeleteLayerOutput, crate::error::DeleteLayerError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_delete_layer_error(response)
} else {
crate::operation_deser::parse_delete_layer_response(response)
}
}
}
/// Operation shape for `DeleteStack`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`delete_stack`](crate::client::Client::delete_stack).
///
/// See [`crate::client::fluent_builders::DeleteStack`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DeleteStack {
_private: (),
}
impl DeleteStack {
/// Creates a new builder-style object to manufacture [`DeleteStackInput`](crate::input::DeleteStackInput)
pub fn builder() -> crate::input::delete_stack_input::Builder {
crate::input::delete_stack_input::Builder::default()
}
/// Creates a new `DeleteStack` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DeleteStack {
type Output =
std::result::Result<crate::output::DeleteStackOutput, crate::error::DeleteStackError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_delete_stack_error(response)
} else {
crate::operation_deser::parse_delete_stack_response(response)
}
}
}
/// Operation shape for `DeleteUserProfile`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`delete_user_profile`](crate::client::Client::delete_user_profile).
///
/// See [`crate::client::fluent_builders::DeleteUserProfile`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DeleteUserProfile {
_private: (),
}
impl DeleteUserProfile {
/// Creates a new builder-style object to manufacture [`DeleteUserProfileInput`](crate::input::DeleteUserProfileInput)
pub fn builder() -> crate::input::delete_user_profile_input::Builder {
crate::input::delete_user_profile_input::Builder::default()
}
/// Creates a new `DeleteUserProfile` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DeleteUserProfile {
type Output = std::result::Result<
crate::output::DeleteUserProfileOutput,
crate::error::DeleteUserProfileError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_delete_user_profile_error(response)
} else {
crate::operation_deser::parse_delete_user_profile_response(response)
}
}
}
/// Operation shape for `DeregisterEcsCluster`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`deregister_ecs_cluster`](crate::client::Client::deregister_ecs_cluster).
///
/// See [`crate::client::fluent_builders::DeregisterEcsCluster`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DeregisterEcsCluster {
_private: (),
}
impl DeregisterEcsCluster {
/// Creates a new builder-style object to manufacture [`DeregisterEcsClusterInput`](crate::input::DeregisterEcsClusterInput)
pub fn builder() -> crate::input::deregister_ecs_cluster_input::Builder {
crate::input::deregister_ecs_cluster_input::Builder::default()
}
/// Creates a new `DeregisterEcsCluster` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DeregisterEcsCluster {
type Output = std::result::Result<
crate::output::DeregisterEcsClusterOutput,
crate::error::DeregisterEcsClusterError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_deregister_ecs_cluster_error(response)
} else {
crate::operation_deser::parse_deregister_ecs_cluster_response(response)
}
}
}
/// Operation shape for `DeregisterElasticIp`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`deregister_elastic_ip`](crate::client::Client::deregister_elastic_ip).
///
/// See [`crate::client::fluent_builders::DeregisterElasticIp`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DeregisterElasticIp {
_private: (),
}
impl DeregisterElasticIp {
/// Creates a new builder-style object to manufacture [`DeregisterElasticIpInput`](crate::input::DeregisterElasticIpInput)
pub fn builder() -> crate::input::deregister_elastic_ip_input::Builder {
crate::input::deregister_elastic_ip_input::Builder::default()
}
/// Creates a new `DeregisterElasticIp` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DeregisterElasticIp {
type Output = std::result::Result<
crate::output::DeregisterElasticIpOutput,
crate::error::DeregisterElasticIpError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_deregister_elastic_ip_error(response)
} else {
crate::operation_deser::parse_deregister_elastic_ip_response(response)
}
}
}
/// Operation shape for `DeregisterInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`deregister_instance`](crate::client::Client::deregister_instance).
///
/// See [`crate::client::fluent_builders::DeregisterInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DeregisterInstance {
_private: (),
}
impl DeregisterInstance {
/// Creates a new builder-style object to manufacture [`DeregisterInstanceInput`](crate::input::DeregisterInstanceInput)
pub fn builder() -> crate::input::deregister_instance_input::Builder {
crate::input::deregister_instance_input::Builder::default()
}
/// Creates a new `DeregisterInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DeregisterInstance {
type Output = std::result::Result<
crate::output::DeregisterInstanceOutput,
crate::error::DeregisterInstanceError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_deregister_instance_error(response)
} else {
crate::operation_deser::parse_deregister_instance_response(response)
}
}
}
/// Operation shape for `DeregisterRdsDbInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`deregister_rds_db_instance`](crate::client::Client::deregister_rds_db_instance).
///
/// See [`crate::client::fluent_builders::DeregisterRdsDbInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DeregisterRdsDbInstance {
_private: (),
}
impl DeregisterRdsDbInstance {
/// Creates a new builder-style object to manufacture [`DeregisterRdsDbInstanceInput`](crate::input::DeregisterRdsDbInstanceInput)
pub fn builder() -> crate::input::deregister_rds_db_instance_input::Builder {
crate::input::deregister_rds_db_instance_input::Builder::default()
}
/// Creates a new `DeregisterRdsDbInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DeregisterRdsDbInstance {
type Output = std::result::Result<
crate::output::DeregisterRdsDbInstanceOutput,
crate::error::DeregisterRdsDbInstanceError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_deregister_rds_db_instance_error(response)
} else {
crate::operation_deser::parse_deregister_rds_db_instance_response(response)
}
}
}
/// Operation shape for `DeregisterVolume`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`deregister_volume`](crate::client::Client::deregister_volume).
///
/// See [`crate::client::fluent_builders::DeregisterVolume`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DeregisterVolume {
_private: (),
}
impl DeregisterVolume {
/// Creates a new builder-style object to manufacture [`DeregisterVolumeInput`](crate::input::DeregisterVolumeInput)
pub fn builder() -> crate::input::deregister_volume_input::Builder {
crate::input::deregister_volume_input::Builder::default()
}
/// Creates a new `DeregisterVolume` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DeregisterVolume {
type Output = std::result::Result<
crate::output::DeregisterVolumeOutput,
crate::error::DeregisterVolumeError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_deregister_volume_error(response)
} else {
crate::operation_deser::parse_deregister_volume_response(response)
}
}
}
/// Operation shape for `DescribeAgentVersions`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_agent_versions`](crate::client::Client::describe_agent_versions).
///
/// See [`crate::client::fluent_builders::DescribeAgentVersions`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeAgentVersions {
_private: (),
}
impl DescribeAgentVersions {
/// Creates a new builder-style object to manufacture [`DescribeAgentVersionsInput`](crate::input::DescribeAgentVersionsInput)
pub fn builder() -> crate::input::describe_agent_versions_input::Builder {
crate::input::describe_agent_versions_input::Builder::default()
}
/// Creates a new `DescribeAgentVersions` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeAgentVersions {
type Output = std::result::Result<
crate::output::DescribeAgentVersionsOutput,
crate::error::DescribeAgentVersionsError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_agent_versions_error(response)
} else {
crate::operation_deser::parse_describe_agent_versions_response(response)
}
}
}
/// Operation shape for `DescribeApps`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_apps`](crate::client::Client::describe_apps).
///
/// See [`crate::client::fluent_builders::DescribeApps`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeApps {
_private: (),
}
impl DescribeApps {
/// Creates a new builder-style object to manufacture [`DescribeAppsInput`](crate::input::DescribeAppsInput)
pub fn builder() -> crate::input::describe_apps_input::Builder {
crate::input::describe_apps_input::Builder::default()
}
/// Creates a new `DescribeApps` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeApps {
type Output =
std::result::Result<crate::output::DescribeAppsOutput, crate::error::DescribeAppsError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_apps_error(response)
} else {
crate::operation_deser::parse_describe_apps_response(response)
}
}
}
/// Operation shape for `DescribeCommands`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_commands`](crate::client::Client::describe_commands).
///
/// See [`crate::client::fluent_builders::DescribeCommands`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeCommands {
_private: (),
}
impl DescribeCommands {
/// Creates a new builder-style object to manufacture [`DescribeCommandsInput`](crate::input::DescribeCommandsInput)
pub fn builder() -> crate::input::describe_commands_input::Builder {
crate::input::describe_commands_input::Builder::default()
}
/// Creates a new `DescribeCommands` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeCommands {
type Output = std::result::Result<
crate::output::DescribeCommandsOutput,
crate::error::DescribeCommandsError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_commands_error(response)
} else {
crate::operation_deser::parse_describe_commands_response(response)
}
}
}
/// Operation shape for `DescribeDeployments`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_deployments`](crate::client::Client::describe_deployments).
///
/// See [`crate::client::fluent_builders::DescribeDeployments`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeDeployments {
_private: (),
}
impl DescribeDeployments {
/// Creates a new builder-style object to manufacture [`DescribeDeploymentsInput`](crate::input::DescribeDeploymentsInput)
pub fn builder() -> crate::input::describe_deployments_input::Builder {
crate::input::describe_deployments_input::Builder::default()
}
/// Creates a new `DescribeDeployments` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeDeployments {
type Output = std::result::Result<
crate::output::DescribeDeploymentsOutput,
crate::error::DescribeDeploymentsError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_deployments_error(response)
} else {
crate::operation_deser::parse_describe_deployments_response(response)
}
}
}
/// Operation shape for `DescribeEcsClusters`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_ecs_clusters`](crate::client::Client::describe_ecs_clusters).
///
/// See [`crate::client::fluent_builders::DescribeEcsClusters`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeEcsClusters {
_private: (),
}
impl DescribeEcsClusters {
/// Creates a new builder-style object to manufacture [`DescribeEcsClustersInput`](crate::input::DescribeEcsClustersInput)
pub fn builder() -> crate::input::describe_ecs_clusters_input::Builder {
crate::input::describe_ecs_clusters_input::Builder::default()
}
/// Creates a new `DescribeEcsClusters` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeEcsClusters {
type Output = std::result::Result<
crate::output::DescribeEcsClustersOutput,
crate::error::DescribeEcsClustersError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_ecs_clusters_error(response)
} else {
crate::operation_deser::parse_describe_ecs_clusters_response(response)
}
}
}
/// Operation shape for `DescribeElasticIps`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_elastic_ips`](crate::client::Client::describe_elastic_ips).
///
/// See [`crate::client::fluent_builders::DescribeElasticIps`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeElasticIps {
_private: (),
}
impl DescribeElasticIps {
/// Creates a new builder-style object to manufacture [`DescribeElasticIpsInput`](crate::input::DescribeElasticIpsInput)
pub fn builder() -> crate::input::describe_elastic_ips_input::Builder {
crate::input::describe_elastic_ips_input::Builder::default()
}
/// Creates a new `DescribeElasticIps` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeElasticIps {
type Output = std::result::Result<
crate::output::DescribeElasticIpsOutput,
crate::error::DescribeElasticIpsError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_elastic_ips_error(response)
} else {
crate::operation_deser::parse_describe_elastic_ips_response(response)
}
}
}
/// Operation shape for `DescribeElasticLoadBalancers`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_elastic_load_balancers`](crate::client::Client::describe_elastic_load_balancers).
///
/// See [`crate::client::fluent_builders::DescribeElasticLoadBalancers`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeElasticLoadBalancers {
_private: (),
}
impl DescribeElasticLoadBalancers {
/// Creates a new builder-style object to manufacture [`DescribeElasticLoadBalancersInput`](crate::input::DescribeElasticLoadBalancersInput)
pub fn builder() -> crate::input::describe_elastic_load_balancers_input::Builder {
crate::input::describe_elastic_load_balancers_input::Builder::default()
}
/// Creates a new `DescribeElasticLoadBalancers` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeElasticLoadBalancers {
type Output = std::result::Result<
crate::output::DescribeElasticLoadBalancersOutput,
crate::error::DescribeElasticLoadBalancersError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_elastic_load_balancers_error(response)
} else {
crate::operation_deser::parse_describe_elastic_load_balancers_response(response)
}
}
}
/// Operation shape for `DescribeInstances`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_instances`](crate::client::Client::describe_instances).
///
/// See [`crate::client::fluent_builders::DescribeInstances`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeInstances {
_private: (),
}
impl DescribeInstances {
/// Creates a new builder-style object to manufacture [`DescribeInstancesInput`](crate::input::DescribeInstancesInput)
pub fn builder() -> crate::input::describe_instances_input::Builder {
crate::input::describe_instances_input::Builder::default()
}
/// Creates a new `DescribeInstances` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeInstances {
type Output = std::result::Result<
crate::output::DescribeInstancesOutput,
crate::error::DescribeInstancesError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_instances_error(response)
} else {
crate::operation_deser::parse_describe_instances_response(response)
}
}
}
/// Operation shape for `DescribeLayers`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_layers`](crate::client::Client::describe_layers).
///
/// See [`crate::client::fluent_builders::DescribeLayers`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeLayers {
_private: (),
}
impl DescribeLayers {
/// Creates a new builder-style object to manufacture [`DescribeLayersInput`](crate::input::DescribeLayersInput)
pub fn builder() -> crate::input::describe_layers_input::Builder {
crate::input::describe_layers_input::Builder::default()
}
/// Creates a new `DescribeLayers` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeLayers {
type Output =
std::result::Result<crate::output::DescribeLayersOutput, crate::error::DescribeLayersError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_layers_error(response)
} else {
crate::operation_deser::parse_describe_layers_response(response)
}
}
}
/// Operation shape for `DescribeLoadBasedAutoScaling`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_load_based_auto_scaling`](crate::client::Client::describe_load_based_auto_scaling).
///
/// See [`crate::client::fluent_builders::DescribeLoadBasedAutoScaling`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeLoadBasedAutoScaling {
_private: (),
}
impl DescribeLoadBasedAutoScaling {
/// Creates a new builder-style object to manufacture [`DescribeLoadBasedAutoScalingInput`](crate::input::DescribeLoadBasedAutoScalingInput)
pub fn builder() -> crate::input::describe_load_based_auto_scaling_input::Builder {
crate::input::describe_load_based_auto_scaling_input::Builder::default()
}
/// Creates a new `DescribeLoadBasedAutoScaling` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeLoadBasedAutoScaling {
type Output = std::result::Result<
crate::output::DescribeLoadBasedAutoScalingOutput,
crate::error::DescribeLoadBasedAutoScalingError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_load_based_auto_scaling_error(response)
} else {
crate::operation_deser::parse_describe_load_based_auto_scaling_response(response)
}
}
}
/// Operation shape for `DescribeMyUserProfile`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_my_user_profile`](crate::client::Client::describe_my_user_profile).
///
/// See [`crate::client::fluent_builders::DescribeMyUserProfile`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeMyUserProfile {
_private: (),
}
impl DescribeMyUserProfile {
/// Creates a new builder-style object to manufacture [`DescribeMyUserProfileInput`](crate::input::DescribeMyUserProfileInput)
pub fn builder() -> crate::input::describe_my_user_profile_input::Builder {
crate::input::describe_my_user_profile_input::Builder::default()
}
/// Creates a new `DescribeMyUserProfile` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeMyUserProfile {
type Output = std::result::Result<
crate::output::DescribeMyUserProfileOutput,
crate::error::DescribeMyUserProfileError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_my_user_profile_error(response)
} else {
crate::operation_deser::parse_describe_my_user_profile_response(response)
}
}
}
/// Operation shape for `DescribeOperatingSystems`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_operating_systems`](crate::client::Client::describe_operating_systems).
///
/// See [`crate::client::fluent_builders::DescribeOperatingSystems`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeOperatingSystems {
_private: (),
}
impl DescribeOperatingSystems {
/// Creates a new builder-style object to manufacture [`DescribeOperatingSystemsInput`](crate::input::DescribeOperatingSystemsInput)
pub fn builder() -> crate::input::describe_operating_systems_input::Builder {
crate::input::describe_operating_systems_input::Builder::default()
}
/// Creates a new `DescribeOperatingSystems` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeOperatingSystems {
type Output = std::result::Result<
crate::output::DescribeOperatingSystemsOutput,
crate::error::DescribeOperatingSystemsError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_operating_systems_error(response)
} else {
crate::operation_deser::parse_describe_operating_systems_response(response)
}
}
}
/// Operation shape for `DescribePermissions`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_permissions`](crate::client::Client::describe_permissions).
///
/// See [`crate::client::fluent_builders::DescribePermissions`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribePermissions {
_private: (),
}
impl DescribePermissions {
/// Creates a new builder-style object to manufacture [`DescribePermissionsInput`](crate::input::DescribePermissionsInput)
pub fn builder() -> crate::input::describe_permissions_input::Builder {
crate::input::describe_permissions_input::Builder::default()
}
/// Creates a new `DescribePermissions` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribePermissions {
type Output = std::result::Result<
crate::output::DescribePermissionsOutput,
crate::error::DescribePermissionsError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_permissions_error(response)
} else {
crate::operation_deser::parse_describe_permissions_response(response)
}
}
}
/// Operation shape for `DescribeRaidArrays`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_raid_arrays`](crate::client::Client::describe_raid_arrays).
///
/// See [`crate::client::fluent_builders::DescribeRaidArrays`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeRaidArrays {
_private: (),
}
impl DescribeRaidArrays {
/// Creates a new builder-style object to manufacture [`DescribeRaidArraysInput`](crate::input::DescribeRaidArraysInput)
pub fn builder() -> crate::input::describe_raid_arrays_input::Builder {
crate::input::describe_raid_arrays_input::Builder::default()
}
/// Creates a new `DescribeRaidArrays` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeRaidArrays {
type Output = std::result::Result<
crate::output::DescribeRaidArraysOutput,
crate::error::DescribeRaidArraysError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_raid_arrays_error(response)
} else {
crate::operation_deser::parse_describe_raid_arrays_response(response)
}
}
}
/// Operation shape for `DescribeRdsDbInstances`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_rds_db_instances`](crate::client::Client::describe_rds_db_instances).
///
/// See [`crate::client::fluent_builders::DescribeRdsDbInstances`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeRdsDbInstances {
_private: (),
}
impl DescribeRdsDbInstances {
/// Creates a new builder-style object to manufacture [`DescribeRdsDbInstancesInput`](crate::input::DescribeRdsDbInstancesInput)
pub fn builder() -> crate::input::describe_rds_db_instances_input::Builder {
crate::input::describe_rds_db_instances_input::Builder::default()
}
/// Creates a new `DescribeRdsDbInstances` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeRdsDbInstances {
type Output = std::result::Result<
crate::output::DescribeRdsDbInstancesOutput,
crate::error::DescribeRdsDbInstancesError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_rds_db_instances_error(response)
} else {
crate::operation_deser::parse_describe_rds_db_instances_response(response)
}
}
}
/// Operation shape for `DescribeServiceErrors`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_service_errors`](crate::client::Client::describe_service_errors).
///
/// See [`crate::client::fluent_builders::DescribeServiceErrors`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeServiceErrors {
_private: (),
}
impl DescribeServiceErrors {
/// Creates a new builder-style object to manufacture [`DescribeServiceErrorsInput`](crate::input::DescribeServiceErrorsInput)
pub fn builder() -> crate::input::describe_service_errors_input::Builder {
crate::input::describe_service_errors_input::Builder::default()
}
/// Creates a new `DescribeServiceErrors` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeServiceErrors {
type Output = std::result::Result<
crate::output::DescribeServiceErrorsOutput,
crate::error::DescribeServiceErrorsError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_service_errors_error(response)
} else {
crate::operation_deser::parse_describe_service_errors_response(response)
}
}
}
/// Operation shape for `DescribeStackProvisioningParameters`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_stack_provisioning_parameters`](crate::client::Client::describe_stack_provisioning_parameters).
///
/// See [`crate::client::fluent_builders::DescribeStackProvisioningParameters`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeStackProvisioningParameters {
_private: (),
}
impl DescribeStackProvisioningParameters {
/// Creates a new builder-style object to manufacture [`DescribeStackProvisioningParametersInput`](crate::input::DescribeStackProvisioningParametersInput)
pub fn builder() -> crate::input::describe_stack_provisioning_parameters_input::Builder {
crate::input::describe_stack_provisioning_parameters_input::Builder::default()
}
/// Creates a new `DescribeStackProvisioningParameters` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeStackProvisioningParameters {
type Output = std::result::Result<
crate::output::DescribeStackProvisioningParametersOutput,
crate::error::DescribeStackProvisioningParametersError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_stack_provisioning_parameters_error(response)
} else {
crate::operation_deser::parse_describe_stack_provisioning_parameters_response(response)
}
}
}
/// Operation shape for `DescribeStacks`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_stacks`](crate::client::Client::describe_stacks).
///
/// See [`crate::client::fluent_builders::DescribeStacks`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeStacks {
_private: (),
}
impl DescribeStacks {
/// Creates a new builder-style object to manufacture [`DescribeStacksInput`](crate::input::DescribeStacksInput)
pub fn builder() -> crate::input::describe_stacks_input::Builder {
crate::input::describe_stacks_input::Builder::default()
}
/// Creates a new `DescribeStacks` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeStacks {
type Output =
std::result::Result<crate::output::DescribeStacksOutput, crate::error::DescribeStacksError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_stacks_error(response)
} else {
crate::operation_deser::parse_describe_stacks_response(response)
}
}
}
/// Operation shape for `DescribeStackSummary`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_stack_summary`](crate::client::Client::describe_stack_summary).
///
/// See [`crate::client::fluent_builders::DescribeStackSummary`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeStackSummary {
_private: (),
}
impl DescribeStackSummary {
/// Creates a new builder-style object to manufacture [`DescribeStackSummaryInput`](crate::input::DescribeStackSummaryInput)
pub fn builder() -> crate::input::describe_stack_summary_input::Builder {
crate::input::describe_stack_summary_input::Builder::default()
}
/// Creates a new `DescribeStackSummary` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeStackSummary {
type Output = std::result::Result<
crate::output::DescribeStackSummaryOutput,
crate::error::DescribeStackSummaryError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_stack_summary_error(response)
} else {
crate::operation_deser::parse_describe_stack_summary_response(response)
}
}
}
/// Operation shape for `DescribeTimeBasedAutoScaling`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_time_based_auto_scaling`](crate::client::Client::describe_time_based_auto_scaling).
///
/// See [`crate::client::fluent_builders::DescribeTimeBasedAutoScaling`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeTimeBasedAutoScaling {
_private: (),
}
impl DescribeTimeBasedAutoScaling {
/// Creates a new builder-style object to manufacture [`DescribeTimeBasedAutoScalingInput`](crate::input::DescribeTimeBasedAutoScalingInput)
pub fn builder() -> crate::input::describe_time_based_auto_scaling_input::Builder {
crate::input::describe_time_based_auto_scaling_input::Builder::default()
}
/// Creates a new `DescribeTimeBasedAutoScaling` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeTimeBasedAutoScaling {
type Output = std::result::Result<
crate::output::DescribeTimeBasedAutoScalingOutput,
crate::error::DescribeTimeBasedAutoScalingError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_time_based_auto_scaling_error(response)
} else {
crate::operation_deser::parse_describe_time_based_auto_scaling_response(response)
}
}
}
/// Operation shape for `DescribeUserProfiles`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_user_profiles`](crate::client::Client::describe_user_profiles).
///
/// See [`crate::client::fluent_builders::DescribeUserProfiles`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeUserProfiles {
_private: (),
}
impl DescribeUserProfiles {
/// Creates a new builder-style object to manufacture [`DescribeUserProfilesInput`](crate::input::DescribeUserProfilesInput)
pub fn builder() -> crate::input::describe_user_profiles_input::Builder {
crate::input::describe_user_profiles_input::Builder::default()
}
/// Creates a new `DescribeUserProfiles` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeUserProfiles {
type Output = std::result::Result<
crate::output::DescribeUserProfilesOutput,
crate::error::DescribeUserProfilesError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_user_profiles_error(response)
} else {
crate::operation_deser::parse_describe_user_profiles_response(response)
}
}
}
/// Operation shape for `DescribeVolumes`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`describe_volumes`](crate::client::Client::describe_volumes).
///
/// See [`crate::client::fluent_builders::DescribeVolumes`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DescribeVolumes {
_private: (),
}
impl DescribeVolumes {
/// Creates a new builder-style object to manufacture [`DescribeVolumesInput`](crate::input::DescribeVolumesInput)
pub fn builder() -> crate::input::describe_volumes_input::Builder {
crate::input::describe_volumes_input::Builder::default()
}
/// Creates a new `DescribeVolumes` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DescribeVolumes {
type Output = std::result::Result<
crate::output::DescribeVolumesOutput,
crate::error::DescribeVolumesError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_describe_volumes_error(response)
} else {
crate::operation_deser::parse_describe_volumes_response(response)
}
}
}
/// Operation shape for `DetachElasticLoadBalancer`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`detach_elastic_load_balancer`](crate::client::Client::detach_elastic_load_balancer).
///
/// See [`crate::client::fluent_builders::DetachElasticLoadBalancer`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DetachElasticLoadBalancer {
_private: (),
}
impl DetachElasticLoadBalancer {
/// Creates a new builder-style object to manufacture [`DetachElasticLoadBalancerInput`](crate::input::DetachElasticLoadBalancerInput)
pub fn builder() -> crate::input::detach_elastic_load_balancer_input::Builder {
crate::input::detach_elastic_load_balancer_input::Builder::default()
}
/// Creates a new `DetachElasticLoadBalancer` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DetachElasticLoadBalancer {
type Output = std::result::Result<
crate::output::DetachElasticLoadBalancerOutput,
crate::error::DetachElasticLoadBalancerError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_detach_elastic_load_balancer_error(response)
} else {
crate::operation_deser::parse_detach_elastic_load_balancer_response(response)
}
}
}
/// Operation shape for `DisassociateElasticIp`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`disassociate_elastic_ip`](crate::client::Client::disassociate_elastic_ip).
///
/// See [`crate::client::fluent_builders::DisassociateElasticIp`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct DisassociateElasticIp {
_private: (),
}
impl DisassociateElasticIp {
/// Creates a new builder-style object to manufacture [`DisassociateElasticIpInput`](crate::input::DisassociateElasticIpInput)
pub fn builder() -> crate::input::disassociate_elastic_ip_input::Builder {
crate::input::disassociate_elastic_ip_input::Builder::default()
}
/// Creates a new `DisassociateElasticIp` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for DisassociateElasticIp {
type Output = std::result::Result<
crate::output::DisassociateElasticIpOutput,
crate::error::DisassociateElasticIpError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_disassociate_elastic_ip_error(response)
} else {
crate::operation_deser::parse_disassociate_elastic_ip_response(response)
}
}
}
/// Operation shape for `GetHostnameSuggestion`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`get_hostname_suggestion`](crate::client::Client::get_hostname_suggestion).
///
/// See [`crate::client::fluent_builders::GetHostnameSuggestion`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct GetHostnameSuggestion {
_private: (),
}
impl GetHostnameSuggestion {
/// Creates a new builder-style object to manufacture [`GetHostnameSuggestionInput`](crate::input::GetHostnameSuggestionInput)
pub fn builder() -> crate::input::get_hostname_suggestion_input::Builder {
crate::input::get_hostname_suggestion_input::Builder::default()
}
/// Creates a new `GetHostnameSuggestion` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for GetHostnameSuggestion {
type Output = std::result::Result<
crate::output::GetHostnameSuggestionOutput,
crate::error::GetHostnameSuggestionError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_get_hostname_suggestion_error(response)
} else {
crate::operation_deser::parse_get_hostname_suggestion_response(response)
}
}
}
/// Operation shape for `GrantAccess`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`grant_access`](crate::client::Client::grant_access).
///
/// See [`crate::client::fluent_builders::GrantAccess`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct GrantAccess {
_private: (),
}
impl GrantAccess {
/// Creates a new builder-style object to manufacture [`GrantAccessInput`](crate::input::GrantAccessInput)
pub fn builder() -> crate::input::grant_access_input::Builder {
crate::input::grant_access_input::Builder::default()
}
/// Creates a new `GrantAccess` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for GrantAccess {
type Output =
std::result::Result<crate::output::GrantAccessOutput, crate::error::GrantAccessError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_grant_access_error(response)
} else {
crate::operation_deser::parse_grant_access_response(response)
}
}
}
/// Operation shape for `ListTags`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`list_tags`](crate::client::Client::list_tags).
///
/// See [`crate::client::fluent_builders::ListTags`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct ListTags {
_private: (),
}
impl ListTags {
/// Creates a new builder-style object to manufacture [`ListTagsInput`](crate::input::ListTagsInput)
pub fn builder() -> crate::input::list_tags_input::Builder {
crate::input::list_tags_input::Builder::default()
}
/// Creates a new `ListTags` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for ListTags {
type Output = std::result::Result<crate::output::ListTagsOutput, crate::error::ListTagsError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_list_tags_error(response)
} else {
crate::operation_deser::parse_list_tags_response(response)
}
}
}
/// Operation shape for `RebootInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`reboot_instance`](crate::client::Client::reboot_instance).
///
/// See [`crate::client::fluent_builders::RebootInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct RebootInstance {
_private: (),
}
impl RebootInstance {
/// Creates a new builder-style object to manufacture [`RebootInstanceInput`](crate::input::RebootInstanceInput)
pub fn builder() -> crate::input::reboot_instance_input::Builder {
crate::input::reboot_instance_input::Builder::default()
}
/// Creates a new `RebootInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for RebootInstance {
type Output =
std::result::Result<crate::output::RebootInstanceOutput, crate::error::RebootInstanceError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_reboot_instance_error(response)
} else {
crate::operation_deser::parse_reboot_instance_response(response)
}
}
}
/// Operation shape for `RegisterEcsCluster`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`register_ecs_cluster`](crate::client::Client::register_ecs_cluster).
///
/// See [`crate::client::fluent_builders::RegisterEcsCluster`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct RegisterEcsCluster {
_private: (),
}
impl RegisterEcsCluster {
/// Creates a new builder-style object to manufacture [`RegisterEcsClusterInput`](crate::input::RegisterEcsClusterInput)
pub fn builder() -> crate::input::register_ecs_cluster_input::Builder {
crate::input::register_ecs_cluster_input::Builder::default()
}
/// Creates a new `RegisterEcsCluster` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for RegisterEcsCluster {
type Output = std::result::Result<
crate::output::RegisterEcsClusterOutput,
crate::error::RegisterEcsClusterError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_register_ecs_cluster_error(response)
} else {
crate::operation_deser::parse_register_ecs_cluster_response(response)
}
}
}
/// Operation shape for `RegisterElasticIp`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`register_elastic_ip`](crate::client::Client::register_elastic_ip).
///
/// See [`crate::client::fluent_builders::RegisterElasticIp`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct RegisterElasticIp {
_private: (),
}
impl RegisterElasticIp {
/// Creates a new builder-style object to manufacture [`RegisterElasticIpInput`](crate::input::RegisterElasticIpInput)
pub fn builder() -> crate::input::register_elastic_ip_input::Builder {
crate::input::register_elastic_ip_input::Builder::default()
}
/// Creates a new `RegisterElasticIp` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for RegisterElasticIp {
type Output = std::result::Result<
crate::output::RegisterElasticIpOutput,
crate::error::RegisterElasticIpError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_register_elastic_ip_error(response)
} else {
crate::operation_deser::parse_register_elastic_ip_response(response)
}
}
}
/// Operation shape for `RegisterInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`register_instance`](crate::client::Client::register_instance).
///
/// See [`crate::client::fluent_builders::RegisterInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct RegisterInstance {
_private: (),
}
impl RegisterInstance {
/// Creates a new builder-style object to manufacture [`RegisterInstanceInput`](crate::input::RegisterInstanceInput)
pub fn builder() -> crate::input::register_instance_input::Builder {
crate::input::register_instance_input::Builder::default()
}
/// Creates a new `RegisterInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for RegisterInstance {
type Output = std::result::Result<
crate::output::RegisterInstanceOutput,
crate::error::RegisterInstanceError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_register_instance_error(response)
} else {
crate::operation_deser::parse_register_instance_response(response)
}
}
}
/// Operation shape for `RegisterRdsDbInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`register_rds_db_instance`](crate::client::Client::register_rds_db_instance).
///
/// See [`crate::client::fluent_builders::RegisterRdsDbInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct RegisterRdsDbInstance {
_private: (),
}
impl RegisterRdsDbInstance {
/// Creates a new builder-style object to manufacture [`RegisterRdsDbInstanceInput`](crate::input::RegisterRdsDbInstanceInput)
pub fn builder() -> crate::input::register_rds_db_instance_input::Builder {
crate::input::register_rds_db_instance_input::Builder::default()
}
/// Creates a new `RegisterRdsDbInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for RegisterRdsDbInstance {
type Output = std::result::Result<
crate::output::RegisterRdsDbInstanceOutput,
crate::error::RegisterRdsDbInstanceError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_register_rds_db_instance_error(response)
} else {
crate::operation_deser::parse_register_rds_db_instance_response(response)
}
}
}
/// Operation shape for `RegisterVolume`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`register_volume`](crate::client::Client::register_volume).
///
/// See [`crate::client::fluent_builders::RegisterVolume`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct RegisterVolume {
_private: (),
}
impl RegisterVolume {
/// Creates a new builder-style object to manufacture [`RegisterVolumeInput`](crate::input::RegisterVolumeInput)
pub fn builder() -> crate::input::register_volume_input::Builder {
crate::input::register_volume_input::Builder::default()
}
/// Creates a new `RegisterVolume` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for RegisterVolume {
type Output =
std::result::Result<crate::output::RegisterVolumeOutput, crate::error::RegisterVolumeError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_register_volume_error(response)
} else {
crate::operation_deser::parse_register_volume_response(response)
}
}
}
/// Operation shape for `SetLoadBasedAutoScaling`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`set_load_based_auto_scaling`](crate::client::Client::set_load_based_auto_scaling).
///
/// See [`crate::client::fluent_builders::SetLoadBasedAutoScaling`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct SetLoadBasedAutoScaling {
_private: (),
}
impl SetLoadBasedAutoScaling {
/// Creates a new builder-style object to manufacture [`SetLoadBasedAutoScalingInput`](crate::input::SetLoadBasedAutoScalingInput)
pub fn builder() -> crate::input::set_load_based_auto_scaling_input::Builder {
crate::input::set_load_based_auto_scaling_input::Builder::default()
}
/// Creates a new `SetLoadBasedAutoScaling` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for SetLoadBasedAutoScaling {
type Output = std::result::Result<
crate::output::SetLoadBasedAutoScalingOutput,
crate::error::SetLoadBasedAutoScalingError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_set_load_based_auto_scaling_error(response)
} else {
crate::operation_deser::parse_set_load_based_auto_scaling_response(response)
}
}
}
/// Operation shape for `SetPermission`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`set_permission`](crate::client::Client::set_permission).
///
/// See [`crate::client::fluent_builders::SetPermission`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct SetPermission {
_private: (),
}
impl SetPermission {
/// Creates a new builder-style object to manufacture [`SetPermissionInput`](crate::input::SetPermissionInput)
pub fn builder() -> crate::input::set_permission_input::Builder {
crate::input::set_permission_input::Builder::default()
}
/// Creates a new `SetPermission` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for SetPermission {
type Output =
std::result::Result<crate::output::SetPermissionOutput, crate::error::SetPermissionError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_set_permission_error(response)
} else {
crate::operation_deser::parse_set_permission_response(response)
}
}
}
/// Operation shape for `SetTimeBasedAutoScaling`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`set_time_based_auto_scaling`](crate::client::Client::set_time_based_auto_scaling).
///
/// See [`crate::client::fluent_builders::SetTimeBasedAutoScaling`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct SetTimeBasedAutoScaling {
_private: (),
}
impl SetTimeBasedAutoScaling {
/// Creates a new builder-style object to manufacture [`SetTimeBasedAutoScalingInput`](crate::input::SetTimeBasedAutoScalingInput)
pub fn builder() -> crate::input::set_time_based_auto_scaling_input::Builder {
crate::input::set_time_based_auto_scaling_input::Builder::default()
}
/// Creates a new `SetTimeBasedAutoScaling` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for SetTimeBasedAutoScaling {
type Output = std::result::Result<
crate::output::SetTimeBasedAutoScalingOutput,
crate::error::SetTimeBasedAutoScalingError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_set_time_based_auto_scaling_error(response)
} else {
crate::operation_deser::parse_set_time_based_auto_scaling_response(response)
}
}
}
/// Operation shape for `StartInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`start_instance`](crate::client::Client::start_instance).
///
/// See [`crate::client::fluent_builders::StartInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct StartInstance {
_private: (),
}
impl StartInstance {
/// Creates a new builder-style object to manufacture [`StartInstanceInput`](crate::input::StartInstanceInput)
pub fn builder() -> crate::input::start_instance_input::Builder {
crate::input::start_instance_input::Builder::default()
}
/// Creates a new `StartInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for StartInstance {
type Output =
std::result::Result<crate::output::StartInstanceOutput, crate::error::StartInstanceError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_start_instance_error(response)
} else {
crate::operation_deser::parse_start_instance_response(response)
}
}
}
/// Operation shape for `StartStack`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`start_stack`](crate::client::Client::start_stack).
///
/// See [`crate::client::fluent_builders::StartStack`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct StartStack {
_private: (),
}
impl StartStack {
/// Creates a new builder-style object to manufacture [`StartStackInput`](crate::input::StartStackInput)
pub fn builder() -> crate::input::start_stack_input::Builder {
crate::input::start_stack_input::Builder::default()
}
/// Creates a new `StartStack` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for StartStack {
type Output =
std::result::Result<crate::output::StartStackOutput, crate::error::StartStackError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_start_stack_error(response)
} else {
crate::operation_deser::parse_start_stack_response(response)
}
}
}
/// Operation shape for `StopInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`stop_instance`](crate::client::Client::stop_instance).
///
/// See [`crate::client::fluent_builders::StopInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct StopInstance {
_private: (),
}
impl StopInstance {
/// Creates a new builder-style object to manufacture [`StopInstanceInput`](crate::input::StopInstanceInput)
pub fn builder() -> crate::input::stop_instance_input::Builder {
crate::input::stop_instance_input::Builder::default()
}
/// Creates a new `StopInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for StopInstance {
type Output =
std::result::Result<crate::output::StopInstanceOutput, crate::error::StopInstanceError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_stop_instance_error(response)
} else {
crate::operation_deser::parse_stop_instance_response(response)
}
}
}
/// Operation shape for `StopStack`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`stop_stack`](crate::client::Client::stop_stack).
///
/// See [`crate::client::fluent_builders::StopStack`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct StopStack {
_private: (),
}
impl StopStack {
/// Creates a new builder-style object to manufacture [`StopStackInput`](crate::input::StopStackInput)
pub fn builder() -> crate::input::stop_stack_input::Builder {
crate::input::stop_stack_input::Builder::default()
}
/// Creates a new `StopStack` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for StopStack {
type Output = std::result::Result<crate::output::StopStackOutput, crate::error::StopStackError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_stop_stack_error(response)
} else {
crate::operation_deser::parse_stop_stack_response(response)
}
}
}
/// Operation shape for `TagResource`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`tag_resource`](crate::client::Client::tag_resource).
///
/// See [`crate::client::fluent_builders::TagResource`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct TagResource {
_private: (),
}
impl TagResource {
/// Creates a new builder-style object to manufacture [`TagResourceInput`](crate::input::TagResourceInput)
pub fn builder() -> crate::input::tag_resource_input::Builder {
crate::input::tag_resource_input::Builder::default()
}
/// Creates a new `TagResource` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for TagResource {
type Output =
std::result::Result<crate::output::TagResourceOutput, crate::error::TagResourceError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_tag_resource_error(response)
} else {
crate::operation_deser::parse_tag_resource_response(response)
}
}
}
/// Operation shape for `UnassignInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`unassign_instance`](crate::client::Client::unassign_instance).
///
/// See [`crate::client::fluent_builders::UnassignInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct UnassignInstance {
_private: (),
}
impl UnassignInstance {
/// Creates a new builder-style object to manufacture [`UnassignInstanceInput`](crate::input::UnassignInstanceInput)
pub fn builder() -> crate::input::unassign_instance_input::Builder {
crate::input::unassign_instance_input::Builder::default()
}
/// Creates a new `UnassignInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for UnassignInstance {
type Output = std::result::Result<
crate::output::UnassignInstanceOutput,
crate::error::UnassignInstanceError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_unassign_instance_error(response)
} else {
crate::operation_deser::parse_unassign_instance_response(response)
}
}
}
/// Operation shape for `UnassignVolume`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`unassign_volume`](crate::client::Client::unassign_volume).
///
/// See [`crate::client::fluent_builders::UnassignVolume`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct UnassignVolume {
_private: (),
}
impl UnassignVolume {
/// Creates a new builder-style object to manufacture [`UnassignVolumeInput`](crate::input::UnassignVolumeInput)
pub fn builder() -> crate::input::unassign_volume_input::Builder {
crate::input::unassign_volume_input::Builder::default()
}
/// Creates a new `UnassignVolume` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for UnassignVolume {
type Output =
std::result::Result<crate::output::UnassignVolumeOutput, crate::error::UnassignVolumeError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_unassign_volume_error(response)
} else {
crate::operation_deser::parse_unassign_volume_response(response)
}
}
}
/// Operation shape for `UntagResource`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`untag_resource`](crate::client::Client::untag_resource).
///
/// See [`crate::client::fluent_builders::UntagResource`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct UntagResource {
_private: (),
}
impl UntagResource {
/// Creates a new builder-style object to manufacture [`UntagResourceInput`](crate::input::UntagResourceInput)
pub fn builder() -> crate::input::untag_resource_input::Builder {
crate::input::untag_resource_input::Builder::default()
}
/// Creates a new `UntagResource` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for UntagResource {
type Output =
std::result::Result<crate::output::UntagResourceOutput, crate::error::UntagResourceError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_untag_resource_error(response)
} else {
crate::operation_deser::parse_untag_resource_response(response)
}
}
}
/// Operation shape for `UpdateApp`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`update_app`](crate::client::Client::update_app).
///
/// See [`crate::client::fluent_builders::UpdateApp`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct UpdateApp {
_private: (),
}
impl UpdateApp {
/// Creates a new builder-style object to manufacture [`UpdateAppInput`](crate::input::UpdateAppInput)
pub fn builder() -> crate::input::update_app_input::Builder {
crate::input::update_app_input::Builder::default()
}
/// Creates a new `UpdateApp` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for UpdateApp {
type Output = std::result::Result<crate::output::UpdateAppOutput, crate::error::UpdateAppError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_update_app_error(response)
} else {
crate::operation_deser::parse_update_app_response(response)
}
}
}
/// Operation shape for `UpdateElasticIp`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`update_elastic_ip`](crate::client::Client::update_elastic_ip).
///
/// See [`crate::client::fluent_builders::UpdateElasticIp`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct UpdateElasticIp {
_private: (),
}
impl UpdateElasticIp {
/// Creates a new builder-style object to manufacture [`UpdateElasticIpInput`](crate::input::UpdateElasticIpInput)
pub fn builder() -> crate::input::update_elastic_ip_input::Builder {
crate::input::update_elastic_ip_input::Builder::default()
}
/// Creates a new `UpdateElasticIp` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for UpdateElasticIp {
type Output = std::result::Result<
crate::output::UpdateElasticIpOutput,
crate::error::UpdateElasticIpError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_update_elastic_ip_error(response)
} else {
crate::operation_deser::parse_update_elastic_ip_response(response)
}
}
}
/// Operation shape for `UpdateInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`update_instance`](crate::client::Client::update_instance).
///
/// See [`crate::client::fluent_builders::UpdateInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct UpdateInstance {
_private: (),
}
impl UpdateInstance {
/// Creates a new builder-style object to manufacture [`UpdateInstanceInput`](crate::input::UpdateInstanceInput)
pub fn builder() -> crate::input::update_instance_input::Builder {
crate::input::update_instance_input::Builder::default()
}
/// Creates a new `UpdateInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for UpdateInstance {
type Output =
std::result::Result<crate::output::UpdateInstanceOutput, crate::error::UpdateInstanceError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_update_instance_error(response)
} else {
crate::operation_deser::parse_update_instance_response(response)
}
}
}
/// Operation shape for `UpdateLayer`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`update_layer`](crate::client::Client::update_layer).
///
/// See [`crate::client::fluent_builders::UpdateLayer`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct UpdateLayer {
_private: (),
}
impl UpdateLayer {
/// Creates a new builder-style object to manufacture [`UpdateLayerInput`](crate::input::UpdateLayerInput)
pub fn builder() -> crate::input::update_layer_input::Builder {
crate::input::update_layer_input::Builder::default()
}
/// Creates a new `UpdateLayer` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for UpdateLayer {
type Output =
std::result::Result<crate::output::UpdateLayerOutput, crate::error::UpdateLayerError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_update_layer_error(response)
} else {
crate::operation_deser::parse_update_layer_response(response)
}
}
}
/// Operation shape for `UpdateMyUserProfile`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`update_my_user_profile`](crate::client::Client::update_my_user_profile).
///
/// See [`crate::client::fluent_builders::UpdateMyUserProfile`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct UpdateMyUserProfile {
_private: (),
}
impl UpdateMyUserProfile {
/// Creates a new builder-style object to manufacture [`UpdateMyUserProfileInput`](crate::input::UpdateMyUserProfileInput)
pub fn builder() -> crate::input::update_my_user_profile_input::Builder {
crate::input::update_my_user_profile_input::Builder::default()
}
/// Creates a new `UpdateMyUserProfile` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for UpdateMyUserProfile {
type Output = std::result::Result<
crate::output::UpdateMyUserProfileOutput,
crate::error::UpdateMyUserProfileError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_update_my_user_profile_error(response)
} else {
crate::operation_deser::parse_update_my_user_profile_response(response)
}
}
}
/// Operation shape for `UpdateRdsDbInstance`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`update_rds_db_instance`](crate::client::Client::update_rds_db_instance).
///
/// See [`crate::client::fluent_builders::UpdateRdsDbInstance`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct UpdateRdsDbInstance {
_private: (),
}
impl UpdateRdsDbInstance {
/// Creates a new builder-style object to manufacture [`UpdateRdsDbInstanceInput`](crate::input::UpdateRdsDbInstanceInput)
pub fn builder() -> crate::input::update_rds_db_instance_input::Builder {
crate::input::update_rds_db_instance_input::Builder::default()
}
/// Creates a new `UpdateRdsDbInstance` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for UpdateRdsDbInstance {
type Output = std::result::Result<
crate::output::UpdateRdsDbInstanceOutput,
crate::error::UpdateRdsDbInstanceError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_update_rds_db_instance_error(response)
} else {
crate::operation_deser::parse_update_rds_db_instance_response(response)
}
}
}
/// Operation shape for `UpdateStack`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`update_stack`](crate::client::Client::update_stack).
///
/// See [`crate::client::fluent_builders::UpdateStack`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct UpdateStack {
_private: (),
}
impl UpdateStack {
/// Creates a new builder-style object to manufacture [`UpdateStackInput`](crate::input::UpdateStackInput)
pub fn builder() -> crate::input::update_stack_input::Builder {
crate::input::update_stack_input::Builder::default()
}
/// Creates a new `UpdateStack` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for UpdateStack {
type Output =
std::result::Result<crate::output::UpdateStackOutput, crate::error::UpdateStackError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_update_stack_error(response)
} else {
crate::operation_deser::parse_update_stack_response(response)
}
}
}
/// Operation shape for `UpdateUserProfile`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`update_user_profile`](crate::client::Client::update_user_profile).
///
/// See [`crate::client::fluent_builders::UpdateUserProfile`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct UpdateUserProfile {
_private: (),
}
impl UpdateUserProfile {
/// Creates a new builder-style object to manufacture [`UpdateUserProfileInput`](crate::input::UpdateUserProfileInput)
pub fn builder() -> crate::input::update_user_profile_input::Builder {
crate::input::update_user_profile_input::Builder::default()
}
/// Creates a new `UpdateUserProfile` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for UpdateUserProfile {
type Output = std::result::Result<
crate::output::UpdateUserProfileOutput,
crate::error::UpdateUserProfileError,
>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_update_user_profile_error(response)
} else {
crate::operation_deser::parse_update_user_profile_response(response)
}
}
}
/// Operation shape for `UpdateVolume`.
///
/// This is usually constructed for you using the the fluent builder returned by
/// [`update_volume`](crate::client::Client::update_volume).
///
/// See [`crate::client::fluent_builders::UpdateVolume`] for more details about the operation.
#[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)]
pub struct UpdateVolume {
_private: (),
}
impl UpdateVolume {
/// Creates a new builder-style object to manufacture [`UpdateVolumeInput`](crate::input::UpdateVolumeInput)
pub fn builder() -> crate::input::update_volume_input::Builder {
crate::input::update_volume_input::Builder::default()
}
/// Creates a new `UpdateVolume` operation.
pub fn new() -> Self {
Self { _private: () }
}
}
impl aws_smithy_http::response::ParseStrictResponse for UpdateVolume {
type Output =
std::result::Result<crate::output::UpdateVolumeOutput, crate::error::UpdateVolumeError>;
fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_update_volume_error(response)
} else {
crate::operation_deser::parse_update_volume_response(response)
}
}
}
| 42.322041 | 158 | 0.69069 |
4ba59788896d875a9b5a07d4f34c0e48bdb3a216 | 105 | pub mod constant;
pub mod error;
pub mod http;
pub mod tile;
#[cfg(feature = "layers")]
pub mod layers;
| 13.125 | 26 | 0.695238 |
0ee149e5aeb8530c4c4bb020ac3792ab3d9001b8 | 4,923 | use crate::error;
use crate::r#mut::Mut;
use crate::sparse_set::SparseSet;
use crate::storage::EntityId;
use crate::view::{View, ViewMut};
use core::any::type_name;
/// Retrives components based on their type and entity id.
pub trait Get {
type Out;
type FastOut;
/// Retrieve components of `entity`.
///
/// Multiple components can be queried at the same time using a tuple.
///
/// ### Example:
/// ```
/// use shipyard::{EntitiesViewMut, Get, ViewMut, World};
///
/// let world = World::new();
///
/// world.run(
/// |mut entities: EntitiesViewMut, mut usizes: ViewMut<usize>, mut u32s: ViewMut<u32>| {
/// let entity = entities.add_entity((&mut usizes, &mut u32s), (0usize, 1u32));
/// assert_eq!((&usizes, &u32s).get(entity), Ok((&0, &1)));
/// },
/// );
/// ```
fn get(self, entity: EntityId) -> Result<Self::Out, error::MissingComponent>;
fn fast_get(self, entity: EntityId) -> Result<Self::FastOut, error::MissingComponent>;
}
impl<'a: 'b, 'b, T: 'static> Get for &'b View<'a, T> {
type Out = &'b T;
type FastOut = &'b T;
#[inline]
fn get(self, entity: EntityId) -> Result<Self::Out, error::MissingComponent> {
(**self)
.private_get(entity)
.ok_or_else(|| error::MissingComponent {
id: entity,
name: type_name::<T>(),
})
}
#[inline]
fn fast_get(self, entity: EntityId) -> Result<Self::FastOut, error::MissingComponent> {
(**self)
.private_get(entity)
.ok_or_else(|| error::MissingComponent {
id: entity,
name: type_name::<T>(),
})
}
}
impl<'a: 'b, 'b, T: 'static> Get for &'b ViewMut<'a, T> {
type Out = &'b T;
type FastOut = &'b T;
#[inline]
fn get(self, entity: EntityId) -> Result<Self::Out, error::MissingComponent> {
(**self)
.private_get(entity)
.ok_or_else(|| error::MissingComponent {
id: entity,
name: type_name::<T>(),
})
}
#[inline]
fn fast_get(self, entity: EntityId) -> Result<Self::FastOut, error::MissingComponent> {
(**self)
.private_get(entity)
.ok_or_else(|| error::MissingComponent {
id: entity,
name: type_name::<T>(),
})
}
}
impl<'a: 'b, 'b, T: 'static> Get for &'b mut ViewMut<'a, T> {
type Out = Mut<'b, T>;
type FastOut = &'b mut T;
#[inline]
fn get(self, entity: EntityId) -> Result<Self::Out, error::MissingComponent> {
let index = self
.index_of(entity)
.ok_or_else(|| error::MissingComponent {
id: entity,
name: type_name::<T>(),
})?;
if self.metadata.update.is_some() {
let SparseSet {
sparse: _,
dense,
data,
metadata: _,
} = &mut **self;
let entity = unsafe { dense.get_unchecked_mut(index) };
Ok(Mut {
flag: if !entity.is_inserted() {
Some(entity)
} else {
None
},
data: unsafe { data.get_unchecked_mut(index) },
})
} else {
Ok(Mut {
flag: None,
data: unsafe { self.data.get_unchecked_mut(index) },
})
}
}
#[inline]
fn fast_get(self, entity: EntityId) -> Result<Self::FastOut, error::MissingComponent> {
self.private_get_mut(entity)
.ok_or_else(|| error::MissingComponent {
id: entity,
name: type_name::<T>(),
})
}
}
macro_rules! impl_get_component {
($(($type: ident, $index: tt))+) => {
impl<$($type: Get),+> Get for ($($type,)+) {
type Out = ($($type::Out,)+);
type FastOut = ($($type::FastOut,)+);
#[inline]
fn get(self, entity: EntityId) -> Result<Self::Out, error::MissingComponent> {
Ok(($(self.$index.get(entity)?,)+))
}
#[inline]
fn fast_get(self, entity: EntityId) -> Result<Self::FastOut, error::MissingComponent> {
Ok(($(self.$index.fast_get(entity)?,)+))
}
}
}
}
macro_rules! get_component {
($(($type: ident, $index: tt))+; ($type1: ident, $index1: tt) $(($queue_type: ident, $queue_index: tt))*) => {
impl_get_component![$(($type, $index))*];
get_component![$(($type, $index))* ($type1, $index1); $(($queue_type, $queue_index))*];
};
($(($type: ident, $index: tt))+;) => {
impl_get_component![$(($type, $index))*];
}
}
get_component![(A, 0); (B, 1) (C, 2) (D, 3) (E, 4) (F, 5) (G, 6) (H, 7) (I, 8) (J, 9)];
| 31.356688 | 114 | 0.490555 |
622714a3fbb087c720c37ebf6088f7481ece0d62 | 169,869 | use std::collections::HashMap;
use std::cell::RefCell;
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 {
/// View your basic profile info, including your age range and language
Login,
/// Associate you with your personal info on Google
Me,
/// View your email address
UserinfoEmail,
/// See your personal info, including any personal info you've made publicly available
UserinfoProfile,
}
impl AsRef<str> for Scope {
fn as_ref(&self) -> &str {
match *self {
Scope::Login => "https://www.googleapis.com/auth/plus.login",
Scope::Me => "https://www.googleapis.com/auth/plus.me",
Scope::UserinfoEmail => "https://www.googleapis.com/auth/userinfo.email",
Scope::UserinfoProfile => "https://www.googleapis.com/auth/userinfo.profile",
}
}
}
impl Default for Scope {
fn default() -> Scope {
Scope::Me
}
}
// ########
// HUB ###
// ######
/// Central instance to access all Plus related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_plus1 as plus1;
/// use plus1::{Result, Error};
/// # async fn dox() {
/// use std::default::Default;
/// use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// // 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 = oauth2::InstalledFlowAuthenticator::builder(
/// secret,
/// oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// ).build().await.unwrap();
/// let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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.people().list("userId", "collection")
/// .page_token("ipsum")
/// .order_by("gubergren")
/// .max_results(50)
/// .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),
/// }
/// # }
/// ```
#[derive(Clone)]
pub struct Plus<> {
pub client: hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>,
pub auth: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>,
_user_agent: String,
_base_url: String,
_root_url: String,
}
impl<'a, > client::Hub for Plus<> {}
impl<'a, > Plus<> {
pub fn new(client: hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>, authenticator: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>) -> Plus<> {
Plus {
client,
auth: authenticator,
_user_agent: "google-api-rust-client/3.1.0".to_string(),
_base_url: "https://www.googleapis.com/plus/v1/".to_string(),
_root_url: "https://www.googleapis.com/".to_string(),
}
}
pub fn activities(&'a self) -> ActivityMethods<'a> {
ActivityMethods { hub: &self }
}
pub fn comments(&'a self) -> CommentMethods<'a> {
CommentMethods { hub: &self }
}
pub fn people(&'a self) -> PeopleMethods<'a> {
PeopleMethods { hub: &self }
}
/// Set the user-agent header field to use in all requests to the server.
/// It defaults to `google-api-rust-client/3.1.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://www.googleapis.com/plus/v1/`.
///
/// 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://www.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.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Acl {
/// Description of the access granted, suitable for display.
pub description: Option<String>,
/// The list of access entries.
pub items: Option<Vec<PlusAclentryResource>>,
/// Identifies this resource as a collection of access controls. Value: "plus#acl".
pub kind: Option<String>,
}
impl client::Part for Acl {}
/// 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 activities](ActivityGetCall) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Activity {
/// Identifies who has access to see this activity.
pub access: Option<Acl>,
/// The person who performed this activity.
pub actor: Option<ActivityActor>,
/// Street address where this activity occurred.
pub address: Option<String>,
/// Additional content added by the person who shared this activity, applicable only when resharing an activity.
pub annotation: Option<String>,
/// If this activity is a crosspost from another system, this property specifies the ID of the original activity.
#[serde(rename="crosspostSource")]
pub crosspost_source: Option<String>,
/// ETag of this response for caching purposes.
pub etag: Option<String>,
/// Latitude and longitude where this activity occurred. Format is latitude followed by longitude, space separated.
pub geocode: Option<String>,
/// The ID of this activity.
pub id: Option<String>,
/// Identifies this resource as an activity. Value: "plus#activity".
pub kind: Option<String>,
/// The location where this activity occurred.
pub location: Option<Place>,
/// The object of this activity.
pub object: Option<ActivityObject>,
/// ID of the place where this activity occurred.
#[serde(rename="placeId")]
pub place_id: Option<String>,
/// Name of the place where this activity occurred.
#[serde(rename="placeName")]
pub place_name: Option<String>,
/// The service provider that initially published this activity.
pub provider: Option<ActivityProvider>,
/// The time at which this activity was initially published. Formatted as an RFC 3339 timestamp.
pub published: Option<String>,
/// Radius, in meters, of the region where this activity occurred, centered at the latitude and longitude identified in geocode.
pub radius: Option<String>,
/// Title of this activity.
pub title: Option<String>,
/// The time at which this activity was last updated. Formatted as an RFC 3339 timestamp.
pub updated: Option<String>,
/// The link to this activity.
pub url: Option<String>,
/// This activity's verb, which indicates the action that was performed. Possible values include, but are not limited to, the following values:
/// - "post" - Publish content to the stream.
/// - "share" - Reshare an activity.
pub verb: Option<String>,
}
impl client::ResponseResult for Activity {}
/// 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 activities](ActivityListCall) (response)
/// * [search activities](ActivitySearchCall) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityFeed {
/// ETag of this response for caching purposes.
pub etag: Option<String>,
/// The ID of this collection of activities. Deprecated.
pub id: Option<String>,
/// The activities in this page of results.
pub items: Option<Vec<Activity>>,
/// Identifies this resource as a collection of activities. Value: "plus#activityFeed".
pub kind: Option<String>,
/// Link to the next page of activities.
#[serde(rename="nextLink")]
pub next_link: Option<String>,
/// The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// Link to this activity resource.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
/// The title of this collection of activities, which is a truncated portion of the content.
pub title: Option<String>,
/// The time at which this collection of activities was last updated. Formatted as an RFC 3339 timestamp.
pub updated: Option<String>,
}
impl client::ResponseResult for ActivityFeed {}
/// 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 comments](CommentGetCall) (response)
/// * [list comments](CommentListCall) (none)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Comment {
/// The person who posted this comment.
pub actor: Option<CommentActor>,
/// ETag of this response for caching purposes.
pub etag: Option<String>,
/// The ID of this comment.
pub id: Option<String>,
/// The activity this comment replied to.
#[serde(rename="inReplyTo")]
pub in_reply_to: Option<Vec<CommentInReplyTo>>,
/// Identifies this resource as a comment. Value: "plus#comment".
pub kind: Option<String>,
/// The object of this comment.
pub object: Option<CommentObject>,
/// People who +1'd this comment.
pub plusoners: Option<CommentPlusoners>,
/// The time at which this comment was initially published. Formatted as an RFC 3339 timestamp.
pub published: Option<String>,
/// Link to this comment resource.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
/// The time at which this comment was last updated. Formatted as an RFC 3339 timestamp.
pub updated: Option<String>,
/// This comment's verb, indicating what action was performed. Possible values are:
/// - "post" - Publish content to the stream.
pub verb: Option<String>,
}
impl client::Resource for Comment {}
impl client::ResponseResult for Comment {}
/// 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 comments](CommentListCall) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentFeed {
/// ETag of this response for caching purposes.
pub etag: Option<String>,
/// The ID of this collection of comments.
pub id: Option<String>,
/// The comments in this page of results.
pub items: Option<Vec<Comment>>,
/// Identifies this resource as a collection of comments. Value: "plus#commentFeed".
pub kind: Option<String>,
/// Link to the next page of activities.
#[serde(rename="nextLink")]
pub next_link: Option<String>,
/// The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// The title of this collection of comments.
pub title: Option<String>,
/// The time at which this collection of comments was last updated. Formatted as an RFC 3339 timestamp.
pub updated: Option<String>,
}
impl client::ResponseResult for CommentFeed {}
/// 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 people](PeopleListCall) (response)
/// * [list by activity people](PeopleListByActivityCall) (response)
/// * [search people](PeopleSearchCall) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PeopleFeed {
/// ETag of this response for caching purposes.
pub etag: Option<String>,
/// The people in this page of results. Each item includes the id, displayName, image, and url for the person. To retrieve additional profile data, see the people.get method.
pub items: Option<Vec<Person>>,
/// Identifies this resource as a collection of people. Value: "plus#peopleFeed".
pub kind: Option<String>,
/// The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// Link to this resource.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
/// The title of this collection of people.
pub title: Option<String>,
/// The total number of people available in this list. The number of people in a response might be smaller due to paging. This might not be set for all collections.
#[serde(rename="totalItems")]
pub total_items: Option<i32>,
}
impl client::ResponseResult for PeopleFeed {}
/// 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 people](PeopleGetCall) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Person {
/// A short biography for this person.
#[serde(rename="aboutMe")]
pub about_me: Option<String>,
/// The age range of the person. Valid ranges are 17 or younger, 18 to 20, and 21 or older. Age is determined from the user's birthday using Western age reckoning.
#[serde(rename="ageRange")]
pub age_range: Option<PersonAgeRange>,
/// The person's date of birth, represented as YYYY-MM-DD.
pub birthday: Option<String>,
/// The "bragging rights" line of this person.
#[serde(rename="braggingRights")]
pub bragging_rights: Option<String>,
/// For followers who are visible, the number of people who have added this person or page to a circle.
#[serde(rename="circledByCount")]
pub circled_by_count: Option<i32>,
/// The cover photo content.
pub cover: Option<PersonCover>,
/// (this field is not currently used)
#[serde(rename="currentLocation")]
pub current_location: Option<String>,
/// The name of this person, which is suitable for display.
#[serde(rename="displayName")]
pub display_name: Option<String>,
/// The hosted domain name for the user's Google Apps account. For instance, example.com. The plus.profile.emails.read or email scope is needed to get this domain name.
pub domain: Option<String>,
/// A list of email addresses that this person has, including their Google account email address, and the public verified email addresses on their Google+ profile. The plus.profile.emails.read scope is needed to retrieve these email addresses, or the email scope can be used to retrieve just the Google account email address.
pub emails: Option<Vec<PersonEmails>>,
/// ETag of this response for caching purposes.
pub etag: Option<String>,
/// The person's gender. Possible values include, but are not limited to, the following values:
/// - "male" - Male gender.
/// - "female" - Female gender.
/// - "other" - Other.
pub gender: Option<String>,
/// The ID of this person.
pub id: Option<String>,
/// The representation of the person's profile photo.
pub image: Option<PersonImage>,
/// Whether this user has signed up for Google+.
#[serde(rename="isPlusUser")]
pub is_plus_user: Option<bool>,
/// Identifies this resource as a person. Value: "plus#person".
pub kind: Option<String>,
/// The user's preferred language for rendering.
pub language: Option<String>,
/// An object representation of the individual components of a person's name.
pub name: Option<PersonName>,
/// The nickname of this person.
pub nickname: Option<String>,
/// Type of person within Google+. Possible values include, but are not limited to, the following values:
/// - "person" - represents an actual person.
/// - "page" - represents a page.
#[serde(rename="objectType")]
pub object_type: Option<String>,
/// The occupation of this person.
pub occupation: Option<String>,
/// A list of current or past organizations with which this person is associated.
pub organizations: Option<Vec<PersonOrganizations>>,
/// A list of places where this person has lived.
#[serde(rename="placesLived")]
pub places_lived: Option<Vec<PersonPlacesLived>>,
/// If a Google+ Page, the number of people who have +1'd this page.
#[serde(rename="plusOneCount")]
pub plus_one_count: Option<i32>,
/// The person's relationship status. Possible values include, but are not limited to, the following values:
/// - "single" - Person is single.
/// - "in_a_relationship" - Person is in a relationship.
/// - "engaged" - Person is engaged.
/// - "married" - Person is married.
/// - "its_complicated" - The relationship is complicated.
/// - "open_relationship" - Person is in an open relationship.
/// - "widowed" - Person is widowed.
/// - "in_domestic_partnership" - Person is in a domestic partnership.
/// - "in_civil_union" - Person is in a civil union.
#[serde(rename="relationshipStatus")]
pub relationship_status: Option<String>,
/// The person's skills.
pub skills: Option<String>,
/// The brief description (tagline) of this person.
pub tagline: Option<String>,
/// The URL of this person's profile.
pub url: Option<String>,
/// A list of URLs for this person.
pub urls: Option<Vec<PersonUrls>>,
/// Whether the person or Google+ Page has been verified.
pub verified: Option<bool>,
}
impl client::ResponseResult for Person {}
/// There is no detailed description.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Place {
/// The physical address of the place.
pub address: Option<PlaceAddress>,
/// The display name of the place.
#[serde(rename="displayName")]
pub display_name: Option<String>,
/// The id of the place.
pub id: Option<String>,
/// Identifies this resource as a place. Value: "plus#place".
pub kind: Option<String>,
/// The position of the place.
pub position: Option<PlacePosition>,
}
impl client::Part for Place {}
/// There is no detailed description.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlusAclentryResource {
/// A descriptive name for this entry. Suitable for display.
#[serde(rename="displayName")]
pub display_name: Option<String>,
/// The ID of the entry. For entries of type "person" or "circle", this is the ID of the resource. For other types, this property is not set.
pub id: Option<String>,
/// The type of entry describing to whom access is granted. Possible values are:
/// - "person" - Access to an individual.
/// - "circle" - Access to members of a circle.
/// - "myCircles" - Access to members of all the person's circles.
/// - "extendedCircles" - Access to members of all the person's circles, plus all of the people in their circles.
/// - "domain" - Access to members of the person's Google Apps domain.
/// - "public" - Access to anyone on the web.
#[serde(rename="type")]
pub type_: Option<String>,
}
impl client::Part for PlusAclentryResource {}
/// The person who performed this activity.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityActor {
/// Actor info specific to particular clients.
#[serde(rename="clientSpecificActorInfo")]
pub client_specific_actor_info: Option<ActivityActorClientSpecificActorInfo>,
/// The name of the actor, suitable for display.
#[serde(rename="displayName")]
pub display_name: Option<String>,
/// The ID of the actor's Person resource.
pub id: Option<String>,
/// The image representation of the actor.
pub image: Option<ActivityActorImage>,
/// An object representation of the individual components of name.
pub name: Option<ActivityActorName>,
/// The link to the actor's Google profile.
pub url: Option<String>,
/// Verification status of actor.
pub verification: Option<ActivityActorVerification>,
}
impl client::NestedType for ActivityActor {}
impl client::Part for ActivityActor {}
/// Actor info specific to particular clients.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityActorClientSpecificActorInfo {
/// Actor info specific to YouTube clients.
#[serde(rename="youtubeActorInfo")]
pub youtube_actor_info: Option<ActivityActorClientSpecificActorInfoYoutubeActorInfo>,
}
impl client::NestedType for ActivityActorClientSpecificActorInfo {}
impl client::Part for ActivityActorClientSpecificActorInfo {}
/// Actor info specific to YouTube clients.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityActorClientSpecificActorInfoYoutubeActorInfo {
/// ID of the YouTube channel owned by the Actor.
#[serde(rename="channelId")]
pub channel_id: Option<String>,
}
impl client::NestedType for ActivityActorClientSpecificActorInfoYoutubeActorInfo {}
impl client::Part for ActivityActorClientSpecificActorInfoYoutubeActorInfo {}
/// The image representation of the actor.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityActorImage {
/// The URL of the actor's profile photo. To resize the image and crop it to a square, append the query string ?sz=x, where x is the dimension in pixels of each side.
pub url: Option<String>,
}
impl client::NestedType for ActivityActorImage {}
impl client::Part for ActivityActorImage {}
/// An object representation of the individual components of name.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityActorName {
/// The family name ("last name") of the actor.
#[serde(rename="familyName")]
pub family_name: Option<String>,
/// The given name ("first name") of the actor.
#[serde(rename="givenName")]
pub given_name: Option<String>,
}
impl client::NestedType for ActivityActorName {}
impl client::Part for ActivityActorName {}
/// Verification status of actor.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityActorVerification {
/// Verification for one-time or manual processes.
#[serde(rename="adHocVerified")]
pub ad_hoc_verified: Option<String>,
}
impl client::NestedType for ActivityActorVerification {}
impl client::Part for ActivityActorVerification {}
/// The object of this activity.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObject {
/// If this activity's object is itself another activity, such as when a person reshares an activity, this property specifies the original activity's actor.
pub actor: Option<ActivityObjectActor>,
/// The media objects attached to this activity.
pub attachments: Option<Vec<ActivityObjectAttachments>>,
/// The HTML-formatted content, which is suitable for display.
pub content: Option<String>,
/// The ID of the object. When resharing an activity, this is the ID of the activity that is being reshared.
pub id: Option<String>,
/// The type of the object. Possible values include, but are not limited to, the following values:
/// - "note" - Textual content.
/// - "activity" - A Google+ activity.
#[serde(rename="objectType")]
pub object_type: Option<String>,
/// The content (text) as provided by the author, which is stored without any HTML formatting. When creating or updating an activity, this value must be supplied as plain text in the request.
#[serde(rename="originalContent")]
pub original_content: Option<String>,
/// People who +1'd this activity.
pub plusoners: Option<ActivityObjectPlusoners>,
/// Comments in reply to this activity.
pub replies: Option<ActivityObjectReplies>,
/// People who reshared this activity.
pub resharers: Option<ActivityObjectResharers>,
/// The URL that points to the linked resource.
pub url: Option<String>,
}
impl client::NestedType for ActivityObject {}
impl client::Part for ActivityObject {}
/// If this activity's object is itself another activity, such as when a person reshares an activity, this property specifies the original activity's actor.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectActor {
/// Actor info specific to particular clients.
#[serde(rename="clientSpecificActorInfo")]
pub client_specific_actor_info: Option<ActivityObjectActorClientSpecificActorInfo>,
/// The original actor's name, which is suitable for display.
#[serde(rename="displayName")]
pub display_name: Option<String>,
/// ID of the original actor.
pub id: Option<String>,
/// The image representation of the original actor.
pub image: Option<ActivityObjectActorImage>,
/// A link to the original actor's Google profile.
pub url: Option<String>,
/// Verification status of actor.
pub verification: Option<ActivityObjectActorVerification>,
}
impl client::NestedType for ActivityObjectActor {}
impl client::Part for ActivityObjectActor {}
/// Actor info specific to particular clients.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectActorClientSpecificActorInfo {
/// Actor info specific to YouTube clients.
#[serde(rename="youtubeActorInfo")]
pub youtube_actor_info: Option<ActivityObjectActorClientSpecificActorInfoYoutubeActorInfo>,
}
impl client::NestedType for ActivityObjectActorClientSpecificActorInfo {}
impl client::Part for ActivityObjectActorClientSpecificActorInfo {}
/// Actor info specific to YouTube clients.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectActorClientSpecificActorInfoYoutubeActorInfo {
/// ID of the YouTube channel owned by the Actor.
#[serde(rename="channelId")]
pub channel_id: Option<String>,
}
impl client::NestedType for ActivityObjectActorClientSpecificActorInfoYoutubeActorInfo {}
impl client::Part for ActivityObjectActorClientSpecificActorInfoYoutubeActorInfo {}
/// The image representation of the original actor.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectActorImage {
/// A URL that points to a thumbnail photo of the original actor.
pub url: Option<String>,
}
impl client::NestedType for ActivityObjectActorImage {}
impl client::Part for ActivityObjectActorImage {}
/// Verification status of actor.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectActorVerification {
/// Verification for one-time or manual processes.
#[serde(rename="adHocVerified")]
pub ad_hoc_verified: Option<String>,
}
impl client::NestedType for ActivityObjectActorVerification {}
impl client::Part for ActivityObjectActorVerification {}
/// The media objects attached to this activity.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectAttachments {
/// If the attachment is an article, this property contains a snippet of text from the article. It can also include descriptions for other types.
pub content: Option<String>,
/// The title of the attachment, such as a photo caption or an article title.
#[serde(rename="displayName")]
pub display_name: Option<String>,
/// If the attachment is a video, the embeddable link.
pub embed: Option<ActivityObjectAttachmentsEmbed>,
/// The full image URL for photo attachments.
#[serde(rename="fullImage")]
pub full_image: Option<ActivityObjectAttachmentsFullImage>,
/// The ID of the attachment.
pub id: Option<String>,
/// The preview image for photos or videos.
pub image: Option<ActivityObjectAttachmentsImage>,
/// The type of media object. Possible values include, but are not limited to, the following values:
/// - "photo" - A photo.
/// - "album" - A photo album.
/// - "video" - A video.
/// - "article" - An article, specified by a link.
#[serde(rename="objectType")]
pub object_type: Option<String>,
/// If the attachment is an album, this property is a list of potential additional thumbnails from the album.
pub thumbnails: Option<Vec<ActivityObjectAttachmentsThumbnails>>,
/// The link to the attachment, which should be of type text/html.
pub url: Option<String>,
}
impl client::NestedType for ActivityObjectAttachments {}
impl client::Part for ActivityObjectAttachments {}
/// If the attachment is a video, the embeddable link.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectAttachmentsEmbed {
/// Media type of the link.
#[serde(rename="type")]
pub type_: Option<String>,
/// URL of the link.
pub url: Option<String>,
}
impl client::NestedType for ActivityObjectAttachmentsEmbed {}
impl client::Part for ActivityObjectAttachmentsEmbed {}
/// The full image URL for photo attachments.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectAttachmentsFullImage {
/// The height, in pixels, of the linked resource.
pub height: Option<u32>,
/// Media type of the link.
#[serde(rename="type")]
pub type_: Option<String>,
/// URL of the image.
pub url: Option<String>,
/// The width, in pixels, of the linked resource.
pub width: Option<u32>,
}
impl client::NestedType for ActivityObjectAttachmentsFullImage {}
impl client::Part for ActivityObjectAttachmentsFullImage {}
/// The preview image for photos or videos.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectAttachmentsImage {
/// The height, in pixels, of the linked resource.
pub height: Option<u32>,
/// Media type of the link.
#[serde(rename="type")]
pub type_: Option<String>,
/// Image URL.
pub url: Option<String>,
/// The width, in pixels, of the linked resource.
pub width: Option<u32>,
}
impl client::NestedType for ActivityObjectAttachmentsImage {}
impl client::Part for ActivityObjectAttachmentsImage {}
/// If the attachment is an album, this property is a list of potential additional thumbnails from the album.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectAttachmentsThumbnails {
/// Potential name of the thumbnail.
pub description: Option<String>,
/// Image resource.
pub image: Option<ActivityObjectAttachmentsThumbnailsImage>,
/// URL of the webpage containing the image.
pub url: Option<String>,
}
impl client::NestedType for ActivityObjectAttachmentsThumbnails {}
impl client::Part for ActivityObjectAttachmentsThumbnails {}
/// Image resource.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectAttachmentsThumbnailsImage {
/// The height, in pixels, of the linked resource.
pub height: Option<u32>,
/// Media type of the link.
#[serde(rename="type")]
pub type_: Option<String>,
/// Image url.
pub url: Option<String>,
/// The width, in pixels, of the linked resource.
pub width: Option<u32>,
}
impl client::NestedType for ActivityObjectAttachmentsThumbnailsImage {}
impl client::Part for ActivityObjectAttachmentsThumbnailsImage {}
/// People who +1'd this activity.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectPlusoners {
/// The URL for the collection of people who +1'd this activity.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
/// Total number of people who +1'd this activity.
#[serde(rename="totalItems")]
pub total_items: Option<u32>,
}
impl client::NestedType for ActivityObjectPlusoners {}
impl client::Part for ActivityObjectPlusoners {}
/// Comments in reply to this activity.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectReplies {
/// The URL for the collection of comments in reply to this activity.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
/// Total number of comments on this activity.
#[serde(rename="totalItems")]
pub total_items: Option<u32>,
}
impl client::NestedType for ActivityObjectReplies {}
impl client::Part for ActivityObjectReplies {}
/// People who reshared this activity.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityObjectResharers {
/// The URL for the collection of resharers.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
/// Total number of people who reshared this activity.
#[serde(rename="totalItems")]
pub total_items: Option<u32>,
}
impl client::NestedType for ActivityObjectResharers {}
impl client::Part for ActivityObjectResharers {}
/// The service provider that initially published this activity.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ActivityProvider {
/// Name of the service provider.
pub title: Option<String>,
}
impl client::NestedType for ActivityProvider {}
impl client::Part for ActivityProvider {}
/// The person who posted this comment.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentActor {
/// Actor info specific to particular clients.
#[serde(rename="clientSpecificActorInfo")]
pub client_specific_actor_info: Option<CommentActorClientSpecificActorInfo>,
/// The name of this actor, suitable for display.
#[serde(rename="displayName")]
pub display_name: Option<String>,
/// The ID of the actor.
pub id: Option<String>,
/// The image representation of this actor.
pub image: Option<CommentActorImage>,
/// A link to the Person resource for this actor.
pub url: Option<String>,
/// Verification status of actor.
pub verification: Option<CommentActorVerification>,
}
impl client::NestedType for CommentActor {}
impl client::Part for CommentActor {}
/// Actor info specific to particular clients.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentActorClientSpecificActorInfo {
/// Actor info specific to YouTube clients.
#[serde(rename="youtubeActorInfo")]
pub youtube_actor_info: Option<CommentActorClientSpecificActorInfoYoutubeActorInfo>,
}
impl client::NestedType for CommentActorClientSpecificActorInfo {}
impl client::Part for CommentActorClientSpecificActorInfo {}
/// Actor info specific to YouTube clients.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentActorClientSpecificActorInfoYoutubeActorInfo {
/// ID of the YouTube channel owned by the Actor.
#[serde(rename="channelId")]
pub channel_id: Option<String>,
}
impl client::NestedType for CommentActorClientSpecificActorInfoYoutubeActorInfo {}
impl client::Part for CommentActorClientSpecificActorInfoYoutubeActorInfo {}
/// The image representation of this actor.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentActorImage {
/// The URL of the actor's profile photo. To resize the image and crop it to a square, append the query string ?sz=x, where x is the dimension in pixels of each side.
pub url: Option<String>,
}
impl client::NestedType for CommentActorImage {}
impl client::Part for CommentActorImage {}
/// Verification status of actor.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentActorVerification {
/// Verification for one-time or manual processes.
#[serde(rename="adHocVerified")]
pub ad_hoc_verified: Option<String>,
}
impl client::NestedType for CommentActorVerification {}
impl client::Part for CommentActorVerification {}
/// The activity this comment replied to.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentInReplyTo {
/// The ID of the activity.
pub id: Option<String>,
/// The URL of the activity.
pub url: Option<String>,
}
impl client::NestedType for CommentInReplyTo {}
impl client::Part for CommentInReplyTo {}
/// The object of this comment.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentObject {
/// The HTML-formatted content, suitable for display.
pub content: Option<String>,
/// The object type of this comment. Possible values are:
/// - "comment" - A comment in reply to an activity.
#[serde(rename="objectType")]
pub object_type: Option<String>,
/// The content (text) as provided by the author, stored without any HTML formatting. When creating or updating a comment, this value must be supplied as plain text in the request.
#[serde(rename="originalContent")]
pub original_content: Option<String>,
}
impl client::NestedType for CommentObject {}
impl client::Part for CommentObject {}
/// People who +1'd this comment.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CommentPlusoners {
/// Total number of people who +1'd this comment.
#[serde(rename="totalItems")]
pub total_items: Option<u32>,
}
impl client::NestedType for CommentPlusoners {}
impl client::Part for CommentPlusoners {}
/// The age range of the person. Valid ranges are 17 or younger, 18 to 20, and 21 or older. Age is determined from the user's birthday using Western age reckoning.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PersonAgeRange {
/// The age range's upper bound, if any. Possible values include, but are not limited to, the following:
/// - "17" - for age 17
/// - "20" - for age 20
pub max: Option<i32>,
/// The age range's lower bound, if any. Possible values include, but are not limited to, the following:
/// - "21" - for age 21
/// - "18" - for age 18
pub min: Option<i32>,
}
impl client::NestedType for PersonAgeRange {}
impl client::Part for PersonAgeRange {}
/// The cover photo content.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PersonCover {
/// Extra information about the cover photo.
#[serde(rename="coverInfo")]
pub cover_info: Option<PersonCoverCoverInfo>,
/// The person's primary cover image.
#[serde(rename="coverPhoto")]
pub cover_photo: Option<PersonCoverCoverPhoto>,
/// The layout of the cover art. Possible values include, but are not limited to, the following values:
/// - "banner" - One large image banner.
pub layout: Option<String>,
}
impl client::NestedType for PersonCover {}
impl client::Part for PersonCover {}
/// Extra information about the cover photo.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PersonCoverCoverInfo {
/// The difference between the left position of the cover image and the actual displayed cover image. Only valid for banner layout.
#[serde(rename="leftImageOffset")]
pub left_image_offset: Option<i32>,
/// The difference between the top position of the cover image and the actual displayed cover image. Only valid for banner layout.
#[serde(rename="topImageOffset")]
pub top_image_offset: Option<i32>,
}
impl client::NestedType for PersonCoverCoverInfo {}
impl client::Part for PersonCoverCoverInfo {}
/// The person's primary cover image.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PersonCoverCoverPhoto {
/// The height of the image.
pub height: Option<i32>,
/// The URL of the image.
pub url: Option<String>,
/// The width of the image.
pub width: Option<i32>,
}
impl client::NestedType for PersonCoverCoverPhoto {}
impl client::Part for PersonCoverCoverPhoto {}
/// A list of email addresses that this person has, including their Google account email address, and the public verified email addresses on their Google+ profile. The plus.profile.emails.read scope is needed to retrieve these email addresses, or the email scope can be used to retrieve just the Google account email address.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PersonEmails {
/// The type of address. Possible values include, but are not limited to, the following values:
/// - "account" - Google account email address.
/// - "home" - Home email address.
/// - "work" - Work email address.
/// - "other" - Other.
#[serde(rename="type")]
pub type_: Option<String>,
/// The email address.
pub value: Option<String>,
}
impl client::NestedType for PersonEmails {}
impl client::Part for PersonEmails {}
/// The representation of the person's profile photo.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PersonImage {
/// Whether the person's profile photo is the default one
#[serde(rename="isDefault")]
pub is_default: Option<bool>,
/// The URL of the person's profile photo. To resize the image and crop it to a square, append the query string ?sz=x, where x is the dimension in pixels of each side.
pub url: Option<String>,
}
impl client::NestedType for PersonImage {}
impl client::Part for PersonImage {}
/// An object representation of the individual components of a person's name.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PersonName {
/// The family name (last name) of this person.
#[serde(rename="familyName")]
pub family_name: Option<String>,
/// The full name of this person, including middle names, suffixes, etc.
pub formatted: Option<String>,
/// The given name (first name) of this person.
#[serde(rename="givenName")]
pub given_name: Option<String>,
/// The honorific prefixes (such as "Dr." or "Mrs.") for this person.
#[serde(rename="honorificPrefix")]
pub honorific_prefix: Option<String>,
/// The honorific suffixes (such as "Jr.") for this person.
#[serde(rename="honorificSuffix")]
pub honorific_suffix: Option<String>,
/// The middle name of this person.
#[serde(rename="middleName")]
pub middle_name: Option<String>,
}
impl client::NestedType for PersonName {}
impl client::Part for PersonName {}
/// A list of current or past organizations with which this person is associated.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PersonOrganizations {
/// The department within the organization. Deprecated.
pub department: Option<String>,
/// A short description of the person's role in this organization. Deprecated.
pub description: Option<String>,
/// The date that the person left this organization.
#[serde(rename="endDate")]
pub end_date: Option<String>,
/// The location of this organization. Deprecated.
pub location: Option<String>,
/// The name of the organization.
pub name: Option<String>,
/// If "true", indicates this organization is the person's primary one, which is typically interpreted as the current one.
pub primary: Option<bool>,
/// The date that the person joined this organization.
#[serde(rename="startDate")]
pub start_date: Option<String>,
/// The person's job title or role within the organization.
pub title: Option<String>,
/// The type of organization. Possible values include, but are not limited to, the following values:
/// - "work" - Work.
/// - "school" - School.
#[serde(rename="type")]
pub type_: Option<String>,
}
impl client::NestedType for PersonOrganizations {}
impl client::Part for PersonOrganizations {}
/// A list of places where this person has lived.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PersonPlacesLived {
/// If "true", this place of residence is this person's primary residence.
pub primary: Option<bool>,
/// A place where this person has lived. For example: "Seattle, WA", "Near Toronto".
pub value: Option<String>,
}
impl client::NestedType for PersonPlacesLived {}
impl client::Part for PersonPlacesLived {}
/// A list of URLs for this person.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PersonUrls {
/// The label of the URL.
pub label: Option<String>,
/// The type of URL. Possible values include, but are not limited to, the following values:
/// - "otherProfile" - URL for another profile.
/// - "contributor" - URL to a site for which this person is a contributor.
/// - "website" - URL for this Google+ Page's primary website.
/// - "other" - Other URL.
#[serde(rename="type")]
pub type_: Option<String>,
/// The URL value.
pub value: Option<String>,
}
impl client::NestedType for PersonUrls {}
impl client::Part for PersonUrls {}
/// The physical address of the place.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlaceAddress {
/// The formatted address for display.
pub formatted: Option<String>,
}
impl client::NestedType for PlaceAddress {}
impl client::Part for PlaceAddress {}
/// The position of the place.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PlacePosition {
/// The latitude of this position.
pub latitude: Option<f64>,
/// The longitude of this position.
pub longitude: Option<f64>,
}
impl client::NestedType for PlacePosition {}
impl client::Part for PlacePosition {}
// ###################
// MethodBuilders ###
// #################
/// A builder providing access to all methods supported on *activity* resources.
/// It is not used directly, but through the `Plus` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_plus1 as plus1;
///
/// # async fn dox() {
/// use std::default::Default;
/// use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
/// secret,
/// oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// ).build().await.unwrap();
/// let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `get(...)`, `list(...)` and `search(...)`
/// // to build up your call.
/// let rb = hub.activities();
/// # }
/// ```
pub struct ActivityMethods<'a>
where {
hub: &'a Plus<>,
}
impl<'a> client::MethodsBuilder for ActivityMethods<'a> {}
impl<'a> ActivityMethods<'a> {
/// Create a builder to help you perform the following task:
///
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// # Arguments
///
/// * `activityId` - The ID of the activity to get.
pub fn get(&self, activity_id: &str) -> ActivityGetCall<'a> {
ActivityGetCall {
hub: self.hub,
_activity_id: activity_id.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// # Arguments
///
/// * `userId` - The ID of the user to get activities for. The special value "me" can be used to indicate the authenticated user.
/// * `collection` - The collection of activities to list.
pub fn list(&self, user_id: &str, collection: &str) -> ActivityListCall<'a> {
ActivityListCall {
hub: self.hub,
_user_id: user_id.to_string(),
_collection: collection.to_string(),
_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:
///
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// # Arguments
///
/// * `query` - Full-text search query string.
pub fn search(&self, query: &str) -> ActivitySearchCall<'a> {
ActivitySearchCall {
hub: self.hub,
_query: query.to_string(),
_page_token: Default::default(),
_order_by: Default::default(),
_max_results: Default::default(),
_language: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *comment* resources.
/// It is not used directly, but through the `Plus` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_plus1 as plus1;
///
/// # async fn dox() {
/// use std::default::Default;
/// use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
/// secret,
/// oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// ).build().await.unwrap();
/// let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `get(...)` and `list(...)`
/// // to build up your call.
/// let rb = hub.comments();
/// # }
/// ```
pub struct CommentMethods<'a>
where {
hub: &'a Plus<>,
}
impl<'a> client::MethodsBuilder for CommentMethods<'a> {}
impl<'a> CommentMethods<'a> {
/// Create a builder to help you perform the following task:
///
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// # Arguments
///
/// * `commentId` - The ID of the comment to get.
pub fn get(&self, comment_id: &str) -> CommentGetCall<'a> {
CommentGetCall {
hub: self.hub,
_comment_id: comment_id.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// # Arguments
///
/// * `activityId` - The ID of the activity to get comments for.
pub fn list(&self, activity_id: &str) -> CommentListCall<'a> {
CommentListCall {
hub: self.hub,
_activity_id: activity_id.to_string(),
_sort_order: Default::default(),
_page_token: Default::default(),
_max_results: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *people* resources.
/// It is not used directly, but through the `Plus` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_plus1 as plus1;
///
/// # async fn dox() {
/// use std::default::Default;
/// use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = oauth2::InstalledFlowAuthenticator::builder(
/// secret,
/// oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// ).build().await.unwrap();
/// let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `get(...)`, `list(...)`, `list_by_activity(...)` and `search(...)`
/// // to build up your call.
/// let rb = hub.people();
/// # }
/// ```
pub struct PeopleMethods<'a>
where {
hub: &'a Plus<>,
}
impl<'a> client::MethodsBuilder for PeopleMethods<'a> {}
impl<'a> PeopleMethods<'a> {
/// Create a builder to help you perform the following task:
///
/// Get a person's profile. If your app uses scope https://www.googleapis.com/auth/plus.login, this method is guaranteed to return ageRange and language.
///
/// # Arguments
///
/// * `userId` - The ID of the person to get the profile for. The special value "me" can be used to indicate the authenticated user.
pub fn get(&self, user_id: &str) -> PeopleGetCall<'a> {
PeopleGetCall {
hub: self.hub,
_user_id: user_id.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// List all of the people in the specified collection.
///
/// # Arguments
///
/// * `userId` - Get the collection of people for the person identified. Use "me" to indicate the authenticated user.
/// * `collection` - The collection of people to list.
pub fn list(&self, user_id: &str, collection: &str) -> PeopleListCall<'a> {
PeopleListCall {
hub: self.hub,
_user_id: user_id.to_string(),
_collection: collection.to_string(),
_page_token: Default::default(),
_order_by: 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:
///
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// # Arguments
///
/// * `activityId` - The ID of the activity to get the list of people for.
/// * `collection` - The collection of people to list.
pub fn list_by_activity(&self, activity_id: &str, collection: &str) -> PeopleListByActivityCall<'a> {
PeopleListByActivityCall {
hub: self.hub,
_activity_id: activity_id.to_string(),
_collection: collection.to_string(),
_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:
///
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// # Arguments
///
/// * `query` - Specify a query string for full text search of public text in all profiles.
pub fn search(&self, query: &str) -> PeopleSearchCall<'a> {
PeopleSearchCall {
hub: self.hub,
_query: query.to_string(),
_page_token: Default::default(),
_max_results: Default::default(),
_language: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
// ###################
// CallBuilders ###
// #################
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// A builder for the *get* method supported by a *activity* resource.
/// It is not used directly, but through a `ActivityMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_plus1 as plus1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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.activities().get("activityId")
/// .doit().await;
/// # }
/// ```
pub struct ActivityGetCall<'a>
where {
hub: &'a Plus<>,
_activity_id: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a> client::CallBuilder for ActivityGetCall<'a> {}
impl<'a> ActivityGetCall<'a> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Activity)> {
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: "plus.activities.get",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
params.push(("activityId", self._activity_id.to_string()));
for &field in ["alt", "activityId"].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() + "activities/{activityId}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Login.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{activityId}", "activityId")].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 ["activityId"].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 token = match self.hub.auth.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 client = &self.hub.client;
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.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 (parts, _) = res.into_parts();
let body = hyper::Body::from(res_body_string.clone());
let restored_response = hyper::Response::from_parts(parts, body);
let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();
if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
sleep(d);
continue;
}
dlg.finished(false);
return match server_response {
Some(error_value) => Err(client::Error::BadRequest(error_value)),
None => Err(client::Error::Failure(restored_response)),
}
}
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)
}
}
}
}
/// The ID of the activity to get.
///
/// Sets the *activity id* 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 activity_id(mut self, new_value: &str) -> ActivityGetCall<'a> {
self._activity_id = 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) -> ActivityGetCall<'a> {
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
///
/// * *alt* (query-string) - Data format for the response.
/// * *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) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ActivityGetCall<'a>
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::Login`.
///
/// 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) -> ActivityGetCall<'a>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// A builder for the *list* method supported by a *activity* resource.
/// It is not used directly, but through a `ActivityMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_plus1 as plus1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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.activities().list("userId", "collection")
/// .page_token("ea")
/// .max_results(46)
/// .doit().await;
/// # }
/// ```
pub struct ActivityListCall<'a>
where {
hub: &'a Plus<>,
_user_id: String,
_collection: String,
_page_token: Option<String>,
_max_results: Option<u32>,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a> client::CallBuilder for ActivityListCall<'a> {}
impl<'a> ActivityListCall<'a> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, ActivityFeed)> {
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: "plus.activities.list",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
params.push(("userId", self._user_id.to_string()));
params.push(("collection", self._collection.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()));
}
for &field in ["alt", "userId", "collection", "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() + "people/{userId}/activities/{collection}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Login.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{userId}", "userId"), ("{collection}", "collection")].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 ["collection", "userId"].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 token = match self.hub.auth.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 client = &self.hub.client;
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.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 (parts, _) = res.into_parts();
let body = hyper::Body::from(res_body_string.clone());
let restored_response = hyper::Response::from_parts(parts, body);
let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();
if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
sleep(d);
continue;
}
dlg.finished(false);
return match server_response {
Some(error_value) => Err(client::Error::BadRequest(error_value)),
None => Err(client::Error::Failure(restored_response)),
}
}
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)
}
}
}
}
/// The ID of the user to get activities for. The special value "me" can be used to indicate the authenticated user.
///
/// Sets the *user id* 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 user_id(mut self, new_value: &str) -> ActivityListCall<'a> {
self._user_id = new_value.to_string();
self
}
/// The collection of activities to list.
///
/// Sets the *collection* 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 collection(mut self, new_value: &str) -> ActivityListCall<'a> {
self._collection = new_value.to_string();
self
}
/// The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ActivityListCall<'a> {
self._page_token = Some(new_value.to_string());
self
}
/// The maximum number of activities to include in the response, which is used for paging. For any response, the actual number returned might be less than the specified maxResults.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> ActivityListCall<'a> {
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) -> ActivityListCall<'a> {
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
///
/// * *alt* (query-string) - Data format for the response.
/// * *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) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ActivityListCall<'a>
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::Login`.
///
/// 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) -> ActivityListCall<'a>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// A builder for the *search* method supported by a *activity* resource.
/// It is not used directly, but through a `ActivityMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_plus1 as plus1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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.activities().search("query")
/// .page_token("amet")
/// .order_by("duo")
/// .max_results(51)
/// .language("sed")
/// .doit().await;
/// # }
/// ```
pub struct ActivitySearchCall<'a>
where {
hub: &'a Plus<>,
_query: String,
_page_token: Option<String>,
_order_by: Option<String>,
_max_results: Option<u32>,
_language: Option<String>,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a> client::CallBuilder for ActivitySearchCall<'a> {}
impl<'a> ActivitySearchCall<'a> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, ActivityFeed)> {
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: "plus.activities.search",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(7 + self._additional_params.len());
params.push(("query", self._query.to_string()));
if let Some(value) = self._page_token {
params.push(("pageToken", value.to_string()));
}
if let Some(value) = self._order_by {
params.push(("orderBy", value.to_string()));
}
if let Some(value) = self._max_results {
params.push(("maxResults", value.to_string()));
}
if let Some(value) = self._language {
params.push(("language", value.to_string()));
}
for &field in ["alt", "query", "pageToken", "orderBy", "maxResults", "language"].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() + "activities";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Login.as_ref().to_string(), ());
}
let url = url::Url::parse_with_params(&url, params).unwrap();
loop {
let token = match self.hub.auth.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 client = &self.hub.client;
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.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 (parts, _) = res.into_parts();
let body = hyper::Body::from(res_body_string.clone());
let restored_response = hyper::Response::from_parts(parts, body);
let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();
if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
sleep(d);
continue;
}
dlg.finished(false);
return match server_response {
Some(error_value) => Err(client::Error::BadRequest(error_value)),
None => Err(client::Error::Failure(restored_response)),
}
}
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)
}
}
}
}
/// Full-text search query string.
///
/// Sets the *query* query 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 query(mut self, new_value: &str) -> ActivitySearchCall<'a> {
self._query = new_value.to_string();
self
}
/// The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response. This token can be of any length.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ActivitySearchCall<'a> {
self._page_token = Some(new_value.to_string());
self
}
/// Specifies how to order search results.
///
/// Sets the *order by* query property to the given value.
pub fn order_by(mut self, new_value: &str) -> ActivitySearchCall<'a> {
self._order_by = Some(new_value.to_string());
self
}
/// The maximum number of activities to include in the response, which is used for paging. For any response, the actual number returned might be less than the specified maxResults.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> ActivitySearchCall<'a> {
self._max_results = Some(new_value);
self
}
/// Specify the preferred language to search with. See search language codes for available values.
///
/// Sets the *language* query property to the given value.
pub fn language(mut self, new_value: &str) -> ActivitySearchCall<'a> {
self._language = 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) -> ActivitySearchCall<'a> {
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
///
/// * *alt* (query-string) - Data format for the response.
/// * *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) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ActivitySearchCall<'a>
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::Login`.
///
/// 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) -> ActivitySearchCall<'a>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// A builder for the *get* method supported by a *comment* resource.
/// It is not used directly, but through a `CommentMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_plus1 as plus1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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.comments().get("commentId")
/// .doit().await;
/// # }
/// ```
pub struct CommentGetCall<'a>
where {
hub: &'a Plus<>,
_comment_id: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a> client::CallBuilder for CommentGetCall<'a> {}
impl<'a> CommentGetCall<'a> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Comment)> {
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: "plus.comments.get",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
params.push(("commentId", self._comment_id.to_string()));
for &field in ["alt", "commentId"].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() + "comments/{commentId}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Login.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{commentId}", "commentId")].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 ["commentId"].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 token = match self.hub.auth.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 client = &self.hub.client;
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.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 (parts, _) = res.into_parts();
let body = hyper::Body::from(res_body_string.clone());
let restored_response = hyper::Response::from_parts(parts, body);
let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();
if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
sleep(d);
continue;
}
dlg.finished(false);
return match server_response {
Some(error_value) => Err(client::Error::BadRequest(error_value)),
None => Err(client::Error::Failure(restored_response)),
}
}
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)
}
}
}
}
/// The ID of the comment to get.
///
/// Sets the *comment id* 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 comment_id(mut self, new_value: &str) -> CommentGetCall<'a> {
self._comment_id = 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) -> CommentGetCall<'a> {
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
///
/// * *alt* (query-string) - Data format for the response.
/// * *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) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> CommentGetCall<'a>
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::Login`.
///
/// 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) -> CommentGetCall<'a>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// A builder for the *list* method supported by a *comment* resource.
/// It is not used directly, but through a `CommentMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_plus1 as plus1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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.comments().list("activityId")
/// .sort_order("rebum.")
/// .page_token("est")
/// .max_results(51)
/// .doit().await;
/// # }
/// ```
pub struct CommentListCall<'a>
where {
hub: &'a Plus<>,
_activity_id: String,
_sort_order: Option<String>,
_page_token: Option<String>,
_max_results: Option<u32>,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a> client::CallBuilder for CommentListCall<'a> {}
impl<'a> CommentListCall<'a> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, CommentFeed)> {
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: "plus.comments.list",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
params.push(("activityId", self._activity_id.to_string()));
if let Some(value) = self._sort_order {
params.push(("sortOrder", 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()));
}
for &field in ["alt", "activityId", "sortOrder", "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() + "activities/{activityId}/comments";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Login.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{activityId}", "activityId")].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 ["activityId"].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 token = match self.hub.auth.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 client = &self.hub.client;
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.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 (parts, _) = res.into_parts();
let body = hyper::Body::from(res_body_string.clone());
let restored_response = hyper::Response::from_parts(parts, body);
let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();
if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
sleep(d);
continue;
}
dlg.finished(false);
return match server_response {
Some(error_value) => Err(client::Error::BadRequest(error_value)),
None => Err(client::Error::Failure(restored_response)),
}
}
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)
}
}
}
}
/// The ID of the activity to get comments for.
///
/// Sets the *activity id* 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 activity_id(mut self, new_value: &str) -> CommentListCall<'a> {
self._activity_id = new_value.to_string();
self
}
/// The order in which to sort the list of comments.
///
/// Sets the *sort order* query property to the given value.
pub fn sort_order(mut self, new_value: &str) -> CommentListCall<'a> {
self._sort_order = Some(new_value.to_string());
self
}
/// The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> CommentListCall<'a> {
self._page_token = Some(new_value.to_string());
self
}
/// The maximum number of comments to include in the response, which is used for paging. For any response, the actual number returned might be less than the specified maxResults.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> CommentListCall<'a> {
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) -> CommentListCall<'a> {
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
///
/// * *alt* (query-string) - Data format for the response.
/// * *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) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> CommentListCall<'a>
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::Login`.
///
/// 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) -> CommentListCall<'a>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Get a person's profile. If your app uses scope https://www.googleapis.com/auth/plus.login, this method is guaranteed to return ageRange and language.
///
/// A builder for the *get* method supported by a *people* resource.
/// It is not used directly, but through a `PeopleMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_plus1 as plus1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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.people().get("userId")
/// .doit().await;
/// # }
/// ```
pub struct PeopleGetCall<'a>
where {
hub: &'a Plus<>,
_user_id: String,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a> client::CallBuilder for PeopleGetCall<'a> {}
impl<'a> PeopleGetCall<'a> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, Person)> {
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: "plus.people.get",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
params.push(("userId", self._user_id.to_string()));
for &field in ["alt", "userId"].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() + "people/{userId}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Login.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{userId}", "userId")].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 ["userId"].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 token = match self.hub.auth.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 client = &self.hub.client;
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.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 (parts, _) = res.into_parts();
let body = hyper::Body::from(res_body_string.clone());
let restored_response = hyper::Response::from_parts(parts, body);
let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();
if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
sleep(d);
continue;
}
dlg.finished(false);
return match server_response {
Some(error_value) => Err(client::Error::BadRequest(error_value)),
None => Err(client::Error::Failure(restored_response)),
}
}
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)
}
}
}
}
/// The ID of the person to get the profile for. The special value "me" can be used to indicate the authenticated user.
///
/// Sets the *user id* 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 user_id(mut self, new_value: &str) -> PeopleGetCall<'a> {
self._user_id = 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) -> PeopleGetCall<'a> {
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
///
/// * *alt* (query-string) - Data format for the response.
/// * *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) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> PeopleGetCall<'a>
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::Login`.
///
/// 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) -> PeopleGetCall<'a>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// List all of the people in the specified collection.
///
/// A builder for the *list* method supported by a *people* resource.
/// It is not used directly, but through a `PeopleMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_plus1 as plus1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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.people().list("userId", "collection")
/// .page_token("ea")
/// .order_by("dolor")
/// .max_results(45)
/// .doit().await;
/// # }
/// ```
pub struct PeopleListCall<'a>
where {
hub: &'a Plus<>,
_user_id: String,
_collection: String,
_page_token: Option<String>,
_order_by: Option<String>,
_max_results: Option<u32>,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a> client::CallBuilder for PeopleListCall<'a> {}
impl<'a> PeopleListCall<'a> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, PeopleFeed)> {
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: "plus.people.list",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(7 + self._additional_params.len());
params.push(("userId", self._user_id.to_string()));
params.push(("collection", self._collection.to_string()));
if let Some(value) = self._page_token {
params.push(("pageToken", value.to_string()));
}
if let Some(value) = self._order_by {
params.push(("orderBy", value.to_string()));
}
if let Some(value) = self._max_results {
params.push(("maxResults", value.to_string()));
}
for &field in ["alt", "userId", "collection", "pageToken", "orderBy", "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() + "people/{userId}/people/{collection}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Login.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{userId}", "userId"), ("{collection}", "collection")].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 ["collection", "userId"].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 token = match self.hub.auth.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 client = &self.hub.client;
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.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 (parts, _) = res.into_parts();
let body = hyper::Body::from(res_body_string.clone());
let restored_response = hyper::Response::from_parts(parts, body);
let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();
if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
sleep(d);
continue;
}
dlg.finished(false);
return match server_response {
Some(error_value) => Err(client::Error::BadRequest(error_value)),
None => Err(client::Error::Failure(restored_response)),
}
}
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)
}
}
}
}
/// Get the collection of people for the person identified. Use "me" to indicate the authenticated user.
///
/// Sets the *user id* 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 user_id(mut self, new_value: &str) -> PeopleListCall<'a> {
self._user_id = new_value.to_string();
self
}
/// The collection of people to list.
///
/// Sets the *collection* 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 collection(mut self, new_value: &str) -> PeopleListCall<'a> {
self._collection = new_value.to_string();
self
}
/// The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> PeopleListCall<'a> {
self._page_token = Some(new_value.to_string());
self
}
/// The order to return people in.
///
/// Sets the *order by* query property to the given value.
pub fn order_by(mut self, new_value: &str) -> PeopleListCall<'a> {
self._order_by = Some(new_value.to_string());
self
}
/// The maximum number of people to include in the response, which is used for paging. For any response, the actual number returned might be less than the specified maxResults.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> PeopleListCall<'a> {
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) -> PeopleListCall<'a> {
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
///
/// * *alt* (query-string) - Data format for the response.
/// * *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) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> PeopleListCall<'a>
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::Login`.
///
/// 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) -> PeopleListCall<'a>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// A builder for the *listByActivity* method supported by a *people* resource.
/// It is not used directly, but through a `PeopleMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_plus1 as plus1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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.people().list_by_activity("activityId", "collection")
/// .page_token("sed")
/// .max_results(31)
/// .doit().await;
/// # }
/// ```
pub struct PeopleListByActivityCall<'a>
where {
hub: &'a Plus<>,
_activity_id: String,
_collection: String,
_page_token: Option<String>,
_max_results: Option<u32>,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a> client::CallBuilder for PeopleListByActivityCall<'a> {}
impl<'a> PeopleListByActivityCall<'a> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, PeopleFeed)> {
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: "plus.people.listByActivity",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
params.push(("activityId", self._activity_id.to_string()));
params.push(("collection", self._collection.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()));
}
for &field in ["alt", "activityId", "collection", "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() + "activities/{activityId}/people/{collection}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Login.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{activityId}", "activityId"), ("{collection}", "collection")].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 ["collection", "activityId"].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 token = match self.hub.auth.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 client = &self.hub.client;
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.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 (parts, _) = res.into_parts();
let body = hyper::Body::from(res_body_string.clone());
let restored_response = hyper::Response::from_parts(parts, body);
let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();
if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
sleep(d);
continue;
}
dlg.finished(false);
return match server_response {
Some(error_value) => Err(client::Error::BadRequest(error_value)),
None => Err(client::Error::Failure(restored_response)),
}
}
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)
}
}
}
}
/// The ID of the activity to get the list of people for.
///
/// Sets the *activity id* 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 activity_id(mut self, new_value: &str) -> PeopleListByActivityCall<'a> {
self._activity_id = new_value.to_string();
self
}
/// The collection of people to list.
///
/// Sets the *collection* 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 collection(mut self, new_value: &str) -> PeopleListByActivityCall<'a> {
self._collection = new_value.to_string();
self
}
/// The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> PeopleListByActivityCall<'a> {
self._page_token = Some(new_value.to_string());
self
}
/// The maximum number of people to include in the response, which is used for paging. For any response, the actual number returned might be less than the specified maxResults.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> PeopleListByActivityCall<'a> {
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) -> PeopleListByActivityCall<'a> {
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
///
/// * *alt* (query-string) - Data format for the response.
/// * *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) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> PeopleListByActivityCall<'a>
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::Login`.
///
/// 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) -> PeopleListByActivityCall<'a>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Shut down. See https://developers.google.com/+/api-shutdown for more details.
///
/// A builder for the *search* method supported by a *people* resource.
/// It is not used directly, but through a `PeopleMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_plus1 as plus1;
/// # async fn dox() {
/// # use std::default::Default;
/// # use plus1::{Plus, oauth2, hyper, hyper_rustls};
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = Plus::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), 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.people().search("query")
/// .page_token("no")
/// .max_results(86)
/// .language("kasd")
/// .doit().await;
/// # }
/// ```
pub struct PeopleSearchCall<'a>
where {
hub: &'a Plus<>,
_query: String,
_page_token: Option<String>,
_max_results: Option<u32>,
_language: Option<String>,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a> client::CallBuilder for PeopleSearchCall<'a> {}
impl<'a> PeopleSearchCall<'a> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, PeopleFeed)> {
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: "plus.people.search",
http_method: hyper::Method::GET });
let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
params.push(("query", self._query.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._language {
params.push(("language", value.to_string()));
}
for &field in ["alt", "query", "pageToken", "maxResults", "language"].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() + "people";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::Login.as_ref().to_string(), ());
}
let url = url::Url::parse_with_params(&url, params).unwrap();
loop {
let token = match self.hub.auth.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 client = &self.hub.client;
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.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 (parts, _) = res.into_parts();
let body = hyper::Body::from(res_body_string.clone());
let restored_response = hyper::Response::from_parts(parts, body);
let server_response = json::from_str::<serde_json::Value>(&res_body_string).ok();
if let client::Retry::After(d) = dlg.http_failure(&restored_response, server_response.clone()) {
sleep(d);
continue;
}
dlg.finished(false);
return match server_response {
Some(error_value) => Err(client::Error::BadRequest(error_value)),
None => Err(client::Error::Failure(restored_response)),
}
}
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)
}
}
}
}
/// Specify a query string for full text search of public text in all profiles.
///
/// Sets the *query* query 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 query(mut self, new_value: &str) -> PeopleSearchCall<'a> {
self._query = new_value.to_string();
self
}
/// The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response. This token can be of any length.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> PeopleSearchCall<'a> {
self._page_token = Some(new_value.to_string());
self
}
/// The maximum number of people to include in the response, which is used for paging. For any response, the actual number returned might be less than the specified maxResults.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> PeopleSearchCall<'a> {
self._max_results = Some(new_value);
self
}
/// Specify the preferred language to search with. See search language codes for available values.
///
/// Sets the *language* query property to the given value.
pub fn language(mut self, new_value: &str) -> PeopleSearchCall<'a> {
self._language = 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) -> PeopleSearchCall<'a> {
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
///
/// * *alt* (query-string) - Data format for the response.
/// * *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) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> PeopleSearchCall<'a>
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::Login`.
///
/// 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) -> PeopleSearchCall<'a>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
| 41.370921 | 329 | 0.601728 |
879d1a91c88eceff52bef4ab43d3a51f029256d8 | 2,960 | use crate::ffi2::object::*;
use std::os::raw::{c_char, c_int, c_long, c_uchar};
#[repr(C)]
#[derive(Copy)]
pub struct PyImport_Struct_inittab {
pub name: *mut c_char,
pub initfunc: Option<unsafe extern "C" fn()>,
}
impl Clone for PyImport_Struct_inittab {
#[inline]
fn clone(&self) -> PyImport_Struct_inittab {
*self
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct PyImport_Struct_frozen {
pub name: *mut c_char,
pub code: *mut c_uchar,
pub size: c_int,
}
#[inline]
pub unsafe fn PyImport_ImportModuleEx(
name: *mut c_char,
globals: *mut PyObject,
locals: *mut PyObject,
fromlist: *mut PyObject,
) -> *mut PyObject {
PyImport_ImportModuleLevel(name, globals, locals, fromlist, -1)
}
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
pub fn PyImport_ImportModule(name: *const c_char) -> *mut PyObject;
pub fn PyImport_ImportModuleNoBlock(name: *const c_char) -> *mut PyObject;
pub fn PyImport_ImportModuleLevel(
name: *mut c_char,
globals: *mut PyObject,
locals: *mut PyObject,
fromlist: *mut PyObject,
level: c_int,
) -> *mut PyObject;
pub fn PyImport_Import(name: *mut PyObject) -> *mut PyObject;
pub fn PyImport_ReloadModule(m: *mut PyObject) -> *mut PyObject;
pub fn PyImport_AddModule(name: *const c_char) -> *mut PyObject;
pub fn PyImport_ExecCodeModule(name: *mut c_char, co: *mut PyObject) -> *mut PyObject;
pub fn PyImport_ExecCodeModuleEx(
name: *mut c_char,
co: *mut PyObject,
pathname: *mut c_char,
) -> *mut PyObject;
pub fn PyImport_GetMagicNumber() -> c_long;
pub fn PyImport_GetImporter(path: *mut PyObject) -> *mut PyObject;
pub fn PyImport_GetModuleDict() -> *mut PyObject;
pub fn PyImport_ImportFrozenModule(name: *mut c_char) -> c_int;
pub fn PyImport_AppendInittab(
name: *const c_char,
initfunc: Option<unsafe extern "C" fn()>,
) -> c_int;
pub fn PyImport_ExtendInittab(newtab: *mut PyImport_Struct_inittab) -> c_int;
pub static mut PyImport_Inittab: *mut PyImport_Struct_inittab;
pub static mut PyImport_FrozenModules: *mut PyImport_Struct_frozen;
/*for internal use only:
pub fn PyImport_Cleanup();
pub fn _PyImport_AcquireLock();
pub fn _PyImport_ReleaseLock() -> c_int;
pub fn _PyImport_FindModule(arg1: *const c_char,
arg2: *mut PyObject,
arg3: *mut c_char, arg4: size_t,
arg5: *mut *mut FILE,
arg6: *mut *mut PyObject)
-> *mut Struct_filedescr;
pub fn _PyImport_IsScript(arg1: *mut Struct_filedescr) -> c_int;
pub fn _PyImport_ReInitLock();
pub fn _PyImport_FindExtension(arg1: *mut c_char,
arg2: *mut c_char)
-> *mut PyObject;
pub fn _PyImport_FixupExtension(arg1: *mut c_char,
arg2: *mut c_char)
-> *mut PyObject;*/
}
| 32.888889 | 90 | 0.645946 |
8f8cbeee3c4165b9a990e3989442f0510f1606bf | 2,371 | use nom::bytes::complete::take;
use nom::character::{is_alphanumeric, is_space};
use nom::number::complete::be_u16;
use nom::IResult;
pub fn length_value(input: &[u8]) -> IResult<&[u8], &[u8]> {
let (input, length) = be_u16(input)?;
take(length)(input)
}
named!(method, take_while1!(is_alphanumeric));
named!(space, take_while1!(|c| c == b' '));
named!(url, take_while1!(|c| c != b' '));
named!(http, tag!("HTTP/"));
named!(
version,
take_while1!(|c| c >= b'0' && c <= b'9' || c == b'.')
);
named!(crlf, tag!("\r\n"));
named!(http_version, preceded!(http, version));
// Primitives
fn is_token_char(i: u8) -> bool {
is_alphanumeric(i) || b"!#$%&'*+-.^_`|~".contains(&i)
}
named!(token, take_while!(is_token_char));
named!(
message_header<Header>,
do_parse!(
name: token
>> tag!(":")
>> opt!(take_while!(is_space))
>> value: take_while!(is_header_value_char)
>> crlf
>> (Header {
name: name,
value: value
})
)
);
named!(
headers<Vec<Header>>,
terminated!(many0!(message_header), opt!(crlf))
);
named!(
http_req<&[u8], (&[u8], &[u8],&[u8], &[u8],&[u8], &[u8], Vec<Header>) >,
tuple!(method, space, url, space, http_version, crlf, headers)
);
fn is_header_value_char(i: u8) -> bool {
i == 9 || (i >= 32 && i <= 126) || i >= 160
}
#[derive(PartialEq, Debug, Default)]
pub struct Header<'a> {
pub name: &'a [u8],
pub value: &'a [u8],
}
#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;
#[test]
fn test_request_line() {
let req_line = b"GET /pub/WWW/TheProject.html HTTP/1.1\r\nHost: www.w3.org\r\nForwarded: proto:https;for=27.0.0.1:1234;by:proxy\r\n\r\n";
let request = http_req(req_line);
let (_, (method, _, url, _, http_version, _, header)) = request.unwrap();
assert_eq!(b"GET", method);
assert_eq!(b"/pub/WWW/TheProject.html", url);
assert_eq!(b"1.1", http_version);
assert_eq!(vec![
Header{
name: b"Host",
value: b"www.w3.org",
},
Header{
name: b"Forwarded",
value: b"proto:https;for=27.0.0.1:1234;by:proxy",
},
], header);
}
}
| 27.569767 | 145 | 0.538591 |
3a6417255dfd97db9198142cc1c6691689305554 | 379 | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
impl super::FCFG_B1_SSIZE3 {
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R { bits: self.register.get() }
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
}
| 19.947368 | 51 | 0.546174 |
e49c3a21bd0bbd7ca66191f3d60fddba4825cfd8 | 620 | use std::collections::HashMap;
const NUCLEOTIDES: [char; 4] = ['A', 'C', 'G', 'T'];
pub fn count(nucleotide: char, strand: &str) -> Result<usize, &'static str> {
if !NUCLEOTIDES.contains(&nucleotide) {
return Err("Invalid nucleotide");
}
if strand.chars().any(|c| !NUCLEOTIDES.contains(&c)) {
return Err("Invalid DNA strand");
}
Ok(strand.chars().filter(|&c| c == nucleotide).count())
}
pub fn nucleotide_counts(strand: &str) -> Result<HashMap<char, usize>, &'static str> {
NUCLEOTIDES
.iter()
.map(|&n| count(n, strand).map(|c| (n, c)))
.collect()
}
| 26.956522 | 86 | 0.585484 |
4b0dab20a798e8888b61318725c5239b0198e322 | 8,858 | #![allow(unused_imports, non_camel_case_types)]
use crate::models::r4::Element::Element;
use crate::models::r4::Extension::Extension;
use serde_json::json;
use serde_json::value::Value;
use std::borrow::Cow;
/// A compartment definition that defines how resources are accessed on a server.
#[derive(Debug)]
pub struct CompartmentDefinition_Resource<'a> {
pub(crate) value: Cow<'a, Value>,
}
impl CompartmentDefinition_Resource<'_> {
pub fn new(value: &Value) -> CompartmentDefinition_Resource {
CompartmentDefinition_Resource {
value: Cow::Borrowed(value),
}
}
pub fn to_json(&self) -> Value {
(*self.value).clone()
}
/// Extensions for code
pub fn _code(&self) -> Option<Element> {
if let Some(val) = self.value.get("_code") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for documentation
pub fn _documentation(&self) -> Option<Element> {
if let Some(val) = self.value.get("_documentation") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for param
pub fn _param(&self) -> Option<Vec<Element>> {
if let Some(Value::Array(val)) = self.value.get("_param") {
return Some(
val.into_iter()
.map(|e| Element {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// The name of a resource supported by the server.
pub fn code(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("code") {
return Some(string);
}
return None;
}
/// Additional documentation about the resource and compartment.
pub fn documentation(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("documentation") {
return Some(string);
}
return None;
}
/// May be used to represent additional information that is not part of the basic
/// definition of the element. To make the use of extensions safe and manageable,
/// there is a strict set of governance applied to the definition and use of
/// extensions. Though any implementer can define an extension, there is a set of
/// requirements that SHALL be met as part of the definition of the extension.
pub fn extension(&self) -> Option<Vec<Extension>> {
if let Some(Value::Array(val)) = self.value.get("extension") {
return Some(
val.into_iter()
.map(|e| Extension {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// Unique id for the element within a resource (for internal references). This may be
/// any string value that does not contain spaces.
pub fn id(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("id") {
return Some(string);
}
return None;
}
/// May be used to represent additional information that is not part of the basic
/// definition of the element and that modifies the understanding of the element
/// in which it is contained and/or the understanding of the containing element's
/// descendants. Usually modifier elements provide negation or qualification. To make
/// the use of extensions safe and manageable, there is a strict set of governance
/// applied to the definition and use of extensions. Though any implementer can define
/// an extension, there is a set of requirements that SHALL be met as part of the
/// definition of the extension. Applications processing a resource are required to
/// check for modifier extensions. Modifier extensions SHALL NOT change the meaning
/// of any elements on Resource or DomainResource (including cannot change the meaning
/// of modifierExtension itself).
pub fn modifier_extension(&self) -> Option<Vec<Extension>> {
if let Some(Value::Array(val)) = self.value.get("modifierExtension") {
return Some(
val.into_iter()
.map(|e| Extension {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// The name of a search parameter that represents the link to the compartment. More
/// than one may be listed because a resource may be linked to a compartment in more
/// than one way,.
pub fn param(&self) -> Option<Vec<&str>> {
if let Some(Value::Array(val)) = self.value.get("param") {
return Some(
val.into_iter()
.map(|e| e.as_str().unwrap())
.collect::<Vec<_>>(),
);
}
return None;
}
pub fn validate(&self) -> bool {
if let Some(_val) = self._code() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._documentation() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._param() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.code() {}
if let Some(_val) = self.documentation() {}
if let Some(_val) = self.extension() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.id() {}
if let Some(_val) = self.modifier_extension() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.param() {
_val.into_iter().for_each(|_e| {});
}
return true;
}
}
#[derive(Debug)]
pub struct CompartmentDefinition_ResourceBuilder {
pub(crate) value: Value,
}
impl CompartmentDefinition_ResourceBuilder {
pub fn build(&self) -> CompartmentDefinition_Resource {
CompartmentDefinition_Resource {
value: Cow::Owned(self.value.clone()),
}
}
pub fn with(existing: CompartmentDefinition_Resource) -> CompartmentDefinition_ResourceBuilder {
CompartmentDefinition_ResourceBuilder {
value: (*existing.value).clone(),
}
}
pub fn new() -> CompartmentDefinition_ResourceBuilder {
let mut __value: Value = json!({});
return CompartmentDefinition_ResourceBuilder { value: __value };
}
pub fn _code<'a>(&'a mut self, val: Element) -> &'a mut CompartmentDefinition_ResourceBuilder {
self.value["_code"] = json!(val.value);
return self;
}
pub fn _documentation<'a>(
&'a mut self,
val: Element,
) -> &'a mut CompartmentDefinition_ResourceBuilder {
self.value["_documentation"] = json!(val.value);
return self;
}
pub fn _param<'a>(
&'a mut self,
val: Vec<Element>,
) -> &'a mut CompartmentDefinition_ResourceBuilder {
self.value["_param"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn code<'a>(&'a mut self, val: &str) -> &'a mut CompartmentDefinition_ResourceBuilder {
self.value["code"] = json!(val);
return self;
}
pub fn documentation<'a>(
&'a mut self,
val: &str,
) -> &'a mut CompartmentDefinition_ResourceBuilder {
self.value["documentation"] = json!(val);
return self;
}
pub fn extension<'a>(
&'a mut self,
val: Vec<Extension>,
) -> &'a mut CompartmentDefinition_ResourceBuilder {
self.value["extension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn id<'a>(&'a mut self, val: &str) -> &'a mut CompartmentDefinition_ResourceBuilder {
self.value["id"] = json!(val);
return self;
}
pub fn modifier_extension<'a>(
&'a mut self,
val: Vec<Extension>,
) -> &'a mut CompartmentDefinition_ResourceBuilder {
self.value["modifierExtension"] =
json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn param<'a>(
&'a mut self,
val: Vec<&str>,
) -> &'a mut CompartmentDefinition_ResourceBuilder {
self.value["param"] = json!(val);
return self;
}
}
| 33.426415 | 100 | 0.562655 |
75dd49473090f616a114da84532e89beef74d43c | 4,372 | use std::fs;
//struct with the instruction: the direction and the action
// then implement the move on N,S,E,W; rotate on L,R; move N,S,E,W on F
// the problem with direction facing is that the byte values aren't 1:1 mapped to compass angles
// So N = 0, E = 90, S = 180, W = 270 rotating right
// N = 0, W = 90, S = 180, E = 270 rotating left
// but that's if you're facing N, is it not?
struct Ship {
x: i32,
y: i32,
facing: u8,
}
struct Instruction {
direction: u8, //This is a char
distance: i32,
}
impl Ship {
fn new() -> Self {
Self {
x: 0,
y: 0,
facing: b'E', //this is problematic. Should have used an enum
}
}
//Oh my god I love this. RECURSION! YEAH! :D
fn move_direction(self: &mut Self, inst: Instruction) {
match inst.direction {
b'N' => self.x += inst.distance,
b'S' => self.x -= inst.distance,
b'E' => self.y += inst.distance,
b'W' => self.y -= inst.distance,
b'L' => self.rotate_left(inst.distance),
b'R' => self.rotate_right(inst.distance),
b'F' => self.move_direction(Instruction::new(self.facing, inst.distance)),
_ => panic!("Hoh baby, something went wrong in move_direciton"),
}
}
fn rotate_left(self: &mut Self, degree: i32) {
let adjust_to = degree / 90;
match self.facing {
b'N' => match adjust_to {
1 => self.facing = b'W',
2 => self.facing = b'S',
3 => self.facing = b'E',
_ => {}
},
b'S' => match adjust_to {
1 => self.facing = b'E',
2 => self.facing = b'N',
3 => self.facing = b'W',
_ => {}
},
b'E' => match adjust_to {
1 => self.facing = b'N',
2 => self.facing = b'W',
3 => self.facing = b'S',
_ => {}
},
b'W' => match adjust_to {
1 => self.facing = b'S',
2 => self.facing = b'E',
3 => self.facing = b'N',
_ => {}
},
_ => {}
}
}
fn rotate_right(self: &mut Self, degree: i32) {
let adjust_to = degree / 90;
match self.facing {
b'N' => match adjust_to {
1 => self.facing = b'E',
2 => self.facing = b'S',
3 => self.facing = b'W',
_ => {}
},
b'S' => match adjust_to {
1 => self.facing = b'W',
2 => self.facing = b'N',
3 => self.facing = b'E',
_ => {}
},
b'E' => match adjust_to {
1 => self.facing = b'S',
2 => self.facing = b'W',
3 => self.facing = b'N',
_ => {}
},
b'W' => match adjust_to {
1 => self.facing = b'N',
2 => self.facing = b'E',
3 => self.facing = b'S',
_ => {}
},
_ => {}
}
}
}
impl Instruction {
fn new(direction: u8, distance: i32) -> Self {
Self {
direction,
distance,
}
}
}
pub fn execute_daytwelve() -> i32 {
let path = "./input/day12.txt";
let working = prepare_input(path);
let destination = process_movement(working);
let manhattan_dist = destination.x.abs() + destination.y.abs();
println!("manhattan distance is {}", manhattan_dist);
manhattan_dist
}
fn process_movement(instuct: Vec<Instruction>) -> Ship {
let mut boat = Ship::new();
for x in instuct {
//println!(" Go {} for {}", &x.direction, &x.distance);
boat.move_direction(x);
println!("Boat is at {}, {}, and faces {}", &boat.x, &boat.y, &boat.facing)
}
println!("Arrived at {},{}", &boat.x, &boat.y);
boat
}
fn prepare_input(filepath: &str) -> Vec<Instruction> {
let list = fs::read_to_string(filepath).expect("Yeah, that's not a file");
let ret: Vec<Instruction> = list
.as_str()
.split('\n')
.map(|x| {
let mut dist = String::from(x);
let direc = dist.split_off(1);
Instruction::new(dist.bytes().next().unwrap(), direc.parse::<i32>().unwrap())
})
.collect();
ret
}
| 29.741497 | 96 | 0.465233 |
6a7e7e8c23cc0e5544895236438f3699cbd86058 | 19,526 | // This file is part of Substrate.
// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd. SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under
// the License.
//! A set of election algorithms to be used with a substrate runtime, typically within the staking
//! sub-system. Notable implementation include:
//!
//! - [`seq_phragmen`]: Implements the Phragmén Sequential Method. An un-ranked, relatively fast
//! election method that ensures PJR, but does not provide a constant factor approximation of the
//! maximin problem.
//! - [`phragmms`](phragmms::phragmms): Implements a hybrid approach inspired by Phragmén which is
//! executed faster but it can achieve a constant factor approximation of the maximin problem,
//! similar to that of the MMS algorithm.
//! - [`balance`](balancing::balance): Implements the star balancing algorithm. This iterative
//! process can push a solution toward being more "balanced", which in turn can increase its
//! score.
//!
//! ### Terminology
//!
//! This crate uses context-independent words, not to be confused with staking. This is because the
//! election algorithms of this crate, while designed for staking, can be used in other contexts as
//! well.
//!
//! `Voter`: The entity casting some votes to a number of `Targets`. This is the same as `Nominator`
//! in the context of staking. `Target`: The entities eligible to be voted upon. This is the same as
//! `Validator` in the context of staking. `Edge`: A mapping from a `Voter` to a `Target`.
//!
//! The goal of an election algorithm is to provide an `ElectionResult`. A data composed of:
//! - `winners`: A flat list of identifiers belonging to those who have won the election, usually
//! ordered in some meaningful way. They are zipped with their total backing stake.
//! - `assignment`: A mapping from each voter to their winner-only targets, zipped with a ration
//! denoting the amount of support given to that particular target.
//!
//! ```rust
//! # use sp_npos_elections::*;
//! # use sp_runtime::Perbill;
//! // the winners.
//! let winners = vec![(1, 100), (2, 50)];
//! let assignments = vec![
//! // A voter, giving equal backing to both 1 and 2.
//! Assignment {
//! who: 10,
//! distribution: vec![(1, Perbill::from_percent(50)), (2, Perbill::from_percent(50))],
//! },
//! // A voter, Only backing 1.
//! Assignment { who: 20, distribution: vec![(1, Perbill::from_percent(100))] },
//! ];
//!
//! // the combination of the two makes the election result.
//! let election_result = ElectionResult { winners, assignments };
//! ```
//!
//! The `Assignment` field of the election result is voter-major, i.e. it is from the perspective of
//! the voter. The struct that represents the opposite is called a `Support`. This struct is usually
//! accessed in a map-like manner, i.e. keyed by voters, therefor it is stored as a mapping called
//! `SupportMap`.
//!
//! Moreover, the support is built from absolute backing values, not ratios like the example above.
//! A struct similar to `Assignment` that has stake value instead of ratios is called an
//! `StakedAssignment`.
//!
//!
//! More information can be found at: <https://arxiv.org/abs/2004.12990>
#![cfg_attr(not(feature = "std"), no_std)]
use sp_arithmetic::{traits::Zero, Normalizable, PerThing, Rational128, ThresholdOrd};
use sp_core::RuntimeDebug;
use sp_std::{cell::RefCell, cmp::Ordering, collections::btree_map::BTreeMap, prelude::*, rc::Rc};
use codec::{Decode, Encode};
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
mod assignments;
pub mod balancing;
pub mod helpers;
pub mod node;
pub mod phragmen;
pub mod phragmms;
pub mod pjr;
pub mod reduce;
pub mod traits;
pub use assignments::{Assignment, IndexAssignment, IndexAssignmentOf, StakedAssignment};
pub use balancing::*;
pub use helpers::*;
pub use phragmen::*;
pub use phragmms::*;
pub use pjr::*;
pub use reduce::reduce;
pub use traits::{IdentifierT, NposSolution, PerThing128, __OrInvalidIndex};
// re-export for the solution macro, with the dependencies of the macro.
#[doc(hidden)]
pub use codec;
#[doc(hidden)]
pub use sp_arithmetic;
#[doc(hidden)]
pub use sp_std;
// re-export the solution type macro.
pub use sp_npos_elections_solution_type::generate_solution_type;
/// The errors that might occur in the this crate and solution-type.
#[derive(Eq, PartialEq, RuntimeDebug)]
pub enum Error {
/// While going from solution indices to ratio, the weight of all the edges has gone above the
/// total.
SolutionWeightOverflow,
/// The solution type has a voter who's number of targets is out of bound.
SolutionTargetOverflow,
/// One of the index functions returned none.
SolutionInvalidIndex,
/// One of the page indices was invalid
SolutionInvalidPageIndex,
/// An error occurred in some arithmetic operation.
ArithmeticError(&'static str),
/// The data provided to create support map was invalid.
InvalidSupportEdge,
}
/// A type which is used in the API of this crate as a numeric weight of a vote, most often the
/// stake of the voter. It is always converted to [`ExtendedBalance`] for computation.
pub type VoteWeight = u64;
/// A type in which performing operations on vote weights are safe.
pub type ExtendedBalance = u128;
/// The score of an assignment. This can be computed from the support map via
/// [`EvaluateSupport::evaluate`].
pub type ElectionScore = [ExtendedBalance; 3];
/// A winner, with their respective approval stake.
pub type WithApprovalOf<A> = (A, ExtendedBalance);
/// A pointer to a candidate struct with interior mutability.
pub type CandidatePtr<A> = Rc<RefCell<Candidate<A>>>;
/// A candidate entity for the election.
#[derive(RuntimeDebug, Clone, Default)]
pub struct Candidate<AccountId> {
/// Identifier.
who: AccountId,
/// Score of the candidate.
///
/// Used differently in seq-phragmen and max-score.
score: Rational128,
/// Approval stake of the candidate. Merely the sum of all the voter's stake who approve this
/// candidate.
approval_stake: ExtendedBalance,
/// The final stake of this candidate. Will be equal to a subset of approval stake.
backed_stake: ExtendedBalance,
/// True if this candidate is already elected in the current election.
elected: bool,
/// The round index at which this candidate was elected.
round: usize,
}
impl<AccountId> Candidate<AccountId> {
pub fn to_ptr(self) -> CandidatePtr<AccountId> {
Rc::new(RefCell::new(self))
}
}
/// A vote being casted by a [`Voter`] to a [`Candidate`] is an `Edge`.
#[derive(Clone, Default)]
pub struct Edge<AccountId> {
/// Identifier of the target.
///
/// This is equivalent of `self.candidate.borrow().who`, yet it helps to avoid double borrow
/// errors of the candidate pointer.
who: AccountId,
/// Load of this edge.
load: Rational128,
/// Pointer to the candidate.
candidate: CandidatePtr<AccountId>,
/// The weight (i.e. stake given to `who`) of this edge.
weight: ExtendedBalance,
}
#[cfg(feature = "std")]
impl<A: IdentifierT> sp_std::fmt::Debug for Edge<A> {
fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result {
write!(f, "Edge({:?}, weight = {:?})", self.who, self.weight)
}
}
/// A voter entity.
#[derive(Clone, Default)]
pub struct Voter<AccountId> {
/// Identifier.
who: AccountId,
/// List of candidates approved by this voter.
edges: Vec<Edge<AccountId>>,
/// The stake of this voter.
budget: ExtendedBalance,
/// Load of the voter.
load: Rational128,
}
#[cfg(feature = "std")]
impl<A: IdentifierT> std::fmt::Debug for Voter<A> {
fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result {
write!(f, "Voter({:?}, budget = {}, edges = {:?})", self.who, self.budget, self.edges)
}
}
impl<AccountId: IdentifierT> Voter<AccountId> {
/// Create a new `Voter`.
pub fn new(who: AccountId) -> Self {
Self { who, ..Default::default() }
}
/// Returns `true` if `self` votes for `target`.
///
/// Note that this does not take into account if `target` is elected (i.e. is *active*) or not.
pub fn votes_for(&self, target: &AccountId) -> bool {
self.edges.iter().any(|e| &e.who == target)
}
/// Returns none if this voter does not have any non-zero distributions.
///
/// Note that this might create _un-normalized_ assignments, due to accuracy loss of `P`. Call
/// site might compensate by calling `normalize()` on the returned `Assignment` as a
/// post-precessing.
pub fn into_assignment<P: PerThing>(self) -> Option<Assignment<AccountId, P>> {
let who = self.who;
let budget = self.budget;
let distribution = self
.edges
.into_iter()
.filter_map(|e| {
let per_thing = P::from_rational(e.weight, budget);
// trim zero edges.
if per_thing.is_zero() {
None
} else {
Some((e.who, per_thing))
}
})
.collect::<Vec<_>>();
if distribution.len() > 0 {
Some(Assignment { who, distribution })
} else {
None
}
}
/// Try and normalize the votes of self.
///
/// If the normalization is successful then `Ok(())` is returned.
///
/// Note that this will not distinguish between elected and unelected edges. Thus, it should
/// only be called on a voter who has already been reduced to only elected edges.
///
/// ### Errors
///
/// This will return only if the internal `normalize` fails. This can happen if the sum of the
/// weights exceeds `ExtendedBalance::max_value()`.
pub fn try_normalize(&mut self) -> Result<(), &'static str> {
let edge_weights = self.edges.iter().map(|e| e.weight).collect::<Vec<_>>();
edge_weights.normalize(self.budget).map(|normalized| {
// here we count on the fact that normalize does not change the order.
for (edge, corrected) in self.edges.iter_mut().zip(normalized.into_iter()) {
let mut candidate = edge.candidate.borrow_mut();
// first, subtract the incorrect weight
candidate.backed_stake = candidate.backed_stake.saturating_sub(edge.weight);
edge.weight = corrected;
// Then add the correct one again.
candidate.backed_stake = candidate.backed_stake.saturating_add(edge.weight);
}
})
}
/// Same as [`Self::try_normalize`] but the normalization is only limited between elected edges.
pub fn try_normalize_elected(&mut self) -> Result<(), &'static str> {
let elected_edge_weights = self
.edges
.iter()
.filter_map(|e| if e.candidate.borrow().elected { Some(e.weight) } else { None })
.collect::<Vec<_>>();
elected_edge_weights.normalize(self.budget).map(|normalized| {
// here we count on the fact that normalize does not change the order, and that vector
// iteration is deterministic.
for (edge, corrected) in self
.edges
.iter_mut()
.filter(|e| e.candidate.borrow().elected)
.zip(normalized.into_iter())
{
let mut candidate = edge.candidate.borrow_mut();
// first, subtract the incorrect weight
candidate.backed_stake = candidate.backed_stake.saturating_sub(edge.weight);
edge.weight = corrected;
// Then add the correct one again.
candidate.backed_stake = candidate.backed_stake.saturating_add(edge.weight);
}
})
}
/// This voter's budget
#[inline]
pub fn budget(&self) -> ExtendedBalance {
self.budget
}
}
/// Final result of the election.
#[derive(RuntimeDebug)]
pub struct ElectionResult<AccountId, P: PerThing> {
/// Just winners zipped with their approval stake. Note that the approval stake is merely the
/// sub of their received stake and could be used for very basic sorting and approval voting.
pub winners: Vec<WithApprovalOf<AccountId>>,
/// Individual assignments. for each tuple, the first elements is a voter and the second is the
/// list of candidates that it supports.
pub assignments: Vec<Assignment<AccountId, P>>,
}
/// A structure to demonstrate the election result from the perspective of the candidate, i.e. how
/// much support each candidate is receiving.
///
/// This complements the [`ElectionResult`] and is needed to run the balancing post-processing.
///
/// This, at the current version, resembles the `Exposure` defined in the Staking pallet, yet they
/// do not necessarily have to be the same.
#[derive(Default, RuntimeDebug, Encode, Decode, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct Support<AccountId> {
/// Total support.
pub total: ExtendedBalance,
/// Support from voters.
pub voters: Vec<(AccountId, ExtendedBalance)>,
}
/// A target-major representation of the the election outcome.
///
/// Essentially a flat variant of [`SupportMap`].
///
/// The main advantage of this is that it is encodable.
pub type Supports<A> = Vec<(A, Support<A>)>;
/// Linkage from a winner to their [`Support`].
///
/// This is more helpful than a normal [`Supports`] as it allows faster error checking.
pub type SupportMap<A> = BTreeMap<A, Support<A>>;
/// Helper trait to convert from a support map to a flat support vector.
pub trait FlattenSupportMap<A> {
/// Flatten the support.
fn flatten(self) -> Supports<A>;
}
impl<A> FlattenSupportMap<A> for SupportMap<A> {
fn flatten(self) -> Supports<A> {
self.into_iter().collect::<Vec<_>>()
}
}
/// Build the support map from the winners and assignments.
///
/// The list of winners is basically a redundancy for error checking only; It ensures that all the
/// targets pointed to by the [`Assignment`] are present in the `winners`.
pub fn to_support_map<AccountId: IdentifierT>(
winners: &[AccountId],
assignments: &[StakedAssignment<AccountId>],
) -> Result<SupportMap<AccountId>, Error> {
// Initialize the support of each candidate.
let mut supports = <SupportMap<AccountId>>::new();
winners.iter().for_each(|e| {
supports.insert(e.clone(), Default::default());
});
// build support struct.
for StakedAssignment { who, distribution } in assignments.iter() {
for (c, weight_extended) in distribution.iter() {
if let Some(support) = supports.get_mut(c) {
support.total = support.total.saturating_add(*weight_extended);
support.voters.push((who.clone(), *weight_extended));
} else {
return Err(Error::InvalidSupportEdge)
}
}
}
Ok(supports)
}
/// Same as [`to_support_map`] except it calls `FlattenSupportMap` on top of the result to return a
/// flat vector.
///
/// Similar to [`to_support_map`], `winners` is used for error checking.
pub fn to_supports<AccountId: IdentifierT>(
winners: &[AccountId],
assignments: &[StakedAssignment<AccountId>],
) -> Result<Supports<AccountId>, Error> {
to_support_map(winners, assignments).map(FlattenSupportMap::flatten)
}
/// Extension trait for evaluating a support map or vector.
pub trait EvaluateSupport<K> {
/// Evaluate a support map. The returned tuple contains:
///
/// - Minimum support. This value must be **maximized**.
/// - Sum of all supports. This value must be **maximized**.
/// - Sum of all supports squared. This value must be **minimized**.
fn evaluate(self) -> ElectionScore;
}
/// A common wrapper trait for both (&A, &B) and &(A, B).
///
/// This allows us to implemented something for both `Vec<_>` and `BTreeMap<_>`, such as
/// [`EvaluateSupport`].
pub trait TupleRef<K, V> {
fn extract(&self) -> (&K, &V);
}
impl<K, V> TupleRef<K, V> for &(K, V) {
fn extract(&self) -> (&K, &V) {
(&self.0, &self.1)
}
}
impl<K, V> TupleRef<K, V> for (K, V) {
fn extract(&self) -> (&K, &V) {
(&self.0, &self.1)
}
}
impl<K, V> TupleRef<K, V> for (&K, &V) {
fn extract(&self) -> (&K, &V) {
(self.0, self.1)
}
}
impl<A, C, I> EvaluateSupport<A> for C
where
C: IntoIterator<Item = I>,
I: TupleRef<A, Support<A>>,
A: IdentifierT,
{
fn evaluate(self) -> ElectionScore {
let mut min_support = ExtendedBalance::max_value();
let mut sum: ExtendedBalance = Zero::zero();
// NOTE: The third element might saturate but fine for now since this will run on-chain and
// need to be fast.
let mut sum_squared: ExtendedBalance = Zero::zero();
for item in self {
let (_, support) = item.extract();
sum = sum.saturating_add(support.total);
let squared = support.total.saturating_mul(support.total);
sum_squared = sum_squared.saturating_add(squared);
if support.total < min_support {
min_support = support.total;
}
}
[min_support, sum, sum_squared]
}
}
/// Compares two sets of election scores based on desirability and returns true if `this` is better
/// than `that`.
///
/// Evaluation is done in a lexicographic manner, and if each element of `this` is `that * epsilon`
/// greater or less than `that`.
///
/// Note that the third component should be minimized.
pub fn is_score_better<P: PerThing>(this: ElectionScore, that: ElectionScore, epsilon: P) -> bool {
match this
.iter()
.zip(that.iter())
.map(|(thi, tha)| (thi.ge(&tha), thi.tcmp(&tha, epsilon.mul_ceil(*tha))))
.collect::<Vec<(bool, Ordering)>>()
.as_slice()
{
// epsilon better in the score[0], accept.
[(_, Ordering::Greater), _, _] => true,
// less than epsilon better in score[0], but more than epsilon better in the second.
[(true, Ordering::Equal), (_, Ordering::Greater), _] => true,
// less than epsilon better in score[0, 1], but more than epsilon better in the third
[(true, Ordering::Equal), (true, Ordering::Equal), (_, Ordering::Less)] => true,
// anything else is not a good score.
_ => false,
}
}
/// Converts raw inputs to types used in this crate.
///
/// This will perform some cleanup that are most often important:
/// - It drops any votes that are pointing to non-candidates.
/// - It drops duplicate targets within a voter.
pub fn setup_inputs<AccountId: IdentifierT>(
initial_candidates: Vec<AccountId>,
initial_voters: Vec<(AccountId, VoteWeight, Vec<AccountId>)>,
) -> (Vec<CandidatePtr<AccountId>>, Vec<Voter<AccountId>>) {
// used to cache and access candidates index.
let mut c_idx_cache = BTreeMap::<AccountId, usize>::new();
let candidates = initial_candidates
.into_iter()
.enumerate()
.map(|(idx, who)| {
c_idx_cache.insert(who.clone(), idx);
Candidate { who, ..Default::default() }.to_ptr()
})
.collect::<Vec<CandidatePtr<AccountId>>>();
let voters = initial_voters
.into_iter()
.filter_map(|(who, voter_stake, votes)| {
let mut edges: Vec<Edge<AccountId>> = Vec::with_capacity(votes.len());
for v in votes {
if edges.iter().any(|e| e.who == v) {
// duplicate edge.
continue
}
if let Some(idx) = c_idx_cache.get(&v) {
// This candidate is valid + already cached.
let mut candidate = candidates[*idx].borrow_mut();
candidate.approval_stake =
candidate.approval_stake.saturating_add(voter_stake.into());
edges.push(Edge {
who: v.clone(),
candidate: Rc::clone(&candidates[*idx]),
..Default::default()
});
} // else {} would be wrong votes. We don't really care about it.
}
if edges.is_empty() {
None
} else {
Some(Voter { who, edges, budget: voter_stake.into(), load: Rational128::zero() })
}
})
.collect::<Vec<_>>();
(candidates, voters)
}
| 35.055655 | 100 | 0.692615 |
014027b79273f59133d21ef7bbcc6d64c4b5c45b | 660 | use linfa_clustering::{KMeans, KMeansHyperParams};
#[test]
#[should_panic]
fn n_clusters_cannot_be_zero() {
KMeans::<f32>::params(0).build();
}
#[test]
#[should_panic]
fn tolerance_has_to_positive() {
KMeansHyperParams::new(1).tolerance(-1.).build();
}
#[test]
#[should_panic]
fn tolerance_cannot_be_zero() {
KMeansHyperParams::new(1).tolerance(0.).build();
}
#[test]
#[should_panic]
fn max_n_iterations_cannot_be_zero() {
KMeansHyperParams::new(1)
.tolerance(1.)
.max_n_iterations(0)
.build();
}
#[test]
#[should_panic]
fn n_runs_cannot_be_zero() {
KMeansHyperParams::new(1).tolerance(1.).n_runs(0).build();
}
| 18.857143 | 62 | 0.677273 |
7a63555f74b3eed4d82980c26edc9741d1c5139a | 1,189 | //! Format commands.
use crate::models::AclId;
use crate::requests::{BackendId, ErrorFlag};
use std::io::{Result, Write};
pub fn end<W: Write>(w: &mut W) -> Result<()> {
w.write_all(b"\n")
}
pub fn add_acl<W: Write>(w: &mut W, id: AclId, entry: &str) -> Result<()> {
w.write_fmt(format_args!("add acl {} {}", id, entry))
}
pub fn show_acl<W: Write>(w: &mut W) -> Result<()> {
w.write_all(b"show acl")
}
pub fn show_acl_entries<W: Write>(w: &mut W, id: AclId) -> Result<()> {
w.write_fmt(format_args!("show acl {}", id))
}
pub fn show_cli_level<W: Write>(w: &mut W) -> Result<()> {
w.write_all(b"show cli level")
}
pub fn show_cli_sockets<W: Write>(w: &mut W) -> Result<()> {
w.write_all(b"show cli sockets")
}
pub fn show_errors<W: Write>(w: &mut W) -> Result<()> {
w.write_all(b"show errors")
}
pub fn show_errors_backend<W: Write>(
w: &mut W,
id: BackendId,
error_type: ErrorFlag,
) -> Result<()> {
let error_type_str = match error_type {
ErrorFlag::All => "",
ErrorFlag::Request => " request",
ErrorFlag::Response => " response",
};
w.write_fmt(format_args!("show errors {}{}", id, error_type_str))
}
| 25.297872 | 75 | 0.59714 |
d5d3ca1879eeb8f6f5c3af0450584c16eb1450de | 1,462 | #![deny(clippy::all)]
#![deny(clippy::pedantic)]
#![deny(warnings, intra_doc_link_resolution_failure)]
//! This integration test checks for memory leaks that stem from improper
//! arena handling in `ValueLike::funcall`.
//!
//! Checks for memory leaks stemming from improperly grabage collecting Ruby
//! objects created in C functions, like the call to `sys::mrb_funcall_argv`.
//!
//! This test creates a 1MB Ruby string and calls `dup` in a loop. The test
//! reuses one artichoke interpreter for all `ITERATIONS`.
//!
//! If resident memory increases more than 10MB during the test, we likely are
//! leaking memory.
use artichoke_backend::convert::Convert;
use artichoke_backend::gc::MrbGarbageCollection;
use artichoke_backend::value::Value;
use artichoke_core::value::Value as ValueLike;
mod leak;
const ITERATIONS: usize = 100;
const LEAK_TOLERANCE: i64 = 1024 * 1024 * 30;
#[test]
fn funcall_arena() {
let interp = artichoke_backend::interpreter().expect("init");
let s: Value = interp.convert("a".repeat(1024 * 1024));
leak::Detector::new("ValueLike::funcall", ITERATIONS, LEAK_TOLERANCE).check_leaks(|_| {
let expected = format!(r#""{}""#, "a".repeat(1024 * 1024));
// we have to call a function that calls into the Ruby VM, so we can't
// just use `to_s`.
let inspect = s.funcall::<String>("inspect", &[], None);
assert_eq!(inspect, Ok(expected));
interp.incremental_gc();
});
}
| 35.658537 | 91 | 0.692202 |
61e6486bdd1fe672ce8ca9eb1d6921a107b881b1 | 268 | #![no_std]
extern crate alloc;
mod consts;
#[cfg(not(feature = "minimal"))]
mod default;
#[cfg(feature = "minimal")]
mod minimal;
#[cfg(not(feature = "minimal"))]
pub use default::{Blake2b, Blake2s};
#[cfg(feature = "minimal")]
pub use minimal::{Blake2b, Blake2s};
| 17.866667 | 36 | 0.66791 |
b913f7f73e524b4548ca38a58313f582578c446e | 11,446 | //! Setting functionality - set cookie data
use url::{utf8_percent_encode, FORM_URLENCODED_ENCODE_SET};
use serialize::json::{Json, Number, String, Boolean, List, Object, Null};
use iron::Response;
use super::Cookie;
use time::Tm;
use std::collections::TreeMap;
/// Set cookies.
///
/// This trait is added as a mix-in to `Response`, allowing
/// simple cookie-setting.
pub trait SetCookie {
/// Set a cookie.
///
/// Set cookies directly on the response with `res.set_cookie("coo=kie;")`.
/// Only one cookie may sent per response, with the given key/value.
/// Doing otherwise will result in ***undefined behavior***.
///
/// Keys/values may contain restricted characters, but they will be URI encoded in the cookie.
///
/// They will be decoded when the cookie is returned to the server.
///
/// Cookies ***must*** be set before the response body is sent.
/// Headers are flushed as soon anything is sent in the response body.
fn set_cookie(&mut self, &Cookie, (String, String), HeaderCollection);
/// Set a cookie as JSON.
///
/// Cookies set as JSON will be available under `cookie.json`.
/// Otherwise, they behave exactly as normally serialized cookies.
///
/// Note that restricted characters will still be URI encoded in your cookie.
///
/// They will be decoded when the cookie is returned to the server.
fn set_json_cookie(&mut self, &Cookie, (String, Json), HeaderCollection);
}
impl SetCookie for Response {
fn set_cookie(&mut self,
signer: &Cookie,
(key, value): (String, String),
options: HeaderCollection) {
self.headers.extensions.insert("Set-Cookie".to_string(),
match signer.sign(&value) {
Some(signature) => {
utf8_percent_encode(key.as_slice(), FORM_URLENCODED_ENCODE_SET)
.append("=")
.append("s:")
.append(utf8_percent_encode(value.as_slice(), FORM_URLENCODED_ENCODE_SET).as_slice())
.append(".")
.append(signature.as_slice())
},
None => {
utf8_percent_encode(key.as_slice(), FORM_URLENCODED_ENCODE_SET)
.append("=")
.append(utf8_percent_encode(value.as_slice(), FORM_URLENCODED_ENCODE_SET).as_slice())
}
}.append(options.to_cookie_av().as_slice())
);
}
fn set_json_cookie(&mut self,
signer: &Cookie,
(key, value): (String, Json),
options: HeaderCollection) {
let json = "j:".to_string().append(stringify_json(&value).as_slice());
self.set_cookie(signer, (key, json), options)
}
}
fn stringify_json(json: &Json) -> String {
match *json {
Object(ref object) => {
let obj: Vec<String> = object.iter().map(stringify_pair).collect();
"{".to_string().append(obj.connect(",").as_slice()).append("}")
},
List(ref list) => {
let ary: Vec<String> = list.iter().map(stringify_json).collect();
"[".to_string().append(ary.connect(",").as_slice()).append("]")
},
Number(number) => number.to_string(),
String(ref string) => "\"".to_string().append(string.as_slice()).append("\""),
Boolean(true) => "true".to_string(),
Boolean(false) => "false".to_string(),
Null => "null".to_string()
}
}
fn stringify_pair((key, val): (&String, &Json)) -> String {
"\"".to_string().append(key.as_slice()).append("\":").append(stringify_json(val).as_slice())
}
/// The headers used to set a cookie.
///
/// These headers are defined by [RFC 6265](http://tools.ietf.org/html/rfc6265)
pub struct HeaderCollection {
/// An absolute date/time at which this cookie should expire.
pub expires: Option<Tm>,
/// A relative time (in seconds) at which this cookie should expire.
pub max_age: Option<u32>,
/// The scope of the cookie.
///
/// If set, the browser will send this cookie to the set domain and all subdomains.
/// If not set, the browser will only send this cookie to the originating domain.
///
/// This may only be set to the sending domain and its subdomains.
pub domain: Option<String>,
/// The scope of the cookie.
pub path: Option<String>,
/// A cookie with this flag should only be sent over secured/encrypted connections.
///
/// This will be respected by the browser.
pub secure: bool,
/// A cookie with this flag is only accessible through HTTP and HTTPS.
///
/// This helps to prevent Javascript and, specifically, XSS attacks.
pub http_only: bool,
/// Any additional headers.
///
/// This may be any sequence of valid characters.
///
/// Extensions will be separated with `;`.
/// If a value is specified in the `Map`, the extension will be
/// written as `[key]=[value]`.
pub extensions: Option<TreeMap<String, Option<String>>>
}
impl HeaderCollection {
#[doc(hidden)]
pub fn to_cookie_av(self) -> String {
let mut options = String::new()
.append(head("Expires", self.expires, |v| v.rfc822()).as_slice())
.append(head("Max-Age", self.max_age, |v| v.to_string()).as_slice())
.append(head("Domain", self.domain, |v| v).as_slice())
.append(head("Path", self.path, |v| v).as_slice());
if self.secure { options.push_str("; Secure"); }
if self.http_only { options.push_str("; Http-Only"); }
match self.extensions {
Some(map) => {
for (header, value) in map.iter() {
options.push_str(extension(header, value.clone()).as_slice());
}
},
None => ()
}
options
}
}
impl HeaderCollection {
/// Convenience function for a set of empty cookie headers
pub fn empty() -> HeaderCollection {
HeaderCollection {
expires: None,
max_age: None,
domain: None,
path: None,
secure: false,
http_only: false,
extensions: None
}
}
/// Convenience function for a set of cookie headers
/// that will expire the cookie in `seconds` seconds
pub fn aged(seconds: u32) -> HeaderCollection {
HeaderCollection {
expires: None,
max_age: Some(seconds),
domain: None,
path: None,
secure: false,
http_only: false,
extensions: None
}
}
/// Convenience function for a set of cookie headers
/// declaring the cookie `Secure` and `HttpOnly`
pub fn secured() -> HeaderCollection {
HeaderCollection {
expires: None,
max_age: None,
domain: None,
path: None,
secure: true,
http_only: true,
extensions: None
}
}
}
fn head<V>(header: &str, value: Option<V>, mutator: |V| -> String) -> String {
match value {
Some(val) => {
// Delimit from previous cookie/options
"; ".to_string()
// Add the header
.append(header).append("=")
// Add the mutated value
.append(mutator(val).as_slice())
},
None => String::new()
}
}
fn extension(header: &String, value: Option<String>) -> String {
match value {
Some(val) => head(header.as_slice(), Some(val), |v| v),
None => "; ".to_string().append(header.as_slice())
}
}
#[cfg(test)]
mod test {
use std::collections::TreeMap;
use super::*;
use super::super::cookie::*;
use serialize::json::{Json, Object, String};
use test::mock::response;
// Set a cookie and return its set value
fn get_cookie<'a>(headers: HeaderCollection, secret: Option<String>, key: &str, value: &str) -> String {
let mut res = response::new();
let signer = Cookie::new(secret);
let cookie = (key.to_string(), value.to_string());
res.set_cookie(&signer, cookie, headers);
res.headers.extensions.find(&"Set-Cookie".to_string()).unwrap().clone()
}
// Set a JSON cookie and return its set value
fn get_json_cookie<'a>(headers: HeaderCollection, secret: Option<String>, key: &str, value: Json) -> String {
let mut res = response::new();
let signer = Cookie::new(secret);
let cookie = (key.to_string(), value);
res.set_json_cookie(&signer, cookie, headers);
res.headers.extensions.find(&"Set-Cookie".to_string()).unwrap().clone()
}
#[test]
fn check_stringify_json() {
let mut obj_map = TreeMap::new();
obj_map.insert("foo".to_string(), String("bar".to_string()));
let json = Object(obj_map);
assert_eq!("{\"foo\":\"bar\"}".to_string(), super::stringify_json(&json)) // FIXME
}
#[test]
fn check_cookie() {
let headers = HeaderCollection::empty();
assert_eq!(get_cookie(headers, None, "thing", "thing"), "thing=thing".to_string());
}
#[test]
fn check_escaping() {
let headers = HeaderCollection::empty();
assert_eq!(get_cookie(headers, None, "~`!@#$%^&*()_+-={}|[]\\:\";'<>?,./'", "~`!@#$%^&*()_+-={}|[]\\:\";'<>?,./'"),
// Url component encoding should escape these characters
"~%60%21%40%23%24%25%5E%26*%28%29_%2B-%3D%7B%7D%7C%5B%5D%5C%3A%22%3B%27%3C%3E%3F%2C.%2F%27=\
~%60%21%40%23%24%25%5E%26*%28%29_%2B-%3D%7B%7D%7C%5B%5D%5C%3A%22%3B%27%3C%3E%3F%2C.%2F%27".to_string());
}
#[test]
fn check_headers() {
// Mock the cookie headers
let mut headers = HeaderCollection {
expires: None,
max_age: Some(42),
domain: Some("example.com".to_string()),
path: Some("/a/path".to_string()),
secure: true,
http_only: true,
extensions: Some(TreeMap::<String, Option<String>>::new())
};
headers.extensions.as_mut().unwrap().insert("foo".to_string(), Some("bar".to_string()));
headers.extensions.as_mut().unwrap().insert("@zzmp".to_string(), None);
assert_eq!(get_cookie(headers, None, "thing", "thing"),
"thing=thing; Max-Age=42; Domain=example.com; Path=/a/path; Secure; Http-Only; @zzmp; foo=bar".to_string());
}
#[test]
fn check_signature() {
let headers = HeaderCollection::empty();
assert_eq!(get_cookie(headers, Some("@zzmp".to_string()), "thing", "thung"),
// HMAC-SHA256 of key "@zzmp" and message "thung"
"thing=s:thung.e99abddcf60cad18f8d4b993efae53e81410cf2b2855af0309f1ae46fa527fbb".to_string());
}
#[test]
fn check_json() {
let headers = HeaderCollection::empty();
let mut obj_map = TreeMap::new();
obj_map.insert("foo".to_string(), String("bar".to_string()));
let json = Object(obj_map);
assert_eq!(get_json_cookie(headers, None, "thing", json),
// Url component encoded JSON: {"foo":"bar"}
"thing=j%3A%7B%22foo%22%3A%22bar%22%7D".to_string());
}
}
| 37.651316 | 123 | 0.568321 |
48fb25e6e32c2fc38d518a83845fafe44028702d | 18,970 | //! Implementation of a renderer for Dioxus on the web.
//!
//! Oustanding todos:
//! - Removing event listeners (delegation)
//! - Passive event listeners
//! - no-op event listener patch for safari
//! - tests to ensure dyn_into works for various event types.
//! - Partial delegation?>
use dioxus_core::{DomEdit, ElementId, SchedulerMsg, UserEvent};
use dioxus_interpreter_js::Interpreter;
use js_sys::Function;
use std::{any::Any, rc::Rc, sync::Arc};
use wasm_bindgen::{closure::Closure, JsCast};
use web_sys::{Document, Element, Event, HtmlElement};
use crate::WebConfig;
pub struct WebsysDom {
pub interpreter: Interpreter,
pub(crate) root: Element,
pub handler: Closure<dyn FnMut(&Event)>,
}
impl WebsysDom {
pub fn new(cfg: WebConfig, sender_callback: Rc<dyn Fn(SchedulerMsg)>) -> Self {
// eventually, we just want to let the interpreter do all the work of decoding events into our event type
let callback: Box<dyn FnMut(&Event)> = Box::new(move |event: &web_sys::Event| {
let mut target = event
.target()
.expect("missing target")
.dyn_into::<Element>()
.expect("not a valid element");
let typ = event.type_();
let decoded: anyhow::Result<UserEvent> = loop {
match target.get_attribute("data-dioxus-id").map(|f| f.parse()) {
Some(Ok(id)) => {
break Ok(UserEvent {
name: event_name_from_typ(&typ),
data: virtual_event_from_websys_event(event.clone(), target.clone()),
element: Some(ElementId(id)),
scope_id: None,
priority: dioxus_core::EventPriority::Medium,
});
}
Some(Err(e)) => {
break Err(e.into());
}
None => {
// walk the tree upwards until we actually find an event target
if let Some(parent) = target.parent_element() {
target = parent;
} else {
break Ok(UserEvent {
name: event_name_from_typ(&typ),
data: virtual_event_from_websys_event(
event.clone(),
target.clone(),
),
element: None,
scope_id: None,
priority: dioxus_core::EventPriority::Low,
});
}
}
}
};
if let Ok(synthetic_event) = decoded {
// Try to prevent default if the attribute is set
if let Some(node) = target.dyn_ref::<HtmlElement>() {
if let Some(name) = node.get_attribute("dioxus-prevent-default") {
if name == synthetic_event.name
|| name.trim_start_matches("on") == synthetic_event.name
{
log::trace!("Preventing default");
event.prevent_default();
}
}
}
sender_callback.as_ref()(SchedulerMsg::Event(synthetic_event))
}
});
let document = load_document();
let root = match document.get_element_by_id(&cfg.rootname) {
Some(root) => root,
// a match here in order to avoid some error during runtime browser test
None => {
let body = document.create_element("body").ok().unwrap();
body
}
};
Self {
interpreter: Interpreter::new(root.clone()),
handler: Closure::wrap(callback),
root,
}
}
pub fn apply_edits(&mut self, mut edits: Vec<DomEdit>) {
for edit in edits.drain(..) {
match edit {
DomEdit::PushRoot { root } => self.interpreter.PushRoot(root),
DomEdit::AppendChildren { many } => self.interpreter.AppendChildren(many),
DomEdit::ReplaceWith { root, m } => self.interpreter.ReplaceWith(root, m),
DomEdit::InsertAfter { root, n } => self.interpreter.InsertAfter(root, n),
DomEdit::InsertBefore { root, n } => self.interpreter.InsertBefore(root, n),
DomEdit::Remove { root } => self.interpreter.Remove(root),
DomEdit::CreateElement { tag, root } => self.interpreter.CreateElement(tag, root),
DomEdit::CreateElementNs { tag, root, ns } => {
self.interpreter.CreateElementNs(tag, root, ns)
}
DomEdit::CreatePlaceholder { root } => self.interpreter.CreatePlaceholder(root),
DomEdit::NewEventListener {
event_name, root, ..
} => {
let handler: &Function = self.handler.as_ref().unchecked_ref();
self.interpreter.NewEventListener(event_name, root, handler);
}
DomEdit::RemoveEventListener { root, event } => {
self.interpreter.RemoveEventListener(root, event)
}
DomEdit::RemoveAttribute { root, name } => {
self.interpreter.RemoveAttribute(root, name)
}
DomEdit::CreateTextNode { text, root } => {
let text = serde_wasm_bindgen::to_value(text).unwrap();
self.interpreter.CreateTextNode(text, root)
}
DomEdit::SetText { root, text } => {
let text = serde_wasm_bindgen::to_value(text).unwrap();
self.interpreter.SetText(root, text)
}
DomEdit::SetAttribute {
root,
field,
value,
ns,
} => {
let value = serde_wasm_bindgen::to_value(value).unwrap();
self.interpreter.SetAttribute(root, field, value, ns)
}
}
}
}
}
pub struct DioxusWebsysEvent(web_sys::Event);
// safety: currently the web is not multithreaded and our VirtualDom exists on the same thread
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for DioxusWebsysEvent {}
unsafe impl Sync for DioxusWebsysEvent {}
// todo: some of these events are being casted to the wrong event type.
// We need tests that simulate clicks/etc and make sure every event type works.
fn virtual_event_from_websys_event(
event: web_sys::Event,
target: Element,
) -> Arc<dyn Any + Send + Sync> {
use dioxus_html::on::*;
use dioxus_html::KeyCode;
match event.type_().as_str() {
"copy" | "cut" | "paste" => Arc::new(ClipboardData {}),
"compositionend" | "compositionstart" | "compositionupdate" => {
let evt: &web_sys::CompositionEvent = event.dyn_ref().unwrap();
Arc::new(CompositionData {
data: evt.data().unwrap_or_default(),
})
}
"keydown" | "keypress" | "keyup" => {
let evt: &web_sys::KeyboardEvent = event.dyn_ref().unwrap();
Arc::new(KeyboardData {
alt_key: evt.alt_key(),
char_code: evt.char_code(),
key: evt.key(),
key_code: KeyCode::from_raw_code(evt.key_code() as u8),
ctrl_key: evt.ctrl_key(),
locale: "not implemented".to_string(),
location: evt.location() as usize,
meta_key: evt.meta_key(),
repeat: evt.repeat(),
shift_key: evt.shift_key(),
which: evt.which() as usize,
})
}
"focus" | "blur" => Arc::new(FocusData {}),
// todo: these handlers might get really slow if the input box gets large and allocation pressure is heavy
// don't have a good solution with the serialized event problem
"change" | "input" | "invalid" | "reset" | "submit" => {
let value: String = (&target)
.dyn_ref()
.map(|input: &web_sys::HtmlInputElement| {
// todo: special case more input types
match input.type_().as_str() {
"checkbox" => {
match input.checked() {
true => "true".to_string(),
false => "false".to_string(),
}
},
_ => {
input.value()
}
}
})
.or_else(|| {
target
.dyn_ref()
.map(|input: &web_sys::HtmlTextAreaElement| input.value())
})
// select elements are NOT input events - because - why woudn't they be??
.or_else(|| {
target
.dyn_ref()
.map(|input: &web_sys::HtmlSelectElement| input.value())
})
.or_else(|| {
target
.dyn_ref::<web_sys::HtmlElement>()
.unwrap()
.text_content()
})
.expect("only an InputElement or TextAreaElement or an element with contenteditable=true can have an oninput event listener");
let mut values = std::collections::HashMap::new();
// try to fill in form values
if let Some(form) = target.dyn_ref::<web_sys::HtmlFormElement>() {
let elements = form.elements();
for x in 0..elements.length() {
let element = elements.item(x).unwrap();
if let Some(name) = element.get_attribute("name") {
let value: String = (&element)
.dyn_ref()
.map(|input: &web_sys::HtmlInputElement| {
match input.type_().as_str() {
"checkbox" => {
match input.checked() {
true => "true".to_string(),
false => "false".to_string(),
}
},
_ => input.value()
}
})
.or_else(|| target.dyn_ref().map(|input: &web_sys::HtmlTextAreaElement| input.value()))
.or_else(|| target.dyn_ref().map(|input: &web_sys::HtmlSelectElement| input.value()))
.or_else(|| target.dyn_ref::<web_sys::HtmlElement>().unwrap().text_content())
.expect("only an InputElement or TextAreaElement or an element with contenteditable=true can have an oninput event listener");
values.insert(name, value);
}
}
}
Arc::new(FormData { value, values })
}
"click" | "contextmenu" | "doubleclick" | "drag" | "dragend" | "dragenter" | "dragexit"
| "dragleave" | "dragover" | "dragstart" | "drop" | "mousedown" | "mouseenter"
| "mouseleave" | "mousemove" | "mouseout" | "mouseover" | "mouseup" => {
let evt: &web_sys::MouseEvent = event.dyn_ref().unwrap();
Arc::new(MouseData {
alt_key: evt.alt_key(),
button: evt.button(),
buttons: evt.buttons(),
client_x: evt.client_x(),
client_y: evt.client_y(),
ctrl_key: evt.ctrl_key(),
meta_key: evt.meta_key(),
screen_x: evt.screen_x(),
screen_y: evt.screen_y(),
shift_key: evt.shift_key(),
page_x: evt.page_x(),
page_y: evt.page_y(),
})
}
"pointerdown" | "pointermove" | "pointerup" | "pointercancel" | "gotpointercapture"
| "lostpointercapture" | "pointerenter" | "pointerleave" | "pointerover" | "pointerout" => {
let evt: &web_sys::PointerEvent = event.dyn_ref().unwrap();
Arc::new(PointerData {
alt_key: evt.alt_key(),
button: evt.button(),
buttons: evt.buttons(),
client_x: evt.client_x(),
client_y: evt.client_y(),
ctrl_key: evt.ctrl_key(),
meta_key: evt.meta_key(),
page_x: evt.page_x(),
page_y: evt.page_y(),
screen_x: evt.screen_x(),
screen_y: evt.screen_y(),
shift_key: evt.shift_key(),
pointer_id: evt.pointer_id(),
width: evt.width(),
height: evt.height(),
pressure: evt.pressure(),
tangential_pressure: evt.tangential_pressure(),
tilt_x: evt.tilt_x(),
tilt_y: evt.tilt_y(),
twist: evt.twist(),
pointer_type: evt.pointer_type(),
is_primary: evt.is_primary(),
// get_modifier_state: evt.get_modifier_state(),
})
}
"select" => Arc::new(SelectionData {}),
"touchcancel" | "touchend" | "touchmove" | "touchstart" => {
let evt: &web_sys::TouchEvent = event.dyn_ref().unwrap();
Arc::new(TouchData {
alt_key: evt.alt_key(),
ctrl_key: evt.ctrl_key(),
meta_key: evt.meta_key(),
shift_key: evt.shift_key(),
})
}
"scroll" => Arc::new(()),
"wheel" => {
let evt: &web_sys::WheelEvent = event.dyn_ref().unwrap();
Arc::new(WheelData {
delta_x: evt.delta_x(),
delta_y: evt.delta_y(),
delta_z: evt.delta_z(),
delta_mode: evt.delta_mode(),
})
}
"animationstart" | "animationend" | "animationiteration" => {
let evt: &web_sys::AnimationEvent = event.dyn_ref().unwrap();
Arc::new(AnimationData {
elapsed_time: evt.elapsed_time(),
animation_name: evt.animation_name(),
pseudo_element: evt.pseudo_element(),
})
}
"transitionend" => {
let evt: &web_sys::TransitionEvent = event.dyn_ref().unwrap();
Arc::new(TransitionData {
elapsed_time: evt.elapsed_time(),
property_name: evt.property_name(),
pseudo_element: evt.pseudo_element(),
})
}
"abort" | "canplay" | "canplaythrough" | "durationchange" | "emptied" | "encrypted"
| "ended" | "error" | "loadeddata" | "loadedmetadata" | "loadstart" | "pause" | "play"
| "playing" | "progress" | "ratechange" | "seeked" | "seeking" | "stalled" | "suspend"
| "timeupdate" | "volumechange" | "waiting" => Arc::new(MediaData {}),
"toggle" => Arc::new(ToggleData {}),
_ => Arc::new(()),
}
}
pub(crate) fn load_document() -> Document {
web_sys::window()
.expect("should have access to the Window")
.document()
.expect("should have access to the Document")
}
fn event_name_from_typ(typ: &str) -> &'static str {
match typ {
"copy" => "copy",
"cut" => "cut",
"paste" => "paste",
"compositionend" => "compositionend",
"compositionstart" => "compositionstart",
"compositionupdate" => "compositionupdate",
"keydown" => "keydown",
"keypress" => "keypress",
"keyup" => "keyup",
"focus" => "focus",
"blur" => "blur",
"change" => "change",
"input" => "input",
"invalid" => "invalid",
"reset" => "reset",
"submit" => "submit",
"click" => "click",
"contextmenu" => "contextmenu",
"doubleclick" => "doubleclick",
"drag" => "drag",
"dragend" => "dragend",
"dragenter" => "dragenter",
"dragexit" => "dragexit",
"dragleave" => "dragleave",
"dragover" => "dragover",
"dragstart" => "dragstart",
"drop" => "drop",
"mousedown" => "mousedown",
"mouseenter" => "mouseenter",
"mouseleave" => "mouseleave",
"mousemove" => "mousemove",
"mouseout" => "mouseout",
"mouseover" => "mouseover",
"mouseup" => "mouseup",
"pointerdown" => "pointerdown",
"pointermove" => "pointermove",
"pointerup" => "pointerup",
"pointercancel" => "pointercancel",
"gotpointercapture" => "gotpointercapture",
"lostpointercapture" => "lostpointercapture",
"pointerenter" => "pointerenter",
"pointerleave" => "pointerleave",
"pointerover" => "pointerover",
"pointerout" => "pointerout",
"select" => "select",
"touchcancel" => "touchcancel",
"touchend" => "touchend",
"touchmove" => "touchmove",
"touchstart" => "touchstart",
"scroll" => "scroll",
"wheel" => "wheel",
"animationstart" => "animationstart",
"animationend" => "animationend",
"animationiteration" => "animationiteration",
"transitionend" => "transitionend",
"abort" => "abort",
"canplay" => "canplay",
"canplaythrough" => "canplaythrough",
"durationchange" => "durationchange",
"emptied" => "emptied",
"encrypted" => "encrypted",
"ended" => "ended",
"error" => "error",
"loadeddata" => "loadeddata",
"loadedmetadata" => "loadedmetadata",
"loadstart" => "loadstart",
"pause" => "pause",
"play" => "play",
"playing" => "playing",
"progress" => "progress",
"ratechange" => "ratechange",
"seeked" => "seeked",
"seeking" => "seeking",
"stalled" => "stalled",
"suspend" => "suspend",
"timeupdate" => "timeupdate",
"volumechange" => "volumechange",
"waiting" => "waiting",
"toggle" => "toggle",
_ => {
panic!("unsupported event type")
}
}
}
| 41.23913 | 158 | 0.478229 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.