text stringlengths 8 4.13M |
|---|
extern crate find_folder;
extern crate piston_window;
extern crate conrod_piston;
extern crate sprite;
extern crate piston;
use sprite::Scene;
use self::piston_window::{PistonWindow, Window, WindowSettings};
use self::piston_window::{G2d, G2dTexture, TextureSettings, Texture, Flip};
use self::piston_window::OpenGL;
use self::piston_window::texture::UpdateTexture;
use qwe::core::state::State;
use qwe::core::websocket::chat::Client as ChatClient;
use qwe::core::websocket::movement::Client as MoveClient;
extern crate conrod_core;
extern crate rand;
extern crate reqwest;
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate ws;
use ws::{connect};
use std::thread;
use std::sync::mpsc;
use std::rc::Rc;
pub const WIN_W: u32 = 600;
pub const WIN_H: u32 = 420;
pub fn theme() -> conrod_core::Theme {
use conrod_core::position::{Align, Direction, Padding, Position, Relative};
conrod_core::Theme {
name: "Theme".to_string(),
padding: Padding::none(),
x_position: Position::Relative(Relative::Align(Align::Start), None),
y_position: Position::Relative(Relative::Direction(Direction::Backwards, 20.0), None),
background_color: conrod_core::color::DARK_CHARCOAL,
shape_color: conrod_core::color::LIGHT_CHARCOAL,
border_color: conrod_core::color::BLACK,
border_width: 0.0,
label_color: conrod_core::color::WHITE,
font_id: None,
font_size_large: 26,
font_size_medium: 18,
font_size_small: 12,
widget_styling: conrod_core::theme::StyleMap::default(),
mouse_drag_threshold: 0.0,
double_click_threshold: std::time::Duration::from_millis(500),
}
}
pub fn main() {
const WIDTH: u32 = 1920;
const HEIGHT: u32 = 1080;
let mut window: PistonWindow =
WindowSettings::new("qwe", [WIDTH, HEIGHT])
.opengl(OpenGL::V3_2)
.samples(4)
.exit_on_esc(true)
.vsync(true)
.build()
.unwrap();
let mut ui = conrod_core::UiBuilder::new([WIDTH as f64, HEIGHT as f64])
.theme(theme())
.build();
let assets = find_folder::Search::KidsThenParents(3, 5).for_folder("assets").unwrap();
let mut scene = Scene::new();
let tex = Rc::new(Texture::from_path(
&mut window.factory,
assets.join("sprites/player/idle1.png"),
Flip::None,
&TextureSettings::new()
).unwrap());
let mut state = State::new(&mut ui, tex.clone());
let (tx_receive, rx_receive) = mpsc::channel();
let (tx_send, rx_send) = mpsc::channel();
state.chat_receiver = Some(&rx_receive);
state.chat_sender = Some(&tx_send);
thread::spawn(move || {
connect("ws://127.0.0.1:3333/chat", |out| ChatClient::new(out, &tx_receive, &rx_send) ).unwrap()
});
let (tx_move_receive, rx_move_receive) = mpsc::channel();
let (tx_move_send, rx_move_send) = mpsc::channel();
state.move_receiver = Some(&rx_move_receive);
state.move_sender = Some(&tx_move_send);
thread::spawn(move || {
connect("ws://127.0.0.1:3333/move", |out| MoveClient::new(out, &tx_move_receive, &rx_move_send) ).unwrap()
});
let font_path = assets.join("fonts/FiraSans-Regular.ttf");
ui.fonts.insert_from_file(font_path).unwrap();
let mut text_vertex_data = Vec::new();
let (mut glyph_cache, mut text_texture_cache) = {
const SCALE_TOLERANCE: f32 = 0.1;
const POSITION_TOLERANCE: f32 = 0.1;
let cache = conrod_core::text::GlyphCache::builder()
.dimensions(WIDTH, HEIGHT)
.scale_tolerance(SCALE_TOLERANCE)
.position_tolerance(POSITION_TOLERANCE)
.build();
let buffer_len = WIDTH as usize * HEIGHT as usize;
let init = vec![128; buffer_len];
let settings = TextureSettings::new();
let factory = &mut window.factory;
let texture = G2dTexture::from_memory_alpha(factory, &init, WIDTH, HEIGHT, &settings).unwrap();
(cache, texture)
};
let image_map = conrod_core::image::Map::new();
while let Some(event) = window.next() {
scene.event(&event);
let size = window.size();
let (win_w, win_h) = (size.width as conrod_core::Scalar, size.height as conrod_core::Scalar);
if let Some(e) = conrod_piston::event::convert(event.clone(), win_w, win_h) {
ui.handle_event(e);
}
let mut ui = ui.set_widgets();
state.perform(&mut ui, &mut scene, &event.clone());
window.draw_2d(&event, |context, graphics| {
scene.draw(context.transform, graphics);
if let Some(primitives) = ui.draw_if_changed() {
let cache_queued_glyphs = |graphics: &mut G2d,
cache: &mut G2dTexture,
rect: conrod_core::text::rt::Rect<u32>,
data: &[u8]|
{
let offset = [rect.min.x, rect.min.y];
let size = [rect.width(), rect.height()];
let format = piston_window::texture::Format::Rgba8;
let encoder = &mut graphics.encoder;
text_vertex_data.clear();
text_vertex_data.extend(data.iter().flat_map(|&b| vec![255, 255, 255, b]));
UpdateTexture::update(cache, encoder, format, &text_vertex_data[..], offset, size)
.expect("failed to update texture")
};
fn texture_from_image<T>(img: &T) -> &T { img }
conrod_piston::draw::primitives(primitives,
context,
graphics,
&mut text_texture_cache,
&mut glyph_cache,
&image_map,
cache_queued_glyphs,
texture_from_image);
}
});
}
}
|
use crate::util::{Direction, Point2};
use std::iter;
use std::str::FromStr;
impl Point2 {
fn move_in_direction(&mut self, direction: Direction) {
self.x += match direction {
Direction::Right => 1,
Direction::Left => -1,
_ => 0,
};
self.y += match direction {
Direction::Up => 1,
Direction::Down => -1,
_ => 0,
}
}
}
#[derive(Debug)]
struct Node {
direction: Direction,
len: u32,
}
impl Node {
fn parse(string: &str) -> Self {
let direction = match string.chars().next() {
Some('U') => Direction::Up,
Some('D') => Direction::Down,
Some('L') => Direction::Left,
Some('R') => Direction::Right,
_ => panic!("bad direction"),
};
let len = string[1..].parse::<u32>().unwrap();
Node { direction, len }
}
}
#[derive(Debug)]
pub struct Wire {
nodes: Vec<Node>,
}
impl FromStr for Wire {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let nodes: Vec<Node> = s.split(',').map(Node::parse).collect();
Ok(Wire { nodes })
}
}
impl Wire {
pub fn iter(&self) -> impl Iterator<Item = Point2> + '_ {
self.nodes
.iter()
.flat_map(|node| iter::repeat(node.direction).take(node.len as usize))
.scan(Point2::default(), |cursor, direction| {
cursor.move_in_direction(direction);
Some(*cursor)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::util;
use std::collections::HashMap;
fn parse_wires(input: &str) -> (Wire, Wire) {
let mut wires: Vec<Wire> = input
.split("\n")
.take(2)
.map(Wire::from_str)
.filter_map(Result::ok)
.collect();
assert_eq!(wires.len(), 2);
(wires.remove(0), wires.remove(0))
}
#[test]
fn test_advent_puzzle() {
let wires_str: String = util::load_input_file("day03.txt").unwrap();
let (first_wire, second_wire): (Wire, Wire) = parse_wires(&wires_str);
let first_wire_path: HashMap<_, u32> = first_wire.iter().zip(1..).collect();
let distance = second_wire
.iter()
.zip(1..)
.filter_map(|(cursor, idx)| first_wire_path.get(&cursor).map(|m| idx + m))
.min()
.unwrap();
assert_eq!(distance, 5672);
}
}
|
//! Schemas and processing logic for GoodReads data.
//!
//! This module contains the code for processing GoodReads data from the UCSD Book Graph.
//! The data layout is documented at <https://bookdata.piret.info/data/goodreads.html>.
pub mod author;
pub mod book;
pub mod genres;
pub mod interaction;
pub mod simple_interaction;
pub mod work;
|
extern crate llvm_sys;
extern crate iron_llvm;
use self::llvm_sys::prelude::LLVMValueRef;
use self::iron_llvm::core;
use self::iron_llvm::core::types::{RealTypeCtor, RealTypeRef};
use self::iron_llvm::{LLVMRef, LLVMRefCtor};
use parser::{ParseResult, AST, ASTNode, Prototype, Function, Expression};
pub fn compile_ast(ast: AST) {
println!("Compiling!");
}
/*
pub struct Context {
context: core::Context,
builder: core::Builder,
named_values: HashMap<String, LLVMValueRef>,
ty: RealTypeRef,
}
impl Context {
pub fn new() -> Context {
let context = core::Context::get_global();
let builder = core::Builder::new();
let named_values = HashMap::new();
let ty = RealTypeRef::get_double();
Context {
context: context,
builder: builder,
named_values: named_values,
ty: ty,
}
}
}
pub trait ModuleProvider {
fn dump(&self);
fn get_module(&mut self) -> &mut core::Module;
fn get_function(&mut self, name: &str) -> Option<(FunctionRef, bool)>;
}
pub struct SimpleModuleProvider {
module: core::Module,
}
impl SimpleModuleProvider {
pub fn new(name: &str) -> SimpleModuleProvider {
let module = core::Module::new(name);
SimpleModuleProvider {
module: module,
}
}
}
impl ModuleProvider for SimpleModuleProvider {
fn dump(&self) {
self.module.dump();
}
fn get_module(&mut self) -> &mut core::Module {
&mut self.module
}
fn get_function(&mut self, name: &str) -> Option<(FunctionRef, bool)> {
match self.module.get_function_by_name(name) {
Some(f) => Some((f, f.count_basic_block() > 0)),
None => None
}
}
}
pub type IRBuildingResult = Result<(LLVMValueRef, bool), String>;
fn error(msg: &str) -> IRBuildingResult {
Err(msg.to_string())
}
pub trait IRBuilder {
fn codegen(&self, context: &mut Context, module_provider: &mut ModuleProvider) -> IRBuildingResult;
}
impl IRBuilder for ParseResult<AST> {
fn codegen(&self, context: &mut Context, module_provider: &mut ModuleProvider) -> IRBuildingResult {
match self {
&Ok(ast) => ast.codegen(context, module_provider),
&Err(err) => Err(err.msg.clone())
}
}
}
impl IRBuilder for AST {
fn codegen(&self, context: &mut Context, module_provider: &mut ModuleProvider) -> IRBuildingResult {
let mut result = error("empty AST");
for node in self.iter() {
result = Ok(try!(node.codegen(context, module_provider)));
}
result
}
}
impl IRBuilder for ASTNode {
fn codegen(&self, context: &mut Context, module_provider: &mut ModuleProvider) -> IRBuildingResult {
match self {
&ASTNode::ExprNode(ref expression) => expression.codegen(context, module_provider),
&ASTNode::FuncNode(ref function) => function.codegen(context, module_provider),
}
}
}
impl IRBuilder for Function {
fn codegen(&self, context: &mut Context, module_provider: &mut ModuleProvider) -> IRBuildingResult {
unimplemented!()
}
}
impl IRBuilder for Expression {
fn codegen(&self, context: &mut Context, module_provider: &mut ModuleProvider) -> IRBuildingResult {
unimplemented!()
}
}
*/
|
// Copyright 2019, 2020 Wingchain
//
// 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.
#![allow(clippy::single_match)]
#![allow(clippy::type_complexity)]
use std::sync::Arc;
pub use node_network::{
ed25519, Keypair, LinkedHashMap, Multiaddr, Network, NetworkConfig, NetworkInMessage,
NetworkState, OpenedPeer, PeerId, Protocol, UnopenedPeer,
};
use primitives::codec::Encode;
use primitives::errors::CommonResult;
use crate::protocol::{Handshake, ProtocolMessage};
use crate::stream::CoordinatorStream;
use crate::support::CoordinatorSupport;
use futures::channel::mpsc::{unbounded, UnboundedSender};
use node_network::HandshakeBuilder;
use parking_lot::RwLock;
use primitives::{BlockNumber, Hash};
mod errors;
mod peer_report;
mod protocol;
mod stream;
pub mod support;
mod sync;
mod verifier;
pub struct CoordinatorConfig {
pub network_config: NetworkConfig,
}
pub enum CoordinatorInMessage {
Network(NetworkInMessage),
}
pub struct Coordinator<S>
where
S: CoordinatorSupport,
{
#[allow(dead_code)]
network: Arc<Network>,
#[allow(dead_code)]
support: Arc<S>,
coordinator_tx: UnboundedSender<CoordinatorInMessage>,
}
impl<S> Coordinator<S>
where
S: CoordinatorSupport,
{
pub fn new(config: CoordinatorConfig, support: Arc<S>) -> CommonResult<Self> {
let current_state = support.get_current_state();
let handshake_builder = Arc::new(DefaultHandshakeBuilder {
genesis_hash: current_state.genesis_hash.clone(),
confirmed: RwLock::new((
current_state.confirmed_number,
current_state.confirmed_block_hash.clone(),
)),
});
let mut network_config = config.network_config;
network_config.handshake_builder = Some(handshake_builder.clone());
let network = Network::new(network_config)?;
let peer_manager_tx = network.peer_manager_tx();
let network_tx = network.network_tx();
let network_rx = network.network_rx().expect("Coordinator is the only taker");
let chain_rx = support.chain_rx().expect("Coordinator is the only taker");
let txpool_rx = support.txpool_rx().expect("Coordinator is the only taker");
let consensus_tx = support.consensus_tx();
let consensus_rx = support
.consensus_rx()
.expect("Coordinator is the only taker");
let (in_tx, in_rx) = unbounded();
CoordinatorStream::spawn(
handshake_builder,
chain_rx,
txpool_rx,
peer_manager_tx,
network_tx,
network_rx,
consensus_tx,
consensus_rx,
in_rx,
support.clone(),
)?;
let coordinator = Coordinator {
network: Arc::new(network),
support,
coordinator_tx: in_tx,
};
Ok(coordinator)
}
pub fn coordinator_tx(&self) -> UnboundedSender<CoordinatorInMessage> {
self.coordinator_tx.clone()
}
}
pub struct DefaultHandshakeBuilder {
genesis_hash: Hash,
confirmed: RwLock<(BlockNumber, Hash)>,
}
impl HandshakeBuilder for DefaultHandshakeBuilder {
fn build(&self, nonce: u64) -> Vec<u8> {
let (confirmed_number, confirmed_hash) = (*self.confirmed.read()).clone();
ProtocolMessage::Handshake(Handshake {
genesis_hash: self.genesis_hash.clone(),
confirmed_number,
confirmed_hash,
nonce,
})
.encode()
}
}
|
use super::{Object, TaggedValue};
use crate::runtime::Symbol;
use crate::SchemeExpression;
macro_rules! impl_from {
($T:ty, $as:ty, $constructor:path) => {
impl From<$T> for Object {
fn from(x: $T) -> Object {
$constructor(x as $as)
}
}
};
}
impl_from!(i64, i64, Object::integer);
impl_from!(i32, i64, Object::integer);
impl_from!(i16, i64, Object::integer);
impl_from!(i8, i64, Object::integer);
impl_from!(u32, i64, Object::integer);
impl_from!(u16, i64, Object::integer);
impl_from!(u8, i64, Object::integer);
impl_from!(f64, f64, Object::float);
impl_from!(f32, f64, Object::float);
impl_from!(Symbol, Symbol, Object::symbol);
impl Object {
pub fn list_to_vec(&self) -> Option<Vec<Object>> {
let mut acc = vec![];
let mut cursor = self;
while let TaggedValue::Pair(car, cdr) = cursor.as_value() {
acc.push((**car).clone());
cursor = cdr;
}
Some(acc)
}
}
|
use super::Block;
impl super::Block {
/// Constructor.
pub fn new(value: u16, length: u8) -> Block {
Block { value, length }
}
/// Returns a content (total rank to go) of the block.
pub fn value(&self) -> u16 {
self.value
}
/// Returns size of the block.
pub fn length(&self) -> u8 {
self.length
}
}
|
mod cone;
pub use self::cone::*;
|
#![feature(test)]
extern crate fnv;
extern crate rand;
extern crate rayon;
extern crate rayon_hash;
extern crate test;
use rand::{Rng, SeedableRng, XorShiftRng};
use std::collections::{HashMap as StdHashMap, HashSet as StdHashSet};
use rayon_hash::{HashMap as RayonHashMap, HashSet as RayonHashSet};
use std::iter::FromIterator;
use rayon::prelude::*;
use test::Bencher;
use fnv::FnvBuildHasher;
fn default_set<C: FromIterator<u32>>(n: usize) -> C {
let mut rng = XorShiftRng::from_seed([0, 1, 2, 3]);
(0..n).map(|_| rng.next_u32()).collect()
}
macro_rules! bench_set_sum {
($id:ident, $ty:ty, $iter:ident) => {
#[bench]
fn $id(b: &mut Bencher) {
let set: $ty = default_set(1024 * 1024);
let sum: u64 = set.iter().map(|&x| x as u64).sum();
b.iter(|| {
let s: u64 = set.$iter().map(|&x| x as u64).sum();
assert_eq!(s, sum);
})
}
}
}
bench_set_sum!{std_set_sum_serial, StdHashSet<_>, iter}
bench_set_sum!{std_set_sum_parallel, StdHashSet<_>, par_iter}
bench_set_sum!{rayon_set_sum_serial, RayonHashSet<_>, iter}
bench_set_sum!{rayon_set_sum_parallel, RayonHashSet<_>, par_iter}
macro_rules! bench_collect {
($id:ident, $ty:ty, $iter:ident) => {
#[bench]
fn $id(b: &mut Bencher) {
b.iter(|| {
let set: $ty = (0u32 .. 1<<20).$iter().map(|x| (x >> 1, ())).collect();
assert_eq!(1<<19, set.len());
})
}
}
}
bench_collect!{std_collect_serial, StdHashMap<_, _>, into_iter}
bench_collect!{std_collect_parallel, StdHashMap<_, _>, into_par_iter}
bench_collect!{rayon_collect_serial, RayonHashMap<_, _>, into_iter}
bench_collect!{rayon_collect_parallel, RayonHashMap<_, _>, into_par_iter}
bench_collect!{rayon_collect_fnv, RayonHashMap<_, _, FnvBuildHasher>, into_iter}
bench_collect!{std_collect_fnv, StdHashMap<_, _, FnvBuildHasher>, into_iter} |
#[cfg(test)]
mod test;
use crate::{
bson::{doc, Document},
cmap::{Command, RawCommandResponse, StreamDescription},
error::Result,
operation::{append_options, remove_empty_write_concern, OperationWithDefaults},
options::{DropIndexOptions, WriteConcern},
Namespace,
};
pub(crate) struct DropIndexes {
ns: Namespace,
name: String,
options: Option<DropIndexOptions>,
}
impl DropIndexes {
pub(crate) fn new(ns: Namespace, name: String, options: Option<DropIndexOptions>) -> Self {
Self { ns, name, options }
}
#[cfg(test)]
pub(crate) fn empty() -> Self {
Self {
ns: Namespace {
db: String::new(),
coll: String::new(),
},
name: String::new(),
options: None,
}
}
}
impl OperationWithDefaults for DropIndexes {
type O = ();
type Command = Document;
const NAME: &'static str = "dropIndexes";
fn build(&mut self, _description: &StreamDescription) -> Result<Command> {
let mut body = doc! {
Self::NAME: self.ns.coll.clone(),
"index": self.name.clone(),
};
remove_empty_write_concern!(self.options);
append_options(&mut body, self.options.as_ref())?;
Ok(Command::new(
Self::NAME.to_string(),
self.ns.db.clone(),
body,
))
}
fn handle_response(
&self,
_response: RawCommandResponse,
_description: &StreamDescription,
) -> Result<Self::O> {
Ok(())
}
fn write_concern(&self) -> Option<&WriteConcern> {
self.options
.as_ref()
.and_then(|opts| opts.write_concern.as_ref())
}
}
|
use super::regex_handle::*;
use ego_tree::NodeRef;
use reqwest::blocking::Response;
use scraper::{ElementRef, Html, Node};
pub(super) fn graphql_response_parse(rep: Response) -> Result<serde_json::Value, String> {
match rep.text() {
Ok(c) => {
//dbg!(&c);
serde_json::from_str(&c).map_err(|e| e.to_string())
}
Err(e) => Err(e.to_string()),
}
}
pub(super) fn find_question_id_from_graphql_req(obj: &serde_json::Value) -> Result<String, String> {
match obj.get("data") {
Some(d) => match d.get("question") {
Some(q) => match q.get("questionFrontendId") {
Some(id) => id.as_str().map(|x| x.into()).ok_or("Not Found".into()),
None => Err("Not Found".into()),
},
None => Err("Not Found".into()),
},
None => Err("Not Found".into()),
}
}
pub(super) fn find_question_level_from_graphql_req(
obj: &serde_json::Value,
) -> Result<String, String> {
match obj.get("data") {
Some(d) => match d.get("question") {
Some(q) => match q.get("difficulty") {
Some(id) => id.as_str().map(|x| x.into()).ok_or("Not Found".into()),
None => Err("Not Found".into()),
},
None => Err("Not Found".into()),
},
None => Err("Not Found".into()),
}
}
pub(super) fn find_question_title_from_graphql_req(
obj: &serde_json::Value,
) -> Result<String, String> {
match obj.get("data") {
Some(d) => match d.get("question") {
Some(q) => match q.get("title") {
Some(id) => id.as_str().map(|x| x.into()).ok_or("Not Found".into()),
None => Err("Not Found".into()),
},
None => Err("Not Found".into()),
},
None => Err("Not Found".into()),
}
}
/// Get question content from graphql response
pub(super) fn find_question_content(obj: &serde_json::Value) -> Result<&str, String> {
match obj.get("data") {
Some(d) => match d.get("question") {
Some(q) => match q.get("content") {
Some(id) => id.as_str().ok_or("Not Found".into()),
None => Err("Not Found".into()),
},
None => Err("Not Found".into()),
},
None => Err("Not Found".into()),
}
}
/// Give back html element of quiz content
pub(super) fn description_in_graphql(h: &Html) -> impl Iterator<Item = NodeRef<'_, Node>> {
h.root_element().children()
}
/// Parse html quiz content to markdown
pub(super) fn description_markdown<'a>(ir: impl Iterator<Item = NodeRef<'a, Node>>) -> Vec<String> {
ir.filter_map(|n| match n.value() {
Node::Text(s) => Some(s.to_string()),
Node::Element(e) => match e.name() {
"p" => Some(ElementRef::wrap(n).unwrap().inner_html()),
"pre" => Some(ElementRef::wrap(n).unwrap().html()),
"ul" => Some(ElementRef::wrap(n).unwrap().inner_html()),
_ => None,
},
_ => None,
})
.map(|mut chunk| {
//dbg!(&chunk);
clean_all_tags(&mut chunk);
chunk
})
.collect::<Vec<String>>()
}
pub(super) fn find_code_snippets(
content: &serde_json::Value,
) -> Result<&Vec<serde_json::Value>, String> {
match content.get("data") {
Some(d) => match d.get("question") {
Some(q) => match q.get("codeSnippets") {
Some(cs) => cs.as_array().ok_or("Not Found".into()),
None => Err("Not Found codeSnippets".into()),
},
None => Err("Not Found question".into()),
},
None => Err("Not Found data".into()),
}
}
pub(super) fn find_code_snippet<'quiz>(
content: &'quiz serde_json::Value,
lang: &str,
) -> Result<Option<&'quiz str>, String> {
let all = find_code_snippets(content)?;
match all
.iter()
.find(|v| v.get("langSlug").map_or("", |v| v.as_str().unwrap()) == lang)
{
Some(cs) => Ok(cs.get("code").unwrap().as_str()),
None => Err("Cannot found langSlug".into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use scraper::{ElementRef, Html};
use std::fs::File;
use std::io::Write;
#[test]
fn test_find_description_from_graphql() {
// content from graphql
let a = include_str!("../tests/questions_description_test_case1");
let fragment = Html::parse_fragment(a);
let mut vv = description_in_graphql(&fragment);
assert_eq!(ElementRef::wrap(vv.next().unwrap()).unwrap().html(),"<p>A conveyor belt has packages that must be shipped from one port to another within <code>days</code> days.</p>".to_string());
}
//#[test]
fn test_description_markdown() {
// test graphql content
let a = include_str!("../tests/questions_description_test_case1");
let fragment = Html::parse_fragment(a);
let content = description_markdown(description_in_graphql(&fragment));
//dbg!(&content);
let mut file = File::create("./tests/questions_description_test_case1.md").unwrap();
for c in content {
file.write(&c.as_bytes()).unwrap();
}
}
}
|
pub use board::*;
pub use entity::*;
mod board;
mod entity;
|
/*
Copyright (c) 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
extern crate libc;
mod ffi;
use ffi::*;
use libc::c_char;
use std::ffi::*;
/// Result of opening a file dialog
pub enum NFDResult {
/// User pressed okay. `String` is the file path selected
Okay(String),
/// User pressed cancel
Cancel,
/// Program error. `String` is the error description
Error(String),
}
enum DialogType {
SingleFile,
SaveFile
}
/// Open single file dialog
#[inline(always)]
pub fn open_file_dialog(filter_list: Option<&str>, default_path: Option<&str>) -> NFDResult {
open_dialog(filter_list, default_path, &DialogType::SingleFile)
}
/// Open save dialog
#[inline(always)]
pub fn open_save_dialog(filter_list: Option<&str>, default_path: Option<&str>) -> NFDResult {
open_dialog(filter_list, default_path, &DialogType::SaveFile)
}
fn open_dialog(filter_list: Option<&str>, default_path: Option<&str>, dialog_type: &DialogType) -> NFDResult {
let result: nfdresult_t;
let result_cstring;
let filter_list_cstring;
let filter_list_ptr = match filter_list {
Some(fl_str) => {
filter_list_cstring = CString::new(fl_str).unwrap();
filter_list_cstring.as_ptr()
}
None => std::ptr::null()
};
let default_path_cstring;
let default_path_ptr = match default_path {
Some(dp_str) => {
default_path_cstring = CString::new(dp_str).unwrap();
default_path_cstring.as_ptr()
}
None => std::ptr::null()
};
let mut out_path: *mut c_char = std::ptr::null_mut();
let ptr_out_path = &mut out_path as *mut *mut c_char;
unsafe {
result = match dialog_type {
&DialogType::SingleFile => {
NFD_OpenDialog(filter_list_ptr, default_path_ptr, ptr_out_path)
},
&DialogType::SaveFile => {
NFD_SaveDialog(filter_list_ptr, default_path_ptr, ptr_out_path)
},
};
result_cstring = match result {
nfdresult_t::NFD_OKAY => CStr::from_ptr(out_path).to_owned(),
nfdresult_t::NFD_ERROR => CStr::from_ptr(NFD_GetError()).to_owned(),
_ => CString::new("").unwrap()
}
}
let result_string = result_cstring.to_str().unwrap().to_string();
match result {
nfdresult_t::NFD_OKAY => NFDResult::Okay(result_string),
nfdresult_t::NFD_CANCEL => NFDResult::Cancel,
nfdresult_t::NFD_ERROR => NFDResult::Error(result_string)
}
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub mod dimensions {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list_by_subscription(
operation_config: &crate::OperationConfig,
scope: &str,
filter: Option<&str>,
expand: Option<&str>,
skiptoken: Option<&str>,
top: Option<i64>,
) -> std::result::Result<DimensionsListResult, list_by_subscription::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/{}/providers/Microsoft.CostManagement/dimensions",
&operation_config.base_path, scope
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_by_subscription::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
if let Some(filter) = filter {
req_builder = req_builder.query(&[("$filter", filter)]);
}
if let Some(expand) = expand {
req_builder = req_builder.query(&[("$expand", expand)]);
}
if let Some(skiptoken) = skiptoken {
req_builder = req_builder.query(&[("$skiptoken", skiptoken)]);
}
if let Some(top) = top {
req_builder = req_builder.query(&[("$top", top)]);
}
let req = req_builder.build().context(list_by_subscription::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_subscription::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_subscription::ResponseBytesError)?;
let rsp_value: DimensionsListResult =
serde_json::from_slice(&body).context(list_by_subscription::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_subscription::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list_by_subscription::DeserializeError { body })?;
list_by_subscription::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_subscription {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod query {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn usage_by_scope(
operation_config: &crate::OperationConfig,
scope: &str,
parameters: &QueryDefinition,
) -> std::result::Result<QueryResult, usage_by_scope::Error> {
let client = &operation_config.client;
let uri_str = &format!("{}/{}/providers/Microsoft.CostManagement/query", &operation_config.base_path, scope);
let mut req_builder = client.post(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(usage_by_scope::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(usage_by_scope::BuildRequestError)?;
let rsp = client.execute(req).await.context(usage_by_scope::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(usage_by_scope::ResponseBytesError)?;
let rsp_value: QueryResult = serde_json::from_slice(&body).context(usage_by_scope::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(usage_by_scope::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(usage_by_scope::DeserializeError { body })?;
usage_by_scope::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod usage_by_scope {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod exports {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(operation_config: &crate::OperationConfig, scope: &str) -> std::result::Result<ExportListResult, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/{}/providers/Microsoft.CostManagement/exports",
&operation_config.base_path, scope
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: ExportListResult = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn get(operation_config: &crate::OperationConfig, scope: &str, export_name: &str) -> std::result::Result<Export, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/{}/providers/Microsoft.CostManagement/exports/{}",
&operation_config.base_path, scope, export_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: Export = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn create_or_update(
operation_config: &crate::OperationConfig,
scope: &str,
export_name: &str,
parameters: &Export,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/{}/providers/Microsoft.CostManagement/exports/{}",
&operation_config.base_path, scope, export_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(parameters);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: Export = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: Export = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Created201(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
create_or_update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(Export),
Created201(Export),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
scope: &str,
export_name: &str,
) -> std::result::Result<(), delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/{}/providers/Microsoft.CostManagement/exports/{}",
&operation_config.base_path, scope, export_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(()),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(delete::DeserializeError { body })?;
delete::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn execute(
operation_config: &crate::OperationConfig,
scope: &str,
export_name: &str,
) -> std::result::Result<(), execute::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/{}/providers/Microsoft.CostManagement/exports/{}/run",
&operation_config.base_path, scope, export_name
);
let mut req_builder = client.post(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(execute::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.header(reqwest::header::CONTENT_LENGTH, 0);
let req = req_builder.build().context(execute::BuildRequestError)?;
let rsp = client.execute(req).await.context(execute::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(()),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(execute::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(execute::DeserializeError { body })?;
execute::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod execute {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn get_execution_history(
operation_config: &crate::OperationConfig,
scope: &str,
export_name: &str,
) -> std::result::Result<ExportExecutionListResult, get_execution_history::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/{}/providers/Microsoft.CostManagement/exports/{}/runHistory",
&operation_config.base_path, scope, export_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get_execution_history::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get_execution_history::BuildRequestError)?;
let rsp = client.execute(req).await.context(get_execution_history::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get_execution_history::ResponseBytesError)?;
let rsp_value: ExportExecutionListResult =
serde_json::from_slice(&body).context(get_execution_history::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get_execution_history::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(get_execution_history::DeserializeError { body })?;
get_execution_history::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get_execution_history {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod operations {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<OperationListResult, list::Error> {
let client = &operation_config.client;
let uri_str = &format!("{}/providers/Microsoft.CostManagement/operations", &operation_config.base_path,);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: OperationListResult = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: ErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::ErrorResponse,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
|
use std::error;
use std::fmt;
#[derive(Debug, PartialEq)]
pub enum CryptoError {
BadPadding,
}
impl fmt::Display for CryptoError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CryptoError::BadPadding => write!(f, "Bad PKCS7 padding"),
}
}
}
impl error::Error for CryptoError {
fn description(&self) -> &str {
match *self {
CryptoError::BadPadding => "Bad PKCS7 padding",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
CryptoError::BadPadding => None,
}
}
}
|
use lv2_raw::midi;
use lv2_raw::urid;
use lv2::atom;
#[derive(Debug)]
pub enum MidiEvent {
AfterTouch { note_num: u8, pressure: u8 },
Bender { value: u16 },
ChannelPressure { pressure: u8 },
Controller { controller_num: u8, controller_val: u8 },
NoteOn { note_num: u8, velocity: u8 },
NoteOff { note_num: u8, velocity: u8 },
ProgramChange { num: u8 },
Unknown
}
impl MidiEvent {
pub fn new(data: *const u8, size: usize) -> MidiEvent {
unsafe {
match *data {
midi::LV2_MIDI_MSG_NOTE_PRESSURE => {
assert_eq!(size, 3);
MidiEvent::AfterTouch {
note_num: *data.offset(1),
pressure: *data.offset(2),
}
},
midi::LV2_MIDI_MSG_BENDER => {
assert_eq!(size, 3);
MidiEvent::Bender {
value: *data.offset(1) as u16,
}
},
midi::LV2_MIDI_MSG_CHANNEL_PRESSURE => {
assert_eq!(size, 3);
MidiEvent::ChannelPressure {
pressure: *data.offset(1),
}
},
midi::LV2_MIDI_MSG_CONTROLLER => {
assert_eq!(size, 3);
MidiEvent::Controller {
controller_num: *data.offset(1),
controller_val: *data.offset(2),
}
},
midi::LV2_MIDI_MSG_NOTE_ON => {
assert_eq!(size, 3);
MidiEvent::NoteOn {
note_num: *data.offset(1),
velocity: *data.offset(2),
}
},
midi::LV2_MIDI_MSG_NOTE_OFF => {
assert_eq!(size, 3);
MidiEvent::NoteOff {
note_num: *data.offset(1),
velocity: *data.offset(2),
}
},
midi::LV2_MIDI_MSG_PGM_CHANGE => {
assert_eq!(size, 2);
MidiEvent::ProgramChange {
num: *data.offset(1),
}
},
_ => {
MidiEvent::Unknown
}
}
}
}
}
|
use chrono::{DateTime, Local};
use std::collections::VecDeque;
use zellij_tile::prelude::*;
#[derive(Default)]
struct State {
log: VecDeque<DateTime<Local>>,
}
register_plugin!(State);
impl ZellijPlugin for State {
fn load(&mut self) {
// Setup the timer event subscription
subscribe(&[EventType::Timer, EventType::KeyPress]);
// Set how many seconds out from here you want to trigger the timer
set_timeout(1.0);
}
fn update(&mut self, event: Event) {
match event {
Event::Timer(sec) => {
// A timeout was triggered. Save current time to state
self.log.push_front(Local::now());
// Set timeout again
set_timeout(1.0);
}
Event::KeyPress(key) => {
// Clear log if ctrl+l is pressed
if key == Key::Ctrl('l') {
self.log.clear();
}
}
_ => panic!("Error"),
}
}
fn render(&mut self, rows: usize, cols: usize) {
for time in &self.log {
println!("Time: {}", time.format("%T"));
}
}
}
|
use alloc::vec;
use alloc::vec::Vec;
use crate::{Read, Write, NumBytes, UnsignedInt, WriteError, ReadError};
use codec::{Encode, Decode};
#[derive(Clone, Debug, Default, Encode, Decode, PartialEq)]
pub struct FlatMap<K, V> {
maps: Vec<(K, V)>,
}
impl<K, V> FlatMap<K, V> {
pub fn new(key: K, value: V) -> Self {
Self {
maps: vec![(key, value)],
}
}
pub fn size(&self) -> UnsignedInt {
UnsignedInt::from(self.maps.len())
}
pub fn assign(v: Vec<(K, V)>) -> Self {
Self {
maps: v
}
}
}
impl<K: NumBytes, V: NumBytes> NumBytes for FlatMap<K, V> {
fn num_bytes(&self) -> usize {
let mut size = self.size().num_bytes();
for map in self.maps.iter() {
size = size.saturating_add(map.num_bytes());
}
size
}
}
impl<K: Write, V: Write> Write for FlatMap<K, V> {
fn write(&self, bytes: &mut [u8], pos: &mut usize) -> Result<(), WriteError> {
self.size().write(bytes, pos)?;
for map in self.maps.iter() {
map.write(bytes, pos)?;
}
Ok(())
}
}
impl <K: Read, V: Read> Read for FlatMap<K, V> {
fn read(bytes: &[u8], pos: &mut usize) -> Result<Self, ReadError> {
let size = UnsignedInt::read(bytes, pos)?;
let size = usize::from(size);
let mut maps: Vec<(K, V)> = Vec::with_capacity(size);
for _ in 0..size {
let map = <(K, V)>::read(bytes, pos)?;
maps.push(map);
}
Ok(FlatMap { maps })
}
}
|
use clap::{App, Arg};
use tablespanner::render_json_table;
fn main() {
let opts = App::new(env!("CARGO_PKG_NAME"))
.author(env!("CARGO_PKG_AUTHORS"))
.version(env!("CARGO_PKG_VERSION"))
.about("Calculates JSON table layouts")
.arg(Arg::with_name("SPANINFO")
.help(r#"
JSON object mapping cell identifiers to [rows, cols], where
those values specify the number of cells the current cell spans.
Example: {"A": [1, 2], "E": [3, 3]}
Note: It is an error to pass zero for these values.
"#)
.required(true)
.index(1))
.arg(Arg::with_name("TABLESPEC")
.help(r#"
A two-dimensional JSON array of cell identifiers for the table.
Example: [["A", "B"], ["C", "D"]]
Note: It is an error to pass non-string values, including
nulls.
"#)
.required(true)
.index(2))
.get_matches();
let spaninfo = opts.value_of("SPANINFO").unwrap();
let tablespec = opts.value_of("TABLESPEC").unwrap();
println!("{}", render_json_table(spaninfo, tablespec).unwrap());
}
|
use std::collections::BTreeMap;
use std::io::{Error, ErrorKind, Result};
use std::ops::Bound::Included;
use std::pin::Pin;
use std::task::{Context, Poll};
use crypto::digest::Digest;
use crypto::md5::Md5;
use crate::backend::AddressEnable;
use crate::{AsyncReadAll, AsyncWriteAll, Request, Response};
use hash::Hash;
use protocol::Protocol;
pub struct AsyncSharding<B, H, P> {
idx: usize,
// 用于modula分布以及一致性hash定位server
shards: Vec<B>,
// 用于一致性hash分布
consistent_enable: bool,
consistent_map: BTreeMap<i64, usize>,
hasher: H,
parser: P,
}
impl<B, H, P> AsyncSharding<B, H, P>
where
B: AddressEnable,
{
pub fn from(shards: Vec<B>, hasher: H, distribution: &String, parser: P) -> Self {
// 构建一致性hash的treemap,对java版一致性hash做了简化,不支持权重 fishermen
let mut consistent_map = BTreeMap::new();
for idx in 0..shards.len() {
let factor = 40;
for i in 0..factor {
let mut md5 = Md5::new();
let data: String = shards[idx].get_address() + "-" + &i.to_string();
let data_str = data.as_str();
md5.input_str(data_str);
let mut out_bytes = [0u8; 16];
md5.result(&mut out_bytes);
for j in 0..4 {
let hash = (((out_bytes[3 + j * 4] & 0xFF) as i64) << 24)
| (((out_bytes[2 + j * 4] & 0xFF) as i64) << 16)
| (((out_bytes[1 + j * 4] & 0xFF) as i64) << 8)
| ((out_bytes[0 + j * 4] & 0xFF) as i64);
let mut hash = hash.wrapping_rem(i32::MAX as i64);
if hash < 0 {
hash = hash.wrapping_mul(-1);
}
consistent_map.insert(hash, idx);
}
}
}
let idx = 0;
let consistent_enable = hash::DISTRIBUTION_CONSISTENT.eq(distribution.as_str());
Self {
idx,
shards,
consistent_enable,
consistent_map,
hasher,
parser,
}
}
}
impl<B, H, P> AsyncWriteAll for AsyncSharding<B, H, P>
where
B: AsyncWriteAll + Unpin,
H: Unpin + Hash,
P: Unpin + Protocol,
{
#[inline]
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &Request) -> Poll<Result<()>> {
let me = &mut *self;
debug_assert!(me.idx < me.shards.len());
let key = me.parser.key(buf.data());
let h = me.hasher.hash(key) as usize;
// 根据分布策略确定idx
if !me.consistent_enable {
me.idx = h % me.shards.len();
// println!("+++ use mod distribution idx/{}", me.idx);
} else {
// 一致性hash,选择hash环的第一个节点,不支持漂移,避免脏数据 fishermen
let (_, idx) = get_consistent_hash_idx(&me.consistent_map, h as i64);
me.idx = idx;
// println!("+++ use consistent distribution idx/{}", idx);
}
unsafe { Pin::new(me.shards.get_unchecked_mut(me.idx)).poll_write(cx, buf) }
}
}
fn get_consistent_hash_idx(consistent_map: &BTreeMap<i64, usize>, hash: i64) -> (i64, usize) {
// 从[hash, max)范围从map中寻找节点
let idxs = consistent_map.range((Included(hash), Included(i64::MAX)));
for (h, idx) in idxs {
return (*h, *idx);
}
// 如果idxs为空,则选择第一个hash节点,first_entry暂时是unstable,延迟使用
//if let Some(mut entry) = self.consistent_map.first_entry() {
for (h, i) in consistent_map {
return (*h, *i);
}
debug_assert!(false);
println!("++++ should not come here!!!");
return (0, 0);
}
impl<B, H, P> AsyncReadAll for AsyncSharding<B, H, P>
where
B: AsyncReadAll + Unpin,
H: Unpin,
P: Unpin,
{
#[inline]
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<Response>> {
let me = &mut *self;
if me.shards.len() == 0 {
return Poll::Ready(Err(Error::new(
ErrorKind::NotConnected,
"not connected, maybe topology not inited",
)));
}
unsafe { Pin::new(me.shards.get_unchecked_mut(me.idx)).poll_next(cx) }
}
}
|
use std::fs::File;
use std::io;
use std::io::{BufRead, BufReader};
fn read_input() -> Result<Vec<String>, io::Error> {
let filename = "input";
let file = File::open(filename)?;
let reader = BufReader::new(file);
let input: Vec<String> = reader.lines().collect::<Result<_, _>>().unwrap();
Ok(input)
}
fn parse_line(line: &str) -> (usize, usize, char, &str) {
let splitted_line: Vec<&str> = line.split([' ', ':', '-'].as_ref()).collect();
let first_integer = splitted_line[0].parse::<usize>().unwrap();
let second_integer = splitted_line[1].parse::<usize>().unwrap();
let character = splitted_line[2].chars().nth(0).unwrap();
let password = splitted_line[4];
return (first_integer, second_integer, character, password);
}
fn part_1() -> i32 {
let input = read_input();
if let Err(e) = &input {
eprintln!("Error occured: {}", e);
std::process::exit(1);
}
let mut ok_count = 0;
for line in input.unwrap().iter() {
let (min, max, character, password) = parse_line(line);
let count = password.chars().filter(|&c| c == character).count();
if min <= count && count <= max {
ok_count += 1;
}
}
return ok_count;
}
fn part_2() -> i32 {
let input = read_input();
if let Err(e) = &input {
eprintln!("Error occured: {}", e);
std::process::exit(1);
}
let mut ok_count = 0;
for line in input.unwrap().iter() {
let (position1, position2, character, password) = parse_line(line);
if (password.chars().nth(position1 - 1).unwrap() == character)
!= (password.chars().nth(position2 - 1).unwrap() == character) {
ok_count += 1;
}
}
return ok_count;
}
fn main() {
let part1_result = part_1();
println!("The first answer is: {}", part1_result);
let part2_result = part_2();
println!("The second answer is: {}", part2_result);
}
|
#[derive(Clone)]
pub struct Reindeer {
speed: u32,
run_time: u32,
rest_time: u32,
run_timer: u32,
rest_timer: u32,
total_distance: u32,
points: u32,
}
impl Reindeer {
pub fn new(speed: u32, run_time: u32, rest_time: u32) -> Reindeer {
Reindeer {
speed,
run_time,
rest_time,
rest_timer: 0,
run_timer: 0,
total_distance: 0,
points: 0,
}
}
pub fn run_for(&mut self, time: u32) -> u32 {
let mut t = 0;
while t < time {
t += 1;
self.run();
// println!("{}: dist: {} rest: {}, run: {}", t, total_distance, rest_timer, run_timer);
}
self.total_distance
}
pub fn run(&mut self) -> u32 {
if self.run_timer < self.run_time {
self.run_timer += 1;
self.total_distance += self.speed;
} else if self.rest_timer < self.rest_time {
self.rest_timer += 1;
}
if self.rest_timer == self.rest_time {
self.run_timer = 0;
self.rest_timer = 0;
}
self.total_distance
}
pub fn add_point(&mut self) {
self.points += 1;
}
pub fn get_points(&self) -> u32 {
self.points
}
pub fn get_distance(&self) -> u32 {
self.total_distance
}
}
pub fn race_reindeers(reindeers: &mut Vec<Reindeer>, time: u32) {
let mut distances: Vec<u32> = vec![0; reindeers.len()];
for _ in 0..time {
for i in 0..reindeers.len() {
distances[i] = reindeers[i].run();
}
let max_distance = *distances.iter().max().unwrap();
for i in 0..reindeers.len() {
if reindeers[i].get_distance() == max_distance {
reindeers[i].add_point();
}
}
}
}
pub fn get_max_points(reindeers: &Vec<Reindeer>) -> u32 {
reindeers.iter().map(|x| x.get_points()).max().unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_comet() {
let mut r = Reindeer::new(14, 10, 127);
assert_eq!(1120, r.run_for(1000));
}
#[test]
fn test_dancer() {
let mut r = Reindeer::new(16, 11, 162);
assert_eq!(1056, r.run_for(1000));
}
#[test]
fn test_race() {
let mut reindeers = vec![Reindeer::new(14, 10, 127), Reindeer::new(16, 11, 162)];
race_reindeers(&mut reindeers, 1_000);
assert_eq!(reindeers[0].get_points(), 312);
assert_eq!(reindeers[1].get_points(), 689);
assert_eq!(get_max_points(&reindeers), 689);
}
#[test]
fn test_reindeer_clone() {
let mut r1 = Reindeer::new(1, 1, 1);
let r2 = r1.clone();
r1.run();
assert_eq!(r1.get_distance(), 1);
assert_ne!(r1.get_distance(), r2.get_distance());
}
}
|
use crate::{
errors::{AddrError, Error},
peer_store::{
peer_id_serde, PeerId, Score, SessionType, ADDR_MAX_FAILURES, ADDR_MAX_RETRIES,
ADDR_TIMEOUT_MS,
},
};
use ipnetwork::IpNetwork;
use p2p::multiaddr::{self, multihash::Multihash, Multiaddr, Protocol};
use serde::{Deserialize, Serialize};
use std::net::IpAddr;
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct IpPort {
pub ip: IpAddr,
pub port: u16,
}
#[derive(Debug, Clone)]
pub struct PeerInfo {
pub peer_id: PeerId,
pub connected_addr: Multiaddr,
pub session_type: SessionType,
pub last_connected_at_ms: u64,
}
impl PeerInfo {
pub fn new(
peer_id: PeerId,
connected_addr: Multiaddr,
session_type: SessionType,
last_connected_at_ms: u64,
) -> Self {
PeerInfo {
peer_id,
connected_addr,
session_type,
last_connected_at_ms,
}
}
}
#[derive(Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct AddrInfo {
#[serde(with = "peer_id_serde")]
pub peer_id: PeerId,
pub ip_port: IpPort,
pub addr: Multiaddr,
pub score: Score,
pub last_connected_at_ms: u64,
pub last_tried_at_ms: u64,
pub attempts_count: u32,
pub random_id_pos: usize,
}
impl AddrInfo {
pub fn new(
peer_id: PeerId,
ip_port: IpPort,
addr: Multiaddr,
last_connected_at_ms: u64,
score: Score,
) -> Self {
AddrInfo {
peer_id,
ip_port,
addr,
score,
last_connected_at_ms,
last_tried_at_ms: 0,
attempts_count: 0,
random_id_pos: 0,
}
}
pub fn ip_port(&self) -> IpPort {
self.ip_port
}
pub fn had_connected(&self, expires_ms: u64) -> bool {
self.last_connected_at_ms > expires_ms
}
pub fn tried_in_last_minute(&self, now_ms: u64) -> bool {
self.last_tried_at_ms >= now_ms.saturating_sub(60_000)
}
pub fn is_terrible(&self, now_ms: u64) -> bool {
// do not remove addr tried in last minute
if self.tried_in_last_minute(now_ms) {
return false;
}
// we give up if never connect to this addr
if self.last_connected_at_ms == 0 && self.attempts_count >= ADDR_MAX_RETRIES {
return true;
}
// consider addr is terrible if failed too many times
if now_ms.saturating_sub(self.last_connected_at_ms) > ADDR_TIMEOUT_MS
&& (self.attempts_count >= ADDR_MAX_FAILURES)
{
return true;
}
false
}
pub fn mark_tried(&mut self, tried_at_ms: u64) {
self.last_tried_at_ms = tried_at_ms;
self.attempts_count = self.attempts_count.saturating_add(1);
}
pub fn mark_connected(&mut self, connected_at_ms: u64) {
self.last_connected_at_ms = connected_at_ms;
// reset attempts
self.attempts_count = 0;
}
pub fn multiaddr(&self) -> Result<Multiaddr, Error> {
self.addr.attach_p2p(&self.peer_id)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct BannedAddr {
pub address: IpNetwork,
pub ban_until: u64,
pub ban_reason: String,
pub created_at: u64,
}
pub fn multiaddr_to_ip_network(multiaddr: &Multiaddr) -> Option<IpNetwork> {
for addr_component in multiaddr {
match addr_component {
Protocol::Ip4(ipv4) => return Some(IpNetwork::V4(ipv4.into())),
Protocol::Ip6(ipv6) => return Some(IpNetwork::V6(ipv6.into())),
_ => (),
}
}
None
}
pub fn ip_to_network(ip: IpAddr) -> IpNetwork {
match ip {
IpAddr::V4(ipv4) => IpNetwork::V4(ipv4.into()),
IpAddr::V6(ipv6) => IpNetwork::V6(ipv6.into()),
}
}
pub trait MultiaddrExt {
/// extract IP from multiaddr,
fn extract_ip_addr(&self) -> Result<IpPort, Error>;
fn exclude_p2p(&self) -> Multiaddr;
fn attach_p2p(&self, peer_id: &PeerId) -> Result<Multiaddr, Error>;
}
impl MultiaddrExt for Multiaddr {
fn extract_ip_addr(&self) -> Result<IpPort, Error> {
let mut ip = None;
let mut port = None;
for component in self {
match component {
Protocol::Ip4(ipv4) => ip = Some(IpAddr::V4(ipv4)),
Protocol::Ip6(ipv6) => ip = Some(IpAddr::V6(ipv6)),
Protocol::Tcp(tcp_port) => port = Some(tcp_port),
_ => (),
}
}
Ok(IpPort {
ip: ip.ok_or(AddrError::MissingIP)?,
port: port.ok_or(AddrError::MissingPort)?,
})
}
fn exclude_p2p(&self) -> Multiaddr {
self.iter()
.filter_map(|proto| match proto {
Protocol::P2p(_) => None,
value => Some(value),
})
.collect::<Multiaddr>()
}
fn attach_p2p(&self, peer_id: &PeerId) -> Result<Multiaddr, Error> {
let mut addr = self.exclude_p2p();
let peer_id_hash = Multihash::from_bytes(peer_id.as_bytes().to_vec())
.map_err(|_err| AddrError::InvalidPeerId)?;
addr.push(multiaddr::Protocol::P2p(peer_id_hash));
Ok(addr)
}
}
|
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InstantiateMsg {
pub currency: String,
pub count: u32,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
// GetConfig returns the current config as a json-encoded number
GetConfig {},
}
// We define a custom struct for each query response
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct ConfigResponse {
pub currency: String,
pub count: u32,
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// AwsLogsServicesRequest : A list of current AWS services for which Datadog offers automatic log collection.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AwsLogsServicesRequest {
/// Your AWS Account ID without dashes.
#[serde(rename = "account_id")]
pub account_id: String,
/// Array of services IDs set to enable automatic log collection. Discover the list of available services with the get list of AWS log ready services API endpoint.
#[serde(rename = "services")]
pub services: Vec<String>,
}
impl AwsLogsServicesRequest {
/// A list of current AWS services for which Datadog offers automatic log collection.
pub fn new(account_id: String, services: Vec<String>) -> AwsLogsServicesRequest {
AwsLogsServicesRequest {
account_id,
services,
}
}
}
|
//! Module containing the implementation of a SPSC RingBuffer built on futures_rs.
use futures::{
Async,
Future,
Poll,
task
};
use std::{
cmp
};
use std::sync::{
Arc,
Mutex
};
/// The sending end of the SPSC RingBuffer.
#[derive( Debug )]
pub struct Sender< T : Clone + Default > {
inner : Arc< Mutex< RingBuffer< T > > >
}
/// Errors generated while sending elements to the RingBuffer.
#[derive( Debug )]
pub enum SendError {
ReceiverDropped
}
/// Future that completes when at least one element has been written to the RingBuffer.
#[derive( Debug )]
pub struct WriteSome< 'a, T : Clone + Default + 'a > {
sender : Option< Sender< T > >,
buffer : &'a [ T ]
}
/// Future that completes when the entire buffer has been filled from the RingBuffer.
#[derive( Debug )]
pub struct WriteAll< 'a, T : Clone + Default + 'a > {
sender : Option< Sender< T > >,
buffer : &'a [ T ],
elems_written : usize
}
/// The receiving end of the SPSC RingBuffer.
#[derive( Debug )]
pub struct Receiver< T : Clone + Default > {
inner : Arc< Mutex< RingBuffer< T > > >
}
/// Errors generated when reading elements from the RingBuffer.
#[derive( Debug )]
pub enum ReadError {
SenderDropped
}
/// Future that completes when at least one element has been read from the RingBuffer.
#[derive( Debug )]
pub struct ReadSome< 'a, T : Clone + Default + 'a > {
receiver : Option< Receiver< T > >,
buffer : &'a mut [ T ]
}
/// Future that completes when the entire buffer has been read from the RingBuffer.
#[derive( Debug )]
pub struct ReadAll< 'a, T : Clone + Default + 'a > {
receiver : Option< Receiver< T > >,
buffer : &'a mut [ T ],
elems_read : usize
}
#[derive( Debug )]
struct RingBuffer< T : Clone + Default > {
buffer : Vec< T >,
read_offset : usize,
size : usize,
parked_read : ParkedTask,
parked_write : ParkedTask,
buffer_state : RingBufferState
}
#[derive( Debug )]
enum RingBufferState {
Open,
ReceiverDropped,
SenderDropped,
Closed
}
#[derive( Debug )]
struct ParkedTask {
task : Option< task::Task >
}
/// Creates a new RingBuffer with the given internal buffer size.
///
/// # Panics
/// If buffer_size == 0.
pub fn create_buffer< T : Clone + Default >( buffer_size : usize ) -> ( Sender< T >, Receiver< T > ) {
let inner = Arc::new( Mutex::new( RingBuffer::new( buffer_size ) ) );
( Sender { inner : inner.clone( ) }, Receiver { inner : inner } )
}
impl < T : Clone + Default > Sender< T > {
/// Attempts to write as many elements to the RingBuffer without blocking.
///
/// # Errors
/// If there is no Receiver.
pub fn write( &mut self, buffer : &[ T ] ) -> Result< usize, SendError > {
self.inner.lock( ).unwrap( ).write_some( buffer )
}
/// Attempts to write at least one element to the RingBuffer, returning a future
/// that completes when at least one element has been written.
pub fn write_some< 'a, E >( self, buffer : &'a [ T ] ) -> WriteSome< 'a, T > {
WriteSome {
sender : Some( self ),
buffer : buffer
}
}
/// Attempts to write the entire buffer to the RingBuffer, returning a future that
/// completes when the entire buffer has been written.
pub fn write_all< 'a >( self, buffer : &'a [ T ] ) -> WriteAll< 'a, T > {
WriteAll {
sender : Some( self ),
buffer : buffer,
elems_written : 0
}
}
/// Tests to see if a call to write would write at least one element to the RingBuffer.
///
/// If sender is not ready, the current task is parked and later unparked when the above is true.
pub fn poll_write( &mut self ) -> Async< ( ) > {
self.inner.lock( ).unwrap( ).poll_write( )
}
}
impl < T : Clone + Default > Drop for Sender< T > {
fn drop( &mut self ) {
self.inner.lock( ).unwrap( ).close_sender( );
}
}
impl < 'a, T : Clone + Default > Future for WriteSome< 'a, T > {
type Item = ( usize, Sender< T > );
type Error = ( SendError, Sender< T > );
fn poll( &mut self ) -> Poll< Self::Item, Self::Error > {
if let Some( mut sender ) = self.sender.take( ) {
if self.buffer.len( ) == 0 {
return Ok( Async::Ready( ( 0, sender ) ) );
}
if let Async::NotReady = sender.poll_write( ) {
return Ok( Async::NotReady );
}
let result = sender.write( self.buffer );
match result {
Ok( read ) => {
assert!( read != 0 );
Ok( Async::Ready( ( read, sender ) ) )
},
Err( error ) => {
Err( ( error, sender ) )
}
}
}
else {
panic!( "Can not call poll on a completed future." );
}
}
}
impl < 'a, T : Clone + Default > Future for WriteAll< 'a, T > {
type Item = Sender< T >;
type Error = ( SendError, Sender< T > );
fn poll( &mut self ) -> Poll< Self::Item, Self::Error > {
if let Some( mut sender ) = self.sender.take( ) {
if self.buffer.len( ) == 0 {
return Ok( Async::Ready( sender ) );
}
loop {
if let Async::NotReady = sender.poll_write( ) {
self.sender = Some( sender );
return Ok( Async::NotReady );
}
let result = sender.write( &self.buffer[ self.elems_written .. ] );
match result {
Ok( written ) => {
assert!( written != 0 );
self.elems_written += written;
if self.elems_written == self.buffer.len( ) {
return Ok( Async::Ready( sender ) );
}
},
Err( error ) => {
return Err( ( error, sender ) )
}
}
}
}
else {
panic!( "Can not call poll on a completed future." );
}
}
}
impl < T : Clone + Default > Receiver< T > {
/// Attempts to read as many elements from the RingBuffer as possible without blocking.
///
/// # Errors
/// If the buffer is empty and there is no Sender.
pub fn read( &mut self, buffer : &mut [ T ] ) -> Result< usize, ReadError > {
self.inner.lock( ).unwrap( ).read_some( buffer )
}
/// Attempts to read at least one element from the RingBuffer, returning a future that
/// completes when at least one element has been read.
pub fn read_some< 'a >( self, buffer : &'a mut [ T ] ) -> ReadSome< 'a, T > {
ReadSome {
receiver : Some( self ),
buffer : buffer
}
}
/// Attempts to read the entire buffer from the RingBuffer, returning a future that
/// completes when at least the entire buffer has been read.
pub fn read_all< 'a >( self, buffer : &'a mut [ T ] ) -> ReadAll< 'a, T > {
ReadAll {
receiver : Some( self ),
buffer : buffer,
elems_read : 0
}
}
/// Tests to see if a call to read will read at least one element from the RingBuffer.
///
/// If receiver is not ready, the current task is parked and later unparked when the above is true.
pub fn poll_read( &mut self ) -> Async< ( ) > {
self.inner.lock( ).unwrap( ).poll_read( )
}
}
impl < T : Clone + Default > Drop for Receiver< T > {
fn drop( &mut self ) {
self.inner.lock( ).unwrap( ).close_receiver( );
}
}
impl < 'a, T : Clone + Default + 'a > Future for ReadSome< 'a, T > {
type Item = ( usize, Receiver< T > );
type Error = ( ReadError, Receiver< T > );
fn poll( &mut self ) -> Poll< Self::Item, Self::Error > {
if let Some( mut receiver ) = self.receiver.take( ) {
if self.buffer.len( ) == 0 {
return Ok( Async::Ready( ( 0, receiver ) ) );
}
if let Async::NotReady = receiver.poll_read( ) {
self.receiver = Some( receiver );
return Ok( Async::NotReady );
}
let result = receiver.read( self.buffer );
match result {
Ok( read ) => {
assert!( read != 0 );
Ok( Async::Ready( ( read, receiver ) ) )
},
Err( error ) => {
Err( ( error, receiver ) )
}
}
}
else {
panic!( "Can not call poll on already completed future." );
}
}
}
impl < 'a, T : Clone + Default + 'a > Future for ReadAll< 'a, T > {
type Item = Receiver< T >;
type Error = ( ReadError, Receiver< T > );
fn poll( &mut self ) -> Poll< Self::Item, Self::Error > {
if let Some( mut receiver ) = self.receiver.take( ) {
if self.buffer.len( ) == 0 {
return Ok( Async::Ready( receiver ) );
}
loop {
if let Async::NotReady = receiver.poll_read( ) {
self.receiver = Some( receiver );
return Ok( Async::NotReady );
}
let result = receiver.read( &mut self.buffer[ self.elems_read .. ] );
match result {
Ok( read ) => {
assert!( read != 0 );
self.elems_read += read;
if self.elems_read == self.buffer.len( ) {
return Ok( Async::Ready( receiver ) )
}
},
Err( error ) => {
return Err( ( error, receiver ) )
}
}
}
}
else {
panic!( "Can not call poll on already completed future." );
}
}
}
impl < T : Clone + Default > RingBuffer< T > {
fn new( buffer_size : usize ) -> Self {
if buffer_size == 0 {
panic!( "Can not create ring buffer with size == 0." );
}
RingBuffer {
buffer : vec![ T::default( ); buffer_size ],
read_offset : 0,
size : 0,
parked_read : ParkedTask::new( ),
parked_write : ParkedTask::new( ),
buffer_state : RingBufferState::Open
}
}
fn available_slots( &self ) -> usize {
self.buffer.len( ) - self.size
}
fn taken_slots( &self ) -> usize {
self.size
}
fn write_some( &mut self, buffer : &[ T ] ) -> Result< usize, SendError > {
if !self.has_receiver( ) {
return Err( SendError::ReceiverDropped );
}
let buffer_size = self.buffer.len( );
let write_ptr = ( self.read_offset + self.size ) % buffer_size;
let elems_to_write = cmp::min( buffer.len( ), self.available_slots( ) );
let head_elems = cmp::min( elems_to_write, buffer_size - write_ptr );
let tail_elems = elems_to_write - head_elems;
self.buffer[ write_ptr .. write_ptr + head_elems ].clone_from_slice( &buffer[ .. head_elems ] );
self.buffer[ .. tail_elems ].clone_from_slice( &buffer[ head_elems .. elems_to_write ] );
self.size += elems_to_write;
self.parked_read.unpark( );
Ok( elems_to_write )
}
fn read_some( &mut self, buffer : &mut [ T ] ) -> Result< usize, ReadError > {
if self.taken_slots( ) == 0 && !self.has_sender( ) {
return Err( ReadError::SenderDropped );
}
let buffer_size = self.buffer.len( );
let read_ptr = self.read_offset;
let elems_to_read = cmp::min( buffer.len( ), self.taken_slots( ) );
let head_elems = cmp::min( elems_to_read, buffer_size - read_ptr );
let tail_elems = elems_to_read - head_elems;
buffer[ .. head_elems ].clone_from_slice( &self.buffer[ read_ptr .. read_ptr + head_elems ] );
buffer[ head_elems .. elems_to_read ].clone_from_slice( &self.buffer[ .. tail_elems ] );
self.read_offset = ( read_ptr + elems_to_read ) % buffer_size;
self.size -= elems_to_read;
self.parked_write.unpark( );
Ok( elems_to_read )
}
fn poll_read( &mut self ) -> Async< ( ) > {
if self.taken_slots( ) == 0 && self.has_sender( ) {
self.parked_read.park( );
Async::NotReady
}
else {
Async::Ready( ( ) )
}
}
fn poll_write( &mut self ) -> Async< ( ) > {
if self.available_slots( ) == 0 && self.has_receiver( ) {
self.parked_write.park( );
Async::NotReady
}
else {
Async::Ready( ( ) )
}
}
fn has_sender( &self ) -> bool {
match self.buffer_state {
RingBufferState::Open | RingBufferState::ReceiverDropped => true,
_ => false
}
}
fn close_sender( &mut self ) {
self.buffer_state = match self.buffer_state {
RingBufferState::Open => RingBufferState::SenderDropped,
RingBufferState::ReceiverDropped => RingBufferState::Closed,
_ => unreachable!( )
};
self.parked_read.unpark( );
}
fn has_receiver( &self ) -> bool {
match self.buffer_state {
RingBufferState::Open | RingBufferState::SenderDropped => true,
_ => false
}
}
fn close_receiver( &mut self ) {
self.buffer_state = match self.buffer_state {
RingBufferState::Open => RingBufferState::ReceiverDropped,
RingBufferState::SenderDropped => RingBufferState::Closed,
_ => unreachable!( )
};
self.parked_write.unpark( )
}
}
impl ParkedTask {
fn new( ) -> Self {
ParkedTask {
task : None
}
}
fn park( &mut self ) {
let task = task::park( );
self.task = Some( task );
}
fn unpark( &mut self ) {
if let Some( parked_task ) = self.task.take( ) {
parked_task.unpark( );
}
}
} |
use std::collections::{BTreeMap, HashMap, HashSet};
use std::time::Instant;
const INPUT: &str = include_str!("../input.txt");
fn read_data() -> (
HashMap<&'static str, usize>,
HashMap<&'static str, HashSet<&'static str>>,
) {
let mut allergen_to_ingredients = HashMap::new();
let mut ingredient_counts = HashMap::new();
for line in INPUT.lines() {
let mut split = line.split(" (contains ");
let ingredients: HashSet<&'static str> =
split.next().unwrap().split_ascii_whitespace().collect();
for ingredient in &ingredients {
*ingredient_counts.entry(*ingredient).or_insert(0) += 1
}
let allergen_str = split.next().unwrap();
let allergens: HashSet<&'static str> =
allergen_str[..allergen_str.len() - 1].split(", ").collect();
for allergen in allergens {
match allergen_to_ingredients.get_mut(allergen) {
None => {
allergen_to_ingredients.insert(allergen, ingredients.clone());
}
Some(ingredients_so_far) => {
ingredients_so_far.retain(|ing| ingredients.contains(ing));
}
}
}
}
(ingredient_counts, allergen_to_ingredients)
}
fn part1() -> usize {
let (all_ingredients, allergen_to_ingredients) = read_data();
all_ingredients
.iter()
.filter_map(|(ingredient, count)| {
if allergen_to_ingredients
.values()
.all(|ingredients| !ingredients.contains(ingredient))
{
Some(count)
} else {
None
}
})
.sum()
}
fn part2() -> String {
let (_, mut allergen_to_ingredients) = read_data();
let mut allergen_to_ingredient = BTreeMap::new();
while !allergen_to_ingredients.is_empty() {
let single_ingredient_allergen = *allergen_to_ingredients
.keys()
.find(|allergen| allergen_to_ingredients[*allergen].len() == 1)
.unwrap();
let (allergen, ingredient) = allergen_to_ingredients
.remove_entry(single_ingredient_allergen)
.unwrap();
let found_ingredident = ingredient.into_iter().next().unwrap();
for ingredient_list in allergen_to_ingredients.values_mut() {
ingredient_list.remove(&found_ingredident);
}
allergen_to_ingredient.insert(allergen, found_ingredident);
}
let final_ingredients: Vec<String> = allergen_to_ingredient
.values()
.map(|&v| v.to_owned())
.collect();
final_ingredients.join(",")
}
fn main() {
let start = Instant::now();
println!("part 1: {}", part1());
println!("part 1 took {}ms", (Instant::now() - start).as_millis());
let start = Instant::now();
println!("part 2: {}", part2());
println!("part 2 took {}ms", (Instant::now() - start).as_millis());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part1() {
assert_eq!(part1(), 2317);
}
#[test]
fn test_part2() {
assert_eq!(part2(), "kbdgs,sqvv,slkfgq,vgnj,brdd,tpd,csfmb,lrnz");
}
}
|
#![allow(clippy::needless_return)]
use clap::{crate_version, App, Arg};
use rofuse::consts::FOPEN_DIRECT_IO;
#[cfg(feature = "abi-7-26")]
use rofuse::consts::FUSE_HANDLE_KILLPRIV;
#[cfg(feature = "abi-7-31")]
use rofuse::consts::FUSE_WRITE_KILL_PRIV;
use rofuse::TimeOrNow::Now;
use rofuse::{
Filesystem, KernelConfig, MountOption, ReplyAttr, ReplyCreate, ReplyData, ReplyDirectory,
ReplyEmpty, ReplyEntry, ReplyOpen, ReplyStatfs, ReplyWrite, ReplyXattr, Request, TimeOrNow,
FUSE_ROOT_ID,
};
#[cfg(feature = "abi-7-26")]
use log::info;
use log::LevelFilter;
use log::{debug, warn};
use serde::{Deserialize, Serialize};
use std::cmp::min;
use std::collections::BTreeMap;
use std::ffi::OsStr;
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
use std::os::raw::c_int;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::FileExt;
#[cfg(target_os = "linux")]
use std::os::unix::io::IntoRawFd;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::{env, fs, io};
const BLOCK_SIZE: u64 = 512;
const MAX_NAME_LENGTH: u32 = 255;
const MAX_FILE_SIZE: u64 = 1024 * 1024 * 1024 * 1024;
// Top two file handle bits are used to store permissions
// Note: This isn't safe, since the client can modify those bits. However, this implementation
// is just a toy
const FILE_HANDLE_READ_BIT: u64 = 1 << 63;
const FILE_HANDLE_WRITE_BIT: u64 = 1 << 62;
const FMODE_EXEC: i32 = 0x20;
type Inode = u64;
type DirectoryDescriptor = BTreeMap<Vec<u8>, (Inode, FileKind)>;
#[derive(Serialize, Deserialize, Copy, Clone, PartialEq)]
enum FileKind {
File,
Directory,
Symlink,
}
impl From<FileKind> for rofuse::FileType {
fn from(kind: FileKind) -> Self {
match kind {
FileKind::File => rofuse::FileType::RegularFile,
FileKind::Directory => rofuse::FileType::Directory,
FileKind::Symlink => rofuse::FileType::Symlink,
}
}
}
#[derive(Debug)]
enum XattrNamespace {
Security,
System,
Trusted,
User,
}
fn parse_xattr_namespace(key: &[u8]) -> Result<XattrNamespace, c_int> {
let user = b"user.";
if key.len() < user.len() {
return Err(libc::ENOTSUP);
}
if key[..user.len()].eq(user) {
return Ok(XattrNamespace::User);
}
let system = b"system.";
if key.len() < system.len() {
return Err(libc::ENOTSUP);
}
if key[..system.len()].eq(system) {
return Ok(XattrNamespace::System);
}
let trusted = b"trusted.";
if key.len() < trusted.len() {
return Err(libc::ENOTSUP);
}
if key[..trusted.len()].eq(trusted) {
return Ok(XattrNamespace::Trusted);
}
let security = b"security";
if key.len() < security.len() {
return Err(libc::ENOTSUP);
}
if key[..security.len()].eq(security) {
return Ok(XattrNamespace::Security);
}
return Err(libc::ENOTSUP);
}
fn clear_suid_sgid(attr: &mut InodeAttributes) {
attr.mode &= !libc::S_ISUID as u16;
// SGID is only suppose to be cleared if XGRP is set
if attr.mode & libc::S_IXGRP as u16 != 0 {
attr.mode &= !libc::S_ISGID as u16;
}
}
fn creation_gid(parent: &InodeAttributes, gid: u32) -> u32 {
if parent.mode & libc::S_ISGID as u16 != 0 {
return parent.gid;
}
gid
}
fn xattr_access_check(
key: &[u8],
access_mask: i32,
inode_attrs: &InodeAttributes,
request: &Request<'_>,
) -> Result<(), c_int> {
match parse_xattr_namespace(key)? {
XattrNamespace::Security => {
if access_mask != libc::R_OK && request.uid() != 0 {
return Err(libc::EPERM);
}
}
XattrNamespace::Trusted => {
if request.uid() != 0 {
return Err(libc::EPERM);
}
}
XattrNamespace::System => {
if key.eq(b"system.posix_acl_access") {
if !check_access(
inode_attrs.uid,
inode_attrs.gid,
inode_attrs.mode,
request.uid(),
request.gid(),
access_mask,
) {
return Err(libc::EPERM);
}
} else if request.uid() != 0 {
return Err(libc::EPERM);
}
}
XattrNamespace::User => {
if !check_access(
inode_attrs.uid,
inode_attrs.gid,
inode_attrs.mode,
request.uid(),
request.gid(),
access_mask,
) {
return Err(libc::EPERM);
}
}
}
Ok(())
}
fn time_now() -> (i64, u32) {
time_from_system_time(&SystemTime::now())
}
fn system_time_from_time(secs: i64, nsecs: u32) -> SystemTime {
if secs >= 0 {
UNIX_EPOCH + Duration::new(secs as u64, nsecs)
} else {
UNIX_EPOCH - Duration::new((-secs) as u64, nsecs)
}
}
fn time_from_system_time(system_time: &SystemTime) -> (i64, u32) {
// Convert to signed 64-bit time with epoch at 0
match system_time.duration_since(UNIX_EPOCH) {
Ok(duration) => (duration.as_secs() as i64, duration.subsec_nanos()),
Err(before_epoch_error) => (
-(before_epoch_error.duration().as_secs() as i64),
before_epoch_error.duration().subsec_nanos(),
),
}
}
#[derive(Serialize, Deserialize)]
struct InodeAttributes {
pub inode: Inode,
pub open_file_handles: u64, // Ref count of open file handles to this inode
pub size: u64,
pub last_accessed: (i64, u32),
pub last_modified: (i64, u32),
pub last_metadata_changed: (i64, u32),
pub kind: FileKind,
// Permissions and special mode bits
pub mode: u16,
pub hardlinks: u32,
pub uid: u32,
pub gid: u32,
pub xattrs: BTreeMap<Vec<u8>, Vec<u8>>,
}
impl From<InodeAttributes> for rofuse::FileAttr {
fn from(attrs: InodeAttributes) -> Self {
rofuse::FileAttr {
ino: attrs.inode,
size: attrs.size,
blocks: (attrs.size + BLOCK_SIZE - 1) / BLOCK_SIZE,
atime: system_time_from_time(attrs.last_accessed.0, attrs.last_accessed.1),
mtime: system_time_from_time(attrs.last_modified.0, attrs.last_modified.1),
ctime: system_time_from_time(
attrs.last_metadata_changed.0,
attrs.last_metadata_changed.1,
),
crtime: SystemTime::UNIX_EPOCH,
kind: attrs.kind.into(),
perm: attrs.mode,
nlink: attrs.hardlinks,
uid: attrs.uid,
gid: attrs.gid,
rdev: 0,
blksize: BLOCK_SIZE as u32,
flags: 0,
}
}
}
// Stores inode metadata data in "$data_dir/inodes" and file contents in "$data_dir/contents"
// Directory data is stored in the file's contents, as a serialized DirectoryDescriptor
struct SimpleFS {
data_dir: String,
next_file_handle: AtomicU64,
direct_io: bool,
suid_support: bool,
}
impl SimpleFS {
fn new(
data_dir: String,
direct_io: bool,
#[allow(unused_variables)] suid_support: bool,
) -> SimpleFS {
#[cfg(feature = "abi-7-26")]
{
SimpleFS {
data_dir,
next_file_handle: AtomicU64::new(1),
direct_io,
suid_support,
}
}
#[cfg(not(feature = "abi-7-26"))]
{
SimpleFS {
data_dir,
next_file_handle: AtomicU64::new(1),
direct_io,
suid_support: false,
}
}
}
fn creation_mode(&self, mode: u32) -> u16 {
if !self.suid_support {
(mode & !(libc::S_ISUID | libc::S_ISGID) as u32) as u16
} else {
mode as u16
}
}
fn allocate_next_inode(&self) -> Inode {
let path = Path::new(&self.data_dir).join("superblock");
let current_inode = if let Ok(file) = File::open(&path) {
bincode::deserialize_from(file).unwrap()
} else {
rofuse::FUSE_ROOT_ID
};
let file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&path)
.unwrap();
bincode::serialize_into(file, &(current_inode + 1)).unwrap();
current_inode + 1
}
fn allocate_next_file_handle(&self, read: bool, write: bool) -> u64 {
let mut fh = self.next_file_handle.fetch_add(1, Ordering::SeqCst);
// Assert that we haven't run out of file handles
assert!(fh < FILE_HANDLE_WRITE_BIT && fh < FILE_HANDLE_READ_BIT);
if read {
fh |= FILE_HANDLE_READ_BIT;
}
if write {
fh |= FILE_HANDLE_WRITE_BIT;
}
fh
}
fn check_file_handle_read(&self, file_handle: u64) -> bool {
(file_handle & FILE_HANDLE_READ_BIT) != 0
}
fn check_file_handle_write(&self, file_handle: u64) -> bool {
(file_handle & FILE_HANDLE_WRITE_BIT) != 0
}
fn content_path(&self, inode: Inode) -> PathBuf {
Path::new(&self.data_dir)
.join("contents")
.join(inode.to_string())
}
fn get_directory_content(&self, inode: Inode) -> Result<DirectoryDescriptor, c_int> {
let path = Path::new(&self.data_dir)
.join("contents")
.join(inode.to_string());
if let Ok(file) = File::open(&path) {
Ok(bincode::deserialize_from(file).unwrap())
} else {
Err(libc::ENOENT)
}
}
fn write_directory_content(&self, inode: Inode, entries: DirectoryDescriptor) {
let path = Path::new(&self.data_dir)
.join("contents")
.join(inode.to_string());
let file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&path)
.unwrap();
bincode::serialize_into(file, &entries).unwrap();
}
fn get_inode(&self, inode: Inode) -> Result<InodeAttributes, c_int> {
let path = Path::new(&self.data_dir)
.join("inodes")
.join(inode.to_string());
if let Ok(file) = File::open(&path) {
Ok(bincode::deserialize_from(file).unwrap())
} else {
Err(libc::ENOENT)
}
}
fn write_inode(&self, inode: &InodeAttributes) {
let path = Path::new(&self.data_dir)
.join("inodes")
.join(inode.inode.to_string());
let file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&path)
.unwrap();
bincode::serialize_into(file, inode).unwrap();
}
// Check whether a file should be removed from storage. Should be called after decrementing
// the link count, or closing a file handle
fn gc_inode(&self, inode: &InodeAttributes) -> bool {
if inode.hardlinks == 0 && inode.open_file_handles == 0 {
let inode_path = Path::new(&self.data_dir)
.join("inodes")
.join(inode.inode.to_string());
fs::remove_file(inode_path).unwrap();
let content_path = Path::new(&self.data_dir)
.join("contents")
.join(inode.inode.to_string());
fs::remove_file(content_path).unwrap();
return true;
}
return false;
}
fn truncate(
&self,
inode: Inode,
new_length: u64,
uid: u32,
gid: u32,
) -> Result<InodeAttributes, c_int> {
if new_length > MAX_FILE_SIZE {
return Err(libc::EFBIG);
}
let mut attrs = self.get_inode(inode)?;
if !check_access(attrs.uid, attrs.gid, attrs.mode, uid, gid, libc::W_OK) {
return Err(libc::EACCES);
}
let path = self.content_path(inode);
let file = OpenOptions::new().write(true).open(&path).unwrap();
file.set_len(new_length).unwrap();
attrs.size = new_length;
attrs.last_metadata_changed = time_now();
attrs.last_modified = time_now();
// Clear SETUID & SETGID on truncate
clear_suid_sgid(&mut attrs);
self.write_inode(&attrs);
Ok(attrs)
}
fn lookup_name(&self, parent: u64, name: &OsStr) -> Result<InodeAttributes, c_int> {
let entries = self.get_directory_content(parent)?;
if let Some((inode, _)) = entries.get(name.as_bytes()) {
return self.get_inode(*inode);
} else {
return Err(libc::ENOENT);
}
}
fn insert_link(
&self,
req: &Request,
parent: u64,
name: &OsStr,
inode: u64,
kind: FileKind,
) -> Result<(), c_int> {
if self.lookup_name(parent, name).is_ok() {
return Err(libc::EEXIST);
}
let mut parent_attrs = self.get_inode(parent)?;
if !check_access(
parent_attrs.uid,
parent_attrs.gid,
parent_attrs.mode,
req.uid(),
req.gid(),
libc::W_OK,
) {
return Err(libc::EACCES);
}
parent_attrs.last_modified = time_now();
parent_attrs.last_metadata_changed = time_now();
self.write_inode(&parent_attrs);
let mut entries = self.get_directory_content(parent).unwrap();
entries.insert(name.as_bytes().to_vec(), (inode, kind));
self.write_directory_content(parent, entries);
Ok(())
}
}
impl Filesystem for SimpleFS {
fn init(
&mut self,
_req: &Request,
#[allow(unused_variables)] config: &mut KernelConfig,
) -> Result<(), c_int> {
#[cfg(feature = "abi-7-26")]
config.add_capabilities(FUSE_HANDLE_KILLPRIV).unwrap();
fs::create_dir_all(Path::new(&self.data_dir).join("inodes")).unwrap();
fs::create_dir_all(Path::new(&self.data_dir).join("contents")).unwrap();
if self.get_inode(FUSE_ROOT_ID).is_err() {
// Initialize with empty filesystem
let root = InodeAttributes {
inode: FUSE_ROOT_ID,
open_file_handles: 0,
size: 0,
last_accessed: time_now(),
last_modified: time_now(),
last_metadata_changed: time_now(),
kind: FileKind::Directory,
mode: 0o777,
hardlinks: 2,
uid: 0,
gid: 0,
xattrs: Default::default(),
};
self.write_inode(&root);
let mut entries = BTreeMap::new();
entries.insert(b".".to_vec(), (FUSE_ROOT_ID, FileKind::Directory));
self.write_directory_content(FUSE_ROOT_ID, entries);
}
Ok(())
}
fn lookup(&mut self, req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry) {
if name.len() > MAX_NAME_LENGTH as usize {
reply.error(libc::ENAMETOOLONG);
return;
}
let parent_attrs = self.get_inode(parent).unwrap();
if !check_access(
parent_attrs.uid,
parent_attrs.gid,
parent_attrs.mode,
req.uid(),
req.gid(),
libc::X_OK,
) {
reply.error(libc::EACCES);
return;
}
match self.lookup_name(parent, name) {
Ok(attrs) => reply.entry(&Duration::new(0, 0), &attrs.into(), 0),
Err(error_code) => reply.error(error_code),
}
}
fn forget(&mut self, _req: &Request, _ino: u64, _nlookup: u64) {}
fn getattr(&mut self, _req: &Request, inode: u64, reply: ReplyAttr) {
match self.get_inode(inode) {
Ok(attrs) => reply.attr(&Duration::new(0, 0), &attrs.into()),
Err(error_code) => reply.error(error_code),
}
}
fn setattr(
&mut self,
req: &Request,
inode: u64,
mode: Option<u32>,
uid: Option<u32>,
gid: Option<u32>,
size: Option<u64>,
atime: Option<TimeOrNow>,
mtime: Option<TimeOrNow>,
_ctime: Option<SystemTime>,
fh: Option<u64>,
_crtime: Option<SystemTime>,
_chgtime: Option<SystemTime>,
_bkuptime: Option<SystemTime>,
_flags: Option<u32>,
reply: ReplyAttr,
) {
let mut attrs = match self.get_inode(inode) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
if let Some(mode) = mode {
debug!("chmod() called with {:?}, {:o}", inode, mode);
if req.uid() != 0 && req.uid() != attrs.uid {
reply.error(libc::EPERM);
return;
}
if req.uid() != 0
&& req.gid() != attrs.gid
&& !get_groups(req.pid()).contains(&attrs.gid)
{
// If SGID is set and the file belongs to a group that the caller is not part of
// then the SGID bit is suppose to be cleared during chmod
attrs.mode = (mode & !libc::S_ISGID as u32) as u16;
} else {
attrs.mode = mode as u16;
}
attrs.last_metadata_changed = time_now();
self.write_inode(&attrs);
reply.attr(&Duration::new(0, 0), &attrs.into());
return;
}
if uid.is_some() || gid.is_some() {
debug!("chown() called with {:?} {:?} {:?}", inode, uid, gid);
if let Some(gid) = gid {
// Non-root users can only change gid to a group they're in
if req.uid() != 0 && !get_groups(req.pid()).contains(&gid) {
reply.error(libc::EPERM);
return;
}
}
if let Some(uid) = uid {
if req.uid() != 0
// but no-op changes by the owner are not an error
&& !(uid == attrs.uid && req.uid() == attrs.uid)
{
reply.error(libc::EPERM);
return;
}
}
// Only owner may change the group
if gid.is_some() && req.uid() != 0 && req.uid() != attrs.uid {
reply.error(libc::EPERM);
return;
}
if attrs.mode & (libc::S_IXUSR | libc::S_IXGRP | libc::S_IXOTH) as u16 != 0 {
// SUID & SGID are suppose to be cleared when chown'ing an executable file
clear_suid_sgid(&mut attrs);
}
if let Some(uid) = uid {
attrs.uid = uid;
// Clear SETUID on owner change
attrs.mode &= !libc::S_ISUID as u16;
}
if let Some(gid) = gid {
attrs.gid = gid;
// Clear SETGID unless user is root
if req.uid() != 0 {
attrs.mode &= !libc::S_ISGID as u16;
}
}
attrs.last_metadata_changed = time_now();
self.write_inode(&attrs);
reply.attr(&Duration::new(0, 0), &attrs.into());
return;
}
if let Some(size) = size {
debug!("truncate() called with {:?} {:?}", inode, size);
if let Some(handle) = fh {
// If the file handle is available, check access locally.
// This is important as it preserves the semantic that a file handle opened
// with W_OK will never fail to truncate, even if the file has been subsequently
// chmod'ed
if self.check_file_handle_write(handle) {
if let Err(error_code) = self.truncate(inode, size, 0, 0) {
reply.error(error_code);
return;
}
} else {
reply.error(libc::EACCES);
return;
}
} else if let Err(error_code) = self.truncate(inode, size, req.uid(), req.gid()) {
reply.error(error_code);
return;
}
}
let now = time_now();
if let Some(atime) = atime {
debug!("utimens() called with {:?}, atime={:?}", inode, atime);
if attrs.uid != req.uid() && req.uid() != 0 && atime != Now {
reply.error(libc::EPERM);
return;
}
if attrs.uid != req.uid()
&& !check_access(
attrs.uid,
attrs.gid,
attrs.mode,
req.uid(),
req.gid(),
libc::W_OK,
)
{
reply.error(libc::EACCES);
return;
}
attrs.last_accessed = match atime {
TimeOrNow::SpecificTime(time) => time_from_system_time(&time),
Now => now,
};
attrs.last_metadata_changed = now;
self.write_inode(&attrs);
}
if let Some(mtime) = mtime {
debug!("utimens() called with {:?}, mtime={:?}", inode, mtime);
if attrs.uid != req.uid() && req.uid() != 0 && mtime != Now {
reply.error(libc::EPERM);
return;
}
if attrs.uid != req.uid()
&& !check_access(
attrs.uid,
attrs.gid,
attrs.mode,
req.uid(),
req.gid(),
libc::W_OK,
)
{
reply.error(libc::EACCES);
return;
}
attrs.last_modified = match mtime {
TimeOrNow::SpecificTime(time) => time_from_system_time(&time),
Now => now,
};
attrs.last_metadata_changed = now;
self.write_inode(&attrs);
}
let attrs = self.get_inode(inode).unwrap();
reply.attr(&Duration::new(0, 0), &attrs.into());
return;
}
fn readlink(&mut self, _req: &Request, inode: u64, reply: ReplyData) {
debug!("readlink() called on {:?}", inode);
let path = self.content_path(inode);
if let Ok(mut file) = File::open(&path) {
let file_size = file.metadata().unwrap().len();
let mut buffer = vec![0; file_size as usize];
file.read_exact(&mut buffer).unwrap();
reply.data(&buffer);
} else {
reply.error(libc::ENOENT);
}
}
fn mknod(
&mut self,
req: &Request,
parent: u64,
name: &OsStr,
mut mode: u32,
_umask: u32,
_rdev: u32,
reply: ReplyEntry,
) {
let file_type = mode & libc::S_IFMT as u32;
if file_type != libc::S_IFREG as u32
&& file_type != libc::S_IFLNK as u32
&& file_type != libc::S_IFDIR as u32
{
// TODO
warn!("mknod() implementation is incomplete. Only supports regular files, symlinks, and directories. Got {:o}", mode);
reply.error(libc::ENOSYS);
return;
}
if self.lookup_name(parent, name).is_ok() {
reply.error(libc::EEXIST);
return;
}
let mut parent_attrs = match self.get_inode(parent) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
if !check_access(
parent_attrs.uid,
parent_attrs.gid,
parent_attrs.mode,
req.uid(),
req.gid(),
libc::W_OK,
) {
reply.error(libc::EACCES);
return;
}
parent_attrs.last_modified = time_now();
parent_attrs.last_metadata_changed = time_now();
self.write_inode(&parent_attrs);
if req.uid() != 0 {
mode &= !(libc::S_ISUID | libc::S_ISGID) as u32;
}
let inode = self.allocate_next_inode();
let attrs = InodeAttributes {
inode,
open_file_handles: 0,
size: 0,
last_accessed: time_now(),
last_modified: time_now(),
last_metadata_changed: time_now(),
kind: as_file_kind(mode),
mode: self.creation_mode(mode),
hardlinks: 1,
uid: req.uid(),
gid: creation_gid(&parent_attrs, req.gid()),
xattrs: Default::default(),
};
self.write_inode(&attrs);
File::create(self.content_path(inode)).unwrap();
if as_file_kind(mode) == FileKind::Directory {
let mut entries = BTreeMap::new();
entries.insert(b".".to_vec(), (inode, FileKind::Directory));
entries.insert(b"..".to_vec(), (parent, FileKind::Directory));
self.write_directory_content(inode, entries);
}
let mut entries = self.get_directory_content(parent).unwrap();
entries.insert(name.as_bytes().to_vec(), (inode, attrs.kind));
self.write_directory_content(parent, entries);
// TODO: implement flags
reply.entry(&Duration::new(0, 0), &attrs.into(), 0);
}
fn mkdir(
&mut self,
req: &Request,
parent: u64,
name: &OsStr,
mut mode: u32,
_umask: u32,
reply: ReplyEntry,
) {
debug!("mkdir() called with {:?} {:?} {:o}", parent, name, mode);
if self.lookup_name(parent, name).is_ok() {
reply.error(libc::EEXIST);
return;
}
let mut parent_attrs = match self.get_inode(parent) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
if !check_access(
parent_attrs.uid,
parent_attrs.gid,
parent_attrs.mode,
req.uid(),
req.gid(),
libc::W_OK,
) {
reply.error(libc::EACCES);
return;
}
parent_attrs.last_modified = time_now();
parent_attrs.last_metadata_changed = time_now();
self.write_inode(&parent_attrs);
if req.uid() != 0 {
mode &= !(libc::S_ISUID | libc::S_ISGID) as u32;
}
if parent_attrs.mode & libc::S_ISGID as u16 != 0 {
mode |= libc::S_ISGID as u32;
}
let inode = self.allocate_next_inode();
let attrs = InodeAttributes {
inode,
open_file_handles: 0,
size: BLOCK_SIZE,
last_accessed: time_now(),
last_modified: time_now(),
last_metadata_changed: time_now(),
kind: FileKind::Directory,
mode: self.creation_mode(mode),
hardlinks: 2, // Directories start with link count of 2, since they have a self link
uid: req.uid(),
gid: creation_gid(&parent_attrs, req.gid()),
xattrs: Default::default(),
};
self.write_inode(&attrs);
let mut entries = BTreeMap::new();
entries.insert(b".".to_vec(), (inode, FileKind::Directory));
entries.insert(b"..".to_vec(), (parent, FileKind::Directory));
self.write_directory_content(inode, entries);
let mut entries = self.get_directory_content(parent).unwrap();
entries.insert(name.as_bytes().to_vec(), (inode, FileKind::Directory));
self.write_directory_content(parent, entries);
reply.entry(&Duration::new(0, 0), &attrs.into(), 0);
}
fn unlink(&mut self, req: &Request, parent: u64, name: &OsStr, reply: ReplyEmpty) {
debug!("unlink() called with {:?} {:?}", parent, name);
let mut attrs = match self.lookup_name(parent, name) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
let mut parent_attrs = match self.get_inode(parent) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
if !check_access(
parent_attrs.uid,
parent_attrs.gid,
parent_attrs.mode,
req.uid(),
req.gid(),
libc::W_OK,
) {
reply.error(libc::EACCES);
return;
}
let uid = req.uid();
// "Sticky bit" handling
if parent_attrs.mode & libc::S_ISVTX as u16 != 0
&& uid != 0
&& uid != parent_attrs.uid
&& uid != attrs.uid
{
reply.error(libc::EACCES);
return;
}
parent_attrs.last_metadata_changed = time_now();
parent_attrs.last_modified = time_now();
self.write_inode(&parent_attrs);
attrs.hardlinks -= 1;
attrs.last_metadata_changed = time_now();
self.write_inode(&attrs);
self.gc_inode(&attrs);
let mut entries = self.get_directory_content(parent).unwrap();
entries.remove(name.as_bytes());
self.write_directory_content(parent, entries);
reply.ok();
}
fn rmdir(&mut self, req: &Request, parent: u64, name: &OsStr, reply: ReplyEmpty) {
debug!("rmdir() called with {:?} {:?}", parent, name);
let mut attrs = match self.lookup_name(parent, name) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
let mut parent_attrs = match self.get_inode(parent) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
// Directories always have a self and parent link
if self.get_directory_content(attrs.inode).unwrap().len() > 2 {
reply.error(libc::ENOTEMPTY);
return;
}
if !check_access(
parent_attrs.uid,
parent_attrs.gid,
parent_attrs.mode,
req.uid(),
req.gid(),
libc::W_OK,
) {
reply.error(libc::EACCES);
return;
}
// "Sticky bit" handling
if parent_attrs.mode & libc::S_ISVTX as u16 != 0
&& req.uid() != 0
&& req.uid() != parent_attrs.uid
&& req.uid() != attrs.uid
{
reply.error(libc::EACCES);
return;
}
parent_attrs.last_metadata_changed = time_now();
parent_attrs.last_modified = time_now();
self.write_inode(&parent_attrs);
attrs.hardlinks = 0;
attrs.last_metadata_changed = time_now();
self.write_inode(&attrs);
self.gc_inode(&attrs);
let mut entries = self.get_directory_content(parent).unwrap();
entries.remove(name.as_bytes());
self.write_directory_content(parent, entries);
reply.ok();
}
fn symlink(
&mut self,
req: &Request,
parent: u64,
name: &OsStr,
link: &Path,
reply: ReplyEntry,
) {
debug!("symlink() called with {:?} {:?} {:?}", parent, name, link);
let mut parent_attrs = match self.get_inode(parent) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
if !check_access(
parent_attrs.uid,
parent_attrs.gid,
parent_attrs.mode,
req.uid(),
req.gid(),
libc::W_OK,
) {
reply.error(libc::EACCES);
return;
}
parent_attrs.last_modified = time_now();
parent_attrs.last_metadata_changed = time_now();
self.write_inode(&parent_attrs);
let inode = self.allocate_next_inode();
let attrs = InodeAttributes {
inode,
open_file_handles: 0,
size: link.as_os_str().as_bytes().len() as u64,
last_accessed: time_now(),
last_modified: time_now(),
last_metadata_changed: time_now(),
kind: FileKind::Symlink,
mode: 0o777,
hardlinks: 1,
uid: req.uid(),
gid: creation_gid(&parent_attrs, req.gid()),
xattrs: Default::default(),
};
if let Err(error_code) = self.insert_link(req, parent, name, inode, FileKind::Symlink) {
reply.error(error_code);
return;
}
self.write_inode(&attrs);
let path = self.content_path(inode);
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&path)
.unwrap();
file.write_all(link.as_os_str().as_bytes()).unwrap();
reply.entry(&Duration::new(0, 0), &attrs.into(), 0);
}
fn rename(
&mut self,
req: &Request,
parent: u64,
name: &OsStr,
new_parent: u64,
new_name: &OsStr,
flags: u32,
reply: ReplyEmpty,
) {
let mut inode_attrs = match self.lookup_name(parent, name) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
let mut parent_attrs = match self.get_inode(parent) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
if !check_access(
parent_attrs.uid,
parent_attrs.gid,
parent_attrs.mode,
req.uid(),
req.gid(),
libc::W_OK,
) {
reply.error(libc::EACCES);
return;
}
// "Sticky bit" handling
if parent_attrs.mode & libc::S_ISVTX as u16 != 0
&& req.uid() != 0
&& req.uid() != parent_attrs.uid
&& req.uid() != inode_attrs.uid
{
reply.error(libc::EACCES);
return;
}
let mut new_parent_attrs = match self.get_inode(new_parent) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
if !check_access(
new_parent_attrs.uid,
new_parent_attrs.gid,
new_parent_attrs.mode,
req.uid(),
req.gid(),
libc::W_OK,
) {
reply.error(libc::EACCES);
return;
}
// "Sticky bit" handling in new_parent
if new_parent_attrs.mode & libc::S_ISVTX as u16 != 0 {
if let Ok(existing_attrs) = self.lookup_name(new_parent, new_name) {
if req.uid() != 0
&& req.uid() != new_parent_attrs.uid
&& req.uid() != existing_attrs.uid
{
reply.error(libc::EACCES);
return;
}
}
}
#[cfg(target_os = "linux")]
if flags & libc::RENAME_EXCHANGE as u32 != 0 {
let mut new_inode_attrs = match self.lookup_name(new_parent, new_name) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
let mut entries = self.get_directory_content(new_parent).unwrap();
entries.insert(
new_name.as_bytes().to_vec(),
(inode_attrs.inode, inode_attrs.kind),
);
self.write_directory_content(new_parent, entries);
let mut entries = self.get_directory_content(parent).unwrap();
entries.insert(
name.as_bytes().to_vec(),
(new_inode_attrs.inode, new_inode_attrs.kind),
);
self.write_directory_content(parent, entries);
parent_attrs.last_metadata_changed = time_now();
parent_attrs.last_modified = time_now();
self.write_inode(&parent_attrs);
new_parent_attrs.last_metadata_changed = time_now();
new_parent_attrs.last_modified = time_now();
self.write_inode(&new_parent_attrs);
inode_attrs.last_metadata_changed = time_now();
self.write_inode(&inode_attrs);
new_inode_attrs.last_metadata_changed = time_now();
self.write_inode(&new_inode_attrs);
if inode_attrs.kind == FileKind::Directory {
let mut entries = self.get_directory_content(inode_attrs.inode).unwrap();
entries.insert(b"..".to_vec(), (new_parent, FileKind::Directory));
self.write_directory_content(inode_attrs.inode, entries);
}
if new_inode_attrs.kind == FileKind::Directory {
let mut entries = self.get_directory_content(new_inode_attrs.inode).unwrap();
entries.insert(b"..".to_vec(), (parent, FileKind::Directory));
self.write_directory_content(new_inode_attrs.inode, entries);
}
reply.ok();
return;
}
// Only overwrite an existing directory if it's empty
if let Ok(new_name_attrs) = self.lookup_name(new_parent, new_name) {
if new_name_attrs.kind == FileKind::Directory
&& self
.get_directory_content(new_name_attrs.inode)
.unwrap()
.len()
> 2
{
reply.error(libc::ENOTEMPTY);
return;
}
}
// Only move an existing directory to a new parent, if we have write access to it,
// because that will change the ".." link in it
if inode_attrs.kind == FileKind::Directory
&& parent != new_parent
&& !check_access(
inode_attrs.uid,
inode_attrs.gid,
inode_attrs.mode,
req.uid(),
req.gid(),
libc::W_OK,
)
{
reply.error(libc::EACCES);
return;
}
// If target already exists decrement its hardlink count
if let Ok(mut existing_inode_attrs) = self.lookup_name(new_parent, new_name) {
let mut entries = self.get_directory_content(new_parent).unwrap();
entries.remove(new_name.as_bytes());
self.write_directory_content(new_parent, entries);
if existing_inode_attrs.kind == FileKind::Directory {
existing_inode_attrs.hardlinks = 0;
} else {
existing_inode_attrs.hardlinks -= 1;
}
existing_inode_attrs.last_metadata_changed = time_now();
self.write_inode(&existing_inode_attrs);
self.gc_inode(&existing_inode_attrs);
}
let mut entries = self.get_directory_content(parent).unwrap();
entries.remove(name.as_bytes());
self.write_directory_content(parent, entries);
let mut entries = self.get_directory_content(new_parent).unwrap();
entries.insert(
new_name.as_bytes().to_vec(),
(inode_attrs.inode, inode_attrs.kind),
);
self.write_directory_content(new_parent, entries);
parent_attrs.last_metadata_changed = time_now();
parent_attrs.last_modified = time_now();
self.write_inode(&parent_attrs);
new_parent_attrs.last_metadata_changed = time_now();
new_parent_attrs.last_modified = time_now();
self.write_inode(&new_parent_attrs);
inode_attrs.last_metadata_changed = time_now();
self.write_inode(&inode_attrs);
if inode_attrs.kind == FileKind::Directory {
let mut entries = self.get_directory_content(inode_attrs.inode).unwrap();
entries.insert(b"..".to_vec(), (new_parent, FileKind::Directory));
self.write_directory_content(inode_attrs.inode, entries);
}
reply.ok();
}
fn link(
&mut self,
req: &Request,
inode: u64,
new_parent: u64,
new_name: &OsStr,
reply: ReplyEntry,
) {
debug!(
"link() called for {}, {}, {:?}",
inode, new_parent, new_name
);
let mut attrs = match self.get_inode(inode) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
if let Err(error_code) = self.insert_link(&req, new_parent, new_name, inode, attrs.kind) {
reply.error(error_code);
} else {
attrs.hardlinks += 1;
attrs.last_metadata_changed = time_now();
self.write_inode(&attrs);
reply.entry(&Duration::new(0, 0), &attrs.into(), 0);
}
}
fn open(&mut self, req: &Request, inode: u64, flags: i32, reply: ReplyOpen) {
debug!("open() called for {:?}", inode);
let (access_mask, read, write) = match flags & libc::O_ACCMODE {
libc::O_RDONLY => {
// Behavior is undefined, but most filesystems return EACCES
if flags & libc::O_TRUNC != 0 {
reply.error(libc::EACCES);
return;
}
if flags & FMODE_EXEC != 0 {
// Open is from internal exec syscall
(libc::X_OK, true, false)
} else {
(libc::R_OK, true, false)
}
}
libc::O_WRONLY => (libc::W_OK, false, true),
libc::O_RDWR => (libc::R_OK | libc::W_OK, true, true),
// Exactly one access mode flag must be specified
_ => {
reply.error(libc::EINVAL);
return;
}
};
match self.get_inode(inode) {
Ok(mut attr) => {
if check_access(
attr.uid,
attr.gid,
attr.mode,
req.uid(),
req.gid(),
access_mask,
) {
attr.open_file_handles += 1;
self.write_inode(&attr);
let open_flags = if self.direct_io { FOPEN_DIRECT_IO } else { 0 };
reply.opened(self.allocate_next_file_handle(read, write), open_flags);
return;
} else {
reply.error(libc::EACCES);
return;
}
}
Err(error_code) => reply.error(error_code),
}
}
fn read(
&mut self,
_req: &Request,
inode: u64,
fh: u64,
offset: i64,
size: u32,
_flags: i32,
_lock_owner: Option<u64>,
reply: ReplyData,
) {
debug!(
"read() called on {:?} offset={:?} size={:?}",
inode, offset, size
);
assert!(offset >= 0);
if !self.check_file_handle_read(fh) {
reply.error(libc::EACCES);
return;
}
let path = self.content_path(inode);
if let Ok(file) = File::open(&path) {
let file_size = file.metadata().unwrap().len();
// Could underflow if file length is less than local_start
let read_size = min(size, file_size.saturating_sub(offset as u64) as u32);
let mut buffer = vec![0; read_size as usize];
file.read_exact_at(&mut buffer, offset as u64).unwrap();
reply.data(&buffer);
} else {
reply.error(libc::ENOENT);
}
}
fn write(
&mut self,
_req: &Request,
inode: u64,
fh: u64,
offset: i64,
data: &[u8],
_write_flags: u32,
#[allow(unused_variables)] flags: i32,
_lock_owner: Option<u64>,
reply: ReplyWrite,
) {
debug!("write() called with {:?} size={:?}", inode, data.len());
assert!(offset >= 0);
if !self.check_file_handle_write(fh) {
reply.error(libc::EACCES);
return;
}
let path = self.content_path(inode);
if let Ok(mut file) = OpenOptions::new().write(true).open(&path) {
file.seek(SeekFrom::Start(offset as u64)).unwrap();
file.write_all(data).unwrap();
let mut attrs = self.get_inode(inode).unwrap();
attrs.last_metadata_changed = time_now();
attrs.last_modified = time_now();
if data.len() + offset as usize > attrs.size as usize {
attrs.size = (data.len() + offset as usize) as u64;
}
// #[cfg(feature = "abi-7-31")]
// if flags & FUSE_WRITE_KILL_PRIV as i32 != 0 {
// clear_suid_sgid(&mut attrs);
// }
// XXX: In theory we should only need to do this when WRITE_KILL_PRIV is set for 7.31+
// However, xfstests fail in that case
clear_suid_sgid(&mut attrs);
self.write_inode(&attrs);
reply.written(data.len() as u32);
} else {
reply.error(libc::EBADF);
}
}
fn release(
&mut self,
_req: &Request<'_>,
inode: u64,
_fh: u64,
_flags: i32,
_lock_owner: Option<u64>,
_flush: bool,
reply: ReplyEmpty,
) {
if let Ok(mut attrs) = self.get_inode(inode) {
attrs.open_file_handles -= 1;
}
reply.ok();
}
fn opendir(&mut self, req: &Request, inode: u64, flags: i32, reply: ReplyOpen) {
debug!("opendir() called on {:?}", inode);
let (access_mask, read, write) = match flags & libc::O_ACCMODE {
libc::O_RDONLY => {
// Behavior is undefined, but most filesystems return EACCES
if flags & libc::O_TRUNC != 0 {
reply.error(libc::EACCES);
return;
}
(libc::R_OK, true, false)
}
libc::O_WRONLY => (libc::W_OK, false, true),
libc::O_RDWR => (libc::R_OK | libc::W_OK, true, true),
// Exactly one access mode flag must be specified
_ => {
reply.error(libc::EINVAL);
return;
}
};
match self.get_inode(inode) {
Ok(mut attr) => {
if check_access(
attr.uid,
attr.gid,
attr.mode,
req.uid(),
req.gid(),
access_mask,
) {
attr.open_file_handles += 1;
self.write_inode(&attr);
let open_flags = if self.direct_io { FOPEN_DIRECT_IO } else { 0 };
reply.opened(self.allocate_next_file_handle(read, write), open_flags);
return;
} else {
reply.error(libc::EACCES);
return;
}
}
Err(error_code) => reply.error(error_code),
}
}
fn readdir(
&mut self,
_req: &Request,
inode: u64,
_fh: u64,
offset: i64,
mut reply: ReplyDirectory,
) {
debug!("readdir() called with {:?}", inode);
assert!(offset >= 0);
let entries = match self.get_directory_content(inode) {
Ok(entries) => entries,
Err(error_code) => {
reply.error(error_code);
return;
}
};
for (index, entry) in entries.iter().skip(offset as usize).enumerate() {
let (name, (inode, file_type)) = entry;
let buffer_full: bool = reply.add(
*inode,
offset + index as i64 + 1,
(*file_type).into(),
OsStr::from_bytes(name),
);
if buffer_full {
break;
}
}
reply.ok();
}
fn releasedir(
&mut self,
_req: &Request<'_>,
inode: u64,
_fh: u64,
_flags: i32,
reply: ReplyEmpty,
) {
if let Ok(mut attrs) = self.get_inode(inode) {
attrs.open_file_handles -= 1;
}
reply.ok();
}
fn statfs(&mut self, _req: &Request, _ino: u64, reply: ReplyStatfs) {
warn!("statfs() implementation is a stub");
// TODO: real implementation of this
reply.statfs(
10_000,
10_000,
10_000,
1,
10_000,
BLOCK_SIZE as u32,
MAX_NAME_LENGTH,
BLOCK_SIZE as u32,
);
}
fn setxattr(
&mut self,
request: &Request<'_>,
inode: u64,
key: &OsStr,
value: &[u8],
_flags: i32,
_position: u32,
reply: ReplyEmpty,
) {
if let Ok(mut attrs) = self.get_inode(inode) {
if let Err(error) = xattr_access_check(key.as_bytes(), libc::W_OK, &attrs, request) {
reply.error(error);
return;
}
attrs.xattrs.insert(key.as_bytes().to_vec(), value.to_vec());
attrs.last_metadata_changed = time_now();
self.write_inode(&attrs);
reply.ok();
} else {
reply.error(libc::EBADF);
}
}
fn getxattr(
&mut self,
request: &Request<'_>,
inode: u64,
key: &OsStr,
size: u32,
reply: ReplyXattr,
) {
if let Ok(attrs) = self.get_inode(inode) {
if let Err(error) = xattr_access_check(key.as_bytes(), libc::R_OK, &attrs, request) {
reply.error(error);
return;
}
if let Some(data) = attrs.xattrs.get(key.as_bytes()) {
if size == 0 {
reply.size(data.len() as u32);
} else if data.len() <= size as usize {
reply.data(&data);
} else {
reply.error(libc::ERANGE);
}
} else {
#[cfg(target_os = "linux")]
reply.error(libc::ENODATA);
#[cfg(not(target_os = "linux"))]
reply.error(libc::ENOATTR);
}
} else {
reply.error(libc::EBADF);
}
}
fn listxattr(&mut self, _req: &Request<'_>, inode: u64, size: u32, reply: ReplyXattr) {
if let Ok(attrs) = self.get_inode(inode) {
let mut bytes = vec![];
// Convert to concatenated null-terminated strings
for key in attrs.xattrs.keys() {
bytes.extend(key);
bytes.push(0);
}
if size == 0 {
reply.size(bytes.len() as u32);
} else if bytes.len() <= size as usize {
reply.data(&bytes);
} else {
reply.error(libc::ERANGE);
}
} else {
reply.error(libc::EBADF);
}
}
fn removexattr(&mut self, request: &Request<'_>, inode: u64, key: &OsStr, reply: ReplyEmpty) {
if let Ok(mut attrs) = self.get_inode(inode) {
if let Err(error) = xattr_access_check(key.as_bytes(), libc::W_OK, &attrs, request) {
reply.error(error);
return;
}
if attrs.xattrs.remove(key.as_bytes()).is_none() {
#[cfg(target_os = "linux")]
reply.error(libc::ENODATA);
#[cfg(not(target_os = "linux"))]
reply.error(libc::ENOATTR);
return;
}
attrs.last_metadata_changed = time_now();
self.write_inode(&attrs);
reply.ok();
} else {
reply.error(libc::EBADF);
}
}
fn access(&mut self, req: &Request, inode: u64, mask: i32, reply: ReplyEmpty) {
debug!("access() called with {:?} {:?}", inode, mask);
match self.get_inode(inode) {
Ok(attr) => {
if check_access(attr.uid, attr.gid, attr.mode, req.uid(), req.gid(), mask) {
reply.ok();
} else {
reply.error(libc::EACCES);
}
}
Err(error_code) => reply.error(error_code),
}
}
fn create(
&mut self,
req: &Request,
parent: u64,
name: &OsStr,
mut mode: u32,
_umask: u32,
flags: i32,
reply: ReplyCreate,
) {
debug!("create() called with {:?} {:?}", parent, name);
if self.lookup_name(parent, name).is_ok() {
reply.error(libc::EEXIST);
return;
}
let (read, write) = match flags & libc::O_ACCMODE {
libc::O_RDONLY => (true, false),
libc::O_WRONLY => (false, true),
libc::O_RDWR => (true, true),
// Exactly one access mode flag must be specified
_ => {
reply.error(libc::EINVAL);
return;
}
};
let mut parent_attrs = match self.get_inode(parent) {
Ok(attrs) => attrs,
Err(error_code) => {
reply.error(error_code);
return;
}
};
if !check_access(
parent_attrs.uid,
parent_attrs.gid,
parent_attrs.mode,
req.uid(),
req.gid(),
libc::W_OK,
) {
reply.error(libc::EACCES);
return;
}
parent_attrs.last_modified = time_now();
parent_attrs.last_metadata_changed = time_now();
self.write_inode(&parent_attrs);
if req.uid() != 0 {
mode &= !(libc::S_ISUID | libc::S_ISGID) as u32;
}
let inode = self.allocate_next_inode();
let attrs = InodeAttributes {
inode,
open_file_handles: 1,
size: 0,
last_accessed: time_now(),
last_modified: time_now(),
last_metadata_changed: time_now(),
kind: as_file_kind(mode),
mode: self.creation_mode(mode),
hardlinks: 1,
uid: req.uid(),
gid: creation_gid(&parent_attrs, req.gid()),
xattrs: Default::default(),
};
self.write_inode(&attrs);
File::create(self.content_path(inode)).unwrap();
if as_file_kind(mode) == FileKind::Directory {
let mut entries = BTreeMap::new();
entries.insert(b".".to_vec(), (inode, FileKind::Directory));
entries.insert(b"..".to_vec(), (parent, FileKind::Directory));
self.write_directory_content(inode, entries);
}
let mut entries = self.get_directory_content(parent).unwrap();
entries.insert(name.as_bytes().to_vec(), (inode, attrs.kind));
self.write_directory_content(parent, entries);
// TODO: implement flags
reply.created(
&Duration::new(0, 0),
&attrs.into(),
0,
self.allocate_next_file_handle(read, write),
0,
);
}
#[cfg(target_os = "linux")]
fn fallocate(
&mut self,
_req: &Request<'_>,
inode: u64,
_fh: u64,
offset: i64,
length: i64,
mode: i32,
reply: ReplyEmpty,
) {
let path = self.content_path(inode);
if let Ok(file) = OpenOptions::new().write(true).open(&path) {
unsafe {
libc::fallocate64(file.into_raw_fd(), mode, offset, length);
}
if mode & libc::FALLOC_FL_KEEP_SIZE == 0 {
let mut attrs = self.get_inode(inode).unwrap();
attrs.last_metadata_changed = time_now();
attrs.last_modified = time_now();
if (offset + length) as u64 > attrs.size {
attrs.size = (offset + length) as u64;
}
self.write_inode(&attrs);
}
reply.ok();
} else {
reply.error(libc::ENOENT);
}
}
fn copy_file_range(
&mut self,
_req: &Request<'_>,
src_inode: u64,
src_fh: u64,
src_offset: i64,
dest_inode: u64,
dest_fh: u64,
dest_offset: i64,
size: u64,
_flags: u32,
reply: ReplyWrite,
) {
debug!(
"copy_file_range() called with src ({}, {}, {}) dest ({}, {}, {}) size={}",
src_fh, src_inode, src_offset, dest_fh, dest_inode, dest_offset, size
);
if !self.check_file_handle_read(src_fh) {
reply.error(libc::EACCES);
return;
}
if !self.check_file_handle_write(dest_fh) {
reply.error(libc::EACCES);
return;
}
let src_path = self.content_path(src_inode);
if let Ok(file) = File::open(&src_path) {
let file_size = file.metadata().unwrap().len();
// Could underflow if file length is less than local_start
let read_size = min(size, file_size.saturating_sub(src_offset as u64));
let mut data = vec![0; read_size as usize];
file.read_exact_at(&mut data, src_offset as u64).unwrap();
let dest_path = self.content_path(dest_inode);
if let Ok(mut file) = OpenOptions::new().write(true).open(&dest_path) {
file.seek(SeekFrom::Start(dest_offset as u64)).unwrap();
file.write_all(&data).unwrap();
let mut attrs = self.get_inode(dest_inode).unwrap();
attrs.last_metadata_changed = time_now();
attrs.last_modified = time_now();
if data.len() + dest_offset as usize > attrs.size as usize {
attrs.size = (data.len() + dest_offset as usize) as u64;
}
self.write_inode(&attrs);
reply.written(data.len() as u32);
} else {
reply.error(libc::EBADF);
}
} else {
reply.error(libc::ENOENT);
}
}
}
pub fn check_access(
file_uid: u32,
file_gid: u32,
file_mode: u16,
uid: u32,
gid: u32,
mut access_mask: i32,
) -> bool {
// F_OK tests for existence of file
if access_mask == libc::F_OK {
return true;
}
let file_mode = i32::from(file_mode);
// root is allowed to read & write anything
if uid == 0 {
// root only allowed to exec if one of the X bits is set
access_mask &= libc::X_OK;
access_mask -= access_mask & (file_mode >> 6);
access_mask -= access_mask & (file_mode >> 3);
access_mask -= access_mask & file_mode;
return access_mask == 0;
}
if uid == file_uid {
access_mask -= access_mask & (file_mode >> 6);
} else if gid == file_gid {
access_mask -= access_mask & (file_mode >> 3);
} else {
access_mask -= access_mask & file_mode;
}
return access_mask == 0;
}
fn as_file_kind(mut mode: u32) -> FileKind {
mode &= libc::S_IFMT as u32;
if mode == libc::S_IFREG as u32 {
return FileKind::File;
} else if mode == libc::S_IFLNK as u32 {
return FileKind::Symlink;
} else if mode == libc::S_IFDIR as u32 {
return FileKind::Directory;
} else {
unimplemented!("{}", mode);
}
}
fn get_groups(pid: u32) -> Vec<u32> {
let path = format!("/proc/{}/task/{}/status", pid, pid);
let file = File::open(path).unwrap();
for line in BufReader::new(file).lines() {
let line = line.unwrap();
if line.starts_with("Groups:") {
return line["Groups: ".len()..]
.split(' ')
.filter(|x| !x.trim().is_empty())
.map(|x| x.parse::<u32>().unwrap())
.collect();
}
}
vec![]
}
fn fuse_allow_other_enabled() -> io::Result<bool> {
let file = File::open("/etc/fuse.conf")?;
for line in BufReader::new(file).lines() {
if line?.trim_start().starts_with("user_allow_other") {
return Ok(true);
}
}
Ok(false)
}
fn main() {
let matches = App::new("Fuser")
.version(crate_version!())
.author("Christopher Berner")
.arg(
Arg::with_name("data-dir")
.long("data-dir")
.value_name("DIR")
.default_value("/tmp/fuser")
.help("Set local directory used to store data")
.takes_value(true),
)
.arg(
Arg::with_name("mount-point")
.long("mount-point")
.value_name("MOUNT_POINT")
.default_value("")
.help("Act as a client, and mount FUSE at given path")
.takes_value(true),
)
.arg(
Arg::with_name("direct-io")
.long("direct-io")
.requires("mount-point")
.help("Mount FUSE with direct IO"),
)
.arg(
Arg::with_name("fsck")
.long("fsck")
.help("Run a filesystem check"),
)
.arg(
Arg::with_name("suid")
.long("suid")
.help("Enable setuid support when run as root"),
)
.arg(
Arg::with_name("v")
.short("v")
.multiple(true)
.help("Sets the level of verbosity"),
)
.get_matches();
let verbosity: u64 = matches.occurrences_of("v");
let log_level = match verbosity {
0 => LevelFilter::Error,
1 => LevelFilter::Warn,
2 => LevelFilter::Info,
3 => LevelFilter::Debug,
_ => LevelFilter::Trace,
};
env_logger::builder()
.format_timestamp_nanos()
.filter_level(log_level)
.init();
let mut options = vec![MountOption::FSName("fuser".to_string())];
#[cfg(feature = "abi-7-26")]
{
if matches.is_present("suid") {
info!("setuid bit support enabled");
options.push(MountOption::Suid);
} else {
options.push(MountOption::AutoUnmount);
}
}
#[cfg(not(feature = "abi-7-26"))]
{
options.push(MountOption::AutoUnmount);
}
if let Ok(enabled) = fuse_allow_other_enabled() {
if enabled {
options.push(MountOption::AllowOther);
}
} else {
eprintln!("Unable to read /etc/fuse.conf");
}
let data_dir: String = matches.value_of("data-dir").unwrap_or_default().to_string();
let mountpoint: String = matches
.value_of("mount-point")
.unwrap_or_default()
.to_string();
rofuse::mount2(
SimpleFS::new(
data_dir,
matches.is_present("direct-io"),
matches.is_present("suid"),
),
mountpoint,
&options,
)
.unwrap();
}
|
fn main() {
// Listing 8-1: Creating a new, empty vector to hold values of type i32
let v: Vec<i32> = Vec::new() ;
// Lissting 8-2: Creating a new vector containing values
let v = vec![1, 2, 3] ;
// Listing 8-3: Using the push method to add values to a vector
let mut v = Vec::new() ;
v.push(5) ;
v.push(6) ;
v.push(7) ;
v.push(8) ;
// Listing 8-4: Showing where the vector and its elements are dropped
{
let v = vec![1, 2, 3, 4] ;
// do stuff with v
} // v goes out of scope and its elements are dropped
// Listind 8-5: Using indexing syntax or the get method to access an item in a vector
let v = vec![1, 2, 3, 4, 5] ;
let third: &i32 = &v[2] ;
println!("The third element is {}", third) ;
match v.get(2) {
Some(third) => println!("The third element is {}", third),
None => println!("There is no third element."),
}
/*
// Listing 8-6: Attempting to access the element at index 100 in a vector containing five elements
let v = vec![1, 2, 3, 4, 5] ;
let does_not_exist = &v[100] ;
let does_not_exist = v.get(100) ;
*/
/*
// Listing 8-7: Attempting to add an element to a vector while holding a reference to an item
let mut v = vec![1, 2, 3, 4, 5] ;
let first = &v[0] ;
v.push(6) ;
println!("The first element is: {}", first) ;
*/
// Listing 8-8: Printing each element in a vector by iterating over the elements using a for loop
let v = vec![100, 32, 57] ;
for i in &v {
println!("{}", i) ;
}
// Listing 8-9: Iterating over mutable refrences to elements in a vector
let mut v = vec![100, 32, 57] ;
for i in &mut v {
*i += 50 ;
}
// Listing 8-10: Defining an enum to store values of different types in one vector
enum SpreadsheetCell {
Int(i32),
Float(64),
Txt(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("blue")),
SpreadsheetCell::Float(10.12),
] ;
}
|
#[doc = "Register `EXTI_FTSR3` reader"]
pub type R = crate::R<EXTI_FTSR3_SPEC>;
#[doc = "Register `EXTI_FTSR3` writer"]
pub type W = crate::W<EXTI_FTSR3_SPEC>;
#[doc = "Field `FT65` reader - FT65"]
pub type FT65_R = crate::BitReader;
#[doc = "Field `FT65` writer - FT65"]
pub type FT65_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FT66` reader - FT66"]
pub type FT66_R = crate::BitReader;
#[doc = "Field `FT66` writer - FT66"]
pub type FT66_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FT68` reader - FT68"]
pub type FT68_R = crate::BitReader;
#[doc = "Field `FT68` writer - FT68"]
pub type FT68_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FT73` reader - FT73"]
pub type FT73_R = crate::BitReader;
#[doc = "Field `FT73` writer - FT73"]
pub type FT73_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FT74` reader - FT74"]
pub type FT74_R = crate::BitReader;
#[doc = "Field `FT74` writer - FT74"]
pub type FT74_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 1 - FT65"]
#[inline(always)]
pub fn ft65(&self) -> FT65_R {
FT65_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - FT66"]
#[inline(always)]
pub fn ft66(&self) -> FT66_R {
FT66_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 4 - FT68"]
#[inline(always)]
pub fn ft68(&self) -> FT68_R {
FT68_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 9 - FT73"]
#[inline(always)]
pub fn ft73(&self) -> FT73_R {
FT73_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - FT74"]
#[inline(always)]
pub fn ft74(&self) -> FT74_R {
FT74_R::new(((self.bits >> 10) & 1) != 0)
}
}
impl W {
#[doc = "Bit 1 - FT65"]
#[inline(always)]
#[must_use]
pub fn ft65(&mut self) -> FT65_W<EXTI_FTSR3_SPEC, 1> {
FT65_W::new(self)
}
#[doc = "Bit 2 - FT66"]
#[inline(always)]
#[must_use]
pub fn ft66(&mut self) -> FT66_W<EXTI_FTSR3_SPEC, 2> {
FT66_W::new(self)
}
#[doc = "Bit 4 - FT68"]
#[inline(always)]
#[must_use]
pub fn ft68(&mut self) -> FT68_W<EXTI_FTSR3_SPEC, 4> {
FT68_W::new(self)
}
#[doc = "Bit 9 - FT73"]
#[inline(always)]
#[must_use]
pub fn ft73(&mut self) -> FT73_W<EXTI_FTSR3_SPEC, 9> {
FT73_W::new(self)
}
#[doc = "Bit 10 - FT74"]
#[inline(always)]
#[must_use]
pub fn ft74(&mut self) -> FT74_W<EXTI_FTSR3_SPEC, 10> {
FT74_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Contains only register bits for configurable events.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`exti_ftsr3::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`exti_ftsr3::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct EXTI_FTSR3_SPEC;
impl crate::RegisterSpec for EXTI_FTSR3_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`exti_ftsr3::R`](R) reader structure"]
impl crate::Readable for EXTI_FTSR3_SPEC {}
#[doc = "`write(|w| ..)` method takes [`exti_ftsr3::W`](W) writer structure"]
impl crate::Writable for EXTI_FTSR3_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets EXTI_FTSR3 to value 0"]
impl crate::Resettable for EXTI_FTSR3_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
/// Interface to run a child process for the shim.
///
/// Most of this module, especially the part setting up the shild process, is
/// based on how Pip creates an EXE launcher for console scripts, from
/// [distlib], developed in C by Vinay Sajip.
///
/// [distlib]: https://github.com/vsajip/distlib/blob/master/PC/launcher.c
extern crate winapi;
use std::{env, mem};
use std::os::windows::io::AsRawHandle;
use std::path::PathBuf;
use std::process::{Child, Command};
use self::winapi::ctypes::c_void;
use self::winapi::shared::minwindef::{BOOL, DWORD, LPVOID, TRUE};
use self::winapi::um::consoleapi::SetConsoleCtrlHandler;
use self::winapi::um::jobapi2::{
AssignProcessToJobObject, CreateJobObjectW, QueryInformationJobObject,
SetInformationJobObject};
use self::winapi::um::wincon::{CTRL_C_EVENT, GenerateConsoleCtrlEvent};
use self::winapi::um::winnt::{
JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK,
JobObjectExtendedLimitInformation};
static mut PID: u32 = 0;
unsafe extern "system" fn handle_ctrl(etype: DWORD) -> BOOL {
if etype == CTRL_C_EVENT && PID != 0 {
// FIXME: Why does this work? The two arguments of
// GenerateConsoleCtrlEvent are dwCtrlEvent and dwProcessGroupId, so
// we're passing them backwards... But this is what what Python's
// launchers do, and IT ACTUALLY WORKS. I'm letting it stand for now.
GenerateConsoleCtrlEvent(PID, CTRL_C_EVENT);
}
TRUE
}
unsafe fn setup_child(child: &mut Child) -> Result<(), &'static str> {
PID = child.id();
let job = CreateJobObjectW(0 as *mut _, 0 as *const _);
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = mem::zeroed();
let mut ok;
ok = QueryInformationJobObject(
job, JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID,
mem::size_of_val(&info) as DWORD,
0 as *mut _,
);
if ok != TRUE {
return Err("job information query error");
}
info.BasicLimitInformation.LimitFlags =
info.BasicLimitInformation.LimitFlags |
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
ok = SetInformationJobObject(
job, JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID,
mem::size_of_val(&info) as DWORD,
);
if ok != TRUE {
return Err("job information set error");
}
AssignProcessToJobObject(job, child.as_raw_handle() as *mut c_void);
Ok(())
}
/// Run the child process, and return its result.
///
/// The child's exit code is returned, or an error message if the child fails
/// to launch, or does not exit cleanly. If `with_own_args` is `true`, the
/// child process is launched with arguments passed to the parent process,
/// appende after `args`.
pub fn run(exe: &PathBuf, args: &Vec<String>, with_own_args: bool)
-> Result<i32, String> {
let mut cmd = Command::new(exe);
cmd.args(args);
// Hand over arguments passed to the shim (args[0] not included).
if with_own_args {
cmd.args(env::args().skip(1));
}
let mut child = cmd.spawn().map_err(|e| {
format!("failed to spawn child: {}", e)
})?;
unsafe { setup_child(&mut child)? };
let result = child.wait().map_err(|e| {
format!("failed to wait for child: {}", e)
})?;
// Doc seems to suggest this won't happen on Windows, but I'm not sure.
// 137 is a common value seen with SIGKILL terminated programs.
Ok(result.code().unwrap_or(137))
}
/// Set up the parent process.
///
/// This should be called before running the child, to set up the CTRL handler
/// so the parent passes on the CTRL-C event to its child.
pub fn setup() -> Result<(), &'static str> {
let ok = unsafe { SetConsoleCtrlHandler(Some(handle_ctrl), TRUE) };
if ok == TRUE {
Ok(())
} else {
Err("control handler set error")
}
}
|
pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
let mut results: Vec<(usize, usize)> = vec![];
for row in 0..input.len() {
for column in 0..input[row].len() {
let candidate = input[row][column];
if input[row].iter().all(|&x| candidate >= x) {
if input.iter().all(|x| candidate <= x[column]) {
results.push((row, column));
}
}
}
}
results
}
|
use super::*;
use std::str::from_utf8;
pub struct NameSection<'a> {
pub count: u32,
pub entries_raw: &'a [u8],
}
pub struct NameEntryIterator<'a> {
count: u32,
local_count: u32,
iter: &'a [u8]
}
pub enum NameEntry<'a> {
Function(&'a str),
Local(&'a str),
}
impl<'a> NameSection<'a> {
pub fn entries(&self) -> NameEntryIterator<'a> {
NameEntryIterator {
count: self.count,
local_count: 0,
iter: self.entries_raw
}
}
}
impl<'a> Iterator for NameEntryIterator<'a> {
type Item = Result<NameEntry<'a>, Error>;
fn next(&mut self) -> Option<Self::Item> {
if self.count == 0 && self.local_count == 0 {
return None
}
if self.local_count > 0 {
self.local_count -= 1;
let len = try_opt!(read_varuint(&mut self.iter)) as usize;
let name = &self.iter[..len];
self.iter = &self.iter[len..];
let name = try_opt!(from_utf8(name));
return Some(Ok(NameEntry::Local(name)))
}
self.count -= 1;
let len = try_opt!(read_varuint(&mut self.iter)) as usize;
let name = &self.iter[..len];
self.iter = &self.iter[len..];
let name = try_opt!(from_utf8(name));
let count = try_opt!(read_varuint(&mut self.iter)) as u32;
self.local_count = count;
Some(Ok(NameEntry::Function(name)))
}
}
|
use crate::{types::CalendarMonth, Ledger, Transaction};
use chrono::Datelike;
use decimal::d128;
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use uuid::Uuid;
type CategoryID = Uuid;
#[derive(Default)]
pub struct Budget {
/// a list of the transactions that make up the budget
transactions: Ledger,
master_categories: HashMap<CategoryID, MasterCategory>,
categories: Categories,
/// The allocations are the amounts budgeted for each category for a given month
allocations: BTreeMap<(CalendarMonth, CategoryID), Allocation>,
/// A map of transactions summaries. The key is a tuple of Calendar Month, and a category ID.
summaries: BTreeMap<(CalendarMonth, CategoryID), Summary>,
uncategorised_summaries: BTreeMap<CalendarMonth, Summary>,
}
impl Budget {
pub fn master_categories(&self) -> impl Iterator<Item = &MasterCategory> {
self.master_categories.values()
}
pub fn categories(&self) -> impl Iterator<Item = &Category> {
self.categories.values()
}
pub fn add(&mut self, t: Transaction) {
let date: CalendarMonth = t.date().into();
if let Some(name) = t.category() {
let id = self.categories.get_or_create_id(name);
self.summaries.entry((date, id)).or_default().add(&t);
} else {
self.uncategorised_summaries
.entry(date)
.or_default()
.add(&t);
}
self.transactions.add(t);
}
pub fn transfer<'a, S>(
&mut self,
amount: impl Into<d128>,
from_category: S,
to_category: S,
date: impl Datelike,
) -> Result<(), ()>
where
S: Into<Cow<'a, str>>,
{
let month: CalendarMonth = date.into();
let a = amount.into();
let from_id = self.categories.get_or_create_id(from_category);
let to_id = self.categories.get_or_create_id(to_category);
self.allocations
.entry((month.clone(), from_id))
.or_default()
.amount -= a;
self.allocations.entry((month, to_id)).or_default().amount += a;
Ok(())
}
pub fn rename_category<'a, S>(&mut self, old_name: S, new_name: S)
where
S: Into<Cow<'a, str>>,
{
let old = old_name.into();
let new = new_name.into();
if let Some(x) = self
.categories
.values_mut()
.find(|x| x.name == old.as_ref())
{
x.name = new.to_string();
}
(&mut self.transactions)
.into_iter()
.find(|t| t.category() == &Some(old.to_string()))
.map(|t| t.set_category(Some(new)));
}
}
#[derive(Default)]
struct Categories {
categories: HashMap<CategoryID, Category>,
}
impl std::ops::Deref for Categories {
type Target = HashMap<CategoryID, Category>;
fn deref(&self) -> &Self::Target {
&self.categories
}
}
impl std::ops::DerefMut for Categories {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.categories
}
}
impl Categories {
fn get_or_create_id<'a, S>(&mut self, name: S) -> CategoryID
where
S: Into<Cow<'a, str>>,
{
let n = name.into();
if let Some(id) = self.get_id(&n) {
*id
} else {
let id = CategoryID::new_v4();
self.insert(id, Category::new(n));
id
}
}
fn get_id<S: AsRef<str>>(&self, name: S) -> Option<&CategoryID> {
self.iter().find(|x| x.1.name == name.as_ref()).map(|x| x.0)
}
}
struct MasterCategory {
name: String,
sort: i32,
}
struct Category {
name: String,
sort: i32,
hidden: bool,
}
impl Category {
fn new<S: Into<String>>(name: S) -> Self {
Category {
name: name.into(),
sort: 0,
hidden: false,
}
}
}
#[derive(Default)]
struct Allocation {
amount: d128,
}
struct Summary {
n: u32,
sum: d128,
sum_squared: d128,
}
impl Default for Summary {
fn default() -> Summary {
Summary {
n: 0,
sum: d128::zero(),
sum_squared: d128::zero(),
}
}
}
impl Summary {
fn add(&mut self, t: &Transaction) {
self.n += 1;
self.sum += t.amount();
self.sum_squared += t.amount() * t.amount();
}
}
impl From<Ledger> for Budget {
fn from(ledger: Ledger) -> Budget {
let mut budget = Budget::default();
for transaction in ledger {
budget.add(transaction);
}
budget
}
}
impl From<Budget> for Ledger {
fn from(budget: Budget) -> Ledger {
budget.transactions
}
}
|
fn main() {
let mut matrix_to_reduce: Vec<Vec<f64>> = vec![vec![1.0, 2.0 , -1.0, -4.0],
vec![2.0, 3.0, -1.0, -11.0],
vec![-2.0, 0.0, -3.0, 22.0]];
let mut r_mat_to_red = &mut matrix_to_reduce;
let rr_mat_to_red = &mut r_mat_to_red;
println!("Matrix to reduce:\n{:?}", rr_mat_to_red);
let reduced_matrix = reduced_row_echelon_form(rr_mat_to_red);
println!("Reduced matrix:\n{:?}", reduced_matrix);
}
fn reduced_row_echelon_form(matrix: &mut Vec<Vec<f64>>) -> Vec<Vec<f64>> {
let mut matrix_out: Vec<Vec<f64>> = matrix.to_vec();
let mut pivot = 0;
let row_count = matrix_out.len();
let column_count = matrix_out[0].len();
for r in 0..row_count {
if column_count <= pivot {
break;
}
let mut i = r;
while matrix_out[i][pivot] == 0.0 {
i = i+1;
if i == row_count {
i = r;
pivot = pivot + 1;
if column_count == pivot {
pivot = pivot - 1;
break;
}
}
}
for j in 0..row_count {
let temp = matrix_out[r][j];
matrix_out[r][j] = matrix_out[i][j];
matrix_out[i][j] = temp;
}
let divisor = matrix_out[r][pivot];
if divisor != 0.0 {
for j in 0..column_count {
matrix_out[r][j] = matrix_out[r][j] / divisor;
}
}
for j in 0..row_count {
if j != r {
let hold = matrix_out[j][pivot];
for k in 0..column_count {
matrix_out[j][k] = matrix_out[j][k] - ( hold * matrix_out[r][k]);
}
}
}
pivot = pivot + 1;
}
matrix_out
} |
#![feature(globs)]
#![crate_type = "bin"]
extern crate bmp;
use std::os;
use std::rand::{Rng,Isaac64Rng,SeedableRng};
fn main() {
let args = os::args();
let orig_file_path = args[1].as_slice();
let b_img = bmp::BMPimage::open(orig_file_path);
let width = b_img.width as uint;
let height = b_img.height as uint;
let sz = width * height;
let mut diff = 0i64;
let mut rng : Isaac64Rng = SeedableRng::from_seed([12345678u64].as_slice());
for _ in range(0u, 20000) {
let a = rng.gen_range(0, sz);
let b = rng.gen_range(0, sz);
let pa = b_img.get_pixel(a%width, a/width);
let pb = b_img.get_pixel(b%width, b/width);
diff += pa.r as i64 - pb.r as i64 + pa.g as i64 - pa.g as i64 + pa.b as i64 - pa.b as i64;
}
if std::num::abs(diff) > 20000 {
print!("The picture is probably watermarked. The difference is {}.\n", diff);
} else {
print!("The picture is probably not watermarked. The difference is {}.\n", diff);
}
}
|
//extern crate diesel;
//extern crate r2d2;
//extern crate r2d2_diesel;
use actix_web::{
HttpResponse,
web,
};
//use diesel::MysqlConnection;
//use r2d2::Pool;
use super::super::{
service,
request,
response,
};
pub fn index(
payload: web::Query<request::design::Index>,
// db: web::Data<Pool<MysqlConnection>>,
) -> HttpResponse {
let (domain_designs, total) = &service::design::index(
payload.page,
payload.page_size,
);
response::design_index::response(domain_designs, &total)
} |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use super::{models, API_VERSION};
#[non_exhaustive]
#[derive(Debug, thiserror :: Error)]
#[allow(non_camel_case_types)]
pub enum Error {
#[error(transparent)]
BillingAccounts_List(#[from] billing_accounts::list::Error),
#[error(transparent)]
BillingAccounts_Get(#[from] billing_accounts::get::Error),
#[error(transparent)]
BillingAccounts_Update(#[from] billing_accounts::update::Error),
#[error(transparent)]
BillingAccounts_ListInvoiceSectionsByCreateSubscriptionPermission(
#[from] billing_accounts::list_invoice_sections_by_create_subscription_permission::Error,
),
#[error(transparent)]
PaymentMethods_ListByBillingAccount(#[from] payment_methods::list_by_billing_account::Error),
#[error(transparent)]
Address_Validate(#[from] address::validate::Error),
#[error(transparent)]
AvailableBalances_GetByBillingProfile(#[from] available_balances::get_by_billing_profile::Error),
#[error(transparent)]
Instructions_ListByBillingProfile(#[from] instructions::list_by_billing_profile::Error),
#[error(transparent)]
Instructions_Get(#[from] instructions::get::Error),
#[error(transparent)]
Instructions_Put(#[from] instructions::put::Error),
#[error(transparent)]
PaymentMethods_ListByBillingProfile(#[from] payment_methods::list_by_billing_profile::Error),
#[error(transparent)]
BillingProfiles_GetEligibilityToDetachPaymentMethod(#[from] billing_profiles::get_eligibility_to_detach_payment_method::Error),
#[error(transparent)]
BillingProfiles_ListByBillingAccount(#[from] billing_profiles::list_by_billing_account::Error),
#[error(transparent)]
BillingProfiles_Get(#[from] billing_profiles::get::Error),
#[error(transparent)]
BillingProfiles_Create(#[from] billing_profiles::create::Error),
#[error(transparent)]
BillingProfiles_Update(#[from] billing_profiles::update::Error),
#[error(transparent)]
Customers_ListByBillingProfile(#[from] customers::list_by_billing_profile::Error),
#[error(transparent)]
InvoiceSections_ListByBillingProfile(#[from] invoice_sections::list_by_billing_profile::Error),
#[error(transparent)]
InvoiceSections_Get(#[from] invoice_sections::get::Error),
#[error(transparent)]
InvoiceSections_Create(#[from] invoice_sections::create::Error),
#[error(transparent)]
InvoiceSections_Update(#[from] invoice_sections::update::Error),
#[error(transparent)]
Customers_ListByBillingAccount(#[from] customers::list_by_billing_account::Error),
#[error(transparent)]
Customers_Get(#[from] customers::get::Error),
#[error(transparent)]
BillingPermissions_ListByCustomer(#[from] billing_permissions::list_by_customer::Error),
#[error(transparent)]
BillingSubscriptions_ListByCustomer(#[from] billing_subscriptions::list_by_customer::Error),
#[error(transparent)]
BillingSubscriptions_GetByCustomer(#[from] billing_subscriptions::get_by_customer::Error),
#[error(transparent)]
Products_ListByCustomer(#[from] products::list_by_customer::Error),
#[error(transparent)]
Products_GetByCustomer(#[from] products::get_by_customer::Error),
#[error(transparent)]
Transactions_ListByCustomer(#[from] transactions::list_by_customer::Error),
#[error(transparent)]
Departments_ListByBillingAccountName(#[from] departments::list_by_billing_account_name::Error),
#[error(transparent)]
Departments_Get(#[from] departments::get::Error),
#[error(transparent)]
EnrollmentAccounts_ListByBillingAccountName(#[from] enrollment_accounts::list_by_billing_account_name::Error),
#[error(transparent)]
EnrollmentAccounts_GetByEnrollmentAccountId(#[from] enrollment_accounts::get_by_enrollment_account_id::Error),
#[error(transparent)]
Invoices_ListByBillingAccount(#[from] invoices::list_by_billing_account::Error),
#[error(transparent)]
Invoices_DownloadMultipleEaInvoices(#[from] invoices::download_multiple_ea_invoices::Error),
#[error(transparent)]
Invoices_GetBillingAccountInvoice(#[from] invoices::get_billing_account_invoice::Error),
#[error(transparent)]
Invoices_DownloadMultipleBillingSubscriptionInvoices(#[from] invoices::download_multiple_billing_subscription_invoices::Error),
#[error(transparent)]
PriceSheet_Download(#[from] price_sheet::download::Error),
#[error(transparent)]
PriceSheet_DownloadByBillingProfile(#[from] price_sheet::download_by_billing_profile::Error),
#[error(transparent)]
Invoices_ListByBillingProfile(#[from] invoices::list_by_billing_profile::Error),
#[error(transparent)]
Invoices_DownloadMultipleBillingProfileInvoices(#[from] invoices::download_multiple_billing_profile_invoices::Error),
#[error(transparent)]
Invoices_Get(#[from] invoices::get::Error),
#[error(transparent)]
BillingSubscriptions_ListByBillingAccount(#[from] billing_subscriptions::list_by_billing_account::Error),
#[error(transparent)]
Invoices_ListByBillingSubscription(#[from] invoices::list_by_billing_subscription::Error),
#[error(transparent)]
Invoices_GetById(#[from] invoices::get_by_id::Error),
#[error(transparent)]
BillingSubscriptions_ListByBillingProfile(#[from] billing_subscriptions::list_by_billing_profile::Error),
#[error(transparent)]
BillingSubscriptions_ListByInvoiceSection(#[from] billing_subscriptions::list_by_invoice_section::Error),
#[error(transparent)]
BillingSubscriptions_Get(#[from] billing_subscriptions::get::Error),
#[error(transparent)]
BillingSubscriptions_Transfer(#[from] billing_subscriptions::transfer::Error),
#[error(transparent)]
BillingSubscriptions_ValidateTransfer(#[from] billing_subscriptions::validate_transfer::Error),
#[error(transparent)]
Products_ListByBillingAccount(#[from] products::list_by_billing_account::Error),
#[error(transparent)]
Products_ListByInvoiceSection(#[from] products::list_by_invoice_section::Error),
#[error(transparent)]
Products_Get(#[from] products::get::Error),
#[error(transparent)]
Products_Transfer(#[from] products::transfer::Error),
#[error(transparent)]
Products_ValidateTransfer(#[from] products::validate_transfer::Error),
#[error(transparent)]
Transactions_ListByBillingAccount(#[from] transactions::list_by_billing_account::Error),
#[error(transparent)]
Transactions_ListByBillingProfile(#[from] transactions::list_by_billing_profile::Error),
#[error(transparent)]
Transactions_ListByInvoiceSection(#[from] transactions::list_by_invoice_section::Error),
#[error(transparent)]
Transactions_ListByInvoice(#[from] transactions::list_by_invoice::Error),
#[error(transparent)]
Transactions_Get(#[from] transactions::get::Error),
#[error(transparent)]
Policies_GetByBillingProfile(#[from] policies::get_by_billing_profile::Error),
#[error(transparent)]
Policies_Update(#[from] policies::update::Error),
#[error(transparent)]
Policies_GetByCustomer(#[from] policies::get_by_customer::Error),
#[error(transparent)]
Policies_UpdateCustomer(#[from] policies::update_customer::Error),
#[error(transparent)]
BillingProperty_Get(#[from] billing_property::get::Error),
#[error(transparent)]
Products_UpdateAutoRenewByInvoiceSection(#[from] products::update_auto_renew_by_invoice_section::Error),
#[error(transparent)]
InvoiceSections_ElevateToBillingProfile(#[from] invoice_sections::elevate_to_billing_profile::Error),
#[error(transparent)]
Transfers_Initiate(#[from] transfers::initiate::Error),
#[error(transparent)]
Transfers_Get(#[from] transfers::get::Error),
#[error(transparent)]
Transfers_Cancel(#[from] transfers::cancel::Error),
#[error(transparent)]
Transfers_List(#[from] transfers::list::Error),
#[error(transparent)]
PartnerTransfers_Initiate(#[from] partner_transfers::initiate::Error),
#[error(transparent)]
PartnerTransfers_Get(#[from] partner_transfers::get::Error),
#[error(transparent)]
PartnerTransfers_Cancel(#[from] partner_transfers::cancel::Error),
#[error(transparent)]
PartnerTransfers_List(#[from] partner_transfers::list::Error),
#[error(transparent)]
RecipientTransfers_Accept(#[from] recipient_transfers::accept::Error),
#[error(transparent)]
RecipientTransfers_Validate(#[from] recipient_transfers::validate::Error),
#[error(transparent)]
RecipientTransfers_Decline(#[from] recipient_transfers::decline::Error),
#[error(transparent)]
RecipientTransfers_Get(#[from] recipient_transfers::get::Error),
#[error(transparent)]
RecipientTransfers_List(#[from] recipient_transfers::list::Error),
#[error(transparent)]
Operations_List(#[from] operations::list::Error),
#[error(transparent)]
BillingPermissions_ListByBillingAccount(#[from] billing_permissions::list_by_billing_account::Error),
#[error(transparent)]
BillingPermissions_ListByInvoiceSections(#[from] billing_permissions::list_by_invoice_sections::Error),
#[error(transparent)]
BillingPermissions_ListByBillingProfile(#[from] billing_permissions::list_by_billing_profile::Error),
#[error(transparent)]
BillingPermissions_ListByDepartment(#[from] billing_permissions::list_by_department::Error),
#[error(transparent)]
BillingPermissions_ListByEnrollmentAccount(#[from] billing_permissions::list_by_enrollment_account::Error),
#[error(transparent)]
BillingRoleDefinitions_GetByBillingAccount(#[from] billing_role_definitions::get_by_billing_account::Error),
#[error(transparent)]
BillingRoleDefinitions_GetByInvoiceSection(#[from] billing_role_definitions::get_by_invoice_section::Error),
#[error(transparent)]
BillingRoleDefinitions_GetByBillingProfile(#[from] billing_role_definitions::get_by_billing_profile::Error),
#[error(transparent)]
BillingRoleDefinitions_GetByDepartment(#[from] billing_role_definitions::get_by_department::Error),
#[error(transparent)]
BillingRoleDefinitions_GetByEnrollmentAccount(#[from] billing_role_definitions::get_by_enrollment_account::Error),
#[error(transparent)]
BillingRoleDefinitions_ListByBillingAccount(#[from] billing_role_definitions::list_by_billing_account::Error),
#[error(transparent)]
BillingRoleDefinitions_ListByInvoiceSection(#[from] billing_role_definitions::list_by_invoice_section::Error),
#[error(transparent)]
BillingRoleDefinitions_ListByBillingProfile(#[from] billing_role_definitions::list_by_billing_profile::Error),
#[error(transparent)]
BillingRoleDefinitions_ListByDepartment(#[from] billing_role_definitions::list_by_department::Error),
#[error(transparent)]
BillingRoleDefinitions_ListByEnrollmentAccount(#[from] billing_role_definitions::list_by_enrollment_account::Error),
#[error(transparent)]
BillingRoleAssignments_GetByBillingAccount(#[from] billing_role_assignments::get_by_billing_account::Error),
#[error(transparent)]
RoleAssignments_Put(#[from] role_assignments::put::Error),
#[error(transparent)]
BillingRoleAssignments_DeleteByBillingAccount(#[from] billing_role_assignments::delete_by_billing_account::Error),
#[error(transparent)]
BillingRoleAssignments_GetByInvoiceSection(#[from] billing_role_assignments::get_by_invoice_section::Error),
#[error(transparent)]
BillingRoleAssignments_DeleteByInvoiceSection(#[from] billing_role_assignments::delete_by_invoice_section::Error),
#[error(transparent)]
BillingRoleAssignments_GetByBillingProfile(#[from] billing_role_assignments::get_by_billing_profile::Error),
#[error(transparent)]
BillingRoleAssignments_DeleteByBillingProfile(#[from] billing_role_assignments::delete_by_billing_profile::Error),
#[error(transparent)]
BillingRoleAssignments_GetByDepartment(#[from] billing_role_assignments::get_by_department::Error),
#[error(transparent)]
EnrollmentDepartmentRoleAssignments_Put(#[from] enrollment_department_role_assignments::put::Error),
#[error(transparent)]
BillingRoleAssignments_DeleteByDepartment(#[from] billing_role_assignments::delete_by_department::Error),
#[error(transparent)]
BillingRoleAssignments_GetByEnrollmentAccount(#[from] billing_role_assignments::get_by_enrollment_account::Error),
#[error(transparent)]
EnrollmentAccountRoleAssignments_Put(#[from] enrollment_account_role_assignments::put::Error),
#[error(transparent)]
BillingRoleAssignments_DeleteByEnrollmentAccount(#[from] billing_role_assignments::delete_by_enrollment_account::Error),
#[error(transparent)]
BillingRoleAssignments_ListByBillingAccount(#[from] billing_role_assignments::list_by_billing_account::Error),
#[error(transparent)]
BillingRoleAssignments_AddByBillingAccount(#[from] billing_role_assignments::add_by_billing_account::Error),
#[error(transparent)]
BillingRoleAssignments_ListByInvoiceSection(#[from] billing_role_assignments::list_by_invoice_section::Error),
#[error(transparent)]
BillingRoleAssignments_AddByInvoiceSection(#[from] billing_role_assignments::add_by_invoice_section::Error),
#[error(transparent)]
BillingRoleAssignments_ListByBillingProfile(#[from] billing_role_assignments::list_by_billing_profile::Error),
#[error(transparent)]
BillingRoleAssignments_AddByBillingProfile(#[from] billing_role_assignments::add_by_billing_profile::Error),
#[error(transparent)]
BillingRoleAssignments_ListByDepartment(#[from] billing_role_assignments::list_by_department::Error),
#[error(transparent)]
BillingRoleAssignments_ListByEnrollmentAccount(#[from] billing_role_assignments::list_by_enrollment_account::Error),
#[error(transparent)]
Agreements_ListByBillingAccount(#[from] agreements::list_by_billing_account::Error),
#[error(transparent)]
Agreements_Get(#[from] agreements::get::Error),
}
pub mod billing_accounts {
use super::{models, API_VERSION};
pub async fn list(
operation_config: &crate::OperationConfig,
expand: Option<&str>,
) -> std::result::Result<models::BillingAccountListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!("{}/providers/Microsoft.Billing/billingAccounts", operation_config.base_path(),);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingAccountListResult =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
expand: Option<&str>,
) -> std::result::Result<models::BillingAccount, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingAccount =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
parameters: &models::BillingAccountUpdateRequest,
) -> std::result::Result<update::Response, update::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(update::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(update::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(update::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(update::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(update::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingAccount =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(update::Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(update::Response::Accepted202),
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Err(update::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::BillingAccount),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_invoice_sections_by_create_subscription_permission(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
) -> std::result::Result<
models::InvoiceSectionListWithCreateSubPermissionResult,
list_invoice_sections_by_create_subscription_permission::Error,
> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/listInvoiceSectionsWithCreateSubscriptionPermission",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_invoice_sections_by_create_subscription_permission::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_invoice_sections_by_create_subscription_permission::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_invoice_sections_by_create_subscription_permission::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_invoice_sections_by_create_subscription_permission::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::InvoiceSectionListWithCreateSubPermissionResult =
serde_json::from_slice(rsp_body).map_err(|source| {
list_invoice_sections_by_create_subscription_permission::Error::DeserializeError(source, rsp_body.clone())
})?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body).map_err(|source| {
list_invoice_sections_by_create_subscription_permission::Error::DeserializeError(source, rsp_body.clone())
})?;
Err(list_invoice_sections_by_create_subscription_permission::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_invoice_sections_by_create_subscription_permission {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod payment_methods {
use super::{models, API_VERSION};
pub async fn list_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
) -> std::result::Result<models::PaymentMethodsListResult, list_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/paymentMethods",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::PaymentMethodsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
) -> std::result::Result<models::PaymentMethodsListResult, list_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/paymentMethods",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::PaymentMethodsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod address {
use super::{models, API_VERSION};
pub async fn validate(
operation_config: &crate::OperationConfig,
address: &models::AddressDetails,
) -> std::result::Result<models::ValidateAddressResponse, validate::Error> {
let http_client = operation_config.http_client();
let url_str = &format!("{}/providers/Microsoft.Billing/validateAddress", operation_config.base_path(),);
let mut url = url::Url::parse(url_str).map_err(validate::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(validate::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(address).map_err(validate::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(validate::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(validate::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ValidateAddressResponse =
serde_json::from_slice(rsp_body).map_err(|source| validate::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| validate::Error::DeserializeError(source, rsp_body.clone()))?;
Err(validate::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod validate {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod available_balances {
use super::{models, API_VERSION};
pub async fn get_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
) -> std::result::Result<models::AvailableBalance, get_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/availableBalance/default",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::AvailableBalance = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod instructions {
use super::{models, API_VERSION};
pub async fn list_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
) -> std::result::Result<models::InstructionListResult, list_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/instructions",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::InstructionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
instruction_name: &str,
) -> std::result::Result<models::Instruction, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/instructions/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
instruction_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Instruction =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn put(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
instruction_name: &str,
parameters: &models::Instruction,
) -> std::result::Result<models::Instruction, put::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/instructions/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
instruction_name
);
let mut url = url::Url::parse(url_str).map_err(put::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(put::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(put::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(put::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(put::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Instruction =
serde_json::from_slice(rsp_body).map_err(|source| put::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| put::Error::DeserializeError(source, rsp_body.clone()))?;
Err(put::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod put {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod billing_profiles {
use super::{models, API_VERSION};
pub async fn get_eligibility_to_detach_payment_method(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
) -> std::result::Result<models::DetachPaymentMethodEligibilityResult, get_eligibility_to_detach_payment_method::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/validateDetachPaymentMethodEligibility",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(get_eligibility_to_detach_payment_method::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_eligibility_to_detach_payment_method::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_eligibility_to_detach_payment_method::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_eligibility_to_detach_payment_method::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DetachPaymentMethodEligibilityResult = serde_json::from_slice(rsp_body)
.map_err(|source| get_eligibility_to_detach_payment_method::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_eligibility_to_detach_payment_method::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_eligibility_to_detach_payment_method::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_eligibility_to_detach_payment_method {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
expand: Option<&str>,
) -> std::result::Result<models::BillingProfileListResult, list_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingProfileListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
expand: Option<&str>,
) -> std::result::Result<models::BillingProfile, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingProfile =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn create(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
parameters: &models::BillingProfileCreationRequest,
) -> std::result::Result<create::Response, create::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(create::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(create::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(create::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(create::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(create::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingProfile =
serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(create::Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(create::Response::Accepted202),
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?;
Err(create::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod create {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::BillingProfile),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
parameters: &models::BillingProfile,
) -> std::result::Result<update::Response, update::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(update::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(update::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(update::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(update::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(update::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingProfile =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(update::Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(update::Response::Accepted202),
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Err(update::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::BillingProfile),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod customers {
use super::{models, API_VERSION};
pub async fn list_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
filter: Option<&str>,
skiptoken: Option<&str>,
) -> std::result::Result<models::CustomerListResult, list_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/customers",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
if let Some(skiptoken) = skiptoken {
url.query_pairs_mut().append_pair("$skiptoken", skiptoken);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::CustomerListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
filter: Option<&str>,
skiptoken: Option<&str>,
) -> std::result::Result<models::CustomerListResult, list_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/customers",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
if let Some(skiptoken) = skiptoken {
url.query_pairs_mut().append_pair("$skiptoken", skiptoken);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::CustomerListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
customer_name: &str,
expand: Option<&str>,
) -> std::result::Result<models::Customer, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/customers/{}",
operation_config.base_path(),
billing_account_name,
customer_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Customer =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod invoice_sections {
use super::{models, API_VERSION};
pub async fn list_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
) -> std::result::Result<models::InvoiceSectionListResult, list_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::InvoiceSectionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
) -> std::result::Result<models::InvoiceSection, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::InvoiceSection =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn create(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
parameters: &models::InvoiceSectionCreationRequest,
) -> std::result::Result<create::Response, create::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(create::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(create::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(create::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(create::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(create::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::InvoiceSection =
serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(create::Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(create::Response::Accepted202),
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?;
Err(create::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod create {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::InvoiceSection),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
parameters: &models::InvoiceSection,
) -> std::result::Result<update::Response, update::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(update::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(update::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(update::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(update::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(update::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::InvoiceSection =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(update::Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(update::Response::Accepted202),
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Err(update::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::InvoiceSection),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn elevate_to_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
) -> std::result::Result<(), elevate_to_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/elevate",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(elevate_to_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(elevate_to_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(elevate_to_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(elevate_to_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::NO_CONTENT => Ok(()),
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| elevate_to_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(elevate_to_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod elevate_to_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod billing_permissions {
use super::{models, API_VERSION};
pub async fn list_by_customer(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
customer_name: &str,
) -> std::result::Result<models::BillingPermissionsListResult, list_by_customer::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/customers/{}/billingPermissions",
operation_config.base_path(),
billing_account_name,
customer_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_customer::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_customer::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list_by_customer::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_customer::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingPermissionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_customer::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_customer {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
) -> std::result::Result<models::BillingPermissionsListResult, list_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingPermissions",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingPermissionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_invoice_sections(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
) -> std::result::Result<models::BillingPermissionsListResult, list_by_invoice_sections::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/billingPermissions",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_invoice_sections::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_invoice_sections::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_invoice_sections::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_invoice_sections::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingPermissionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice_sections::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice_sections::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_invoice_sections::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_invoice_sections {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
) -> std::result::Result<models::BillingPermissionsListResult, list_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/billingPermissions",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingPermissionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_department(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
department_name: &str,
) -> std::result::Result<models::BillingPermissionsListResult, list_by_department::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/departments/{}/billingPermissions",
operation_config.base_path(),
billing_account_name,
department_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_department::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_department::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list_by_department::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_department::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingPermissionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_department::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_department {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_enrollment_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
enrollment_account_name: &str,
) -> std::result::Result<models::BillingPermissionsListResult, list_by_enrollment_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/enrollmentAccounts/{}/billingPermissions",
operation_config.base_path(),
billing_account_name,
enrollment_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_enrollment_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_enrollment_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_enrollment_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_enrollment_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingPermissionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_enrollment_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_enrollment_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod billing_subscriptions {
use super::{models, API_VERSION};
pub async fn list_by_customer(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
customer_name: &str,
) -> std::result::Result<models::BillingSubscriptionsListResult, list_by_customer::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/customers/{}/billingSubscriptions",
operation_config.base_path(),
billing_account_name,
customer_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_customer::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_customer::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list_by_customer::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_customer::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingSubscriptionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_customer::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_customer {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_customer(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
customer_name: &str,
billing_subscription_name: &str,
) -> std::result::Result<models::BillingSubscription, get_by_customer::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/customers/{}/billingSubscriptions/{}",
operation_config.base_path(),
billing_account_name,
customer_name,
billing_subscription_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_customer::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_customer::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get_by_customer::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_customer::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingSubscription = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_customer::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_customer {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
) -> std::result::Result<models::BillingSubscriptionsListResult, list_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingSubscriptions",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingSubscriptionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
) -> std::result::Result<models::BillingSubscriptionsListResult, list_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/billingSubscriptions",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingSubscriptionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_invoice_section(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
) -> std::result::Result<models::BillingSubscriptionsListResult, list_by_invoice_section::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/billingSubscriptions",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_invoice_section::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_invoice_section::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_invoice_section::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_invoice_section::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingSubscriptionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_invoice_section::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_invoice_section {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
billing_subscription_name: &str,
) -> std::result::Result<models::BillingSubscription, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/billingSubscriptions/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name,
billing_subscription_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingSubscription =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn transfer(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
billing_subscription_name: &str,
parameters: &models::TransferBillingSubscriptionRequestProperties,
) -> std::result::Result<transfer::Response, transfer::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/billingSubscriptions/{}/transfer",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name,
billing_subscription_name
);
let mut url = url::Url::parse(url_str).map_err(transfer::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(transfer::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(transfer::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(transfer::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(transfer::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransferBillingSubscriptionResult =
serde_json::from_slice(rsp_body).map_err(|source| transfer::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(transfer::Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(transfer::Response::Accepted202),
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| transfer::Error::DeserializeError(source, rsp_body.clone()))?;
Err(transfer::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod transfer {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::TransferBillingSubscriptionResult),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn validate_transfer(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
billing_subscription_name: &str,
parameters: &models::TransferBillingSubscriptionRequestProperties,
) -> std::result::Result<models::ValidateSubscriptionTransferEligibilityResult, validate_transfer::Error> {
let http_client = operation_config.http_client();
let url_str = & format ! ("{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/billingSubscriptions/{}/validateTransferEligibility" , operation_config . base_path () , billing_account_name , billing_profile_name , invoice_section_name , billing_subscription_name) ;
let mut url = url::Url::parse(url_str).map_err(validate_transfer::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(validate_transfer::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(validate_transfer::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(validate_transfer::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(validate_transfer::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ValidateSubscriptionTransferEligibilityResult = serde_json::from_slice(rsp_body)
.map_err(|source| validate_transfer::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| validate_transfer::Error::DeserializeError(source, rsp_body.clone()))?;
Err(validate_transfer::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod validate_transfer {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod products {
use super::{models, API_VERSION};
pub async fn list_by_customer(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
customer_name: &str,
filter: Option<&str>,
) -> std::result::Result<models::ProductsListResult, list_by_customer::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/customers/{}/products",
operation_config.base_path(),
billing_account_name,
customer_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_customer::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_customer::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list_by_customer::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_customer::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ProductsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_customer::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_customer {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_customer(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
customer_name: &str,
product_name: &str,
) -> std::result::Result<models::Product, get_by_customer::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/customers/{}/products/{}",
operation_config.base_path(),
billing_account_name,
customer_name,
product_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_customer::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_customer::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get_by_customer::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_customer::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Product = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_customer::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_customer {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
filter: Option<&str>,
) -> std::result::Result<models::ProductsListResult, list_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/products",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ProductsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_invoice_section(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
filter: Option<&str>,
) -> std::result::Result<models::ProductsListResult, list_by_invoice_section::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/products",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_invoice_section::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_invoice_section::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_invoice_section::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_invoice_section::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ProductsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_invoice_section::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_invoice_section {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
product_name: &str,
) -> std::result::Result<models::Product, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/products/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name,
product_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Product =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn transfer(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
product_name: &str,
parameters: &models::TransferProductRequestProperties,
) -> std::result::Result<transfer::Response, transfer::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/products/{}/transfer",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name,
product_name
);
let mut url = url::Url::parse(url_str).map_err(transfer::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(transfer::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(transfer::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(transfer::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(transfer::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Product =
serde_json::from_slice(rsp_body).map_err(|source| transfer::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(transfer::Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(transfer::Response::Accepted202),
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| transfer::Error::DeserializeError(source, rsp_body.clone()))?;
Err(transfer::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod transfer {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Product),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn validate_transfer(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
product_name: &str,
parameters: &models::TransferProductRequestProperties,
) -> std::result::Result<models::ValidateProductTransferEligibilityResult, validate_transfer::Error> {
let http_client = operation_config.http_client();
let url_str = & format ! ("{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/products/{}/validateTransferEligibility" , operation_config . base_path () , billing_account_name , billing_profile_name , invoice_section_name , product_name) ;
let mut url = url::Url::parse(url_str).map_err(validate_transfer::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(validate_transfer::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(validate_transfer::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(validate_transfer::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(validate_transfer::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ValidateProductTransferEligibilityResult = serde_json::from_slice(rsp_body)
.map_err(|source| validate_transfer::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| validate_transfer::Error::DeserializeError(source, rsp_body.clone()))?;
Err(validate_transfer::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod validate_transfer {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn update_auto_renew_by_invoice_section(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
product_name: &str,
body: &models::UpdateAutoRenewRequest,
) -> std::result::Result<models::UpdateAutoRenewOperation, update_auto_renew_by_invoice_section::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/products/{}/updateAutoRenew",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name,
product_name
);
let mut url = url::Url::parse(url_str).map_err(update_auto_renew_by_invoice_section::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(update_auto_renew_by_invoice_section::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(body).map_err(update_auto_renew_by_invoice_section::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(update_auto_renew_by_invoice_section::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(update_auto_renew_by_invoice_section::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::UpdateAutoRenewOperation = serde_json::from_slice(rsp_body)
.map_err(|source| update_auto_renew_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| update_auto_renew_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Err(update_auto_renew_by_invoice_section::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod update_auto_renew_by_invoice_section {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod transactions {
use super::{models, API_VERSION};
pub async fn list_by_customer(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
customer_name: &str,
period_start_date: &str,
period_end_date: &str,
filter: Option<&str>,
) -> std::result::Result<models::TransactionListResult, list_by_customer::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/customers/{}/transactions",
operation_config.base_path(),
billing_account_name,
customer_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_customer::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_customer::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
url.query_pairs_mut().append_pair("periodStartDate", period_start_date);
url.query_pairs_mut().append_pair("periodEndDate", period_end_date);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list_by_customer::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_customer::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransactionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_customer::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_customer {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
period_start_date: &str,
period_end_date: &str,
filter: Option<&str>,
) -> std::result::Result<models::TransactionListResult, list_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/transactions",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
url.query_pairs_mut().append_pair("periodStartDate", period_start_date);
url.query_pairs_mut().append_pair("periodEndDate", period_end_date);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransactionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
period_start_date: &str,
period_end_date: &str,
filter: Option<&str>,
) -> std::result::Result<models::TransactionListResult, list_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/transactions",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
url.query_pairs_mut().append_pair("periodStartDate", period_start_date);
url.query_pairs_mut().append_pair("periodEndDate", period_end_date);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransactionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_invoice_section(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
period_start_date: &str,
period_end_date: &str,
filter: Option<&str>,
) -> std::result::Result<models::TransactionListResult, list_by_invoice_section::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/transactions",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_invoice_section::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_invoice_section::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
url.query_pairs_mut().append_pair("periodStartDate", period_start_date);
url.query_pairs_mut().append_pair("periodEndDate", period_end_date);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_invoice_section::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_invoice_section::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransactionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_invoice_section::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_invoice_section {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_invoice(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_name: &str,
) -> std::result::Result<models::TransactionListResult, list_by_invoice::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoices/{}/transactions",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_invoice::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_invoice::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list_by_invoice::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_invoice::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransactionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_invoice::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_invoice {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
transaction_name: &str,
period_start_date: &str,
period_end_date: &str,
) -> std::result::Result<models::Transaction, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/transactions/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
transaction_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
url.query_pairs_mut().append_pair("periodStartDate", period_start_date);
url.query_pairs_mut().append_pair("periodEndDate", period_end_date);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Transaction =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod departments {
use super::{models, API_VERSION};
pub async fn list_by_billing_account_name(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
expand: Option<&str>,
filter: Option<&str>,
) -> std::result::Result<models::DepartmentListResult, list_by_billing_account_name::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/departments",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account_name::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account_name::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account_name::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account_name::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DepartmentListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account_name::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account_name::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account_name::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account_name {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
department_name: &str,
expand: Option<&str>,
filter: Option<&str>,
) -> std::result::Result<models::Department, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/departments/{}",
operation_config.base_path(),
billing_account_name,
department_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Department =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod enrollment_accounts {
use super::{models, API_VERSION};
pub async fn list_by_billing_account_name(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
expand: Option<&str>,
filter: Option<&str>,
) -> std::result::Result<models::EnrollmentAccountListResult, list_by_billing_account_name::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/enrollmentAccounts",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account_name::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account_name::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account_name::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account_name::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::EnrollmentAccountListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account_name::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account_name::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account_name::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account_name {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_enrollment_account_id(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
enrollment_account_name: &str,
expand: Option<&str>,
filter: Option<&str>,
) -> std::result::Result<models::EnrollmentAccount, get_by_enrollment_account_id::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/enrollmentAccounts/{}",
operation_config.base_path(),
billing_account_name,
enrollment_account_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_enrollment_account_id::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_enrollment_account_id::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_by_enrollment_account_id::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_enrollment_account_id::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::EnrollmentAccount = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_enrollment_account_id::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_enrollment_account_id::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_enrollment_account_id::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_enrollment_account_id {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod invoices {
use super::{models, API_VERSION};
pub async fn list_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
period_start_date: &str,
period_end_date: &str,
) -> std::result::Result<models::InvoiceListResult, list_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/invoices",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
url.query_pairs_mut().append_pair("periodStartDate", period_start_date);
url.query_pairs_mut().append_pair("periodEndDate", period_end_date);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::InvoiceListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn download_multiple_ea_invoices(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
download_urls: &[&str],
) -> std::result::Result<download_multiple_ea_invoices::Response, download_multiple_ea_invoices::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/downloadDocuments",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(download_multiple_ea_invoices::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(download_multiple_ea_invoices::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(download_urls).map_err(download_multiple_ea_invoices::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(download_multiple_ea_invoices::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(download_multiple_ea_invoices::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::ACCEPTED => Ok(download_multiple_ea_invoices::Response::Accepted202),
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DownloadUrl = serde_json::from_slice(rsp_body)
.map_err(|source| download_multiple_ea_invoices::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(download_multiple_ea_invoices::Response::Ok200(rsp_value))
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| download_multiple_ea_invoices::Error::DeserializeError(source, rsp_body.clone()))?;
Err(download_multiple_ea_invoices::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod download_multiple_ea_invoices {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Accepted202,
Ok200(models::DownloadUrl),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_billing_account_invoice(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
invoice_name: &str,
) -> std::result::Result<models::Invoice, get_billing_account_invoice::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/invoices/{}",
operation_config.base_path(),
billing_account_name,
invoice_name
);
let mut url = url::Url::parse(url_str).map_err(get_billing_account_invoice::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_billing_account_invoice::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_billing_account_invoice::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_billing_account_invoice::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Invoice = serde_json::from_slice(rsp_body)
.map_err(|source| get_billing_account_invoice::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_billing_account_invoice::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_billing_account_invoice::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_billing_account_invoice {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn download_multiple_billing_subscription_invoices(
operation_config: &crate::OperationConfig,
subscription_id: &str,
download_urls: &[&str],
) -> std::result::Result<
download_multiple_billing_subscription_invoices::Response,
download_multiple_billing_subscription_invoices::Error,
> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{}/downloadDocuments",
operation_config.base_path(),
subscription_id
);
let mut url = url::Url::parse(url_str).map_err(download_multiple_billing_subscription_invoices::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(download_multiple_billing_subscription_invoices::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body =
azure_core::to_json(download_urls).map_err(download_multiple_billing_subscription_invoices::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(download_multiple_billing_subscription_invoices::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(download_multiple_billing_subscription_invoices::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::ACCEPTED => Ok(download_multiple_billing_subscription_invoices::Response::Accepted202),
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DownloadUrl = serde_json::from_slice(rsp_body)
.map_err(|source| download_multiple_billing_subscription_invoices::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(download_multiple_billing_subscription_invoices::Response::Ok200(rsp_value))
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| download_multiple_billing_subscription_invoices::Error::DeserializeError(source, rsp_body.clone()))?;
Err(download_multiple_billing_subscription_invoices::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod download_multiple_billing_subscription_invoices {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Accepted202,
Ok200(models::DownloadUrl),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
period_start_date: &str,
period_end_date: &str,
) -> std::result::Result<models::InvoiceListResult, list_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoices",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
url.query_pairs_mut().append_pair("periodStartDate", period_start_date);
url.query_pairs_mut().append_pair("periodEndDate", period_end_date);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::InvoiceListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn download_multiple_billing_profile_invoices(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
download_urls: &[&str],
) -> std::result::Result<download_multiple_billing_profile_invoices::Response, download_multiple_billing_profile_invoices::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/downloadDocuments",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(download_multiple_billing_profile_invoices::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(download_multiple_billing_profile_invoices::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(download_urls).map_err(download_multiple_billing_profile_invoices::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(download_multiple_billing_profile_invoices::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(download_multiple_billing_profile_invoices::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::ACCEPTED => Ok(download_multiple_billing_profile_invoices::Response::Accepted202),
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DownloadUrl = serde_json::from_slice(rsp_body)
.map_err(|source| download_multiple_billing_profile_invoices::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(download_multiple_billing_profile_invoices::Response::Ok200(rsp_value))
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| download_multiple_billing_profile_invoices::Error::DeserializeError(source, rsp_body.clone()))?;
Err(download_multiple_billing_profile_invoices::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod download_multiple_billing_profile_invoices {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Accepted202,
Ok200(models::DownloadUrl),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_name: &str,
) -> std::result::Result<models::Invoice, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoices/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Invoice =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_subscription(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_subscription_name: &str,
period_start_date: &str,
period_end_date: &str,
) -> std::result::Result<models::InvoiceListResult, list_by_billing_subscription::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingSubscriptions/{}/invoices",
operation_config.base_path(),
billing_account_name,
billing_subscription_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_subscription::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_subscription::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
url.query_pairs_mut().append_pair("periodStartDate", period_start_date);
url.query_pairs_mut().append_pair("periodEndDate", period_end_date);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_subscription::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_subscription::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::InvoiceListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_subscription::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_subscription::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_subscription::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_subscription {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_id(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_subscription_name: &str,
invoice_name: &str,
) -> std::result::Result<models::Invoice, get_by_id::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingSubscriptions/{}/invoices/{}",
operation_config.base_path(),
billing_account_name,
billing_subscription_name,
invoice_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_id::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_id::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get_by_id::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_id::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Invoice =
serde_json::from_slice(rsp_body).map_err(|source| get_by_id::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get_by_id::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_id::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_id {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod price_sheet {
use super::{models, API_VERSION};
pub async fn download(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_name: &str,
) -> std::result::Result<download::Response, download::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoices/{}/pricesheet/default/download",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_name
);
let mut url = url::Url::parse(url_str).map_err(download::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(download::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(download::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(download::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::ACCEPTED => Ok(download::Response::Accepted202),
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DownloadUrl =
serde_json::from_slice(rsp_body).map_err(|source| download::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(download::Response::Ok200(rsp_value))
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| download::Error::DeserializeError(source, rsp_body.clone()))?;
Err(download::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod download {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Accepted202,
Ok200(models::DownloadUrl),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn download_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
) -> std::result::Result<download_by_billing_profile::Response, download_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/pricesheet/default/download",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(download_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(download_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(download_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(download_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::ACCEPTED => Ok(download_by_billing_profile::Response::Accepted202),
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DownloadUrl = serde_json::from_slice(rsp_body)
.map_err(|source| download_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(download_by_billing_profile::Response::Ok200(rsp_value))
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| download_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(download_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod download_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Accepted202,
Ok200(models::DownloadUrl),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod policies {
use super::{models, API_VERSION};
pub async fn get_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
) -> std::result::Result<models::Policy, get_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/policies/default",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Policy = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
parameters: &models::Policy,
) -> std::result::Result<models::Policy, update::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/policies/default",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(update::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(update::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(update::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(update::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(update::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Policy =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Err(update::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_customer(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
customer_name: &str,
) -> std::result::Result<models::CustomerPolicy, get_by_customer::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/customers/{}/policies/default",
operation_config.base_path(),
billing_account_name,
customer_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_customer::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_customer::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get_by_customer::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_customer::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::CustomerPolicy = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_customer::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_customer {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn update_customer(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
customer_name: &str,
parameters: &models::CustomerPolicy,
) -> std::result::Result<models::CustomerPolicy, update_customer::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/customers/{}/policies/default",
operation_config.base_path(),
billing_account_name,
customer_name
);
let mut url = url::Url::parse(url_str).map_err(update_customer::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(update_customer::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(update_customer::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(update_customer::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(update_customer::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::CustomerPolicy = serde_json::from_slice(rsp_body)
.map_err(|source| update_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| update_customer::Error::DeserializeError(source, rsp_body.clone()))?;
Err(update_customer::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod update_customer {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod billing_property {
use super::{models, API_VERSION};
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
) -> std::result::Result<models::BillingProperty, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Billing/billingProperty/default",
operation_config.base_path(),
subscription_id
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingProperty =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod transfers {
use super::{models, API_VERSION};
pub async fn initiate(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
parameters: &models::InitiateTransferRequest,
) -> std::result::Result<models::TransferDetails, initiate::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/initiateTransfer",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(initiate::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(initiate::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(initiate::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(initiate::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(initiate::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransferDetails =
serde_json::from_slice(rsp_body).map_err(|source| initiate::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| initiate::Error::DeserializeError(source, rsp_body.clone()))?;
Err(initiate::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod initiate {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
transfer_name: &str,
) -> std::result::Result<models::TransferDetails, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/transfers/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name,
transfer_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransferDetails =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn cancel(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
transfer_name: &str,
) -> std::result::Result<models::TransferDetails, cancel::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/transfers/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name,
transfer_name
);
let mut url = url::Url::parse(url_str).map_err(cancel::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(cancel::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(cancel::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(cancel::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransferDetails =
serde_json::from_slice(rsp_body).map_err(|source| cancel::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| cancel::Error::DeserializeError(source, rsp_body.clone()))?;
Err(cancel::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod cancel {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
) -> std::result::Result<models::TransferDetailsListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/transfers",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransferDetailsListResult =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod partner_transfers {
use super::{models, API_VERSION};
pub async fn initiate(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
customer_name: &str,
parameters: &models::InitiateTransferRequest,
) -> std::result::Result<models::TransferDetails, initiate::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/customers/{}/initiateTransfer",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
customer_name
);
let mut url = url::Url::parse(url_str).map_err(initiate::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(initiate::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(initiate::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(initiate::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(initiate::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransferDetails =
serde_json::from_slice(rsp_body).map_err(|source| initiate::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| initiate::Error::DeserializeError(source, rsp_body.clone()))?;
Err(initiate::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod initiate {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
customer_name: &str,
transfer_name: &str,
) -> std::result::Result<models::TransferDetails, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/customers/{}/transfers/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
customer_name,
transfer_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransferDetails =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn cancel(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
customer_name: &str,
transfer_name: &str,
) -> std::result::Result<models::TransferDetails, cancel::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/customers/{}/transfers/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
customer_name,
transfer_name
);
let mut url = url::Url::parse(url_str).map_err(cancel::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(cancel::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(cancel::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(cancel::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransferDetails =
serde_json::from_slice(rsp_body).map_err(|source| cancel::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| cancel::Error::DeserializeError(source, rsp_body.clone()))?;
Err(cancel::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod cancel {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
customer_name: &str,
) -> std::result::Result<models::TransferDetailsListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/customers/{}/transfers",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
customer_name
);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::TransferDetailsListResult =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod recipient_transfers {
use super::{models, API_VERSION};
pub async fn accept(
operation_config: &crate::OperationConfig,
transfer_name: &str,
parameters: &models::AcceptTransferRequest,
) -> std::result::Result<models::RecipientTransferDetails, accept::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/transfers/{}/acceptTransfer",
operation_config.base_path(),
transfer_name
);
let mut url = url::Url::parse(url_str).map_err(accept::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(accept::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(accept::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(accept::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(accept::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::RecipientTransferDetails =
serde_json::from_slice(rsp_body).map_err(|source| accept::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| accept::Error::DeserializeError(source, rsp_body.clone()))?;
Err(accept::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod accept {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn validate(
operation_config: &crate::OperationConfig,
transfer_name: &str,
parameters: &models::AcceptTransferRequest,
) -> std::result::Result<models::ValidateTransferListResponse, validate::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/transfers/{}/validateTransfer",
operation_config.base_path(),
transfer_name
);
let mut url = url::Url::parse(url_str).map_err(validate::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(validate::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(validate::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(validate::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(validate::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ValidateTransferListResponse =
serde_json::from_slice(rsp_body).map_err(|source| validate::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| validate::Error::DeserializeError(source, rsp_body.clone()))?;
Err(validate::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod validate {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn decline(
operation_config: &crate::OperationConfig,
transfer_name: &str,
) -> std::result::Result<models::RecipientTransferDetails, decline::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/transfers/{}/declineTransfer",
operation_config.base_path(),
transfer_name
);
let mut url = url::Url::parse(url_str).map_err(decline::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(decline::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(decline::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(decline::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::RecipientTransferDetails =
serde_json::from_slice(rsp_body).map_err(|source| decline::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| decline::Error::DeserializeError(source, rsp_body.clone()))?;
Err(decline::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod decline {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
transfer_name: &str,
) -> std::result::Result<models::RecipientTransferDetails, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/transfers/{}",
operation_config.base_path(),
transfer_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::RecipientTransferDetails =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list(
operation_config: &crate::OperationConfig,
) -> std::result::Result<models::RecipientTransferDetailsListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!("{}/providers/Microsoft.Billing/transfers", operation_config.base_path(),);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::RecipientTransferDetailsListResult =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod operations {
use super::{models, API_VERSION};
pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<models::OperationListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!("{}/providers/Microsoft.Billing/operations", operation_config.base_path(),);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::OperationListResult =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod billing_role_definitions {
use super::{models, API_VERSION};
pub async fn get_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_role_definition_name: &str,
) -> std::result::Result<models::BillingRoleDefinition, get_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingRoleDefinitions/{}",
operation_config.base_path(),
billing_account_name,
billing_role_definition_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleDefinition = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_invoice_section(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
billing_role_definition_name: &str,
) -> std::result::Result<models::BillingRoleDefinition, get_by_invoice_section::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/billingRoleDefinitions/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name,
billing_role_definition_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_invoice_section::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_invoice_section::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_by_invoice_section::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_invoice_section::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleDefinition = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_invoice_section::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_invoice_section {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
billing_role_definition_name: &str,
) -> std::result::Result<models::BillingRoleDefinition, get_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/billingRoleDefinitions/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
billing_role_definition_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleDefinition = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_department(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
department_name: &str,
billing_role_definition_name: &str,
) -> std::result::Result<models::BillingRoleDefinition, get_by_department::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/departments/{}/billingRoleDefinitions/{}",
operation_config.base_path(),
billing_account_name,
department_name,
billing_role_definition_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_department::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_department::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get_by_department::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_department::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleDefinition = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_department::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_department {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_enrollment_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
enrollment_account_name: &str,
billing_role_definition_name: &str,
) -> std::result::Result<models::BillingRoleDefinition, get_by_enrollment_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/enrollmentAccounts/{}/billingRoleDefinitions/{}",
operation_config.base_path(),
billing_account_name,
enrollment_account_name,
billing_role_definition_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_enrollment_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_enrollment_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_by_enrollment_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_enrollment_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleDefinition = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_enrollment_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_enrollment_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
) -> std::result::Result<models::BillingRoleDefinitionListResult, list_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingRoleDefinitions",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleDefinitionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_invoice_section(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
) -> std::result::Result<models::BillingRoleDefinitionListResult, list_by_invoice_section::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/billingRoleDefinitions",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_invoice_section::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_invoice_section::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_invoice_section::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_invoice_section::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleDefinitionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_invoice_section::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_invoice_section {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
) -> std::result::Result<models::BillingRoleDefinitionListResult, list_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/billingRoleDefinitions",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleDefinitionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_department(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
department_name: &str,
) -> std::result::Result<models::BillingRoleDefinitionListResult, list_by_department::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/departments/{}/billingRoleDefinitions",
operation_config.base_path(),
billing_account_name,
department_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_department::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_department::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list_by_department::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_department::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleDefinitionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_department::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_department {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_enrollment_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
enrollment_account_name: &str,
) -> std::result::Result<models::BillingRoleDefinitionListResult, list_by_enrollment_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/enrollmentAccounts/{}/billingRoleDefinitions",
operation_config.base_path(),
billing_account_name,
enrollment_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_enrollment_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_enrollment_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_enrollment_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_enrollment_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleDefinitionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_enrollment_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_enrollment_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod billing_role_assignments {
use super::{models, API_VERSION};
pub async fn get_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_role_assignment_name: &str,
) -> std::result::Result<models::BillingRoleAssignment, get_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn delete_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_role_assignment_name: &str,
) -> std::result::Result<models::BillingRoleAssignment, delete_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(delete_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(delete_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(delete_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(delete_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment = serde_json::from_slice(rsp_body)
.map_err(|source| delete_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| delete_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(delete_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod delete_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_invoice_section(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
billing_role_assignment_name: &str,
) -> std::result::Result<models::BillingRoleAssignment, get_by_invoice_section::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_invoice_section::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_invoice_section::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_by_invoice_section::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_invoice_section::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_invoice_section::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_invoice_section {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn delete_by_invoice_section(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
billing_role_assignment_name: &str,
) -> std::result::Result<models::BillingRoleAssignment, delete_by_invoice_section::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(delete_by_invoice_section::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(delete_by_invoice_section::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(delete_by_invoice_section::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(delete_by_invoice_section::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment = serde_json::from_slice(rsp_body)
.map_err(|source| delete_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| delete_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Err(delete_by_invoice_section::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod delete_by_invoice_section {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
billing_role_assignment_name: &str,
) -> std::result::Result<models::BillingRoleAssignment, get_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn delete_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
billing_role_assignment_name: &str,
) -> std::result::Result<models::BillingRoleAssignment, delete_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(delete_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(delete_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(delete_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(delete_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment = serde_json::from_slice(rsp_body)
.map_err(|source| delete_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| delete_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(delete_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod delete_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_department(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
department_name: &str,
billing_role_assignment_name: &str,
) -> std::result::Result<models::BillingRoleAssignment, get_by_department::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/departments/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
department_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_department::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_department::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get_by_department::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_department::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_department::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_department {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn delete_by_department(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
department_name: &str,
billing_role_assignment_name: &str,
) -> std::result::Result<models::BillingRoleAssignment, delete_by_department::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/departments/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
department_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(delete_by_department::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(delete_by_department::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(delete_by_department::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(delete_by_department::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment = serde_json::from_slice(rsp_body)
.map_err(|source| delete_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| delete_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Err(delete_by_department::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod delete_by_department {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_by_enrollment_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
enrollment_account_name: &str,
billing_role_assignment_name: &str,
) -> std::result::Result<models::BillingRoleAssignment, get_by_enrollment_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/enrollmentAccounts/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
enrollment_account_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(get_by_enrollment_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_by_enrollment_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_by_enrollment_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_by_enrollment_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_by_enrollment_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_by_enrollment_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn delete_by_enrollment_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
enrollment_account_name: &str,
billing_role_assignment_name: &str,
) -> std::result::Result<models::BillingRoleAssignment, delete_by_enrollment_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/enrollmentAccounts/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
enrollment_account_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(delete_by_enrollment_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(delete_by_enrollment_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(delete_by_enrollment_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(delete_by_enrollment_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment = serde_json::from_slice(rsp_body)
.map_err(|source| delete_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| delete_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(delete_by_enrollment_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod delete_by_enrollment_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
) -> std::result::Result<models::BillingRoleAssignmentListResult, list_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingRoleAssignments",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignmentListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn add_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
parameters: &models::BillingRoleAssignmentPayload,
) -> std::result::Result<models::BillingRoleAssignmentListResult, add_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/createBillingRoleAssignment",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(add_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(add_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(add_by_billing_account::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(add_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(add_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::CREATED => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignmentListResult = serde_json::from_slice(rsp_body)
.map_err(|source| add_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| add_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(add_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod add_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_invoice_section(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
) -> std::result::Result<models::BillingRoleAssignmentListResult, list_by_invoice_section::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/billingRoleAssignments",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_invoice_section::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_invoice_section::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_invoice_section::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_invoice_section::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignmentListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_invoice_section::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_invoice_section {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn add_by_invoice_section(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
invoice_section_name: &str,
parameters: &models::BillingRoleAssignmentPayload,
) -> std::result::Result<models::BillingRoleAssignmentListResult, add_by_invoice_section::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/invoiceSections/{}/createBillingRoleAssignment",
operation_config.base_path(),
billing_account_name,
billing_profile_name,
invoice_section_name
);
let mut url = url::Url::parse(url_str).map_err(add_by_invoice_section::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(add_by_invoice_section::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(add_by_invoice_section::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(add_by_invoice_section::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(add_by_invoice_section::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::CREATED => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignmentListResult = serde_json::from_slice(rsp_body)
.map_err(|source| add_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| add_by_invoice_section::Error::DeserializeError(source, rsp_body.clone()))?;
Err(add_by_invoice_section::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod add_by_invoice_section {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
) -> std::result::Result<models::BillingRoleAssignmentListResult, list_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/billingRoleAssignments",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignmentListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn add_by_billing_profile(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_profile_name: &str,
parameters: &models::BillingRoleAssignmentPayload,
) -> std::result::Result<models::BillingRoleAssignmentListResult, add_by_billing_profile::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingProfiles/{}/createBillingRoleAssignment",
operation_config.base_path(),
billing_account_name,
billing_profile_name
);
let mut url = url::Url::parse(url_str).map_err(add_by_billing_profile::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(add_by_billing_profile::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(add_by_billing_profile::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(add_by_billing_profile::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(add_by_billing_profile::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::CREATED => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignmentListResult = serde_json::from_slice(rsp_body)
.map_err(|source| add_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| add_by_billing_profile::Error::DeserializeError(source, rsp_body.clone()))?;
Err(add_by_billing_profile::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod add_by_billing_profile {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_department(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
department_name: &str,
) -> std::result::Result<models::BillingRoleAssignmentListResult, list_by_department::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/departments/{}/billingRoleAssignments",
operation_config.base_path(),
billing_account_name,
department_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_department::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_department::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list_by_department::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_department::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignmentListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_department::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_department {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_enrollment_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
enrollment_account_name: &str,
) -> std::result::Result<models::BillingRoleAssignmentListResult, list_by_enrollment_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/enrollmentAccounts/{}/billingRoleAssignments",
operation_config.base_path(),
billing_account_name,
enrollment_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_enrollment_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_enrollment_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_enrollment_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_enrollment_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignmentListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_enrollment_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_enrollment_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod role_assignments {
use super::{models, API_VERSION};
pub async fn put(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
billing_role_assignment_name: &str,
parameters: &models::BillingRoleAssignment,
) -> std::result::Result<models::BillingRoleAssignment, put::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(put::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(put::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(put::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(put::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(put::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment =
serde_json::from_slice(rsp_body).map_err(|source| put::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| put::Error::DeserializeError(source, rsp_body.clone()))?;
Err(put::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod put {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod enrollment_department_role_assignments {
use super::{models, API_VERSION};
pub async fn put(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
department_name: &str,
billing_role_assignment_name: &str,
parameters: &models::BillingRoleAssignment,
) -> std::result::Result<models::BillingRoleAssignment, put::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/departments/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
department_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(put::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(put::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(put::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(put::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(put::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment =
serde_json::from_slice(rsp_body).map_err(|source| put::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| put::Error::DeserializeError(source, rsp_body.clone()))?;
Err(put::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod put {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod enrollment_account_role_assignments {
use super::{models, API_VERSION};
pub async fn put(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
enrollment_account_name: &str,
billing_role_assignment_name: &str,
parameters: &models::BillingRoleAssignment,
) -> std::result::Result<models::BillingRoleAssignment, put::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/enrollmentAccounts/{}/billingRoleAssignments/{}",
operation_config.base_path(),
billing_account_name,
enrollment_account_name,
billing_role_assignment_name
);
let mut url = url::Url::parse(url_str).map_err(put::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(put::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(put::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(put::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(put::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::BillingRoleAssignment =
serde_json::from_slice(rsp_body).map_err(|source| put::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| put::Error::DeserializeError(source, rsp_body.clone()))?;
Err(put::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod put {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod agreements {
use super::{models, API_VERSION};
pub async fn list_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
expand: Option<&str>,
) -> std::result::Result<models::AgreementListResult, list_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/agreements",
operation_config.base_path(),
billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::AgreementListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
billing_account_name: &str,
agreement_name: &str,
expand: Option<&str>,
) -> std::result::Result<models::Agreement, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/agreements/{}",
operation_config.base_path(),
billing_account_name,
agreement_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::Agreement =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
|
// Copyright 2018-2020, Wayfair GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[macro_use]
mod prelude;
mod query;
mod script;
pub use tremor_script::highlighter::ErrorLevel;
pub use tremor_script::pos::Location;
// common language trait
pub use prelude::{Language, Token, TokenSpan};
pub const LANGUAGE_NAMES: &[&str] = &[
script::LANGUAGE_NAME,
query::LANGUAGE_NAME,
// alternate names for above
script::FILE_EXTENSION,
query::FILE_EXTENSION,
];
pub const DEFAULT_LANGUAGE_NAME: &str = script::LANGUAGE_NAME;
pub fn lookup(language_name: &str) -> Option<Box<dyn Language>> {
match language_name {
script::LANGUAGE_NAME | script::FILE_EXTENSION => {
Some(Box::new(script::TremorScript::default()))
}
query::LANGUAGE_NAME | query::FILE_EXTENSION => {
Some(Box::new(query::TremorQuery::default()))
}
_ => None,
}
}
|
use super::local_player::LocalPlayer;
use super::offsets;
use crate::sdk::player::Player;
use log::*;
use memlib::memory::{get_module, read_memory, set_global_handle, Address, Handle, Module};
// The context passed into the hack loop containing all of our
pub struct GameContext {
pub client_module: Module,
pub engine_module: Module,
client_base: Address,
engine_base: Address,
}
impl GameContext {
pub fn new(handle: Handle) -> Self {
// Set the global handle so we don't have to store it in the context
set_global_handle(handle);
let client_module = get_module("client.dll").unwrap();
let engine_module = get_module("engine.dll").unwrap();
let client_base = client_module.base_address;
let engine_base = engine_module.base_address;
Self {
client_module,
engine_module,
client_base,
engine_base,
}
}
pub fn is_in_game(&self) -> bool {
read_memory::<i32>(self.client_state_address() + offsets::signatures::dwClientState_State)
== 6
}
pub fn get_local_player(&self) -> Option<LocalPlayer> {
if !self.is_in_game() {
return None;
}
LocalPlayer::new(read_memory(
self.client_base + offsets::signatures::dwLocalPlayer,
))
}
pub fn get_entity(&self, index: u32) -> Option<Player> {
let player_base: Address =
read_memory(self.entity_list_address() + (index * 0x10) as Address);
if player_base == 0 {
return None;
}
trace!("Found player with base 0x{:X}", player_base);
Player::new(player_base)
}
pub fn get_player_list(&self) -> Vec<Player> {
let mut entities: Vec<Player> = Vec::new();
for i in 0..128 {
let player_opt = self.get_entity(i);
if player_opt.is_none() {
continue;
}
entities.push(player_opt.unwrap());
}
entities
}
}
// Pointers
impl GameContext {
fn client_state_address(&self) -> Address {
let addr = read_memory(self.engine_base + offsets::signatures::dwClientState);
trace!("Found client state: 0x{:X}", addr);
addr
}
fn entity_list_address(&self) -> Address {
self.client_base + offsets::signatures::dwEntityList
}
}
|
use std::mem;
use std::sync::Arc;
use tuikit::prelude::*;
use unicode_width::UnicodeWidthStr;
use crate::event::{Event, EventHandler, UpdateScreen};
use crate::options::SkimOptions;
use crate::theme::{ColorTheme, DEFAULT_THEME};
use crate::util::clear_canvas;
#[derive(Clone, Copy, PartialEq)]
enum QueryMode {
Cmd,
Query,
}
pub struct Query {
cmd_before: Vec<char>,
cmd_after: Vec<char>,
fz_query_before: Vec<char>,
fz_query_after: Vec<char>,
yank: Vec<char>,
mode: QueryMode,
base_cmd: String,
replstr: String,
query_prompt: String,
cmd_prompt: String,
cmd_history_before: Vec<String>,
cmd_history_after: Vec<String>,
fz_query_history_before: Vec<String>,
fz_query_history_after: Vec<String>,
pasted: Option<String>,
theme: Arc<ColorTheme>,
}
#[allow(dead_code)]
impl Query {
pub fn builder() -> Self {
Query {
cmd_before: Vec::new(),
cmd_after: Vec::new(),
fz_query_before: Vec::new(),
fz_query_after: Vec::new(),
yank: Vec::new(),
mode: QueryMode::Query,
base_cmd: String::new(),
replstr: "{}".to_string(),
query_prompt: "> ".to_string(),
cmd_prompt: "c> ".to_string(),
cmd_history_before: Vec::new(),
cmd_history_after: Vec::new(),
fz_query_history_before: Vec::new(),
fz_query_history_after: Vec::new(),
pasted: None,
theme: Arc::new(*DEFAULT_THEME),
}
}
pub fn from_options(options: &SkimOptions) -> Self {
let mut query = Self::builder();
query.parse_options(options);
query
}
pub fn replace_base_cmd_if_not_set(mut self, base_cmd: &str) -> Self {
if self.base_cmd.is_empty() {
self.base_cmd = base_cmd.to_owned();
}
self
}
pub fn fz_query(mut self, query: &str) -> Self {
self.fz_query_before = query.chars().collect();
self
}
pub fn theme(mut self, theme: Arc<ColorTheme>) -> Self {
self.theme = theme;
self
}
pub fn cmd_history(mut self, mut history: Vec<String>) -> Self {
self.cmd_history_before.append(&mut history);
self
}
pub fn fz_query_history(mut self, mut history: Vec<String>) -> Self {
self.fz_query_history_before.append(&mut history);
self
}
pub fn build(self) -> Self {
self
}
fn parse_options(&mut self, options: &SkimOptions) {
// some options accept multiple values, thus take the last one
if let Some(base_cmd) = options.cmd {
self.base_cmd = base_cmd.to_string();
}
if let Some(query) = options.query {
self.fz_query_before = query.chars().collect();
}
if let Some(cmd_query) = options.cmd_query {
self.cmd_before = cmd_query.chars().collect();
}
if let Some(replstr) = options.replstr {
self.replstr = replstr.to_string();
}
if options.interactive {
self.mode = QueryMode::Cmd;
}
if let Some(query_prompt) = options.prompt {
self.query_prompt = query_prompt.to_string();
}
if let Some(cmd_prompt) = options.cmd_prompt {
self.cmd_prompt = cmd_prompt.to_string();
}
self.fz_query_history_before = options.query_history.to_vec();
self.cmd_history_before = options.cmd_history.to_vec();
}
pub fn in_query_mode(&self) -> bool {
match self.mode {
QueryMode::Cmd => false,
QueryMode::Query => true,
}
}
pub fn get_fz_query(&self) -> String {
self.fz_query_before
.iter()
.cloned()
.chain(self.fz_query_after.iter().cloned().rev())
.collect()
}
pub fn get_cmd(&self) -> String {
let arg: String = self
.cmd_before
.iter()
.cloned()
.chain(self.cmd_after.iter().cloned().rev())
.collect();
self.base_cmd.replace(&self.replstr, &arg)
}
pub fn get_cmd_query(&self) -> String {
self.cmd_before
.iter()
.cloned()
.chain(self.cmd_after.iter().cloned().rev())
.collect()
}
fn get_query(&mut self) -> String {
match self.mode {
QueryMode::Query => self.get_fz_query(),
QueryMode::Cmd => self.get_cmd_query(),
}
}
fn get_before(&self) -> String {
match self.mode {
QueryMode::Cmd => self.cmd_before.iter().cloned().collect(),
QueryMode::Query => self.fz_query_before.iter().cloned().collect(),
}
}
fn get_after(&self) -> String {
match self.mode {
QueryMode::Cmd => self.cmd_after.iter().cloned().rev().collect(),
QueryMode::Query => self.fz_query_after.iter().cloned().rev().collect(),
}
}
fn get_prompt(&self) -> &str {
match self.mode {
QueryMode::Cmd => &self.cmd_prompt,
QueryMode::Query => &self.query_prompt,
}
}
fn get_query_ref(&mut self) -> (&mut Vec<char>, &mut Vec<char>) {
match self.mode {
QueryMode::Query => (&mut self.fz_query_before, &mut self.fz_query_after),
QueryMode::Cmd => (&mut self.cmd_before, &mut self.cmd_after),
}
}
fn get_history_ref(&mut self) -> (&mut Vec<String>, &mut Vec<String>) {
match self.mode {
QueryMode::Query => (&mut self.fz_query_history_before, &mut self.fz_query_history_after),
QueryMode::Cmd => (&mut self.cmd_history_before, &mut self.cmd_history_after),
}
}
fn save_yank(&mut self, mut yank: Vec<char>, reverse: bool) {
if yank.is_empty() {
return;
}
self.yank.clear();
if reverse {
self.yank.append(&mut yank.into_iter().rev().collect());
} else {
self.yank.append(&mut yank);
}
}
//------------------------------------------------------------------------------
// Actions
//
pub fn act_query_toggle_interactive(&mut self) {
self.mode = match self.mode {
QueryMode::Query => QueryMode::Cmd,
QueryMode::Cmd => QueryMode::Query,
}
}
pub fn act_add_char(&mut self, ch: char) {
let (before, _) = self.get_query_ref();
before.push(ch);
}
pub fn act_backward_delete_char(&mut self) {
let (before, _) = self.get_query_ref();
let _ = before.pop();
}
// delete char foraward
pub fn act_delete_char(&mut self) {
let (_, after) = self.get_query_ref();
let _ = after.pop();
}
pub fn act_backward_char(&mut self) {
let (before, after) = self.get_query_ref();
if let Some(ch) = before.pop() {
after.push(ch);
}
}
pub fn act_forward_char(&mut self) {
let (before, after) = self.get_query_ref();
if let Some(ch) = after.pop() {
before.push(ch);
}
}
pub fn act_unix_word_rubout(&mut self) {
let mut yank = Vec::new();
{
let (before, _) = self.get_query_ref();
// kill things other than whitespace
while !before.is_empty() && before[before.len() - 1].is_whitespace() {
yank.push(before.pop().unwrap());
}
// kill word until whitespace
while !before.is_empty() && !before[before.len() - 1].is_whitespace() {
yank.push(before.pop().unwrap());
}
}
self.save_yank(yank, true);
}
pub fn act_backward_kill_word(&mut self) {
let mut yank = Vec::new();
{
let (before, _) = self.get_query_ref();
// kill things other than alphanumeric
while !before.is_empty() && !before[before.len() - 1].is_alphanumeric() {
yank.push(before.pop().unwrap());
}
// kill word until whitespace (not alphanumeric)
while !before.is_empty() && before[before.len() - 1].is_alphanumeric() {
yank.push(before.pop().unwrap());
}
}
self.save_yank(yank, true);
}
pub fn act_kill_word(&mut self) {
let mut yank = Vec::new();
{
let (_, after) = self.get_query_ref();
// kill non alphanumeric
while !after.is_empty() && !after[after.len() - 1].is_alphanumeric() {
yank.push(after.pop().unwrap());
}
// kill alphanumeric
while !after.is_empty() && after[after.len() - 1].is_alphanumeric() {
yank.push(after.pop().unwrap());
}
}
self.save_yank(yank, false);
}
pub fn act_backward_word(&mut self) {
let (before, after) = self.get_query_ref();
// skip whitespace
while !before.is_empty() && !before[before.len() - 1].is_alphanumeric() {
if let Some(ch) = before.pop() {
after.push(ch);
}
}
// backword char until whitespace
while !before.is_empty() && before[before.len() - 1].is_alphanumeric() {
if let Some(ch) = before.pop() {
after.push(ch);
}
}
}
pub fn act_forward_word(&mut self) {
let (before, after) = self.get_query_ref();
// backword char until whitespace
// skip whitespace
while !after.is_empty() && after[after.len() - 1].is_whitespace() {
if let Some(ch) = after.pop() {
before.push(ch);
}
}
while !after.is_empty() && !after[after.len() - 1].is_whitespace() {
if let Some(ch) = after.pop() {
before.push(ch);
}
}
}
pub fn act_beginning_of_line(&mut self) {
let (before, after) = self.get_query_ref();
while !before.is_empty() {
if let Some(ch) = before.pop() {
after.push(ch);
}
}
}
pub fn act_end_of_line(&mut self) {
let (before, after) = self.get_query_ref();
while !after.is_empty() {
if let Some(ch) = after.pop() {
before.push(ch);
}
}
}
pub fn act_kill_line(&mut self) {
let (_, after) = self.get_query_ref();
let after = std::mem::take(after);
self.save_yank(after, false);
}
pub fn act_line_discard(&mut self) {
let (before, _) = self.get_query_ref();
let before = std::mem::take(before);
self.save_yank(before, false);
}
pub fn act_yank(&mut self) {
let yank = std::mem::take(&mut self.yank);
for &c in &yank {
self.act_add_char(c);
}
let _ = mem::replace(&mut self.yank, yank);
}
pub fn previous_history(&mut self) {
let current_query = self.get_query();
let (history_before, history_after) = self.get_history_ref();
if let Some(history) = history_before.pop() {
history_after.push(current_query);
// store history into current query
let (query_before, _) = self.get_query_ref();
query_before.clear();
let mut new_query_chars = history.chars().collect();
query_before.append(&mut new_query_chars);
}
}
pub fn next_history(&mut self) {
let current_query = self.get_query();
let (history_before, history_after) = self.get_history_ref();
if let Some(history) = history_after.pop() {
history_before.push(current_query);
// store history into current query
let (query_before, _) = self.get_query_ref();
query_before.clear();
let mut new_query_chars = history.chars().collect();
query_before.append(&mut new_query_chars);
}
}
fn query_changed(
&self,
mode: QueryMode,
query_before_len: usize,
query_after_len: usize,
cmd_before_len: usize,
cmd_after_len: usize,
) -> bool {
self.mode != mode
|| self.fz_query_before.len() != query_before_len
|| self.fz_query_after.len() != query_after_len
|| self.cmd_before.len() != cmd_before_len
|| self.cmd_after.len() != cmd_after_len
}
}
impl EventHandler for Query {
fn handle(&mut self, event: &Event) -> UpdateScreen {
use crate::event::Event::*;
let mode = self.mode;
let query_before_len = self.fz_query_before.len();
let query_after_len = self.fz_query_after.len();
let cmd_before_len = self.cmd_before.len();
let cmd_after_len = self.cmd_after.len();
match event {
EvActAddChar(ch) => match self.pasted.as_mut() {
Some(pasted) => pasted.push(*ch),
None => self.act_add_char(*ch),
},
EvActDeleteChar | EvActDeleteCharEOF => {
self.act_delete_char();
}
EvActBackwardChar => {
self.act_backward_char();
}
EvActBackwardDeleteChar => {
self.act_backward_delete_char();
}
EvActBackwardKillWord => {
self.act_backward_kill_word();
}
EvActBackwardWord => {
self.act_backward_word();
}
EvActBeginningOfLine => {
self.act_beginning_of_line();
}
EvActEndOfLine => {
self.act_end_of_line();
}
EvActForwardChar => {
self.act_forward_char();
}
EvActForwardWord => {
self.act_forward_word();
}
EvActKillLine => {
self.act_kill_line();
}
EvActKillWord => {
self.act_kill_word();
}
EvActPreviousHistory => self.previous_history(),
EvActNextHistory => {
self.next_history();
}
EvActUnixLineDiscard => {
self.act_line_discard();
}
EvActUnixWordRubout => {
self.act_unix_word_rubout();
}
EvActYank => {
self.act_yank();
}
EvActToggleInteractive => {
self.act_query_toggle_interactive();
}
EvInputKey(Key::BracketedPasteStart) => {
self.pasted.replace(String::new());
}
EvInputKey(Key::BracketedPasteEnd) => {
let pasted = self.pasted.take().unwrap_or_default();
for ch in pasted.chars() {
self.act_add_char(ch);
}
}
_ => {}
}
if self.query_changed(mode, query_before_len, query_after_len, cmd_before_len, cmd_after_len) {
UpdateScreen::REDRAW
} else {
UpdateScreen::DONT_REDRAW
}
}
}
impl Draw for Query {
fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
canvas.clear()?;
let before = self.get_before();
let after = self.get_after();
let prompt = self.get_prompt();
clear_canvas(canvas)?;
let prompt_width = canvas.print_with_attr(0, 0, prompt, self.theme.prompt())?;
let before_width = canvas.print_with_attr(0, prompt_width, &before, self.theme.query())?;
let col = prompt_width + before_width;
canvas.print_with_attr(0, col, &after, self.theme.query())?;
canvas.set_cursor(0, col)?;
canvas.show_cursor(true)?;
Ok(())
}
}
impl Widget<Event> for Query {
fn size_hint(&self) -> (Option<usize>, Option<usize>) {
let before = self.get_before();
let after = self.get_after();
let prompt = self.get_prompt();
(Some(prompt.width() + before.width() + after.width() + 1), None)
}
}
#[cfg(test)]
mod test {
use super::Query;
#[test]
fn test_new_query() {
let query1 = Query::builder().fz_query("").build();
assert_eq!(query1.get_fz_query(), "");
let query2 = Query::builder().fz_query("abc").build();
assert_eq!(query2.get_fz_query(), "abc");
}
#[test]
fn test_add_char() {
let mut query1 = Query::builder().fz_query("").build();
query1.act_add_char('a');
assert_eq!(query1.get_fz_query(), "a");
query1.act_add_char('b');
assert_eq!(query1.get_fz_query(), "ab");
query1.act_add_char('中');
assert_eq!(query1.get_fz_query(), "ab中");
}
#[test]
fn test_backward_delete_char() {
let mut query = Query::builder().fz_query("AB中c").build();
assert_eq!(query.get_fz_query(), "AB中c");
query.act_backward_delete_char();
assert_eq!(query.get_fz_query(), "AB中");
query.act_backward_delete_char();
assert_eq!(query.get_fz_query(), "AB");
query.act_backward_delete_char();
assert_eq!(query.get_fz_query(), "A");
query.act_backward_delete_char();
assert_eq!(query.get_fz_query(), "");
query.act_backward_delete_char();
assert_eq!(query.get_fz_query(), "");
}
}
|
use serde::{Deserialize, Serialize};
use rmp_serde::{Deserializer, Serializer};
#[derive(Debug, PartialEq, Deserialize, Serialize)]
pub struct Player {
name: String,
pos: (f32, f32, f32),
}
#[cfg(test)]
mod test {
#[test]
fn send() {
let player = Player {
pos: (0., 1., 0.),
name: "Player1".into(),
};
}
}
|
use crate::Result;
use crossterm::{
cursor::{self, MoveTo},
style,
terminal::{self, ClearType},
ExecutableCommand, QueueableCommand,
};
use std::io::Write;
pub struct Graphics<W: Write> {
// 64 * 32 display
pub pixels: [[u8; 64]; 32],
out: W,
debugger_layout: DebuggerLayout,
}
impl<W: Write> Graphics<W> {
pub fn new(mut out: W) -> Result<Self> {
// Draw a screen
out.execute(terminal::Clear(terminal::ClearType::All))?;
out.queue(cursor::MoveTo(0, 0))?
.queue(style::Print("⥨".repeat(66)))?;
for _ in 0..32 {
out.queue(cursor::MoveToNextLine(1))?
.queue(style::Print('⥮'))?
.queue(cursor::MoveToColumn(66))?
.queue(style::Print('⥮'))?;
}
out.queue(cursor::MoveToNextLine(1))?
.queue(style::Print("⥨".repeat(66)))?
.flush()?;
Ok(Self {
pixels: [[0; 64]; 32],
debugger_layout: DebuggerLayout::new((0, 35)),
out,
})
}
pub fn clear(&mut self) -> std::io::Result<()> {
for mut row in self.pixels {
row.fill(0);
}
self.draw()
}
pub fn draw(&mut self) -> std::io::Result<()> {
for y in 0..32 {
for x in 0..64 {
let pixel = if self.pixels[y][x] == 1 { '*' } else { ' ' };
self.out
.queue(cursor::MoveTo(x as u16 + 1, y as u16 + 1))?
.queue(style::Print(pixel))?;
}
}
self.out.flush()
}
fn cursor_move_to(pos: CursorPos) -> MoveTo {
cursor::MoveTo(pos.0, pos.1)
}
pub fn log_op(&mut self, op: &str) -> std::io::Result<()> {
self.out
.queue(Self::cursor_move_to(self.debugger_layout.op))?
.queue(terminal::Clear(ClearType::UntilNewLine))?
.queue(style::Print(op))?
// Move cursor to the end, so that exit program will keep the whole logs
.queue(cursor::MoveDown(17))?
.flush()
}
pub fn log_values(&mut self, registers: [u8; 16], pc: u16, vi: u16) -> std::io::Result<()> {
for (i, v) in registers.iter().enumerate() {
self.out
.queue(Self::cursor_move_to(self.debugger_layout.registers[i]))?
.queue(style::Print(format!("V{:<2}: {:#04X}", i, v)))?;
}
self.out
.queue(Self::cursor_move_to(self.debugger_layout.pc))?
.queue(style::Print(format!("PC: {:#06X}", pc)))?
.queue(Self::cursor_move_to(self.debugger_layout.vi))?
.queue(style::Print(format!(" I: {:#06X}", vi)))?
// Move cursor to the end, so that exit program will keep the whole logs
.queue(cursor::MoveDown(14))?
.flush()
}
pub fn draw_debugger(&mut self) -> std::io::Result<()> {
self.out
.queue(Self::cursor_move_to(self.debugger_layout.start))?
.queue(terminal::Clear(ClearType::FromCursorDown))?
.queue(style::Print("Debugger"))?
.flush()
}
}
type CursorPos = (u16, u16);
struct DebuggerLayout {
start: CursorPos,
registers: [CursorPos; 16],
pc: CursorPos,
vi: CursorPos,
op: CursorPos,
}
impl DebuggerLayout {
fn new(start: CursorPos) -> Self {
let (start_x, start_y) = start;
let op = (start_x, start_y + 2);
let register_start_y = op.1 + 2;
let mut registers = [(0, 0); 16];
let pos = (0..16)
.map(|row| (start_x, register_start_y + row))
.collect::<Vec<_>>();
registers.copy_from_slice(&pos);
Self {
start,
op,
registers,
// V0: 0xFF(5 space) PC: 0xFFFF
pc: (start_x + 12, register_start_y),
// V1: 0xFF(5 space) I: 0xFFFF
vi: (start_x + 12, register_start_y + 1),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::BufWriter;
#[test]
fn it_initialize_screen() -> Result<()> {
let mut buffer = Vec::new();
let out = BufWriter::new(&mut buffer);
let _ = Graphics::new(out)?;
insta::assert_snapshot!(String::from_utf8(buffer)?, @"[2J[1;1H⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥮[66G⥮[1E⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨⥨");
Ok(())
}
}
|
mod boolean;
mod comment;
mod ident;
mod keyword;
mod number;
mod regex;
mod string;
mod template;
pub mod prelude {
pub use super::{
Boolean, Comment, Ident, Keyword, Number, Punct, RegEx, StringLit, Template,
TemplateLiteral, Token,
};
}
pub use boolean::Boolean;
pub use comment::{Comment, CommentKind};
pub use ident::Ident;
pub use keyword::Keyword;
pub use number::{Number, NumberKind};
pub use regex::RegEx;
pub use string::{InnerString, StringLit};
pub use template::{Template, TemplateLiteral};
#[derive(PartialEq, Clone, Debug)]
/// The representation of any single
/// JS part
pub enum Token<T> {
/// `true` of `false`
Boolean(Boolean),
/// The end of the file
EoF,
/// An identifier this will be either a variable name
/// or a function/method name
Ident(Ident<T>),
/// A word that has been reserved to not be used as an identifier
Keyword(Keyword<T>),
/// A `null` literal value
Null,
/// A number, this includes integers (`1`), decimals (`0.1`),
/// hex (`0x8f`), binary (`0b010011010`), and octal (`0o273`)
Number(Number<T>),
/// A punctuation mark, this includes all mathematical operators
/// logical operators and general syntax punctuation
Punct(Punct),
/// A string literal, either double or single quoted, the associated
/// value will be the unquoted string
String(StringLit<T>),
/// A regular expression literal.
/// ```js
/// let regex = /[a-zA-Z]+/g;
/// ```
RegEx(RegEx<T>),
/// The string parts of a template string
Template(Template<T>),
/// A comment, the associated value will contain the raw comment
/// This will capture inline comments `// I am an inline comment`,
/// multi-line comments, HTML-style comments and Unix hashbangs.
/// ```js
/// #!/usr/bin/env node
/// /*multi lines
/// * comments
/// */
/// ```
Comment(Comment<T>),
}
impl<T> PartialEq<&str> for Token<T>
where
T: AsRef<str>,
{
fn eq(&self, other: &&str) -> bool {
match self {
Token::Boolean(b) => b.eq(*other),
Token::EoF => (*other).eq(""),
Token::Ident(s) => s.eq(other),
Token::Keyword(k) => k.as_str().eq(*other),
Token::Null => (*other).eq("null"),
Token::Number(n) => n.eq(other),
Token::Punct(p) => p.eq(*other),
Token::String(s) => s.as_ref().eq(*other),
_ => false,
}
}
}
impl<T> PartialEq<bool> for Token<T> {
fn eq(&self, other: &bool) -> bool {
if let Token::Boolean(b) = self {
b == other
} else {
false
}
}
}
impl<T> Token<T> {
pub fn is_boolean(&self) -> bool {
matches!(self, Token::Boolean(_))
}
pub fn is_boolean_true(&self) -> bool {
match self {
Token::Boolean(ref b) => b.into(),
_ => false,
}
}
pub fn is_boolean_false(&self) -> bool {
match self {
Token::Boolean(ref b) => {
let b: bool = b.into();
!b
}
_ => false,
}
}
pub fn is_eof(&self) -> bool {
matches!(self, Token::EoF)
}
pub fn is_ident(&self) -> bool {
matches!(self, Token::Ident(_))
}
pub fn is_keyword(&self) -> bool {
matches!(self, Token::Keyword(_))
}
pub fn is_strict_reserved(&self) -> bool {
match self {
Token::Keyword(ref k) => k.is_strict_reserved(),
_ => false,
}
}
pub fn is_null(&self) -> bool {
matches!(self, Token::Null)
}
pub fn is_number(&self) -> bool {
matches!(self, Token::Number(_))
}
pub fn is_punct(&self) -> bool {
matches!(self, Token::Punct(_))
}
pub fn is_string(&self) -> bool {
matches!(self, Token::String(_))
}
pub fn is_double_quoted_string(&self) -> bool {
matches!(self, Token::String(StringLit::Double(_)))
}
pub fn is_single_quoted_string(&self) -> bool {
matches!(self, Token::String(StringLit::Single(_)))
}
pub fn is_regex(&self) -> bool {
matches!(self, Token::RegEx(_))
}
pub fn is_template(&self) -> bool {
matches!(self, Token::Template(_))
}
pub fn is_template_no_sub(&self) -> bool {
match self {
Token::Template(ref s) => s.is_no_sub(),
_ => false,
}
}
pub fn is_template_head(&self) -> bool {
match self {
Token::Template(ref s) => s.is_head() || s.is_no_sub(),
_ => false,
}
}
pub fn is_template_body(&self) -> bool {
match self {
Token::Template(ref s) => s.is_middle(),
_ => false,
}
}
pub fn is_template_tail(&self) -> bool {
match self {
Token::Template(ref s) => s.is_tail() || s.is_no_sub(),
_ => false,
}
}
pub fn is_literal(&self) -> bool {
matches!(
self,
Token::Boolean(_)
| Token::String(_)
| Token::Null
| Token::Number(_)
| Token::RegEx(_)
| Token::Template(_)
)
}
pub fn is_comment(&self) -> bool {
matches!(self, Token::Comment(_))
}
pub fn is_multi_line_comment(&self) -> bool {
match self {
Token::Comment(ref t) => t.kind == CommentKind::Multi,
_ => false,
}
}
pub fn is_single_line_comment(&self) -> bool {
match self {
Token::Comment(ref t) => t.kind == CommentKind::Single,
_ => false,
}
}
pub fn matches_boolean(&self, b: Boolean) -> bool {
match self {
Token::Boolean(m) => m == &b,
_ => false,
}
}
pub fn matches_boolean_str(&self, b: &str) -> bool {
match self {
Token::Boolean(ref lit) => matches!(
(lit, b),
(&Boolean::True, "true") | (&Boolean::False, "false")
),
_ => false,
}
}
pub fn matches_keyword<K>(&self, keyword: Keyword<K>) -> bool {
match self {
Token::Keyword(k) => k.eq(&keyword),
_ => false,
}
}
pub fn matches_keyword_str(&self, name: &str) -> bool {
match self {
Token::Keyword(n) => n.as_str() == name,
_ => false,
}
}
pub fn matches_punct(&self, p: Punct) -> bool {
match self {
Token::Punct(m) => m == &p,
_ => false,
}
}
pub fn matches_punct_str(&self, s: &str) -> bool {
match self {
Token::Punct(ref p) => p.matches_str(s),
_ => false,
}
}
}
impl<T> Token<T>
where
T: AsRef<str>,
{
pub fn is_restricted(&self) -> bool {
match self {
Token::Ident(ref i) => i.as_ref() == "arguments" || i.as_ref() == "eval",
_ => false,
}
}
pub fn is_hex_literal(&self) -> bool {
match self {
Token::Number(ref n) => n.is_hex(),
_ => false,
}
}
pub fn is_bin_literal(&self) -> bool {
match self {
Token::Number(ref n) => n.is_bin(),
_ => false,
}
}
pub fn is_oct_literal(&self) -> bool {
match self {
Token::Number(ref n) => n.is_oct(),
_ => false,
}
}
pub fn matches_ident_str(&self, name: &str) -> bool {
match self {
Token::Ident(i) => i.eq(name),
_ => false,
}
}
pub fn matches_number_str(&self, number: &str) -> bool {
match self {
Token::Number(n) => n.eq(number),
_ => false,
}
}
pub fn matches_comment_str(&self, comment: &str) -> bool {
match self {
Token::Comment(t) => t.content.as_ref() == comment,
_ => false,
}
}
pub fn matches_string_content(&self, content: &str) -> bool {
match self {
Token::String(ref lit) => match lit {
StringLit::Single(s) => content == s.content.as_ref(),
StringLit::Double(s) => content == s.content.as_ref(),
},
_ => false,
}
}
}
impl<T> ToString for Token<T>
where
T: AsRef<str>,
{
fn to_string(&self) -> String {
match self {
Token::Boolean(ref b) => b.to_string(),
Token::Comment(ref c) => c.to_string(),
Token::EoF => String::new(),
Token::Ident(ref i) => i.to_string(),
Token::Keyword(ref k) => k.to_string(),
Token::Null => "null".to_string(),
Token::Number(ref n) => n.to_string(),
Token::Punct(ref p) => p.to_string(),
Token::RegEx(ref r) => r.to_string(),
Token::String(ref s) => s.to_string(),
Token::Template(ref t) => t.to_string(),
}
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// All available punctuation
pub enum Punct {
Ampersand,
AmpersandEqual,
Asterisk,
AsteriskEqual,
AtMark,
Bang,
BangDoubleEqual,
BangEqual,
Caret,
CaretEqual,
CloseBrace,
CloseBracket,
CloseParen,
Colon,
Comma,
Dash,
DoubleDash,
DashEqual,
DoubleAmpersand,
DoubleAsterisk,
DoubleAsteriskEqual,
DoubleEqual,
DoubleGreaterThan,
DoubleGreaterThanEqual,
DoubleLessThan,
DoubleLessThanEqual,
DoublePipe,
DoublePlus,
Ellipsis,
Equal,
EqualGreaterThan,
ForwardSlash,
ForwardSlashEqual,
GreaterThan,
GreaterThanEqual,
Hash,
LessThan,
LessThanEqual,
OpenBrace,
OpenBracket,
OpenParen,
Percent,
PercentEqual,
Period,
Pipe,
PipeEqual,
Plus,
PlusEqual,
QuestionMark,
SemiColon,
Tilde,
TripleEqual,
TripleGreaterThanEqual,
TripleGreaterThan,
}
impl PartialEq<str> for Punct {
fn eq(&self, other: &str) -> bool {
self.matches_str(other)
}
}
impl Punct {
fn matches_str(self, s: &str) -> bool {
match self {
Punct::OpenBrace => "{" == s,
Punct::CloseBrace => "}" == s,
Punct::OpenParen => "(" == s,
Punct::CloseParen => ")" == s,
Punct::Period => "." == s,
Punct::SemiColon => ";" == s,
Punct::Comma => "," == s,
Punct::OpenBracket => "[" == s,
Punct::CloseBracket => "]" == s,
Punct::Colon => ":" == s,
Punct::QuestionMark => "?" == s,
Punct::Tilde => "~" == s,
Punct::GreaterThan => ">" == s,
Punct::LessThan => "<" == s,
Punct::Equal => "=" == s,
Punct::Bang => "!" == s,
Punct::Plus => "+" == s,
Punct::Dash => "-" == s,
Punct::Asterisk => "*" == s,
Punct::Percent => "%" == s,
Punct::Pipe => "|" == s,
Punct::Ampersand => "&" == s,
Punct::Caret => "^" == s,
Punct::ForwardSlash => "/" == s,
Punct::TripleGreaterThanEqual => ">>>=" == s,
Punct::Ellipsis => "..." == s,
Punct::TripleEqual => "===" == s,
Punct::BangDoubleEqual => "!==" == s,
Punct::TripleGreaterThan => ">>>" == s,
Punct::DoubleLessThanEqual => "<<=" == s,
Punct::DoubleGreaterThanEqual => ">>=" == s,
Punct::DoubleAsteriskEqual => "**=" == s,
Punct::DoubleAmpersand => "&&" == s,
Punct::DoublePipe => "||" == s,
Punct::DoubleEqual => "==" == s,
Punct::BangEqual => "!=" == s,
Punct::PlusEqual => "+=" == s,
Punct::DashEqual => "-=" == s,
Punct::AsteriskEqual => "*=" == s,
Punct::ForwardSlashEqual => "/=" == s,
Punct::DoublePlus => "++" == s,
Punct::DoubleDash => "--" == s,
Punct::DoubleLessThan => "<<" == s,
Punct::DoubleGreaterThan => ">>" == s,
Punct::AmpersandEqual => "&=" == s,
Punct::PipeEqual => "|=" == s,
Punct::CaretEqual => "^=" == s,
Punct::PercentEqual => "%=" == s,
Punct::EqualGreaterThan => "=>" == s,
Punct::GreaterThanEqual => ">=" == s,
Punct::LessThanEqual => "<=" == s,
Punct::DoubleAsterisk => "**" == s,
Punct::Hash => "#" == s,
Punct::AtMark => "@" == s,
}
}
}
impl ToString for Punct {
fn to_string(&self) -> String {
match self {
Punct::OpenBrace => "{",
Punct::CloseBrace => "}",
Punct::OpenParen => "(",
Punct::CloseParen => ")",
Punct::Period => ".",
Punct::SemiColon => ";",
Punct::Comma => ",",
Punct::OpenBracket => "[",
Punct::CloseBracket => "]",
Punct::Colon => ":",
Punct::QuestionMark => "?",
Punct::Tilde => "~",
Punct::GreaterThan => ">",
Punct::LessThan => "<",
Punct::Equal => "=",
Punct::Bang => "!",
Punct::Plus => "+",
Punct::Dash => "-",
Punct::Asterisk => "*",
Punct::Percent => "%",
Punct::Pipe => "|",
Punct::Ampersand => "&",
Punct::Caret => "^",
Punct::ForwardSlash => "/",
Punct::TripleGreaterThanEqual => ">>>=",
Punct::Ellipsis => "...",
Punct::TripleEqual => "===",
Punct::BangDoubleEqual => "!==",
Punct::TripleGreaterThan => ">>>",
Punct::DoubleLessThanEqual => "<<=",
Punct::DoubleGreaterThanEqual => ">>=",
Punct::DoubleAsteriskEqual => "**=",
Punct::DoubleAmpersand => "&&",
Punct::DoublePipe => "||",
Punct::DoubleEqual => "==",
Punct::BangEqual => "!=",
Punct::PlusEqual => "+=",
Punct::DashEqual => "-=",
Punct::AsteriskEqual => "*=",
Punct::ForwardSlashEqual => "/=",
Punct::DoublePlus => "++",
Punct::DoubleDash => "--",
Punct::DoubleLessThan => "<<",
Punct::DoubleGreaterThan => ">>",
Punct::AmpersandEqual => "&=",
Punct::PipeEqual => "|=",
Punct::CaretEqual => "^=",
Punct::PercentEqual => "%=",
Punct::EqualGreaterThan => "=>",
Punct::GreaterThanEqual => ">=",
Punct::LessThanEqual => "<=",
Punct::DoubleAsterisk => "**",
Punct::Hash => "#",
Punct::AtMark => "@",
}
.into()
}
}
impl<'a> Token<&'a str> {
pub fn is_div_punct(&self) -> bool {
matches!(
self,
Token::Punct(Punct::ForwardSlashEqual) | Token::Punct(Punct::ForwardSlash)
)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn booleans() {
let t = Token::<&str>::Boolean(Boolean::True);
let f = Token::<&str>::Boolean(Boolean::False);
assert!(t.is_boolean());
assert!(f.is_boolean());
assert!(t.is_boolean_true());
assert!(!f.is_boolean_true());
assert_eq!(t, true);
assert_eq!(t, "true");
assert_eq!(f, false);
assert_eq!(f, "false");
}
#[test]
fn comments() {
let c1 = Token::Comment(Comment::new_single_line("comment"));
assert!(c1.is_comment());
assert!(c1.is_single_line_comment());
assert!(!c1.is_multi_line_comment());
let c2 = Token::Comment(Comment::new_multi_line("comment\ncomment"));
assert!(c2.is_comment());
assert!(!c2.is_single_line_comment());
assert!(c2.is_multi_line_comment());
}
#[test]
fn idents() {
let i = Token::Ident(Ident::from("asdf"));
assert!(i.is_ident());
assert!(i.matches_ident_str("asdf"));
assert!(i == "asdf");
}
#[test]
fn keywords() {
check_keyword("await", Token::Keyword(Keyword::Await("await")));
check_keyword("break", Token::Keyword(Keyword::Break("break")));
check_keyword("case", Token::Keyword(Keyword::Case("case")));
check_keyword("catch", Token::Keyword(Keyword::Catch("catch")));
check_keyword("class", Token::Keyword(Keyword::Class("class")));
check_keyword("const", Token::Keyword(Keyword::Const("const")));
check_keyword("continue", Token::Keyword(Keyword::Continue("continue")));
check_keyword("debugger", Token::Keyword(Keyword::Debugger("debugger")));
check_keyword("default", Token::Keyword(Keyword::Default("default")));
check_keyword("import", Token::Keyword(Keyword::Import("import")));
check_keyword("delete", Token::Keyword(Keyword::Delete("delete")));
check_keyword("do", Token::Keyword(Keyword::Do("do")));
check_keyword("else", Token::Keyword(Keyword::Else("else")));
check_keyword("enum", Token::Keyword(Keyword::Enum("enum")));
check_keyword("export", Token::Keyword(Keyword::Export("export")));
check_keyword("extends", Token::Keyword(Keyword::Extends("extends")));
check_keyword("finally", Token::Keyword(Keyword::Finally("finally")));
check_keyword("for", Token::Keyword(Keyword::For("for")));
check_keyword("function", Token::Keyword(Keyword::Function("function")));
check_keyword("if", Token::Keyword(Keyword::If("if")));
check_keyword("in", Token::Keyword(Keyword::In("in")));
check_keyword(
"implements",
Token::Keyword(Keyword::Implements("implements")),
);
check_keyword(
"instanceof",
Token::Keyword(Keyword::InstanceOf("instanceof")),
);
check_keyword("interface", Token::Keyword(Keyword::Interface("interface")));
check_keyword("let", Token::Keyword(Keyword::Let("let")));
check_keyword("new", Token::Keyword(Keyword::New("new")));
check_keyword("package", Token::Keyword(Keyword::Package("package")));
check_keyword("private", Token::Keyword(Keyword::Private("private")));
check_keyword("protected", Token::Keyword(Keyword::Protected("protected")));
check_keyword("public", Token::Keyword(Keyword::Public("public")));
check_keyword("return", Token::Keyword(Keyword::Return("return")));
check_keyword("static", Token::Keyword(Keyword::Static("static")));
check_keyword("super", Token::Keyword(Keyword::Super("super")));
check_keyword("switch", Token::Keyword(Keyword::Switch("switch")));
check_keyword("this", Token::Keyword(Keyword::This("this")));
check_keyword("throw", Token::Keyword(Keyword::Throw("throw")));
check_keyword("try", Token::Keyword(Keyword::Try("try")));
check_keyword("typeof", Token::Keyword(Keyword::TypeOf("typeof")));
check_keyword("var", Token::Keyword(Keyword::Var("var")));
check_keyword("void", Token::Keyword(Keyword::Void("void")));
check_keyword("while", Token::Keyword(Keyword::While("while")));
check_keyword("with", Token::Keyword(Keyword::With("with")));
check_keyword("yield", Token::Keyword(Keyword::Yield("yield")));
}
fn check_keyword(s: &str, tok: Token<&str>) {
assert!(tok.is_keyword());
assert!(tok.matches_keyword(Keyword::new(s)), "{:?} vs {:?}", s, tok);
assert!(tok.matches_keyword_str(s));
assert_eq!(tok, s);
}
#[test]
fn numbers() {
let int = "1234";
let tok = Token::Number(Number::from(int));
assert!(tok.is_number());
assert!(tok.matches_number_str(int));
assert_eq!(tok, int);
assert!(!tok.is_oct_literal());
assert!(!tok.is_bin_literal());
assert!(!tok.is_hex_literal());
let flt = "1.334";
let tok = Token::Number(Number::from(flt));
assert!(tok.is_number());
assert!(tok.matches_number_str(flt));
assert_eq!(tok, flt);
assert!(!tok.is_oct_literal());
assert!(!tok.is_bin_literal());
assert!(!tok.is_hex_literal());
let hex = "0x3";
let tok = Token::Number(Number::from(hex));
assert!(tok.is_number());
assert!(tok.matches_number_str(hex));
assert_eq!(tok, hex);
assert!(!tok.is_oct_literal());
assert!(!tok.is_bin_literal());
assert!(tok.is_hex_literal());
let hex2 = "0X3";
let tok = Token::Number(Number::from(hex2));
assert!(tok.is_number());
assert!(tok.matches_number_str(hex2));
assert_eq!(tok, hex2);
assert!(!tok.is_oct_literal());
assert!(!tok.is_bin_literal());
assert!(tok.is_hex_literal());
let oct = "0o4";
let tok = Token::Number(Number::from(oct));
assert!(tok.is_number());
assert!(tok.matches_number_str(oct));
assert_eq!(tok, oct);
assert!(tok.is_oct_literal());
assert!(!tok.is_bin_literal());
assert!(!tok.is_hex_literal());
let oct2 = "0O3";
let tok = Token::Number(Number::from(oct2));
assert!(tok.is_number());
assert!(tok.matches_number_str(oct2));
assert_eq!(tok, oct2);
assert!(tok.is_oct_literal());
assert!(!tok.is_bin_literal());
assert!(!tok.is_hex_literal());
let bin = "0b0";
let tok = Token::Number(Number::from(bin));
assert!(tok.is_number());
assert!(tok.matches_number_str(bin));
assert_eq!(tok, bin);
assert!(!tok.is_oct_literal());
assert!(tok.is_bin_literal());
assert!(!tok.is_hex_literal());
let bin2 = "0B1";
let tok = Token::Number(Number::from(bin2));
assert!(tok.is_number());
assert!(tok.matches_number_str(bin2));
assert_eq!(tok, bin2);
assert!(!tok.is_oct_literal());
assert!(tok.is_bin_literal());
assert!(!tok.is_hex_literal());
let exp = "1.22e2";
let tok = Token::Number(Number::from(exp));
assert!(tok.is_number());
assert!(tok.matches_number_str(exp));
assert_eq!(tok, exp);
assert!(!tok.is_oct_literal());
assert!(!tok.is_bin_literal());
assert!(!tok.is_hex_literal());
let exp2 = "1.3E8";
let tok = Token::Number(Number::from(exp2));
assert!(tok.is_number());
assert!(tok.matches_number_str(exp2));
assert_eq!(tok, exp2);
assert!(!tok.is_oct_literal());
assert!(!tok.is_bin_literal());
assert!(!tok.is_hex_literal());
}
#[test]
fn regexes() {
let r = Token::RegEx(RegEx::from_parts("asdf", None));
assert!(r.is_regex());
assert_ne!(r, "");
assert_ne!(r, "/asdf/");
}
#[test]
fn strings() {
let s1 = Token::String(StringLit::single("content", false));
assert!(s1.is_string());
assert!(s1.is_single_quoted_string());
assert!(!s1.is_double_quoted_string());
assert_eq!(s1, "content");
let s2 = Token::String(StringLit::double("content", false));
assert!(s2.is_string());
assert!(!s2.is_single_quoted_string());
assert!(s2.is_double_quoted_string());
assert_eq!(s2, "content");
}
#[test]
fn templates() {
let t = Token::Template(Template::no_sub_template("asdf", false, false, false));
assert!(t.is_template());
assert!(t.is_template_head());
assert!(!t.is_template_body());
assert!(t.is_template_tail());
assert!(t.is_template_no_sub());
let t = Token::Template(Template::template_head("asdf", false, false, false));
assert!(t.is_template());
assert!(t.is_template_head());
assert!(!t.is_template_body());
assert!(!t.is_template_tail());
assert!(!t.is_template_no_sub());
let t = Token::Template(Template::template_middle("asdf", false, false, false));
assert!(t.is_template());
assert!(!t.is_template_head());
assert!(t.is_template_body());
assert!(!t.is_template_tail());
assert!(!t.is_template_no_sub());
let t = Token::Template(Template::template_tail("asdf", false, false, false));
assert!(t.is_template());
assert!(!t.is_template_head());
assert!(!t.is_template_body());
assert!(t.is_template_tail());
assert!(!t.is_template_no_sub());
assert_ne!(t, "");
assert_ne!(t, "}asdf`");
}
}
|
use std::fmt;
use std::io;
extern crate nalgebra as na;
use na::{Point3, Real, Rotation3, Vector3};
struct CubicUfo {
base: Vec<Point3<f32>>,
vertices: Vec<Point3<f32>>,
}
impl CubicUfo {
fn new() -> CubicUfo {
let base = vec![
Point3::new(0.5, 0.0, 0.0),
Point3::new(0.0, 0.5, 0.0),
Point3::new(0.0, 0.0, 0.5),
];
let vertices = vec![
Point3::new(0.5, 0.5, 0.5),
Point3::new(-0.5, 0.5, 0.5),
Point3::new(-0.5, 0.5, -0.5),
Point3::new(0.5, 0.5, -0.5),
Point3::new(0.5, -0.5, 0.5),
Point3::new(-0.5, -0.5, 0.5),
Point3::new(-0.5, -0.5, -0.5),
Point3::new(0.5, -0.5, -0.5),
];
CubicUfo { base, vertices }
}
fn apply_rotation(&mut self, rot: Rotation3<f32>) {
for p in self.base.iter_mut() {
*p = rot * *p;
}
for p in self.vertices.iter_mut() {
*p = rot * *p;
}
}
fn shadow(&self) -> f32 {
let exagon = vec![
self.vertices[4].clone(),
self.vertices[5].clone(),
self.vertices[1].clone(),
self.vertices[2].clone(),
self.vertices[3].clone(),
self.vertices[7].clone(),
];
shoelace(exagon)
}
}
impl fmt::Display for CubicUfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {} {}\n{} {} {}\n{} {} {}\n",
self.base[0].x,
self.base[0].y,
self.base[0].z,
self.base[1].x,
self.base[1].y,
self.base[1].z,
self.base[2].x,
self.base[2].y,
self.base[2].z,
)
}
}
fn shoelace(points: Vec<Point3<f32>>) -> f32 {
let n = points.len();
let mut first = 0.0;
for i in 0..n - 1 {
let x_i = points[i].x;
let z_ip1 = points[i + 1].z;
first += x_i * z_ip1;
}
let x_nm1 = points[n - 1].x;
let z_0 = points[0].z;
let n1 = x_nm1 * z_0;
let mut second = 0.0;
for i in 0..n - 1 {
let x_ip1 = points[i + 1].x;
let z_i = points[i].z;
second += x_ip1 * z_i;
}
let x_0 = points[0].x;
let z_nm1 = points[n - 1].z;
let n1n = x_0 * z_nm1;
0.5 * (first + n1 - second - n1n).abs()
}
fn find_angle(a: f32, ufo: &mut CubicUfo) -> f32 {
const MAX_ANGLE: f32 = 0.95547971;
let mut area = 1.0;
let mut l = 0.0;
let mut r = MAX_ANGLE;
let mut angle = 0.0;
while (area - a).abs() > 0.000001 {
angle = ((r - l) / 2.0) + l;
let axis = Vector3::z_axis();
let z_rotation = Rotation3::from_axis_angle(&axis, angle);
ufo.apply_rotation(z_rotation);
area = ufo.shadow();
if a > area {
l = angle;
} else {
r = angle;
}
ufo.apply_rotation(Rotation3::from_axis_angle(&axis, -angle));
}
angle
}
// fn test_set_1(a: f32) -> Ufo {
// let axis = Vector3::z_axis();
// let angle = (1.0 / a).acos();
//
// let rotation = Rotation3::from_axis_angle(&axis, angle);
//
// let mut ufo = Ufo::new();
//
// ufo.apply_rotation(rotation);
//
// ufo
// }
fn test_set_2(a: f32) -> CubicUfo {
let axis = Vector3::y_axis();
let angle: f32 = Real::frac_pi_4();
let y_rotation = Rotation3::from_axis_angle(&axis, angle);
let mut ufo = CubicUfo::new();
ufo.apply_rotation(y_rotation);
let axis = Vector3::z_axis();
let angle = find_angle(a, &mut ufo);
let z_rotation = Rotation3::from_axis_angle(&axis, angle);
ufo.apply_rotation(z_rotation);
ufo
}
fn main() -> std::io::Result<()> {
let mut n = String::new();
io::stdin().read_line(&mut n)
.expect("Failed to read line");
let n: usize = n.trim().parse().unwrap();
for case in 0..n {
let mut a = String::new();
io::stdin().read_line(&mut a)
.expect("Failed to read line");
let a: f32 = a.trim().parse().unwrap();
// println!("{}", test_set_1(a));
print!("Case #{}:\n{}", case + 1, test_set_2(a));
}
Ok(())
}
|
// error-pattern:giraffe
fn main() {
fail do { fail "giraffe" } while true;
}
|
use crate::path::{
is_child_filter, is_child_filter_value_match, matches_pattern, parse_array_child_filter,
parse_array_indexing_operation, ArrayIndices, ParseError, SPLAT,
};
use log::{debug, error};
use yaml_rust::yaml::{Array, Hash};
use yaml_rust::Yaml;
#[derive(Debug)]
pub struct VisitedNode<'a> {
pub yml: &'a Yaml,
pub path: String,
}
fn unwrap(s: &str) -> &str {
if s.len() < 2 {
return "";
}
&s[1..s.len() - 1]
}
fn get_array_idx<F, G>(
path_elem: &str,
array_node: &Vec<Yaml>,
is_final_path_elem: bool,
handle_child_filter: F,
handle_indexing_operation: G,
) -> ArrayIndices
where
F: FnOnce(&str, &Vec<Yaml>, bool) -> Result<ArrayIndices, ParseError>,
G: FnOnce(&str) -> Result<ArrayIndices, ParseError>,
{
debug!("getting array index for path_elem: `{}`", path_elem);
match path_elem {
SPLAT => {
debug!("found splat for array, using all indices");
ArrayIndices::Star
}
_ if is_child_filter(path_elem) => {
let path_elem = unwrap(path_elem);
handle_child_filter(path_elem, array_node, is_final_path_elem).unwrap_or_else(|err| {
error!("{}", err);
std::process::exit(1);
})
}
_ if path_elem.starts_with('[') && path_elem.ends_with(']') => {
let path_elem = unwrap(path_elem);
handle_indexing_operation(path_elem).unwrap_or_else(|err| {
error!("{}", err);
std::process::exit(1);
})
}
_ => {
debug!(
"key `{:?}` is neither a valid array index nor child filter, continuing",
path_elem
);
ArrayIndices::Indices(vec![])
}
}
}
pub fn traverse<'a>(
node: &'a Yaml,
head: &str,
tail: &[String],
path: String,
following_splat: bool,
visited: &mut Vec<VisitedNode<'a>>,
) {
// handle following a splat
if following_splat {
if head == SPLAT {
if tail.len() > 0 {
// first traversal after finding a splat
recurse(node, &tail[0], &tail[1..], path, true, visited)
} else {
// final path element was a splat
if is_scalar(node) {
visit(node, tail, path, visited);
} else {
recurse(node, head, tail, path, false, visited);
}
}
} else if !is_scalar(node) {
// recurse until you find a non-splat match
recurse(node, head, tail, path, true, visited);
}
return;
}
// if parsed_path still has elements and the node is not a scalar, recurse
if tail.len() > 0 && !is_scalar(node) {
recurse(node, &tail[0], &tail[1..], path, false, visited)
} else {
// the parsed path is empty or we have a scalar, try visiting
visit(node, tail, path, visited);
}
}
fn is_scalar(node: &Yaml) -> bool {
match node {
Yaml::String(_) => true,
Yaml::Integer(_) => true,
Yaml::Real(_) => true,
Yaml::Boolean(_) => true,
Yaml::Null => true,
Yaml::BadValue => true,
_ => false,
}
}
fn recurse<'a>(
node: &'a Yaml,
head: &str,
tail: &[String],
path: String,
following_splat: bool,
visited: &mut Vec<VisitedNode<'a>>,
) {
match node {
Yaml::Hash(h) => recurse_hash(h, head, tail, path, following_splat, visited, traverse),
Yaml::Array(v) => recurse_array(v, head, tail, path, following_splat, visited, traverse),
_ => {
error!("can only recurse on maps or arrays. recursing on `{:?}` is not supported, continuing", node);
}
}
}
fn extend_hash_path(p: &String, extend: &str) -> String {
let mut new_path = p.clone();
if new_path.len() > 0 {
new_path.push_str(".")
}
new_path.push_str(extend);
new_path
}
fn recurse_hash<'a, F>(
hash: &'a Hash,
head: &str,
tail: &[String],
path: String,
following_splat: bool,
visited: &mut Vec<VisitedNode<'a>>,
traverse: F,
) where
F: Fn(&'a Yaml, &str, &[String], String, bool, &mut Vec<VisitedNode<'a>>),
{
for (k, v) in hash {
let k_str: String;
match k {
Yaml::String(s) => {
k_str = s.to_string();
}
Yaml::Integer(i) => {
k_str = i.to_string();
}
_ => {
error!("key `{:?}` is not valid, exiting", k);
std::process::exit(1);
}
}
if following_splat {
// traverse deeper, still following a splat
debug!("following splat in map for key: {}, traverse", k_str);
let new_path = extend_hash_path(&path, &k_str);
traverse(v, head, tail, new_path, true, visited);
}
if matches_pattern(&k_str, head) {
debug!("match on key: {}, traverse", &k_str);
let new_path = extend_hash_path(&path, &k_str);
traverse(v, head, tail, new_path, head == SPLAT, visited);
// tail.len() == 0 indicates this is a final path elem
} else if is_child_filter(head) && tail.len() == 0 {
let matches = is_child_filter_value_match(v, unwrap(head)).unwrap_or_else(|err| {
error!("{}", err);
std::process::exit(1);
});
if !matches {
debug!("did not match on key: `{}`, continue", &k_str);
continue;
}
debug!("match on child value filter: `{}`", head);
let new_path = extend_hash_path(&path, &k_str);
traverse(v, head, tail, new_path, false, visited);
} else {
debug!("did not match on key: `{}`, continue", &k_str);
}
}
}
fn extend_array_path(p: &String, idx: usize) -> String {
let mut new_path = p.clone();
new_path.push_str(&format!("[{}]", idx));
new_path
}
// NOTE(wdeuschle): not testing child node filters here (out of scope for recurse_array)
// NOTE(wdeuschle): simplify testability by making `get_array_idx` a param
fn recurse_array<'a, F>(
array: &'a Array,
head: &str,
tail: &[String],
path: String,
following_splat: bool,
visited: &mut Vec<VisitedNode<'a>>,
traverse: F,
) where
F: Fn(&'a Yaml, &str, &[String], String, bool, &mut Vec<VisitedNode<'a>>),
{
if following_splat {
// traverse deeper, still following a splat
debug!(
"following splat in array, traverse all {} indices",
array.len()
);
let array_indices: Vec<usize> = (0..array.len()).collect();
for array_idx in array_indices {
let new_path = extend_array_path(&path, array_idx);
traverse(&array[array_idx], head, tail, new_path, true, visited);
}
}
let array_indices: Vec<usize> = match get_array_idx(
head,
array,
tail.len() == 0,
parse_array_child_filter,
parse_array_indexing_operation,
) {
ArrayIndices::Star => (0..array.len()).collect(),
ArrayIndices::Indices(indices) => {
for i in indices.iter() {
if *i >= array.len() {
debug!("array index {} too large, don't recurse", i);
return;
}
}
indices
}
};
debug!("match on array indices: {:?}, traverse", array_indices);
for array_idx in array_indices {
let new_path = extend_array_path(&path, array_idx);
traverse(
&array[array_idx],
head,
tail,
new_path,
head == SPLAT,
visited,
);
}
}
fn visit<'a>(node: &'a Yaml, tail: &[String], path: String, visited: &mut Vec<VisitedNode<'a>>) {
if tail.len() == 0 {
debug!("tail length is 0, visiting leaf node {:?}", node);
match node {
s @ Yaml::String(_) => {
visited.push(VisitedNode {
yml: s,
path: path.clone(),
});
}
i @ Yaml::Integer(_) => {
visited.push(VisitedNode {
yml: i,
path: path.clone(),
});
}
f @ Yaml::Real(_) => {
visited.push(VisitedNode {
yml: f,
path: path.clone(),
});
}
b @ Yaml::Boolean(_) => {
visited.push(VisitedNode {
yml: b,
path: path.clone(),
});
}
h @ Yaml::Hash(_) => {
visited.push(VisitedNode {
yml: h,
path: path.clone(),
});
}
n @ Yaml::Null => {
visited.push(VisitedNode {
yml: n,
path: path.clone(),
});
}
b @ Yaml::BadValue => {
visited.push(VisitedNode {
yml: b,
path: path.clone(),
});
}
v @ Yaml::Array(_) => {
visited.push(VisitedNode {
yml: v,
path: path.clone(),
});
}
_a @ Yaml::Alias(_) => {
panic!("alias type node yet implemented");
}
}
return;
}
debug!("tail length is not 0, not visiting node {:?}", node);
}
#[cfg(test)]
mod tests {
use super::*;
use yaml_rust::YamlLoader;
#[test]
fn get_array_idx_splat() {
assert_eq!(
ArrayIndices::Star,
get_array_idx(
"**",
&vec![Yaml::Null],
false,
parse_array_child_filter,
parse_array_indexing_operation
)
);
}
#[test]
fn get_array_idx_calls_parse_array_child_filter() {
let ret_val = 1;
assert_eq!(
ArrayIndices::Indices(vec![ret_val]),
get_array_idx(
"(.==crab)",
&vec![Yaml::Null],
false,
|_: &str, _: &Vec<Yaml>, _: bool| Ok(ArrayIndices::Indices(vec![ret_val])),
parse_array_indexing_operation
)
);
}
#[test]
fn get_array_idx_calls_parse_array_indexing_operation() {
let ret_val = 1;
assert_eq!(
ArrayIndices::Indices(vec![ret_val]),
get_array_idx(
"[2]",
&vec![Yaml::Null],
false,
parse_array_child_filter,
|_: &str| Ok(ArrayIndices::Indices(vec![ret_val])),
)
);
}
#[test]
fn get_array_idx_invalid_path_elem() {
assert_eq!(
ArrayIndices::Indices(vec![]),
get_array_idx(
"crabby",
&vec![Yaml::Null],
false,
parse_array_child_filter,
parse_array_indexing_operation
)
);
}
#[test]
fn test_unwrap() {
let s1 = "";
assert_eq!("", unwrap(s1));
let s2 = "(crabby)";
assert_eq!("crabby", unwrap(s2));
let s3 = "[crabby]";
assert_eq!("crabby", unwrap(s3));
}
#[test]
fn test_visit_has_tail() {
let mut visited = Vec::<VisitedNode>::new();
let node = Yaml::String(String::from(""));
visit(
&node,
&[String::from("crab")],
String::from(""),
&mut visited,
);
assert_eq!(visited.len(), 0);
}
#[test]
fn test_visit_tail() {
let mut visited = Vec::<VisitedNode>::new();
assert_eq!(visited.len(), 0);
let node = Yaml::String(String::from("crab"));
visit(
&node,
&[],
String::from(format!("path {}", visited.len())),
&mut visited,
);
assert_eq!(visited.len(), 1);
assert_eq!(visited[visited.len() - 1].yml, &node);
assert_eq!(
visited[visited.len() - 1].path,
format!("path {}", visited.len() - 1)
);
let node = Yaml::Integer(1);
visit(
&node,
&[],
String::from(format!("path {}", visited.len())),
&mut visited,
);
assert_eq!(visited.len(), 2);
assert_eq!(visited[visited.len() - 1].yml, &node);
assert_eq!(
visited[visited.len() - 1].path,
format!("path {}", visited.len() - 1)
);
let node = Yaml::Real(0.01.to_string());
visit(
&node,
&[],
String::from(format!("path {}", visited.len())),
&mut visited,
);
assert_eq!(visited.len(), 3);
assert_eq!(visited[visited.len() - 1].yml, &node);
assert_eq!(
visited[visited.len() - 1].path,
format!("path {}", visited.len() - 1)
);
let node = Yaml::Boolean(true);
visit(
&node,
&[],
String::from(format!("path {}", visited.len())),
&mut visited,
);
assert_eq!(visited.len(), 4);
assert_eq!(visited[visited.len() - 1].yml, &node);
assert_eq!(
visited[visited.len() - 1].path,
format!("path {}", visited.len() - 1)
);
let hash_str = "a: b";
let hash = &YamlLoader::load_from_str(hash_str).unwrap()[0];
match hash {
Yaml::Hash(_) => {}
_ => panic!("invalid, not hash type"),
};
let node = hash;
visit(
&node,
&[],
String::from(format!("path {}", visited.len())),
&mut visited,
);
assert_eq!(visited.len(), 5);
assert_eq!(visited[visited.len() - 1].yml, node);
assert_eq!(
visited[visited.len() - 1].path,
format!("path {}", visited.len() - 1)
);
let array_str = "- a";
let array = &YamlLoader::load_from_str(array_str).unwrap()[0];
match array {
Yaml::Array(_) => {}
_ => panic!("invalid, not array type"),
};
let node = array;
visit(
&node,
&[],
String::from(format!("path {}", visited.len())),
&mut visited,
);
assert_eq!(visited.len(), 6);
assert_eq!(visited[visited.len() - 1].yml, node);
assert_eq!(
visited[visited.len() - 1].path,
format!("path {}", visited.len() - 1)
);
let node = Yaml::Null;
visit(
&node,
&[],
String::from(format!("path {}", visited.len())),
&mut visited,
);
assert_eq!(visited.len(), 7);
assert_eq!(visited[visited.len() - 1].yml, &node);
assert_eq!(
visited[visited.len() - 1].path,
format!("path {}", visited.len() - 1)
);
let node = Yaml::BadValue;
visit(
&node,
&[],
String::from(format!("path {}", visited.len())),
&mut visited,
);
assert_eq!(visited.len(), 8);
assert_eq!(visited[visited.len() - 1].yml, &node);
assert_eq!(
visited[visited.len() - 1].path,
format!("path {}", visited.len() - 1)
);
}
#[test]
fn test_extend_hash_path() {
let no_path = "".to_string();
let existing_path = "existing".to_string();
let extend = "extend";
assert_eq!(extend_hash_path(&no_path, extend), extend);
assert_eq!(
extend_hash_path(&existing_path, extend),
format!("{}.{}", existing_path, extend)
);
}
#[test]
fn test_recurse_hash_handles_integer_keys() {
let hash_str = "0: b";
let hash_yaml = &YamlLoader::load_from_str(hash_str).unwrap()[0];
let hash = match hash_yaml {
Yaml::Hash(h) => h,
_ => panic!("invalid, not hash type"),
};
let head = "";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (true, true);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_hash(
hash,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 1);
assert_eq!(visited[0].yml, &visited_node);
let key = match hash.front().unwrap().0 {
Yaml::Integer(i) => i,
_ => panic!("failed to find hash key"),
};
assert_eq!(visited[0].path, format!("{}.{}", path, key));
}
#[test]
fn test_recurse_hash_splat_no_continue() {
let hash_str = "a: b";
let hash_yaml = &YamlLoader::load_from_str(hash_str).unwrap()[0];
let hash = match hash_yaml {
Yaml::Hash(h) => h,
_ => panic!("invalid, not hash type"),
};
let head = "";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (true, true);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_hash(
hash,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 1);
assert_eq!(visited[0].yml, &visited_node);
let key = match hash.front().unwrap().0 {
Yaml::String(s) => s,
_ => panic!("failed to find hash key"),
};
assert_eq!(visited[0].path, format!("{}.{}", path, key));
}
#[test]
fn test_recurse_hash_splat_continues() {
let hash_str = "a: b";
let hash_yaml = &YamlLoader::load_from_str(hash_str).unwrap()[0];
let hash = match hash_yaml {
Yaml::Hash(h) => h,
_ => panic!("invalid, not hash type"),
};
let head = "a";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat_first, becomes_splat_second) = (true, true, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_hash(
hash,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
if inner_visited.len() == 0 {
assert_eq!(still_splat, becomes_splat_first)
} else {
assert_eq!(still_splat, becomes_splat_second)
}
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 2);
assert_eq!(visited[0].yml, &visited_node);
assert_eq!(visited[1].yml, &visited_node);
let key = match hash.front().unwrap().0 {
Yaml::String(s) => s,
_ => panic!("failed to find hash key"),
};
assert_eq!(visited[0].path, format!("{}.{}", path, key));
assert_eq!(visited[1].path, format!("{}.{}", path, key));
}
#[test]
fn test_recurse_hash_matches_pattern() {
let hash_str = "a: b";
let hash_yaml = &YamlLoader::load_from_str(hash_str).unwrap()[0];
let hash = match hash_yaml {
Yaml::Hash(h) => h,
_ => panic!("invalid, not hash type"),
};
let head = "a";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (false, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_hash(
hash,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 1);
assert_eq!(visited[0].yml, &visited_node);
let key = match hash.front().unwrap().0 {
Yaml::String(s) => s,
_ => panic!("failed to find hash key"),
};
assert_eq!(visited[0].path, format!("{}.{}", path, key));
}
#[test]
fn test_recurse_hash_matches_pattern_and_starts_splat() {
let hash_str = "a: b";
let hash_yaml = &YamlLoader::load_from_str(hash_str).unwrap()[0];
let hash = match hash_yaml {
Yaml::Hash(h) => h,
_ => panic!("invalid, not hash type"),
};
let head = SPLAT;
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (false, true);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_hash(
hash,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 1);
assert_eq!(visited[0].yml, &visited_node);
let key = match hash.front().unwrap().0 {
Yaml::String(s) => s,
_ => panic!("failed to find hash key"),
};
assert_eq!(visited[0].path, format!("{}.{}", path, key));
}
#[test]
fn test_recurse_hash_is_matching_child_filter_with_empty_tail() {
let hash_str = "a: b";
let hash_yaml = &YamlLoader::load_from_str(hash_str).unwrap()[0];
let hash = match hash_yaml {
Yaml::Hash(h) => h,
_ => panic!("invalid, not hash type"),
};
let head = "(.==b)";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (false, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_hash(
hash,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 1);
assert_eq!(visited[0].yml, &visited_node);
let key = match hash.front().unwrap().0 {
Yaml::String(s) => s,
_ => panic!("failed to find hash key"),
};
assert_eq!(visited[0].path, format!("{}.{}", path, key));
}
#[test]
fn test_recurse_hash_is_matching_child_filter_without_empty_tail() {
let hash_str = "a: b";
let hash_yaml = &YamlLoader::load_from_str(hash_str).unwrap()[0];
let hash = match hash_yaml {
Yaml::Hash(h) => h,
_ => panic!("invalid, not hash type"),
};
let head = "(.==b)";
let tail = &["not empty".to_string()];
let path = "start";
let (following_splat, becomes_splat) = (false, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_hash(
hash,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 0);
}
#[test]
fn test_recurse_hash_is_not_matching_child_filter() {
let hash_str = "a: b";
let hash_yaml = &YamlLoader::load_from_str(hash_str).unwrap()[0];
let hash = match hash_yaml {
Yaml::Hash(h) => h,
_ => panic!("invalid, not hash type"),
};
let head = "(.==c)";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (false, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_hash(
hash,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 0);
}
#[test]
fn test_recurse_hash_is_not_matching() {
let hash_str = "a: b";
let hash_yaml = &YamlLoader::load_from_str(hash_str).unwrap()[0];
let hash = match hash_yaml {
Yaml::Hash(h) => h,
_ => panic!("invalid, not hash type"),
};
let head = "b";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (false, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_hash(
hash,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 0);
}
#[test]
fn test_recurse_array_following_splat_no_continue() {
let array_str = "
- a
- b";
let array_yaml = &YamlLoader::load_from_str(array_str).unwrap()[0];
let array = match array_yaml {
Yaml::Array(a) => a,
_ => panic!("invalid, not an array type"),
};
let head = "";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (true, true);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_array(
array,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 2);
assert_eq!(visited[0].yml, &visited_node);
assert_eq!(visited[1].yml, &visited_node);
assert_eq!(visited[0].path, format!("{}[0]", path));
assert_eq!(visited[1].path, format!("{}[1]", path));
}
#[test]
fn test_extend_array_path() {
assert_eq!(extend_array_path(&"path".to_string(), 0), "path[0]");
}
#[test]
fn test_recurse_array_following_splat_continues() {
let array_str = "
- a
- b";
let array_yaml = &YamlLoader::load_from_str(array_str).unwrap()[0];
let array = match array_yaml {
Yaml::Array(a) => a,
_ => panic!("invalid, not an array type"),
};
let head = SPLAT;
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (true, true);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_array(
array,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 4);
assert_eq!(visited[0].yml, &visited_node);
assert_eq!(visited[1].yml, &visited_node);
assert_eq!(visited[2].yml, &visited_node);
assert_eq!(visited[3].yml, &visited_node);
assert_eq!(visited[0].path, format!("{}[0]", path));
assert_eq!(visited[1].path, format!("{}[1]", path));
// note that these are repeated paths because the splat continues to match
assert_eq!(visited[2].path, format!("{}[0]", path));
assert_eq!(visited[3].path, format!("{}[1]", path));
}
#[test]
fn test_recurse_array_matching_splat() {
let array_str = "
- a
- b";
let array_yaml = &YamlLoader::load_from_str(array_str).unwrap()[0];
let array = match array_yaml {
Yaml::Array(a) => a,
_ => panic!("invalid, not an array type"),
};
let head = SPLAT;
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (false, true);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_array(
array,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 2);
assert_eq!(visited[0].yml, &visited_node);
assert_eq!(visited[1].yml, &visited_node);
assert_eq!(visited[0].path, format!("{}[0]", path));
assert_eq!(visited[1].path, format!("{}[1]", path));
}
#[test]
fn test_recurse_array_following_splat_continues_on_sub_match() {
let array_str = "
- a
- b";
let array_yaml = &YamlLoader::load_from_str(array_str).unwrap()[0];
let array = match array_yaml {
Yaml::Array(a) => a,
_ => panic!("invalid, not an array type"),
};
let head = "[1]";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat_first, becomes_splat_second) = (true, true, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_array(
array,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
if inner_visited.len() < array.len() {
assert_eq!(still_splat, becomes_splat_first);
} else {
assert_eq!(still_splat, becomes_splat_second);
}
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 3);
assert_eq!(visited[0].yml, &visited_node);
assert_eq!(visited[1].yml, &visited_node);
assert_eq!(visited[2].yml, &visited_node);
assert_eq!(visited[0].path, format!("{}[0]", path));
assert_eq!(visited[1].path, format!("{}[1]", path));
// note that this is a repeated paths because the splat continues to match
assert_eq!(visited[2].path, format!("{}[1]", path));
}
#[test]
fn test_recurse_array_match_all() {
let array_str = "
- a
- b";
let array_yaml = &YamlLoader::load_from_str(array_str).unwrap()[0];
let array = match array_yaml {
Yaml::Array(a) => a,
_ => panic!("invalid, not an array type"),
};
let head = "[*]";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (false, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_array(
array,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 2);
assert_eq!(visited[0].yml, &visited_node);
assert_eq!(visited[1].yml, &visited_node);
assert_eq!(visited[0].path, format!("{}[0]", path));
assert_eq!(visited[1].path, format!("{}[1]", path));
}
#[test]
fn test_recurse_array_match_one() {
let array_str = "
- a
- b";
let array_yaml = &YamlLoader::load_from_str(array_str).unwrap()[0];
let array = match array_yaml {
Yaml::Array(a) => a,
_ => panic!("invalid, not an array type"),
};
let head = "[1]";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (false, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_array(
array,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 1);
assert_eq!(visited[0].yml, &visited_node);
assert_eq!(visited[0].path, format!("{}[1]", path));
}
#[test]
fn test_recurse_array_match_none_idx_too_large() {
let array_str = "
- a
- b";
let array_yaml = &YamlLoader::load_from_str(array_str).unwrap()[0];
let array = match array_yaml {
Yaml::Array(a) => a,
_ => panic!("invalid, not an array type"),
};
let head = "[2]";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (false, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_array(
array,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 0);
}
#[test]
fn test_recurse_array_partially_matching_child_value_filter() {
let array_str = "
- crab
- bear
- crabby";
let array_yaml = &YamlLoader::load_from_str(array_str).unwrap()[0];
let array = match array_yaml {
Yaml::Array(a) => a,
_ => panic!("invalid, not an array type"),
};
let head = "(.==crab*)";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (false, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_array(
array,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 2);
assert_eq!(visited[0].yml, &visited_node);
assert_eq!(visited[1].yml, &visited_node);
assert_eq!(visited[0].path, format!("{}[0]", path));
assert_eq!(visited[1].path, format!("{}[2]", path));
}
#[test]
fn test_recurse_array_no_matching_child_value_filter() {
let array_str = "
- crab
- crabby";
let array_yaml = &YamlLoader::load_from_str(array_str).unwrap()[0];
let array = match array_yaml {
Yaml::Array(a) => a,
_ => panic!("invalid, not an array type"),
};
let head = "(.==bear*)";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (false, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_array(
array,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 0);
}
#[test]
fn test_recurse_array_star_matching_child_value_filter() {
let array_str = "
- crab
- crabby";
let array_yaml = &YamlLoader::load_from_str(array_str).unwrap()[0];
let array = match array_yaml {
Yaml::Array(a) => a,
_ => panic!("invalid, not an array type"),
};
let head = "(.==*)";
let tail = &[];
let path = "start";
let (following_splat, becomes_splat) = (false, false);
let mut visited = Vec::<VisitedNode>::new();
let visited_node = Yaml::String("test".to_string());
recurse_array(
array,
head,
tail,
String::from(path),
following_splat,
&mut visited,
|_: &Yaml,
_: &str,
_: &[String],
path: String,
still_splat: bool,
inner_visited: &mut Vec<VisitedNode>| {
assert_eq!(still_splat, becomes_splat);
inner_visited.push(VisitedNode {
yml: &visited_node,
path,
});
},
);
assert_eq!(visited.len(), 2);
assert_eq!(visited[0].yml, &visited_node);
assert_eq!(visited[1].yml, &visited_node);
assert_eq!(visited[0].path, format!("{}[0]", path));
assert_eq!(visited[1].path, format!("{}[1]", path));
}
}
|
pub struct Stack<T> {
elements: Vec<T>,
}
impl<T> Stack<T> {
pub fn with_capacity(capacity: usize) -> Self {
Self {
elements: Vec::with_capacity(capacity),
}
}
pub fn capacity(&self) -> usize {
return self.elements.capacity();
}
pub fn len(&self) -> usize {
return self.elements.len();
}
pub fn top(&self) -> Option<&T> {
return self.elements.last();
}
pub fn push(&mut self, element: T) {
self.elements.push(element);
}
pub fn pop(&mut self) -> Option<T> {
return self.elements.pop();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_stack_can_be_instantiated_with_capacity_0() {
let a_zero_capacity_stack = Stack::<String>::with_capacity(0);
assert_eq!(0, a_zero_capacity_stack.capacity());
}
#[test]
fn test_stack_can_be_instantiated_with_string_type() {
let a_stack = Stack::<String>::with_capacity(1);
assert_eq!(1, a_stack.capacity());
}
#[test]
fn test_stack_can_be_instantiated_with_i32_type() {
let a_stack = Stack::<i32>::with_capacity(13);
assert_eq!(13, a_stack.capacity());
}
#[test]
fn test_top_on_zero_capacity_stack_returns_none() {
let a_stack = Stack::<i32>::with_capacity(0);
assert_eq!(None, a_stack.top());
}
#[test]
fn test_top_on_empty_stack_returns_none() {
let a_stack = Stack::<i32>::with_capacity(1);
assert_eq!(None, a_stack.top());
}
#[test]
fn test_len_on_zero_capacity_stack_returns_zero() {
let a_zero_capacity_stack = Stack::<i32>::with_capacity(0);
assert_eq!(0, a_zero_capacity_stack.len());
}
#[test]
fn test_len_on_empty_stack_returns_zero() {
let a_stack = Stack::<i32>::with_capacity(1);
assert_eq!(0, a_stack.len());
}
#[test]
fn test_push_can_be_called_on_empty_stack() {
let mut a_stack = Stack::<i32>::with_capacity(0);
a_stack.push(0);
assert_eq!(1, a_stack.len());
}
#[test]
fn test_push_can_be_called_on_stack() {
let mut a_stack = Stack::<i32>::with_capacity(1);
a_stack.push(0);
assert_eq!(1, a_stack.len());
}
#[test]
fn test_more_pushes_than_capacity_can_be_called_on_stack() {
let mut a_stack = Stack::<i32>::with_capacity(1);
a_stack.push(0);
a_stack.push(1);
assert_eq!(2, a_stack.len());
}
#[test]
fn test_top_on_non_empty_stack_returns_last_inserted_element() {
let mut a_stack = Stack::<i32>::with_capacity(2);
a_stack.push(321);
a_stack.push(123);
assert_eq!(2, a_stack.len());
assert_eq!(Some(&123), a_stack.top());
}
#[test]
fn test_pop_on_zero_capacity_stack_returns_none() {
let mut a_stack = Stack::<i32>::with_capacity(0);
assert_eq!(None, a_stack.pop());
}
#[test]
fn test_pop_on_a_stack_returns_last_inserted_element() {
let mut a_stack = Stack::<i32>::with_capacity(2);
a_stack.push(321);
a_stack.push(123);
assert_eq!(Some(123), a_stack.pop());
assert_eq!(1, a_stack.len());
}
}
|
/*!
Column oriented field storage for tantivy.
It is the equivalent of `Lucene`'s `DocValues`.
Fast fields is a column-oriented fashion storage of `tantivy`.
It is designed for the fast random access of some document
fields given a document id.
`FastField` are useful when a field is required for all or most of
the `DocSet` : for instance for scoring, grouping, filtering, or faceting.
Fields have to be declared as `FAST` in the schema.
Currently only 64-bits integers (signed or unsigned) are
supported.
They are stored in a bit-packed fashion so that their
memory usage is directly linear with the amplitude of the
values stored.
Read access performance is comparable to that of an array lookup.
*/
pub use self::bytes::{BytesFastFieldReader, BytesFastFieldWriter};
pub use self::delete::write_delete_bitset;
pub use self::delete::DeleteBitSet;
pub use self::error::{FastFieldNotAvailableError, Result};
pub use self::facet_reader::FacetReader;
pub use self::multivalued::{MultiValueIntFastFieldReader, MultiValueIntFastFieldWriter};
pub use self::reader::FastFieldReader;
pub use self::serializer::FastFieldSerializer;
pub use self::writer::{FastFieldsWriter, IntFastFieldWriter};
use common;
use schema::Cardinality;
use schema::FieldType;
use schema::Value;
mod bytes;
mod delete;
mod error;
mod facet_reader;
mod multivalued;
mod reader;
mod serializer;
mod writer;
/// Trait for types that are allowed for fast fields: (u64 or i64).
pub trait FastValue: Default + Clone + Copy {
/// Converts a value from u64
///
/// Internally all fast field values are encoded as u64.
fn from_u64(val: u64) -> Self;
/// Converts a value to u64.
///
/// Internally all fast field values are encoded as u64.
fn to_u64(&self) -> u64;
/// Returns the fast field cardinality that can be extracted from the given
/// `FieldType`.
///
/// If the type is not a fast field, `None` is returned.
fn fast_field_cardinality(field_type: &FieldType) -> Option<Cardinality>;
/// Cast value to `u64`.
/// The value is just reinterpreted in memory.
fn as_u64(&self) -> u64;
}
impl FastValue for u64 {
fn from_u64(val: u64) -> Self {
val
}
fn to_u64(&self) -> u64 {
*self
}
fn as_u64(&self) -> u64 {
*self
}
fn fast_field_cardinality(field_type: &FieldType) -> Option<Cardinality> {
match *field_type {
FieldType::U64(ref integer_options) => integer_options.get_fastfield_cardinality(),
FieldType::HierarchicalFacet => Some(Cardinality::MultiValues),
_ => None,
}
}
}
impl FastValue for i64 {
fn from_u64(val: u64) -> Self {
common::u64_to_i64(val)
}
fn to_u64(&self) -> u64 {
common::i64_to_u64(*self)
}
fn fast_field_cardinality(field_type: &FieldType) -> Option<Cardinality> {
match *field_type {
FieldType::I64(ref integer_options) => integer_options.get_fastfield_cardinality(),
_ => None,
}
}
fn as_u64(&self) -> u64 {
*self as u64
}
}
fn value_to_u64(value: &Value) -> u64 {
match *value {
Value::U64(ref val) => *val,
Value::I64(ref val) => common::i64_to_u64(*val),
_ => panic!("Expected a u64/i64 field, got {:?} ", value),
}
}
#[cfg(test)]
mod tests {
use super::*;
use common::CompositeFile;
use directory::{Directory, RAMDirectory, WritePtr};
use fastfield::FastFieldReader;
use rand::Rng;
use rand::SeedableRng;
use rand::XorShiftRng;
use schema::Document;
use schema::Field;
use schema::FAST;
use schema::{Schema, SchemaBuilder};
use std::collections::HashMap;
use std::path::Path;
lazy_static! {
pub static ref SCHEMA: Schema = {
let mut schema_builder = SchemaBuilder::default();
schema_builder.add_u64_field("field", FAST);
schema_builder.build()
};
pub static ref FIELD: Field = { SCHEMA.get_field("field").unwrap() };
}
#[test]
pub fn test_fastfield() {
let test_fastfield = FastFieldReader::<u64>::from(vec![100, 200, 300]);
assert_eq!(test_fastfield.get(0), 100);
assert_eq!(test_fastfield.get(1), 200);
assert_eq!(test_fastfield.get(2), 300);
}
#[test]
fn test_intfastfield_small() {
let path = Path::new("test");
let mut directory: RAMDirectory = RAMDirectory::create();
{
let write: WritePtr = directory.open_write(Path::new("test")).unwrap();
let mut serializer = FastFieldSerializer::from_write(write).unwrap();
let mut fast_field_writers = FastFieldsWriter::from_schema(&SCHEMA);
fast_field_writers.add_document(&doc!(*FIELD=>13u64));
fast_field_writers.add_document(&doc!(*FIELD=>14u64));
fast_field_writers.add_document(&doc!(*FIELD=>2u64));
fast_field_writers
.serialize(&mut serializer, &HashMap::new())
.unwrap();
serializer.close().unwrap();
}
let source = directory.open_read(&path).unwrap();
{
assert_eq!(source.len(), 36 as usize);
}
{
let composite_file = CompositeFile::open(&source).unwrap();
let field_source = composite_file.open_read(*FIELD).unwrap();
let fast_field_reader = FastFieldReader::<u64>::open(field_source);
assert_eq!(fast_field_reader.get(0), 13u64);
assert_eq!(fast_field_reader.get(1), 14u64);
assert_eq!(fast_field_reader.get(2), 2u64);
}
}
#[test]
fn test_intfastfield_large() {
let path = Path::new("test");
let mut directory: RAMDirectory = RAMDirectory::create();
{
let write: WritePtr = directory.open_write(Path::new("test")).unwrap();
let mut serializer = FastFieldSerializer::from_write(write).unwrap();
let mut fast_field_writers = FastFieldsWriter::from_schema(&SCHEMA);
fast_field_writers.add_document(&doc!(*FIELD=>4u64));
fast_field_writers.add_document(&doc!(*FIELD=>14_082_001u64));
fast_field_writers.add_document(&doc!(*FIELD=>3_052u64));
fast_field_writers.add_document(&doc!(*FIELD=>9_002u64));
fast_field_writers.add_document(&doc!(*FIELD=>15_001u64));
fast_field_writers.add_document(&doc!(*FIELD=>777u64));
fast_field_writers.add_document(&doc!(*FIELD=>1_002u64));
fast_field_writers.add_document(&doc!(*FIELD=>1_501u64));
fast_field_writers.add_document(&doc!(*FIELD=>215u64));
fast_field_writers
.serialize(&mut serializer, &HashMap::new())
.unwrap();
serializer.close().unwrap();
}
let source = directory.open_read(&path).unwrap();
{
assert_eq!(source.len(), 61 as usize);
}
{
let fast_fields_composite = CompositeFile::open(&source).unwrap();
let data = fast_fields_composite.open_read(*FIELD).unwrap();
let fast_field_reader = FastFieldReader::<u64>::open(data);
assert_eq!(fast_field_reader.get(0), 4u64);
assert_eq!(fast_field_reader.get(1), 14_082_001u64);
assert_eq!(fast_field_reader.get(2), 3_052u64);
assert_eq!(fast_field_reader.get(3), 9002u64);
assert_eq!(fast_field_reader.get(4), 15_001u64);
assert_eq!(fast_field_reader.get(5), 777u64);
assert_eq!(fast_field_reader.get(6), 1_002u64);
assert_eq!(fast_field_reader.get(7), 1_501u64);
assert_eq!(fast_field_reader.get(8), 215u64);
}
}
#[test]
fn test_intfastfield_null_amplitude() {
let path = Path::new("test");
let mut directory: RAMDirectory = RAMDirectory::create();
{
let write: WritePtr = directory.open_write(Path::new("test")).unwrap();
let mut serializer = FastFieldSerializer::from_write(write).unwrap();
let mut fast_field_writers = FastFieldsWriter::from_schema(&SCHEMA);
for _ in 0..10_000 {
fast_field_writers.add_document(&doc!(*FIELD=>100_000u64));
}
fast_field_writers
.serialize(&mut serializer, &HashMap::new())
.unwrap();
serializer.close().unwrap();
}
let source = directory.open_read(&path).unwrap();
{
assert_eq!(source.len(), 34 as usize);
}
{
let fast_fields_composite = CompositeFile::open(&source).unwrap();
let data = fast_fields_composite.open_read(*FIELD).unwrap();
let fast_field_reader = FastFieldReader::<u64>::open(data);
for doc in 0..10_000 {
assert_eq!(fast_field_reader.get(doc), 100_000u64);
}
}
}
#[test]
fn test_intfastfield_large_numbers() {
let path = Path::new("test");
let mut directory: RAMDirectory = RAMDirectory::create();
{
let write: WritePtr = directory.open_write(Path::new("test")).unwrap();
let mut serializer = FastFieldSerializer::from_write(write).unwrap();
let mut fast_field_writers = FastFieldsWriter::from_schema(&SCHEMA);
// forcing the amplitude to be high
fast_field_writers.add_document(&doc!(*FIELD=>0u64));
for i in 0u64..10_000u64 {
fast_field_writers.add_document(&doc!(*FIELD=>5_000_000_000_000_000_000u64 + i));
}
fast_field_writers
.serialize(&mut serializer, &HashMap::new())
.unwrap();
serializer.close().unwrap();
}
let source = directory.open_read(&path).unwrap();
{
assert_eq!(source.len(), 80042 as usize);
}
{
let fast_fields_composite = CompositeFile::open(&source).unwrap();
let data = fast_fields_composite.open_read(*FIELD).unwrap();
let fast_field_reader = FastFieldReader::<u64>::open(data);
assert_eq!(fast_field_reader.get(0), 0u64);
for doc in 1..10_001 {
assert_eq!(
fast_field_reader.get(doc),
5_000_000_000_000_000_000u64 + doc as u64 - 1u64
);
}
}
}
#[test]
fn test_signed_intfastfield() {
let path = Path::new("test");
let mut directory: RAMDirectory = RAMDirectory::create();
let mut schema_builder = SchemaBuilder::new();
let i64_field = schema_builder.add_i64_field("field", FAST);
let schema = schema_builder.build();
{
let write: WritePtr = directory.open_write(Path::new("test")).unwrap();
let mut serializer = FastFieldSerializer::from_write(write).unwrap();
let mut fast_field_writers = FastFieldsWriter::from_schema(&schema);
for i in -100i64..10_000i64 {
let mut doc = Document::default();
doc.add_i64(i64_field, i);
fast_field_writers.add_document(&doc);
}
fast_field_writers
.serialize(&mut serializer, &HashMap::new())
.unwrap();
serializer.close().unwrap();
}
let source = directory.open_read(&path).unwrap();
{
assert_eq!(source.len(), 17709 as usize);
}
{
let fast_fields_composite = CompositeFile::open(&source).unwrap();
let data = fast_fields_composite.open_read(i64_field).unwrap();
let fast_field_reader = FastFieldReader::<i64>::open(data);
assert_eq!(fast_field_reader.min_value(), -100i64);
assert_eq!(fast_field_reader.max_value(), 9_999i64);
for (doc, i) in (-100i64..10_000i64).enumerate() {
assert_eq!(fast_field_reader.get(doc as u32), i);
}
let mut buffer = vec![0i64; 100];
fast_field_reader.get_range(53, &mut buffer[..]);
for i in 0..100 {
assert_eq!(buffer[i], -100i64 + 53i64 + i as i64);
}
}
}
#[test]
fn test_signed_intfastfield_default_val() {
let path = Path::new("test");
let mut directory: RAMDirectory = RAMDirectory::create();
let mut schema_builder = SchemaBuilder::new();
let i64_field = schema_builder.add_i64_field("field", FAST);
let schema = schema_builder.build();
{
let write: WritePtr = directory.open_write(Path::new("test")).unwrap();
let mut serializer = FastFieldSerializer::from_write(write).unwrap();
let mut fast_field_writers = FastFieldsWriter::from_schema(&schema);
let doc = Document::default();
fast_field_writers.add_document(&doc);
fast_field_writers
.serialize(&mut serializer, &HashMap::new())
.unwrap();
serializer.close().unwrap();
}
let source = directory.open_read(&path).unwrap();
{
let fast_fields_composite = CompositeFile::open(&source).unwrap();
let data = fast_fields_composite.open_read(i64_field).unwrap();
let fast_field_reader = FastFieldReader::<i64>::open(data);
assert_eq!(fast_field_reader.get(0u32), 0i64);
}
}
pub fn generate_permutation() -> Vec<u64> {
let seed: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let mut rng = XorShiftRng::from_seed(seed);
let mut permutation: Vec<u64> = (0u64..1_000_000u64).collect();
rng.shuffle(&mut permutation);
permutation
}
#[test]
fn test_intfastfield_permutation() {
let path = Path::new("test");
let permutation = generate_permutation();
let n = permutation.len();
let mut directory = RAMDirectory::create();
{
let write: WritePtr = directory.open_write(Path::new("test")).unwrap();
let mut serializer = FastFieldSerializer::from_write(write).unwrap();
let mut fast_field_writers = FastFieldsWriter::from_schema(&SCHEMA);
for &x in &permutation {
fast_field_writers.add_document(&doc!(*FIELD=>x));
}
fast_field_writers
.serialize(&mut serializer, &HashMap::new())
.unwrap();
serializer.close().unwrap();
}
let source = directory.open_read(&path).unwrap();
{
let fast_fields_composite = CompositeFile::open(&source).unwrap();
let data = fast_fields_composite.open_read(*FIELD).unwrap();
let fast_field_reader = FastFieldReader::<u64>::open(data);
let mut a = 0u64;
for _ in 0..n {
assert_eq!(fast_field_reader.get(a as u32), permutation[a as usize]);
a = fast_field_reader.get(a as u32);
}
}
}
}
#[cfg(all(test, feature = "unstable"))]
mod bench {
use super::tests::FIELD;
use super::tests::{generate_permutation, SCHEMA};
use super::*;
use common::CompositeFile;
use directory::{Directory, RAMDirectory, WritePtr};
use fastfield::FastFieldReader;
use std::collections::HashMap;
use std::path::Path;
use test::{self, Bencher};
#[bench]
fn bench_intfastfield_linear_veclookup(b: &mut Bencher) {
let permutation = generate_permutation();
b.iter(|| {
let n = test::black_box(7000u32);
let mut a = 0u64;
for i in (0u32..n / 7).map(|v| v * 7) {
a ^= permutation[i as usize];
}
a
});
}
#[bench]
fn bench_intfastfield_veclookup(b: &mut Bencher) {
let permutation = generate_permutation();
b.iter(|| {
let n = test::black_box(1000u32);
let mut a = 0u64;
for _ in 0u32..n {
a = permutation[a as usize];
}
a
});
}
#[bench]
fn bench_intfastfield_linear_fflookup(b: &mut Bencher) {
let path = Path::new("test");
let permutation = generate_permutation();
let mut directory: RAMDirectory = RAMDirectory::create();
{
let write: WritePtr = directory.open_write(Path::new("test")).unwrap();
let mut serializer = FastFieldSerializer::from_write(write).unwrap();
let mut fast_field_writers = FastFieldsWriter::from_schema(&SCHEMA);
for &x in &permutation {
fast_field_writers.add_document(&doc!(*FIELD=>x));
}
fast_field_writers
.serialize(&mut serializer, &HashMap::new())
.unwrap();
serializer.close().unwrap();
}
let source = directory.open_read(&path).unwrap();
{
let fast_fields_composite = CompositeFile::open(&source).unwrap();
let data = fast_fields_composite.open_read(*FIELD).unwrap();
let fast_field_reader = FastFieldReader::<u64>::open(data);
b.iter(|| {
let n = test::black_box(7000u32);
let mut a = 0u64;
for i in (0u32..n / 7).map(|val| val * 7) {
a ^= fast_field_reader.get(i);
}
a
});
}
}
#[bench]
fn bench_intfastfield_fflookup(b: &mut Bencher) {
let path = Path::new("test");
let permutation = generate_permutation();
let mut directory: RAMDirectory = RAMDirectory::create();
{
let write: WritePtr = directory.open_write(Path::new("test")).unwrap();
let mut serializer = FastFieldSerializer::from_write(write).unwrap();
let mut fast_field_writers = FastFieldsWriter::from_schema(&SCHEMA);
for &x in &permutation {
fast_field_writers.add_document(&doc!(*FIELD=>x));
}
fast_field_writers
.serialize(&mut serializer, &HashMap::new())
.unwrap();
serializer.close().unwrap();
}
let source = directory.open_read(&path).unwrap();
{
let fast_fields_composite = CompositeFile::open(&source).unwrap();
let data = fast_fields_composite.open_read(*FIELD).unwrap();
let fast_field_reader = FastFieldReader::<u64>::open(data);
b.iter(|| {
let n = test::black_box(1000u32);
let mut a = 0u32;
for _ in 0u32..n {
a = fast_field_reader.get(a) as u32;
}
a
});
}
}
}
|
pub mod message;
pub mod types;
|
use std::{
fs,
io::{self, Read, Seek},
};
use terminal::util::Point;
/// Returns an iterator over the points from `start_point` to `end_point`.
pub fn get_line_points(start_point: Point, end_point: Point) -> impl Iterator<Item = Point> {
line_drawing::Bresenham::new(
(start_point.x as i16, start_point.y as i16),
(end_point.x as i16, end_point.y as i16),
)
.map(|(x, y)| Point {
x: x as u16,
y: y as u16,
})
}
/// Checks whether `str` is a number consisting of ASCII digits, regardless of the length, negative or not.
///
/// Note that an empty string returns `true`.
///
/// ```
/// assert!(is_numeric("---123"));
/// assert!(is_numeric("-123456789012345678901234567890"));
/// assert!(is_numeric("123"));
/// assert!(is_numeric("0"));
///
/// assert!(!is_numeric("---123-"));
/// assert!(!is_numeric("hello"));
/// assert!(!is_numeric(" "));
/// assert!(!is_numeric("-"));
/// ```
pub fn is_numeric(str: &str) -> bool {
let mut digit_encountered = false;
str.chars().all(|char| {
if char.is_ascii_digit() {
digit_encountered = true;
true
} else {
char == '-' && !digit_encountered
}
}) && digit_encountered
}
/// Returns the optimal string capacity based on the file's length.
pub fn optimal_string_capacity(file: &fs::File) -> io::Result<usize> {
Ok(file.metadata()?.len() as usize + 1)
}
/// Reads the file's content into a string.
pub fn read_file_content(file: &mut fs::File) -> io::Result<String> {
let mut string = String::with_capacity(optimal_string_capacity(&file)?);
file.read_to_string(&mut string)?;
Ok(string)
}
/// Erases all of the writer's file's contents.
pub fn clear_file(writer: &mut io::BufWriter<fs::File>) -> Result<(), &'static str> {
fn inner(writer: &mut io::BufWriter<fs::File>) -> io::Result<()> {
// Truncate the underlying file to zero bytes
writer.get_ref().set_len(0)?;
// `set_len` leaves the cursor unchanged.
// Set the cursor to the start.
writer.seek(io::SeekFrom::Start(0))?;
Ok(())
}
match inner(writer) {
Ok(()) => Ok(()),
Err(_) => Err("File clear failed"),
}
}
|
use crate::tool::Tool;
use clap::arg_enum;
use std::path::PathBuf;
use structopt::StructOpt;
use thiserror::Error;
#[derive(Error, Debug)]
/// Error types for vulkan devices
pub enum ConfigError {
#[error("stepover must be between 1 and 100")]
StepOver,
#[error("angle must be between 1 and 180")]
Angle,
#[error("resolution must be between 0.001 and 1.0")]
Resolution,
#[error("Not a decimal number")]
ParseFloat(#[from] std::num::ParseFloatError),
#[error("Error parsing config")]
Clap(#[from] clap::Error),
}
arg_enum! {
#[derive(Debug)]
pub enum ToolType {
Endmill,
VBit,
Ball
}
}
impl ToolType {
pub fn create(&self, radius: f32, angle: Option<f32>, scale: f32) -> Tool {
match self {
ToolType::Endmill => Tool::new_endmill(radius, scale),
ToolType::VBit => Tool::new_v_bit(radius, angle.expect("V-Bit requires tool angle"), scale),
ToolType::Ball => Tool::new_ball(radius, scale),
}
}
}
fn parse_stepover(src: &str) -> Result<f32, ConfigError> {
let stepover = src.parse::<f32>()?;
if (1. ..=100.).contains(&stepover) {
Ok(stepover)
} else {
Err(ConfigError::StepOver)
}
}
fn parse_angle(src: &str) -> Result<f32, ConfigError> {
let angle = src.parse::<f32>()?;
if (1. ..=180.).contains(&angle) {
Ok(angle)
} else {
Err(ConfigError::Angle)
}
}
fn parse_resolution(src: &str) -> Result<f32, ConfigError> {
let resolution = src.parse::<f32>()?;
if (0.001..=1.).contains(&resolution) {
Ok(resolution)
} else {
Err(ConfigError::Resolution)
}
}
// set up program arguments
#[derive(Debug, StructOpt)]
#[structopt(name = "printer_geo")]
pub struct Opt {
#[structopt(short, long, parse(from_os_str))]
pub input: PathBuf,
#[structopt(short, long, parse(from_os_str))]
pub output: PathBuf,
#[structopt(long, parse(from_os_str))]
pub heightmap: Option<PathBuf>,
#[structopt(long, parse(from_os_str))]
pub restmap: Option<PathBuf>,
#[structopt(short, long)]
pub diameter: Option<f32>,
#[structopt(long)]
pub debug: bool,
#[structopt(short, long, required_if("tool", "vbit"), parse(try_from_str = parse_angle))]
pub angle: Option<f32>,
#[structopt(long, default_value="90", parse(try_from_str = parse_stepover))]
pub stepover: f32,
#[structopt(short, long, default_value="0.05", parse(try_from_str = parse_resolution))]
pub resolution: f32,
#[structopt(short, long, default_value = "340282300000000000000000000000000000000")]
pub stepdown: f32,
#[structopt(short, long, possible_values = &ToolType::variants(), default_value="endmill", case_insensitive = true)]
pub tool: ToolType,
#[structopt(long, parse(from_os_str))]
pub toolfile: Option<PathBuf>,
#[structopt(long)]
pub tooltable: Option<usize>,
#[structopt(long)]
pub toolnumber: Option<usize>,
#[structopt(long)]
pub speed: f32,
#[structopt(long)]
pub feedrate: f32,
}
|
pub mod alternative;
pub mod application;
pub mod assignment;
pub mod boxes;
pub mod closure;
pub mod constant;
pub mod definition;
pub mod expression;
pub mod fixlet;
pub mod function;
pub mod import;
pub mod keyword;
pub mod let_continuation;
pub mod library;
pub mod noop;
pub mod program;
pub mod reference;
pub mod sequence;
pub mod variable;
pub use alternative::Alternative;
pub use application::Application;
pub use assignment::{Assignment, GlobalAssignment, LocalAssignment};
pub use boxes::{BoxCreate, BoxRead, BoxWrite};
pub use closure::FlatClosure;
pub use constant::Constant;
pub use expression::Expression;
pub use fixlet::FixLet;
pub use function::Function;
pub use import::{Import, ImportItem, ImportSet};
pub use keyword::{MagicKeyword, MagicKeywordHandler};
pub use let_continuation::{LetContKind, LetContinuation};
pub use library::{Library, LibraryDeclaration, LibraryExport};
pub use noop::NoOp;
pub use program::Program;
pub use reference::{FreeReference, GlobalReference, LocalReference, Reference};
pub use sequence::Sequence;
pub use variable::{FreeVariable, GlobalVariable, LocalVariable, Variable};
use crate::scm::Scm;
pub trait Reify {
fn reify(&self) -> Scm;
}
|
use serde::{Deserialize, Serialize};
//TODO: 'typing.rs' is deprecated and should be replaced by 'thick_triple.rs'
//the difference is
//1. structs for 'Members' and 'DistinctMembers'
//2. encoding of 'Objects' (requiring 'datatype' key)
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
// RDF
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct RDFList {
//#[serde(rename = "rdf:type")]
//pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "rdf:first")]
pub rdf_first: Vec<Object>,
#[serde(rename = "rdf:rest")]
pub rdf_rest: Vec<Object>,
}
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
// Restrictions
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct SomeValuesFrom {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:onProperty")]
pub owl_on_property: Vec<Object>,
#[serde(rename = "owl:someValuesFrom")]
pub owl_some_values_from: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct AllValuesFrom {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:onProperty")]
pub owl_on_property: Vec<Object>,
#[serde(rename = "owl:allValuesFrom")]
pub owl_all_values_from: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct HasValue {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:onProperty")]
pub owl_on_property: Vec<Object>,
#[serde(rename = "owl:hasValue")]
pub owl_has_value: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct MinCardinality {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:onProperty")]
pub owl_on_property: Vec<Object>,
#[serde(rename = "owl:minCardinality")]
pub owl_min_cardinality: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct MinQualifiedCardinality {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:onProperty")]
pub owl_on_property: Vec<Object>,
#[serde(rename = "owl:minQualifiedCardinality")]
pub owl_min_qualified_cardinality: Vec<Object>,
#[serde(rename = "owl:onClass")]
pub owl_on_class: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct MaxCardinality {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:onProperty")]
pub owl_on_property: Vec<Object>,
#[serde(rename = "owl:maxCardinality")]
pub owl_max_cardinality: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct MaxQualifiedCardinality {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:onProperty")]
pub owl_on_property: Vec<Object>,
#[serde(rename = "owl:maxQualifiedCardinality")]
pub owl_max_qualified_cardinality: Vec<Object>,
#[serde(rename = "owl:onClass")]
pub owl_on_class: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct ExactCardinality {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:onProperty")]
pub owl_on_property: Vec<Object>,
#[serde(rename = "owl:cardinality")]
pub owl_cardinality: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct ExactQualifiedCardinality {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:onProperty")]
pub owl_on_property: Vec<Object>,
#[serde(rename = "owl:qualifiedCardinality")]
pub owl_qualified_cardinality: Vec<Object>,
#[serde(rename = "owl:onClass")]
pub owl_on_class: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct HasSelf {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:onProperty")]
pub owl_on_property: Vec<Object>,
#[serde(rename = "owl:hasSelf")]
pub owl_has_self: Vec<Object>,
}
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
// OWL propositional connectives
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct IntersectionOf {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:intersectionOf")]
pub owl_intersection_of: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct UnionOf {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:unionOf")]
pub owl_union_of: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct OneOf {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:oneOf")]
pub owl_one_of: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct ComplementOf {
#[serde(rename = "rdf:type")]
pub rdf_type: Option<Vec<Object>>,
#[serde(rename = "owl:complementOf")]
pub owl_complement_of: Vec<Object>,
}
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
// OWL Object Properties
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct InverseOf {
#[serde(rename = "owl:inverseOf")]
pub owl_inverse_of: Vec<Object>,
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct Object {
pub object: OWL
}
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
#[serde(untagged)]
pub enum OWL {
Named(String),
//Number(i64), //TODO type numbers for cardinality restrictions ?
SomeValuesFrom(SomeValuesFrom),
AllValuesFrom(AllValuesFrom),
HasValue(HasValue),
HasSelf(HasSelf),
MinCardinality(MinCardinality),
MinQualifiedCardinality(MinQualifiedCardinality),
MaxCardinality(MaxCardinality),
MaxQualifiedCardinality(MaxQualifiedCardinality),
ExactCardinality(ExactCardinality),
ExactQualifiedCardinality(ExactQualifiedCardinality),
IntersectionOf(IntersectionOf),
UnionOf(UnionOf),
OneOf(OneOf),
ComplementOf(ComplementOf),
InverseOf(InverseOf),
RDFList(RDFList),
}
|
use std::collections::{HashSet, VecDeque};
use crate::util::lines_from_file;
pub fn day9() {
println!("== Day 9 ==");
let input = lines_from_file("src/day9/input.txt");
let a = part_a(&input);
println!("Part A: {}", a);
let b = part_b(&input);
println!("Part B: {}", b);
}
fn part_a(input: &Vec<String>) -> u32 {
let height_map: Vec<Vec<u32>> = input.iter()
.map(|s| s.chars().collect::<Vec<char>>().iter().map(|c| c.to_digit(10).unwrap()).collect())
.collect();
let mut lowest_points: Vec<u32> = Vec::new();
for (row_index, row) in height_map.iter().enumerate() {
for (col_index, value) in row.iter().enumerate() {
let left = if col_index == 0 { true } else { value < row.get(col_index - 1).unwrap_or(&u32::MAX) };
let right = if col_index == row.len() - 1 { true } else { value < row.get(col_index + 1).unwrap_or(&u32::MAX) };
let up = if row_index == 0 { true } else { value < height_map.get(row_index - 1).unwrap_or(&vec![u32::MAX; row.len()]).get(col_index).unwrap_or(&u32::MAX) };
let down = if row_index == height_map.len() - 1 { true } else { value < height_map.get(row_index + 1).unwrap_or(&vec![u32::MAX; row.len()]).get(col_index).unwrap_or(&u32::MAX) };
if left && right && up && down {
lowest_points.push(*value);
}
}
}
lowest_points.iter().map(|i| i + 1).sum()
}
#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)]
struct RC {
r: usize,
c: usize,
v: u32,
}
fn part_b(input: &Vec<String>) -> usize {
let height_map: Vec<Vec<u32>> = input.iter()
.map(|s| s.chars().collect::<Vec<char>>().iter().map(|c| c.to_digit(10).unwrap()).collect())
.collect();
let mut basins: Vec<HashSet<RC>> = Vec::new();
let mut seen: HashSet<RC> = HashSet::new();
let rd: Vec<i32> = vec![-1, 0, 1, 0];
let cd: Vec<i32> = vec![0, -1, 0, 1];
let rows = height_map.len() as i32;
let cols = height_map.get(0).unwrap().len() as i32;
for (row, row_vec) in height_map.iter().enumerate() {
for (col, col_value) in row_vec.iter().enumerate() {
let mut r = row;
let mut c = col;
let mut set: HashSet<RC> = HashSet::new();
let mut q: VecDeque<RC> = VecDeque::new();
q.push_back(RC { r, c, v: *col_value });
while !q.is_empty() {
let point = q.pop_front().unwrap();
r = point.r;
c = point.c;
if seen.contains(&point) {
// println!("I've already seen {:?}",point);
continue;
} else {
seen.insert(point);
if point.v != 9 {
set.insert(point.clone());
}
for i in 0..4 {
let rr = r as i32 + *rd.get(i).unwrap();
let cc = c as i32 + *cd.get(i).unwrap();
// println!("{} ({},{}) -- {:?} - ({},{})",i,r,c,point,rr,cc);
if rr >= 0 && rr < rows && cc >= 0 && cc < cols {
let comp_val = *height_map.get(rr as usize)
.map(|r| r.get(cc as usize).unwrap())
.unwrap_or(&9);
if comp_val != 9 {
let rc = RC { r: rr as usize, c: cc as usize, v: comp_val };
// println!("Found {:?} -- {}",rc,option.unwrap());
q.push_back(rc);
}
}
}
}
}
basins.push(set);
}
}
let mut basin_sizes: Vec<usize> = basins.iter()
.map(|b| b.len())
.collect();
// basins.sort_by(|a,b| a.len().cmp(&b.len()));
// for basin in basins {
// println!("{:?}",basin);
// }
basin_sizes.sort();
basin_sizes.reverse();
// println!("{:?}",basin_sizes);
basin_sizes.split_at(3).0.iter().product()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part_a_test_input() {
let filename = "src/day9/test-input.txt";
let input = lines_from_file(filename);
let result = part_a(&input);
assert_eq!(15, result);
}
#[test]
fn part_a_real() {
let filename = "src/day9/input.txt";
let input = lines_from_file(filename);
let result = part_a(&input);
assert_eq!(560, result);
}
#[test]
fn part_b_test_input() {
let filename = "src/day9/test-input.txt";
let input = lines_from_file(filename);
let result = part_b(&input);
assert_eq!(1134, result);
}
#[test]
fn part_b_real() {
let filename = "src/day9/input.txt";
let input = lines_from_file(filename);
let result = part_b(&input);
assert_eq!(959136, result);
}
} |
use amethyst::ecs::{Component, DenseVecStorage};
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Direction {
Left,
Right,
Up,
Down
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Action {
None,
Move(Direction)
}
#[derive(Debug)]
pub struct Intent {
action: Action
}
impl Intent {
pub fn action(&self) -> Action {
self.action
}
pub fn new(action: Action) -> Self {
Intent {
action
}
}
}
impl Component for Intent {
type Storage = DenseVecStorage<Self>;
}
|
mod math;
use std::path::Path;
use sdl2::VideoSubsystem;
use sdl2::event::Event;
use sdl2::gfx::primitives::DrawRenderer;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::render::{Canvas, Texture, TextureCreator, TextureQuery};
use sdl2::ttf::Font;
use sdl2::video::{Window, WindowContext};
use crate::math::vector2::Vector2;
const SCREEN_WIDTH: u32 = 800;
const SCREEN_HEIGHT: u32 = 600;
#[allow(dead_code)]
struct Boid {
pos: Vector2,
rad: f32
}
impl Boid {
fn new(pos: Vector2, rad: f32) -> Boid {
Boid { pos, rad }
}
fn translate(&mut self, dir: Vector2) {
self.pos = self.pos.add(&dir);
}
fn render(&self, canvas: &Canvas<Window>, color: Color) {
canvas.filled_circle(self.pos.x as i16, self.pos.y as i16, self.rad as i16, color).unwrap();
}
}
fn create_window(video_subsystem: &VideoSubsystem, title: &str) -> Window {
video_subsystem
.window(title, SCREEN_WIDTH, SCREEN_HEIGHT)
.position_centered()
.build()
.unwrap()
}
fn create_canvas(window: Window) -> Canvas<Window> {
window.into_canvas().present_vsync().build().unwrap()
}
fn show_fps<'a>(
texture_creator: &'a TextureCreator<WindowContext>,
font_fps: &Font,
mspf: f32,
fps: f32,
) -> (Texture<'a>, Rect) {
let fps_string = format!("ms/f: {:7.3}, fps: {:7.3}", mspf, fps);
let surface = font_fps.render(&fps_string).blended(Color::GREEN).unwrap();
let texture = texture_creator
.create_texture_from_surface(&surface)
.unwrap();
let TextureQuery { width, height, .. } = texture.query();
let texture_rect = Rect::new((SCREEN_WIDTH - width) as i32, 0, width, height);
(texture, texture_rect)
}
#[allow(unused_variables)]
fn main() {
// Initialize
let sdl_context = sdl2::init().unwrap();
let ttf_context = sdl2::ttf::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let perf_freq = timer_subsystem.performance_frequency();
// Rendering bindings
let window = create_window(&video_subsystem, "Boids");
let mut canvas = create_canvas(window);
let texture_creator = canvas.texture_creator();
// Font bindings
let font_path = Path::new("./src/fonts/MesloLGS NF Regular.ttf");
let font_fps = ttf_context.load_font(font_path, 14).unwrap();
let mut event_pump = sdl_context.event_pump().unwrap();
let mut last_perf_counter = timer_subsystem.performance_counter();
let mut deltatime = 0f32;
let mut toggle_fps = false;
let speed = 1f32; // 40f32;
let radius = 8f32;
let mut boids: Vec<Boid> = vec![];
boids.push(Boid::new(Vector2 { x: 400.0, y: 300.0 }, radius));
boids.push(Boid::new(Vector2 { x: 100.0, y: 100.0 }, radius));
// let mut x1 = SCREEN_WIDTH as f32 / 2.0 - 3.0;
// let mut x2 = SCREEN_WIDTH as f32 / 2.0 + 3.0;
// let mut x3 = SCREEN_WIDTH as f32 / 2.0;
// let speed = 10f32;
// let v1 = Vector2::new(1.0, 3.0);
// let v2 = Vector2::right();
// println!("v1 + v2 = {:?}", v1.add(&v2));
// Game loop
'running: loop {
for event in event_pump.poll_iter() {
match event {
Event::Quit { .. } | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => {
break 'running;
},
Event::KeyDown { keycode: Some(Keycode::F3), .. } => {
toggle_fps = !toggle_fps;
}
_ => {},
}
}
canvas.set_draw_color(Color::BLACK);
canvas.clear();
// RULE 1: Going towards the center of mass
let mut average_position = Vector2::zero();
for boid in &boids {
average_position = average_position.add(&boid.pos);
}
let n_boids = boids.len() as f32;
let average_position = Vector2::new(average_position.x / n_boids, average_position.y / n_boids);
for boid in &mut boids {
let direction = average_position.sub(&boid.pos);
boid.translate(Vector2 { x: direction.x * speed * deltatime, y: direction.y * speed * deltatime });
boid.render(&canvas, Color::RGB(123, 145, 210));
}
// FPS calculations
let end_perf_counter = timer_subsystem.performance_counter();
let perf_counter_elapsed = end_perf_counter - last_perf_counter;
deltatime = perf_counter_elapsed as f32 / perf_freq as f32;
let mspf = 1_000f32 * deltatime;
let fps = perf_freq as f32 / perf_counter_elapsed as f32;
last_perf_counter = end_perf_counter;
if toggle_fps {
let (fps_texture, fps_rect) = show_fps(&texture_creator, &font_fps, mspf, fps);
canvas.set_draw_color(Color::BLACK);
canvas.fill_rect(fps_rect).unwrap();
canvas.copy(&fps_texture, None, Some(fps_rect)).unwrap(); // FONT STUFF
}
canvas.present();
}
}
|
use indexmap::map::IndexMap;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Config, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span,
Spanned, Value,
};
#[derive(Clone)]
pub struct FromXml;
impl Command for FromXml {
fn name(&self) -> &str {
"from xml"
}
fn signature(&self) -> Signature {
Signature::build("from xml").category(Category::Formats)
}
fn usage(&self) -> &str {
"Parse text as .xml and create table."
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, ShellError> {
let head = call.head;
let config = engine_state.get_config();
from_xml(input, head, config)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
example: r#"'<?xml version="1.0" encoding="UTF-8"?>
<note>
<remember>Event</remember>
</note>' | from xml"#,
description: "Converts xml formatted string to table",
result: Some(Value::Record {
cols: vec!["note".to_string()],
vals: vec![Value::Record {
cols: vec!["children".to_string(), "attributes".to_string()],
vals: vec![
Value::List {
vals: vec![Value::Record {
cols: vec!["remember".to_string()],
vals: vec![Value::Record {
cols: vec!["children".to_string(), "attributes".to_string()],
vals: vec![
Value::List {
vals: vec![Value::String {
val: "Event".to_string(),
span: Span::test_data(),
}],
span: Span::test_data(),
},
Value::Record {
cols: vec![],
vals: vec![],
span: Span::test_data(),
},
],
span: Span::test_data(),
}],
span: Span::test_data(),
}],
span: Span::test_data(),
},
Value::Record {
cols: vec![],
vals: vec![],
span: Span::test_data(),
},
],
span: Span::test_data(),
}],
span: Span::test_data(),
}),
}]
}
}
fn from_attributes_to_value(attributes: &[roxmltree::Attribute], span: Span) -> Value {
let mut collected = IndexMap::new();
for a in attributes {
collected.insert(String::from(a.name()), Value::string(a.value(), span));
}
let (cols, vals) = collected
.into_iter()
.fold((vec![], vec![]), |mut acc, (k, v)| {
acc.0.push(k);
acc.1.push(v);
acc
});
Value::Record { cols, vals, span }
}
fn from_node_to_value(n: &roxmltree::Node, span: Span) -> Value {
if n.is_element() {
let name = n.tag_name().name().trim().to_string();
let mut children_values = vec![];
for c in n.children() {
children_values.push(from_node_to_value(&c, span));
}
let children_values: Vec<Value> = children_values
.into_iter()
.filter(|x| match x {
Value::String { val: f, .. } => {
!f.trim().is_empty() // non-whitespace characters?
}
_ => true,
})
.collect();
let mut collected = IndexMap::new();
let attribute_value: Value = from_attributes_to_value(n.attributes(), span);
let mut row = IndexMap::new();
row.insert(
String::from("children"),
Value::List {
vals: children_values,
span,
},
);
row.insert(String::from("attributes"), attribute_value);
collected.insert(name, Value::from(Spanned { item: row, span }));
Value::from(Spanned {
item: collected,
span,
})
} else if n.is_comment() {
Value::String {
val: "<comment>".to_string(),
span,
}
} else if n.is_pi() {
Value::String {
val: "<processing_instruction>".to_string(),
span,
}
} else if n.is_text() {
match n.text() {
Some(text) => Value::String {
val: text.to_string(),
span,
},
None => Value::String {
val: "<error>".to_string(),
span,
},
}
} else {
Value::String {
val: "<unknown>".to_string(),
span,
}
}
}
fn from_document_to_value(d: &roxmltree::Document, span: Span) -> Value {
from_node_to_value(&d.root_element(), span)
}
pub fn from_xml_string_to_value(s: String, span: Span) -> Result<Value, roxmltree::Error> {
let parsed = roxmltree::Document::parse(&s)?;
Ok(from_document_to_value(&parsed, span))
}
fn from_xml(input: PipelineData, head: Span, config: &Config) -> Result<PipelineData, ShellError> {
let concat_string = input.collect_string("", config)?;
match from_xml_string_to_value(concat_string, head) {
Ok(x) => Ok(x.into_pipeline_data()),
_ => Err(ShellError::UnsupportedInput(
"Could not parse string as xml".to_string(),
head,
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use indexmap::indexmap;
use indexmap::IndexMap;
use nu_protocol::{Spanned, Value};
fn string(input: impl Into<String>) -> Value {
Value::String {
val: input.into(),
span: Span::test_data(),
}
}
fn row(entries: IndexMap<String, Value>) -> Value {
Value::from(Spanned {
item: entries,
span: Span::test_data(),
})
}
fn table(list: &[Value]) -> Value {
Value::List {
vals: list.to_vec(),
span: Span::test_data(),
}
}
fn parse(xml: &str) -> Result<Value, roxmltree::Error> {
from_xml_string_to_value(xml.to_string(), Span::test_data())
}
#[test]
fn parses_empty_element() -> Result<(), roxmltree::Error> {
let source = "<nu></nu>";
assert_eq!(
parse(source)?,
row(indexmap! {
"nu".into() => row(indexmap! {
"children".into() => table(&[]),
"attributes".into() => row(indexmap! {})
})
})
);
Ok(())
}
#[test]
fn parses_element_with_text() -> Result<(), roxmltree::Error> {
let source = "<nu>La era de los tres caballeros</nu>";
assert_eq!(
parse(source)?,
row(indexmap! {
"nu".into() => row(indexmap! {
"children".into() => table(&[string("La era de los tres caballeros")]),
"attributes".into() => row(indexmap! {})
})
})
);
Ok(())
}
#[test]
fn parses_element_with_elements() -> Result<(), roxmltree::Error> {
let source = "\
<nu>
<dev>Andrés</dev>
<dev>Jonathan</dev>
<dev>Yehuda</dev>
</nu>";
assert_eq!(
parse(source)?,
row(indexmap! {
"nu".into() => row(indexmap! {
"children".into() => table(&[
row(indexmap! {
"dev".into() => row(indexmap! {
"children".into() => table(&[string("Andrés")]),
"attributes".into() => row(indexmap! {})
})
}),
row(indexmap! {
"dev".into() => row(indexmap! {
"children".into() => table(&[string("Jonathan")]),
"attributes".into() => row(indexmap! {})
})
}),
row(indexmap! {
"dev".into() => row(indexmap! {
"children".into() => table(&[string("Yehuda")]),
"attributes".into() => row(indexmap! {})
})
})
]),
"attributes".into() => row(indexmap! {})
})
})
);
Ok(())
}
#[test]
fn parses_element_with_attribute() -> Result<(), roxmltree::Error> {
let source = "\
<nu version=\"2.0\">
</nu>";
assert_eq!(
parse(source)?,
row(indexmap! {
"nu".into() => row(indexmap! {
"children".into() => table(&[]),
"attributes".into() => row(indexmap! {
"version".into() => string("2.0")
})
})
})
);
Ok(())
}
#[test]
fn parses_element_with_attribute_and_element() -> Result<(), roxmltree::Error> {
let source = "\
<nu version=\"2.0\">
<version>2.0</version>
</nu>";
assert_eq!(
parse(source)?,
row(indexmap! {
"nu".into() => row(indexmap! {
"children".into() => table(&[
row(indexmap! {
"version".into() => row(indexmap! {
"children".into() => table(&[string("2.0")]),
"attributes".into() => row(indexmap! {})
})
})
]),
"attributes".into() => row(indexmap! {
"version".into() => string("2.0")
})
})
})
);
Ok(())
}
#[test]
fn parses_element_with_multiple_attributes() -> Result<(), roxmltree::Error> {
let source = "\
<nu version=\"2.0\" age=\"25\">
</nu>";
assert_eq!(
parse(source)?,
row(indexmap! {
"nu".into() => row(indexmap! {
"children".into() => table(&[]),
"attributes".into() => row(indexmap! {
"version".into() => string("2.0"),
"age".into() => string("25")
})
})
})
);
Ok(())
}
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(FromXml {})
}
}
|
// 2019-03-12
// Rédigeons une fonction qui renvoie la plus grande de deux tranches de chaîne
// de caractère. (the longer of two string slices).
use std::fmt::Display;
fn main() {
// Déclarer les deux chaînes
let string1 = String::from("abcd"); // une String
let string2 = "xyz"; // une "string literal"
// comme paramètres : des slices, donc des &str, des références
// on ne veut pas prendre l'ownership
let result = longest(string1.as_str(), string2);
println!("La plus longue chaîne est {}", result);
let result2 = longest_with_annoucement(string1.as_str(), string2, "annonce");
println!("{}", result2);
}
// La fonction avec les annotations d'espérance de vie (lifetime annotations)
// Comme pour les types de données génériques, on utilise des chevrons <> placés
// entre le nom de la fonction et la liste des paramètres.
// On veut donner la même lifetime aux deux paramètres et à la valeur retour
// La lifetime s'appelle <'a>, on l'ajoute partout
fn longest<'a>(x: &'a str, y:&'a str) -> &'a str {
if x.len() > y.len () {
x
} else {
y
}
}
// Du vocabulaire : les input lifetimes, et les output lifetimes
// Maintenant, une fonction qui contient la même chose plus un trait bound
fn longest_with_annoucement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a str
where T: Display
{
println!("Announcement! {}", ann);
if x.len() > y.len () {
x
} else {
y
}
}
|
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[derive(Clone, Debug)]
pub type Error;
#[wasm_bindgen(constructor)]
pub fn new(msg: &str) -> Error;
}
|
#[doc = "Reader of register SENSE_DUTY"]
pub type R = crate::R<u32, super::SENSE_DUTY>;
#[doc = "Writer for register SENSE_DUTY"]
pub type W = crate::W<u32, super::SENSE_DUTY>;
#[doc = "Register SENSE_DUTY `reset()`'s with value 0"]
impl crate::ResetValue for super::SENSE_DUTY {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `SENSE_WIDTH`"]
pub type SENSE_WIDTH_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `SENSE_WIDTH`"]
pub struct SENSE_WIDTH_W<'a> {
w: &'a mut W,
}
impl<'a> SENSE_WIDTH_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0fff) | ((value as u32) & 0x0fff);
self.w
}
}
#[doc = "Reader of field `SENSE_POL`"]
pub type SENSE_POL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SENSE_POL`"]
pub struct SENSE_POL_W<'a> {
w: &'a mut W,
}
impl<'a> SENSE_POL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `OVERLAP_PHI1`"]
pub type OVERLAP_PHI1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OVERLAP_PHI1`"]
pub struct OVERLAP_PHI1_W<'a> {
w: &'a mut W,
}
impl<'a> OVERLAP_PHI1_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 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `OVERLAP_PHI2`"]
pub type OVERLAP_PHI2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OVERLAP_PHI2`"]
pub struct OVERLAP_PHI2_W<'a> {
w: &'a mut W,
}
impl<'a> OVERLAP_PHI2_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 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
impl R {
#[doc = "Bits 0:11 - Defines the length of the first phase of the sense clock in clk_csd cycles. A value of 0 disables this feature and the duty cycle of csd_sense will be 50 percent, which is equal to SENSE_WIDTH = (SENSE_DIV+1)/2, or when clock dithering is used that becomes \\[(SENSE_DIV+1) + (LFSR_OUT << LSFR_SCALE)\\]/2. At all times it must be assured that the phases are at least 2 clk_csd cycles (1 for non overlap, if used), if this rule is violated the result is undefined. Note that this feature is not available when SEL_LFSR_MSB (PRS) is selected."]
#[inline(always)]
pub fn sense_width(&self) -> SENSE_WIDTH_R {
SENSE_WIDTH_R::new((self.bits & 0x0fff) as u16)
}
#[doc = "Bit 16 - Polarity of the sense clock 0 = start with low phase (typical for regular negative transfer CSD) 1 = start with high phase"]
#[inline(always)]
pub fn sense_pol(&self) -> SENSE_POL_R {
SENSE_POL_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 18 - NonOverlap or not for Phi1 (csd_sense=0). 0 = Non-overlap for Phi1, the Phi1 signal is csd_sense inverted except that the signal goes low 1 clk_sample before csd_sense goes high. Intended usage: new low EMI CSD/CSX with static GPIO. 1 = 'Overlap' (= not non-overlap) for Phi1, the Phi1 signal is csd_sense inverted. Intended usage: legacy CSD with GPIO switching, the GPIO internal circuit ensures that the switches are non-overlapping."]
#[inline(always)]
pub fn overlap_phi1(&self) -> OVERLAP_PHI1_R {
OVERLAP_PHI1_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - Same as OVERLAP_PHI1 but for Phi2 (csd_sense=1)."]
#[inline(always)]
pub fn overlap_phi2(&self) -> OVERLAP_PHI2_R {
OVERLAP_PHI2_R::new(((self.bits >> 19) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:11 - Defines the length of the first phase of the sense clock in clk_csd cycles. A value of 0 disables this feature and the duty cycle of csd_sense will be 50 percent, which is equal to SENSE_WIDTH = (SENSE_DIV+1)/2, or when clock dithering is used that becomes \\[(SENSE_DIV+1) + (LFSR_OUT << LSFR_SCALE)\\]/2. At all times it must be assured that the phases are at least 2 clk_csd cycles (1 for non overlap, if used), if this rule is violated the result is undefined. Note that this feature is not available when SEL_LFSR_MSB (PRS) is selected."]
#[inline(always)]
pub fn sense_width(&mut self) -> SENSE_WIDTH_W {
SENSE_WIDTH_W { w: self }
}
#[doc = "Bit 16 - Polarity of the sense clock 0 = start with low phase (typical for regular negative transfer CSD) 1 = start with high phase"]
#[inline(always)]
pub fn sense_pol(&mut self) -> SENSE_POL_W {
SENSE_POL_W { w: self }
}
#[doc = "Bit 18 - NonOverlap or not for Phi1 (csd_sense=0). 0 = Non-overlap for Phi1, the Phi1 signal is csd_sense inverted except that the signal goes low 1 clk_sample before csd_sense goes high. Intended usage: new low EMI CSD/CSX with static GPIO. 1 = 'Overlap' (= not non-overlap) for Phi1, the Phi1 signal is csd_sense inverted. Intended usage: legacy CSD with GPIO switching, the GPIO internal circuit ensures that the switches are non-overlapping."]
#[inline(always)]
pub fn overlap_phi1(&mut self) -> OVERLAP_PHI1_W {
OVERLAP_PHI1_W { w: self }
}
#[doc = "Bit 19 - Same as OVERLAP_PHI1 but for Phi2 (csd_sense=1)."]
#[inline(always)]
pub fn overlap_phi2(&mut self) -> OVERLAP_PHI2_W {
OVERLAP_PHI2_W { w: self }
}
}
|
mod bot;
mod telegram;
mod tools;
use crate::bot::constants::*;
use crate::bot::handlers::Handlers;
use crate::telegram::helpers::*;
use crate::telegram::messages::*;
use crate::telegram::structures::*;
use crate::tools::read_key_env;
use log::LevelFilter;
use redis::Commands;
use reqwest::Client;
use simple_logger::SimpleLogger;
use std::borrow::Borrow;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
SimpleLogger::new()
.with_level(LevelFilter::Info)
.init()
.unwrap();
let token = read_key_env("TG_TOKEN").expect("No TG_TOKEN found!");
let ch_url = read_key_env("CH_URL").expect("No CH_URL found!");
let client = reqwest::Client::new();
let mut redis = redis::Client::open(read_key_env("REDIS").unwrap())?.get_connection()?;
log::info!("Started the bot");
longpoll(&token, &client, &mut redis, &ch_url).await
}
async fn get_updates(
bot_token: &str,
client: &Client,
latest_update_id: i32,
) -> Result<TgResult, Box<dyn std::error::Error>> {
let url = create_tg_url(bot_token, TgMethods::GET_UPDATES);
let offset: String = format!("{}", latest_update_id + 1);
let params: [(&str, &str); 2] = [("offset", &offset), ("timeout", "60")];
let res = client
.get(&url)
.query(¶ms)
.send()
.await?
.bytes()
.await?;
let tg_response = serde_json::from_slice::<TgResult>(&res);
if tg_response.is_err() {
match serde_json::from_slice::<TgError>(&res) {
Ok(tg_error) => log::error!("{:?}", tg_error),
Err(err) => log::error!("{:?}", err),
}
}
Ok(tg_response?)
}
async fn handle_updates(
update: &TgUpdate,
bot_token: &str,
client: &Client,
redis: &mut redis::Connection,
ch_url: &String,
url: &String,
) -> Result<(), Box<dyn std::error::Error>> {
let message_type = update.handle_message_type(redis)?;
let message = update.message.borrow();
if message.is_some() {
log::info!("{:?}", message.as_ref().unwrap());
}
let chat_id = message.as_ref().map(|x| x.from.id);
match &message_type {
UpdateType::Callback(chat, message, d, id) => {
d.handle_callback(id, *chat, *message, redis, client, bot_token)
.await?;
}
_ => (),
}
if chat_id.is_some() {
let user_id = chat_id.unwrap();
let response: Option<OutgoingKeyboardMessage> = match message_type {
UpdateType::Start => Some(OutgoingKeyboardMessage::welcome_message(user_id)),
UpdateType::JoinExisting => Handlers::join_existing(user_id, redis)?,
UpdateType::Create => Handlers::create(user_id, redis)?,
UpdateType::NewRoom => Handlers::new_room(user_id, message, redis)?,
UpdateType::InsertId => {
Handlers::insert_id(user_id, message, client, redis, url, ch_url).await?
}
UpdateType::WaitingForOther => {
Handlers::waiting_for_answer(user_id, client, redis, url, ch_url).await?
}
UpdateType::WaitingForResults => Some(OutgoingKeyboardMessage::with_text(
user_id,
Messages::WAIT_A_MOMENT,
)),
UpdateType::Help => Some(OutgoingKeyboardMessage::with_text(user_id, Messages::HELP)),
UpdateType::UnknownCommand => Some(OutgoingKeyboardMessage::with_text(
user_id,
Messages::ERROR_UNKNOWN_COMMAND,
)),
UpdateType::Error => Some(OutgoingKeyboardMessage::error(user_id)),
_ => Some(OutgoingKeyboardMessage::error(user_id)),
};
if response.is_some() {
send_message(url, &response.unwrap(), client).await?;
}
}
Ok(())
}
async fn longpoll(
bot_token: &str,
client: &Client,
redis: &mut redis::Connection,
ch_url: &String,
) -> Result<(), Box<dyn std::error::Error>> {
let mut latest_update_id: i32 = 0;
let url = create_tg_url(bot_token, TgMethods::SEND_MESSAGE);
loop {
let updates = get_updates(bot_token, client, latest_update_id).await?;
for update in updates.result {
let upd = handle_updates(&update, bot_token, client, redis, ch_url, &url).await;
if upd.is_err() {
let user_id = &update.message.map(|m| m.from.id);
if user_id.is_some() {
send_message(
&url,
&OutgoingKeyboardMessage::internal_error(user_id.unwrap()),
client,
)
.await?;
}
log::error!("{:?}", upd);
}
latest_update_id = update.update_id;
redis.set(RedisKeys::LATEST_MESSAGE, latest_update_id)?;
log::info!("Latest update: {}", latest_update_id);
}
}
Ok(())
}
|
#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
pub struct Setup {
pub request_type: u8,
pub request: u8,
pub value: u16,
pub index: u16,
pub len: u16,
}
impl Setup {
pub fn get_status() -> Setup {
Setup {
request_type: 0b10000000,
request: 0x00,
value: 0,
index: 0,
len: 2,
}
}
pub fn clear_feature(feature: u16) -> Setup {
Setup {
request_type: 0b00000000,
request: 0x01,
value: feature,
index: 0,
len: 0,
}
}
pub fn set_feature(feature: u16) -> Setup {
Setup {
request_type: 0b00000000,
request: 0x03,
value: feature,
index: 0,
len: 0,
}
}
pub fn set_address(address: u8) -> Setup {
Setup {
request_type: 0b00000000,
request: 0x05,
value: (address as u16) & 0x7F,
index: 0,
len: 0,
}
}
pub fn get_descriptor(descriptor_type: u8, descriptor_index: u8, language_id: u16, descriptor_len: u16) -> Setup {
Setup {
request_type: 0b10000000,
request: 0x06,
value: (descriptor_type as u16) << 8 | (descriptor_index as u16),
index: language_id,
len: descriptor_len,
}
}
pub fn set_descriptor(descriptor_type: u8, descriptor_index: u8, language_id: u16, descriptor_len: u16) -> Setup {
Setup {
request_type: 0b00000000,
request: 0x07,
value: (descriptor_type as u16) << 8 | (descriptor_index as u16),
index: language_id,
len: descriptor_len,
}
}
pub fn get_configuration() -> Setup {
Setup {
request_type: 0b10000000,
request: 0x08,
value: 0,
index: 0,
len: 1,
}
}
pub fn set_configuration(value: u8) -> Setup {
Setup {
request_type: 0b00000000,
request: 0x09,
value: value as u16,
index: 0,
len: 0,
}
}
}
|
#[doc = "Reader of register TICKS"]
pub type R = crate::R<u32, super::TICKS>;
#[doc = "Reader of field `CNT128HZ`"]
pub type CNT128HZ_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:5 - 128Hz counter (msb=2Hz) When SECONDS is written this field will be reset."]
#[inline(always)]
pub fn cnt128hz(&self) -> CNT128HZ_R {
CNT128HZ_R::new((self.bits & 0x3f) as u8)
}
}
|
use std::fmt::{Display, Formatter};
// We could use std::ops::RangeInclusive, but we would have to extend it to
// normalize self (not much trouble) and it would not have to handle pretty
// printing for it explicitly. So, let's make rather an own type.
#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct ClosedRange<Idx> {
start: Idx,
end: Idx,
}
impl<Idx> ClosedRange<Idx> {
pub fn start(&self) -> &Idx {
&self.start
}
pub fn end(&self) -> &Idx {
&self.end
}
}
impl<Idx: PartialOrd> ClosedRange<Idx> {
pub fn new(start: Idx, end: Idx) -> Self {
if start <= end {
Self { start, end }
} else {
Self {
end: start,
start: end,
}
}
}
}
// To make test input more compact
impl<Idx: PartialOrd> From<(Idx, Idx)> for ClosedRange<Idx> {
fn from((start, end): (Idx, Idx)) -> Self {
Self::new(start, end)
}
}
// For the required print format
impl<Idx: Display> Display for ClosedRange<Idx> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "[{}, {}]", self.start, self.end)
}
}
fn consolidate<Idx>(a: &ClosedRange<Idx>, b: &ClosedRange<Idx>) -> Option<ClosedRange<Idx>>
where
Idx: PartialOrd + Clone,
{
if a.start() <= b.start() {
if b.end() <= a.end() {
Some(a.clone())
} else if a.end() < b.start() {
None
} else {
Some(ClosedRange::new(a.start().clone(), b.end().clone()))
}
} else {
consolidate(b, a)
}
}
fn consolidate_all<Idx>(mut ranges: Vec<ClosedRange<Idx>>) -> Vec<ClosedRange<Idx>>
where
Idx: PartialOrd + Clone,
{
// Panics for incomparable elements! So no NaN for floats, for instance.
ranges.sort_by(|a, b| a.partial_cmp(b).unwrap());
let mut ranges = ranges.into_iter();
let mut result = Vec::new();
if let Some(current) = ranges.next() {
let leftover = ranges.fold(current, |mut acc, next| {
match consolidate(&acc, &next) {
Some(merger) => {
acc = merger;
}
None => {
result.push(acc);
acc = next;
}
}
acc
});
result.push(leftover);
}
result
}
#[cfg(test)]
mod tests {
use super::{consolidate_all, ClosedRange};
use std::fmt::{Display, Formatter};
struct IteratorToDisplay<F>(F);
impl<F, I> Display for IteratorToDisplay<F>
where
F: Fn() -> I,
I: Iterator,
I::Item: Display,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut items = self.0();
if let Some(item) = items.next() {
write!(f, "{}", item)?;
for item in items {
write!(f, ", {}", item)?;
}
}
Ok(())
}
}
macro_rules! parameterized {
($($name:ident: $value:expr,)*) => {
$(
#[test]
fn $name() {
let (input, expected) = $value;
let expected: Vec<_> = expected.into_iter().map(ClosedRange::from).collect();
let output = consolidate_all(input.into_iter().map(ClosedRange::from).collect());
println!("{}: {}", stringify!($name), IteratorToDisplay(|| output.iter()));
assert_eq!(expected, output);
}
)*
}
}
parameterized! {
single: (vec![(1.1, 2.2)], vec![(1.1, 2.2)]),
touching: (vec![(6.1, 7.2), (7.2, 8.3)], vec![(6.1, 8.3)]),
disjoint: (vec![(4, 3), (2, 1)], vec![(1, 2), (3, 4)]),
overlap: (vec![(4.0, 3.0), (2.0, 1.0), (-1.0, -2.0), (3.9, 10.0)], vec![(-2.0, -1.0), (1.0, 2.0), (3.0, 10.0)]),
integer: (vec![(1, 3), (-6, -1), (-4, -5), (8, 2), (-6, -6)], vec![(-6, -1), (1, 8)]),
}
}
fn main() {
// To prevent dead code and to check empty input
consolidate_all(Vec::<ClosedRange<usize>>::new());
println!("Run: cargo test -- --nocapture");
} |
#![cfg(feature = "ast-parent")]
use crate::{
ast::*,
token::{ByteValue, ControlOperator, Value},
visitor::{self, *},
};
use std::{borrow::Cow, fmt};
/// Parent visitor result
pub type Result<T> = std::result::Result<T, Error>;
/// Parent visitor error
#[derive(Debug)]
pub enum Error {
/// Tree overwrite error
Overwrite,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Overwrite => write!(f, "attempt to overwrite existing tree node"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
/// Parent trait retrieving the implemented type's parent
pub trait Parent<'a, 'b: 'a, T> {
/// Returns the parent for the AST type
fn parent(&'a self, parent_visitor: &'b ParentVisitor<'a, 'b>) -> Option<&T>;
}
macro_rules! impl_parent {
($($parent:ty => ([$($child:ty),+], $p:path)),* $(,)?) => {
$(
$(
impl<'a, 'b: 'a> Parent<'a, 'b, $parent> for $child {
fn parent(&'a self, parent_visitor: &'b ParentVisitor<'a, 'b>) -> Option<&$parent> {
if let Some($p(value)) = CDDLType::from(self).parent(parent_visitor) {
return Some(value);
}
None
}
}
)*
)*
};
}
impl_parent! {
CDDL<'a> => ([Rule<'a>], CDDLType::CDDL),
Rule<'a> => ([GroupRule<'a>, TypeRule<'a>], CDDLType::Rule),
TypeRule<'a> => ([Identifier<'a>, GenericParams<'a>, Type<'a>], CDDLType::TypeRule),
GroupRule<'a> => ([Identifier<'a>, GenericParams<'a>, GroupEntry<'a>], CDDLType::GroupRule),
Type<'a> => ([TypeChoice<'a>], CDDLType::Type),
TypeChoice<'a> => ([Type1<'a>], CDDLType::TypeChoice),
Type1<'a> => ([Operator<'a>, Type2<'a>], CDDLType::Type1),
Operator<'a> => ([Type2<'a>], CDDLType::Operator),
RangeCtlOp => ([ControlOperator], CDDLType::RangeCtlOp),
Type2<'a> => ([Identifier<'a>, GenericArgs<'a>, Type<'a>, Group<'a>], CDDLType::Type2),
Group<'a> => ([GroupChoice<'a>, Occurrence<'a>], CDDLType::Group),
GroupChoice<'a> => ([GroupEntry<'a>], CDDLType::GroupChoice),
GroupEntry<'a> => ([ValueMemberKeyEntry<'a>, TypeGroupnameEntry<'a>, Occurrence<'a>, Group<'a>], CDDLType::GroupEntry),
ValueMemberKeyEntry<'a> => ([Occurrence<'a>, MemberKey<'a>, Type<'a>], CDDLType::ValueMemberKeyEntry),
TypeGroupnameEntry<'a> => ([Occurrence<'a>, GenericArgs<'a>, Identifier<'a>], CDDLType::TypeGroupnameEntry),
MemberKey<'a> => ([Type1<'a>, Identifier<'a>, NonMemberKey<'a>], CDDLType::MemberKey),
GenericArgs<'a> => ([GenericArg<'a>], CDDLType::GenericArgs),
GenericArg<'a> => ([Type1<'a>], CDDLType::GenericArg),
GenericParams<'a> => ([GenericParam<'a>], CDDLType::GenericParams),
GenericParam<'a> => ([Identifier<'a>], CDDLType::GenericParam),
NonMemberKey<'a> => ([Group<'a>, Type<'a>], CDDLType::NonMemberKey),
}
impl<'a, 'b: 'a> Parent<'a, 'b, ()> for CDDL<'a> {
fn parent(&'a self, _parent_visitor: &'b ParentVisitor<'a, 'b>) -> Option<&()> {
None
}
}
impl<'a, 'b: 'a> Parent<'a, 'b, Type2<'a>> for Value<'a> {
fn parent(&'a self, parent_visitor: &'b ParentVisitor<'a, 'b>) -> Option<&Type2<'a>> {
if let Some(CDDLType::Type2(value)) = CDDLType::from(self.to_owned()).parent(parent_visitor) {
return Some(value);
}
None
}
}
impl<'a, 'b: 'a> Parent<'a, 'b, MemberKey<'a>> for Value<'a> {
fn parent(&'a self, parent_visitor: &'b ParentVisitor<'a, 'b>) -> Option<&MemberKey<'a>> {
if let Some(CDDLType::MemberKey(value)) = CDDLType::from(self.to_owned()).parent(parent_visitor)
{
return Some(value);
}
None
}
}
impl<'a, 'b: 'a> Parent<'a, 'b, Occurrence<'a>> for Occur {
fn parent(&self, parent_visitor: &'b ParentVisitor<'a, 'b>) -> Option<&Occurrence<'a>> {
if let Some(CDDLType::Occurrence(value)) = CDDLType::from(*self).parent(parent_visitor) {
return Some(value);
}
None
}
}
#[derive(Debug, Default, Clone)]
struct ArenaTree<'a, 'b: 'a> {
arena: Vec<Node<'a, 'b>>,
}
impl<'a, 'b: 'a> ArenaTree<'a, 'b> {
fn node(&mut self, val: CDDLType<'a, 'b>) -> usize {
for node in self.arena.iter() {
if node.val == val {
return node.idx;
}
}
let idx = self.arena.len();
self.arena.push(Node::new(idx, val));
idx
}
}
#[derive(Debug, Clone)]
struct Node<'a, 'b: 'a> {
idx: usize,
val: CDDLType<'a, 'b>,
parent: Option<usize>,
children: Vec<usize>,
}
impl<'a, 'b: 'a> Node<'a, 'b> {
fn new(idx: usize, val: CDDLType<'a, 'b>) -> Self {
Self {
idx,
val,
parent: None,
children: vec![],
}
}
}
/// Parent visitor type
// #[derive(Clone)]
pub struct ParentVisitor<'a, 'b: 'a> {
arena_tree: ArenaTree<'a, 'b>,
}
impl<'a, 'b: 'a> ParentVisitor<'a, 'b> {
/// Creates a new parent visitor given a CDDL reference
pub fn new(cddl: &'a CDDL<'a>) -> Result<Self> {
let mut p = ParentVisitor {
arena_tree: ArenaTree {
arena: Vec::default(),
},
};
p.visit_cddl(cddl)?;
Ok(p)
}
}
impl<'a, 'b: 'a> ParentVisitor<'a, 'b> {
fn insert(&mut self, parent: usize, child: usize) -> Result<()> {
if self.arena_tree.arena[child].parent.is_none() {
self.arena_tree.arena[child].parent = Some(parent);
}
self.arena_tree.arena[parent].children.push(child);
Ok(())
}
}
impl<'a, 'b: 'a> CDDLType<'a, 'b> {
pub fn parent(&self, visitor: &'b ParentVisitor<'a, 'b>) -> Option<&'b CDDLType<'a, 'b>> {
for node in visitor.arena_tree.arena.iter() {
if self == &node.val {
if let Some(parent_idx) = node.parent {
if let Some(parent) = visitor.arena_tree.arena.get(parent_idx) {
return Some(&parent.val);
}
}
}
}
None
}
}
impl<'a, 'b: 'a> Visitor<'a, 'b, Error> for ParentVisitor<'a, 'b> {
fn visit_cddl(&mut self, cddl: &'b CDDL<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::CDDL(cddl));
for rule in cddl.rules.iter() {
let child = self.arena_tree.node(CDDLType::Rule(rule));
self.insert(parent, child)?;
self.visit_rule(rule)?;
}
Ok(())
}
fn visit_rule(&mut self, rule: &'b Rule<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::Rule(rule));
match rule {
Rule::Group { rule, .. } => {
let child = self.arena_tree.node(CDDLType::GroupRule(rule));
self.insert(parent, child)?;
self.visit_group_rule(rule)?;
}
Rule::Type { rule, .. } => {
let child = self.arena_tree.node(CDDLType::TypeRule(rule));
self.insert(parent, child)?;
self.visit_type_rule(rule)?;
}
}
Ok(())
}
fn visit_type_rule(&mut self, tr: &'b TypeRule<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::TypeRule(tr));
let child = self.arena_tree.node(CDDLType::Identifier(&tr.name));
self.insert(parent, child)?;
if let Some(params) = &tr.generic_params {
let child = self.arena_tree.node(CDDLType::GenericParams(params));
self.insert(parent, child)?;
self.visit_generic_params(params)?;
}
let child = self.arena_tree.node(CDDLType::Type(&tr.value));
self.insert(parent, child)?;
self.visit_type(&tr.value)
}
fn visit_group_rule(&mut self, gr: &'b GroupRule<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::GroupRule(gr));
let child = self.arena_tree.node(CDDLType::Identifier(&gr.name));
self.insert(parent, child)?;
self.visit_identifier(&gr.name)?;
if let Some(params) = &gr.generic_params {
let child = self.arena_tree.node(CDDLType::GenericParams(params));
self.insert(parent, child)?;
self.visit_generic_params(params)?;
}
let child = self.arena_tree.node(CDDLType::GroupEntry(&gr.entry));
self.insert(parent, child)?;
self.visit_group_entry(&gr.entry)
}
fn visit_type(&mut self, t: &'b Type<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::Type(t));
for tc in t.type_choices.iter() {
let child = self.arena_tree.node(CDDLType::TypeChoice(tc));
self.insert(parent, child)?;
self.visit_type_choice(tc)?;
}
Ok(())
}
fn visit_type_choice(&mut self, tc: &'a TypeChoice<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::TypeChoice(tc));
let child = self.arena_tree.node(CDDLType::Type1(&tc.type1));
self.insert(parent, child)?;
self.visit_type1(&tc.type1)
}
fn visit_type1(&mut self, t1: &'b Type1<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::Type1(t1));
if let Some(operator) = &t1.operator {
let child = self.arena_tree.node(CDDLType::Operator(operator));
self.insert(parent, child)?;
self.visit_operator(t1, operator)?;
}
let child = self.arena_tree.node(CDDLType::Type2(&t1.type2));
self.insert(parent, child)?;
self.visit_type2(&t1.type2)
}
fn visit_operator(
&mut self,
target: &'b Type1<'a>,
o: &'b Operator<'a>,
) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::Operator(o));
let child = self.arena_tree.node(CDDLType::Type2(&o.type2));
self.insert(parent, child)?;
let child = self.arena_tree.node(CDDLType::RangeCtlOp(&o.operator));
self.insert(parent, child)?;
self.visit_rangectlop(&o.operator, target, &o.type2)
}
fn visit_rangectlop(
&mut self,
op: &'b RangeCtlOp,
target: &'b Type1<'a>,
controller: &'b Type2<'a>,
) -> visitor::Result<Error> {
match op {
RangeCtlOp::RangeOp { is_inclusive, .. } => {
self.visit_range(&target.type2, controller, *is_inclusive)
}
RangeCtlOp::CtlOp { ctrl, .. } => {
let parent = self.arena_tree.node(CDDLType::RangeCtlOp(op));
let child = self.arena_tree.node(CDDLType::ControlOperator(ctrl));
self.insert(parent, child)?;
self.visit_control_operator(&target.type2, *ctrl, controller)
}
}
}
fn visit_type2(&mut self, t2: &'b Type2<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::Type2(t2));
match t2 {
Type2::IntValue { value, .. } => {
let child = self.arena_tree.node(CDDLType::Value(Value::INT(*value)));
self.insert(parent, child)?;
}
Type2::UintValue { value, .. } => {
let child = self.arena_tree.node(CDDLType::Value(Value::UINT(*value)));
self.insert(parent, child)?;
}
Type2::FloatValue { value, .. } => {
let child = self.arena_tree.node(CDDLType::Value(Value::FLOAT(*value)));
self.insert(parent, child)?;
}
Type2::TextValue { value, .. } => {
let child = self
.arena_tree
.node(CDDLType::Value(Value::TEXT(Cow::Borrowed(value))));
self.insert(parent, child)?;
}
Type2::UTF8ByteString { value, .. } => {
let child = self
.arena_tree
.node(CDDLType::Value(Value::BYTE(ByteValue::UTF8(
Cow::Borrowed(value),
))));
self.insert(parent, child)?;
}
Type2::B16ByteString { value, .. } => {
let child = self
.arena_tree
.node(CDDLType::Value(Value::BYTE(ByteValue::B16(Cow::Borrowed(
value,
)))));
self.insert(parent, child)?;
}
Type2::B64ByteString { value, .. } => {
let child = self
.arena_tree
.node(CDDLType::Value(Value::BYTE(ByteValue::B64(Cow::Borrowed(
value,
)))));
self.insert(parent, child)?;
}
Type2::Typename {
ident,
generic_args,
..
} => {
let child = self.arena_tree.node(CDDLType::Identifier(ident));
self.insert(parent, child)?;
if let Some(generic_args) = generic_args {
let child = self.arena_tree.node(CDDLType::GenericArgs(generic_args));
self.insert(parent, child)?;
self.visit_generic_args(generic_args)?;
}
}
Type2::ParenthesizedType { pt, .. } => {
let child = self.arena_tree.node(CDDLType::Type(pt));
self.insert(parent, child)?;
self.visit_type(pt)?;
}
Type2::Map { group, .. } => {
let child = self.arena_tree.node(CDDLType::Group(group));
self.insert(parent, child)?;
self.visit_group(group)?;
}
Type2::Array { group, .. } => {
let child = self.arena_tree.node(CDDLType::Group(group));
self.insert(parent, child)?;
self.visit_group(group)?;
}
Type2::Unwrap { ident, .. } => {
let child = self.arena_tree.node(CDDLType::Identifier(ident));
self.insert(parent, child)?;
self.visit_identifier(ident)?;
}
Type2::ChoiceFromInlineGroup { group, .. } => {
let child = self.arena_tree.node(CDDLType::Group(group));
self.insert(parent, child)?;
self.visit_group(group)?;
}
Type2::ChoiceFromGroup {
ident,
generic_args,
..
} => {
let child = self.arena_tree.node(CDDLType::Identifier(ident));
self.insert(parent, child)?;
if let Some(generic_args) = generic_args {
let child = self.arena_tree.node(CDDLType::GenericArgs(generic_args));
self.insert(parent, child)?;
self.visit_generic_args(generic_args)?;
}
}
Type2::TaggedData { t, .. } => {
let child = self.arena_tree.node(CDDLType::Type(t));
self.insert(parent, child)?;
self.visit_type(t)?;
}
_ => (),
}
Ok(())
}
fn visit_group(&mut self, g: &'b Group<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::Group(g));
for gc in g.group_choices.iter() {
let child = self.arena_tree.node(CDDLType::GroupChoice(gc));
self.insert(parent, child)?;
self.visit_group_choice(gc)?;
}
Ok(())
}
fn visit_group_choice(&mut self, gc: &'b GroupChoice<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::GroupChoice(gc));
for (ge, _) in gc.group_entries.iter() {
let child = self.arena_tree.node(CDDLType::GroupEntry(ge));
self.insert(parent, child)?;
self.visit_group_entry(ge)?;
}
Ok(())
}
fn visit_group_entry(&mut self, entry: &'b GroupEntry<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::GroupEntry(entry));
match entry {
GroupEntry::ValueMemberKey { ge, .. } => {
let child = self.arena_tree.node(CDDLType::ValueMemberKeyEntry(ge));
self.insert(parent, child)?;
self.visit_value_member_key_entry(ge)?;
}
GroupEntry::TypeGroupname { ge, .. } => {
let child = self.arena_tree.node(CDDLType::TypeGroupnameEntry(ge));
self.insert(parent, child)?;
self.visit_type_groupname_entry(ge)?;
}
GroupEntry::InlineGroup { occur, group, .. } => {
if let Some(occur) = occur {
let child = self.arena_tree.node(CDDLType::Occurrence(occur));
self.insert(parent, child)?;
self.visit_occurrence(occur)?;
}
let child = self.arena_tree.node(CDDLType::Group(group));
self.insert(parent, child)?;
self.visit_group(group)?;
}
}
Ok(())
}
fn visit_value_member_key_entry(
&mut self,
entry: &'b ValueMemberKeyEntry<'a>,
) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::ValueMemberKeyEntry(entry));
if let Some(occur) = &entry.occur {
let child = self.arena_tree.node(CDDLType::Occurrence(occur));
self.insert(parent, child)?;
self.visit_occurrence(occur)?;
}
if let Some(mk) = &entry.member_key {
let child = self.arena_tree.node(CDDLType::MemberKey(mk));
self.insert(parent, child)?;
self.visit_memberkey(mk)?;
}
let child = self.arena_tree.node(CDDLType::Type(&entry.entry_type));
self.insert(parent, child)?;
self.visit_type(&entry.entry_type)
}
fn visit_type_groupname_entry(
&mut self,
entry: &'b TypeGroupnameEntry<'a>,
) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::TypeGroupnameEntry(entry));
if let Some(o) = &entry.occur {
let child = self.arena_tree.node(CDDLType::Occurrence(o));
self.insert(parent, child)?;
self.visit_occurrence(o)?;
}
if let Some(ga) = &entry.generic_args {
let child = self.arena_tree.node(CDDLType::GenericArgs(ga));
self.insert(parent, child)?;
self.visit_generic_args(ga)?;
}
let child = self.arena_tree.node(CDDLType::Identifier(&entry.name));
self.insert(parent, child)?;
self.visit_identifier(&entry.name)
}
fn visit_inline_group_entry(
&mut self,
occur: Option<&'b Occurrence<'a>>,
g: &'b Group<'a>,
) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::Group(g));
if let Some(o) = occur {
self.visit_occurrence(o)?;
}
for gc in g.group_choices.iter() {
let child = self.arena_tree.node(CDDLType::GroupChoice(gc));
self.insert(parent, child)?;
}
self.visit_group(g)
}
fn visit_occurrence(&mut self, o: &'b Occurrence<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::Occurrence(o));
let child = self.arena_tree.node(CDDLType::Occur(o.occur));
self.insert(parent, child)?;
Ok(())
}
fn visit_memberkey(&mut self, mk: &'b MemberKey<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::MemberKey(mk));
match mk {
MemberKey::Type1 { t1, .. } => {
let child = self.arena_tree.node(CDDLType::Type1(t1));
self.insert(parent, child)?;
self.visit_type1(t1)
}
MemberKey::Bareword { ident, .. } => {
let child = self.arena_tree.node(CDDLType::Identifier(ident));
self.insert(parent, child)?;
self.visit_identifier(ident)
}
MemberKey::Value { value, .. } => {
let child = self.arena_tree.node(CDDLType::Value(value.to_owned()));
self.insert(parent, child)?;
self.visit_value(value)
}
MemberKey::NonMemberKey { non_member_key, .. } => {
let child = self.arena_tree.node(CDDLType::NonMemberKey(non_member_key));
self.insert(parent, child)?;
self.visit_nonmemberkey(non_member_key)
}
}
}
fn visit_generic_args(&mut self, args: &'b GenericArgs<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::GenericArgs(args));
for arg in args.args.iter() {
let child = self.arena_tree.node(CDDLType::GenericArg(arg));
self.insert(parent, child)?;
self.visit_generic_arg(arg)?;
}
Ok(())
}
fn visit_generic_arg(&mut self, arg: &'b GenericArg<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::GenericArg(arg));
let child = self.arena_tree.node(CDDLType::Type1(&arg.arg));
self.insert(parent, child)?;
self.visit_type1(&arg.arg)
}
fn visit_generic_params(&mut self, params: &'b GenericParams<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::GenericParams(params));
for param in params.params.iter() {
let child = self.arena_tree.node(CDDLType::GenericParam(param));
self.insert(parent, child)?;
self.visit_generic_param(param)?;
}
Ok(())
}
fn visit_generic_param(&mut self, param: &'b GenericParam<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::GenericParam(param));
let child = self.arena_tree.node(CDDLType::Identifier(¶m.param));
self.insert(parent, child)?;
self.visit_identifier(¶m.param)
}
fn visit_nonmemberkey(&mut self, nmk: &'b NonMemberKey<'a>) -> visitor::Result<Error> {
let parent = self.arena_tree.node(CDDLType::NonMemberKey(nmk));
match nmk {
NonMemberKey::Group(group) => {
let child = self.arena_tree.node(CDDLType::Group(group));
self.insert(parent, child)?;
self.visit_group(group)
}
NonMemberKey::Type(t) => {
let child = self.arena_tree.node(CDDLType::Type(t));
self.insert(parent, child)?;
self.visit_type(t)
}
}
}
}
#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
#![allow(unused_imports)]
use crate::cddl_from_str;
use std::borrow::Borrow;
use super::*;
#[test]
fn rule_parent_is_cddl() -> Result<()> {
let cddl = cddl_from_str(r#"a = "myrule""#, true).unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
let rule = cddl.rules.first().unwrap();
assert_eq!(rule.parent(&pv).unwrap(), &cddl);
Ok(())
}
#[test]
fn type_and_group_rule_parent_is_rule() -> Result<()> {
let cddl = cddl_from_str(
r#"
a = "myrule"
b = ( * tstr )
"#,
true,
)
.unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let r @ Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
assert_eq!(rule.parent(&pv).unwrap(), r);
}
if let r @ Rule::Group { rule, .. } = cddl.rules.get(1).unwrap() {
assert_eq!(rule.parent(&pv).unwrap(), r);
}
Ok(())
}
#[test]
fn type_parent_is_type_rule() -> Result<()> {
let cddl = cddl_from_str(r#"a = "myrule""#, true).unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
let parent: &TypeRule = rule.value.parent(&pv).unwrap();
assert_eq!(parent, rule);
}
Ok(())
}
#[test]
fn type_choice_parent_is_type() -> Result<()> {
let cddl = cddl_from_str(r#"a = "myrule""#, true).unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
assert_eq!(
rule
.value
.type_choices
.first()
.unwrap()
.parent(&pv)
.unwrap(),
&rule.value
);
}
Ok(())
}
#[test]
fn type1_parent_is_type_choice() -> Result<()> {
let cddl = cddl_from_str(r#"a = "myrule""#, true).unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
let parent: &TypeChoice = rule
.value
.type_choices
.first()
.unwrap()
.type1
.parent(&pv)
.unwrap();
assert_eq!(parent, rule.value.type_choices.first().unwrap());
}
Ok(())
}
#[test]
fn type2_parent_is_type1() -> Result<()> {
let cddl = cddl_from_str(r#"a = "myrule""#, true).unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
let parent: &Type1 = rule
.value
.type_choices
.first()
.unwrap()
.type1
.type2
.parent(&pv)
.unwrap();
assert_eq!(parent, &rule.value.type_choices.first().unwrap().type1);
}
Ok(())
}
#[test]
fn text_value_parent_is_type2() -> Result<()> {
let cddl = cddl_from_str(r#"a = "myrule""#, true).unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
if let t2 @ Type2::TextValue { value, .. } =
&rule.value.type_choices.first().unwrap().type1.type2
{
let value = Value::from(value.borrow());
let parent: &Type2 = value.parent(&pv).unwrap();
assert_eq!(parent, t2);
}
}
Ok(())
}
#[test]
fn group_entry_parent_is_group_rule() -> Result<()> {
let cddl = cddl_from_str(r#"a = ( * tstr )"#, true).unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Group { rule, .. } = cddl.rules.first().unwrap() {
let parent: &GroupRule = rule.entry.parent(&pv).unwrap();
assert_eq!(parent, rule.as_ref());
}
Ok(())
}
#[test]
fn type_rule_name_ident_parent_is_type_rule() -> Result<()> {
let cddl = cddl_from_str(r#"a = "myrule""#, true).unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
let parent: &TypeRule = rule.name.parent(&pv).unwrap();
assert_eq!(parent, rule);
}
Ok(())
}
#[test]
fn generic_params_parent_is_type_rule() -> Result<()> {
let cddl = cddl_from_str(r#"a<t> = { type: t }"#, true).unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
let parent: &TypeRule = rule.generic_params.as_ref().unwrap().parent(&pv).unwrap();
assert_eq!(parent, rule);
}
Ok(())
}
#[test]
fn generic_param_parent_is_generic_params() -> Result<()> {
let cddl = cddl_from_str(r#"a<t> = { type: t }"#, true).unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
assert_eq!(
rule
.generic_params
.as_ref()
.unwrap()
.params
.first()
.unwrap()
.parent(&pv)
.unwrap(),
rule.generic_params.as_ref().unwrap()
);
}
Ok(())
}
#[test]
fn generic_args_parent_is_type2() -> Result<()> {
let cddl = cddl_from_str(
r#"
message<name, value> = {}
messages = message<"reboot", "now"> / message<"sleep", 1..100>
"#,
true,
)
.unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
if let t2 @ Type2::Typename {
generic_args: Some(ga),
..
} = &rule.value.type_choices.first().unwrap().type1.type2
{
let parent: &Type2 = ga.parent(&pv).unwrap();
assert_eq!(parent, t2);
}
}
Ok(())
}
#[test]
fn generic_arg_parent_is_generic_args() -> Result<()> {
let cddl = cddl_from_str(
r#"
message<name, value> = {}
messages = message<"reboot", "now"> / message<"sleep", 1..100>
"#,
true,
)
.unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
if let Type2::Typename {
generic_args: Some(ga),
..
} = &rule.value.type_choices.first().unwrap().type1.type2
{
assert_eq!(ga.args.first().unwrap().parent(&pv).unwrap(), ga);
}
}
Ok(())
}
#[test]
fn group_parent_is_type2() -> Result<()> {
let cddl = cddl_from_str(
r#"
a = { b }
b = ( * tstr => int )
"#,
true,
)
.unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
if let t2 @ Type2::Map { group, .. } = &rule.value.type_choices.first().unwrap().type1.type2 {
let parent: &Type2 = group.parent(&pv).unwrap();
assert_eq!(parent, t2);
}
}
Ok(())
}
#[test]
fn identifier_parent_is_type2() -> Result<()> {
let cddl = cddl_from_str(
r#"
terminal-color = &basecolors
basecolors = (
black: 0, red: 1, green: 2, yellow: 3,
blue: 4, magenta: 5, cyan: 6, white: 7,
)
"#,
true,
)
.unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
if let t2 @ Type2::ChoiceFromGroup { ident, .. } =
&rule.value.type_choices.first().unwrap().type1.type2
{
let parent: &Type2 = ident.parent(&pv).unwrap();
assert_eq!(parent, t2);
}
}
Ok(())
}
#[test]
fn ctrl_parent_is_rangectlop() -> Result<()> {
let cddl = cddl_from_str(r#"ip4 = bstr .size 4"#, true).unwrap();
let pv = ParentVisitor::new(&cddl).unwrap();
if let Rule::Type { rule, .. } = cddl.rules.first().unwrap() {
if let op @ RangeCtlOp::CtlOp { ctrl, .. } = &rule
.value
.type_choices
.first()
.unwrap()
.type1
.operator
.as_ref()
.unwrap()
.operator
{
assert_eq!(ctrl.parent(&pv).unwrap(), op)
}
}
Ok(())
}
}
|
use midir::{MidiInput, MidiOutput};
pub struct LaunchKey {
note_in: MidiInput,
control_in: MidiInput,
control_out: MidiOutput
}
impl LaunchKey {
pub fn new() -> LaunchKey {
println!("{}", MidiInput::new("test").unwrap().port_count());
LaunchKey {
note_in: MidiInput::new("note in").unwrap(),
control_in: MidiInput::new("control in").unwrap(),
control_out: MidiOutput::new("control out").unwrap()
}
}
}
|
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct CommitMeta {
pub created: Option<String>,
pub sha: Option<String>,
pub url: Option<String>,
}
impl CommitMeta {
/// Create a builder for this object.
#[inline]
pub fn builder() -> CommitMetaBuilder {
CommitMetaBuilder {
body: Default::default(),
}
}
}
impl Into<CommitMeta> for CommitMetaBuilder {
fn into(self) -> CommitMeta {
self.body
}
}
/// Builder for [`CommitMeta`](./struct.CommitMeta.html) object.
#[derive(Debug, Clone)]
pub struct CommitMetaBuilder {
body: self::CommitMeta,
}
impl CommitMetaBuilder {
#[inline]
pub fn created(mut self, value: impl Into<String>) -> Self {
self.body.created = Some(value.into());
self
}
#[inline]
pub fn sha(mut self, value: impl Into<String>) -> Self {
self.body.sha = Some(value.into());
self
}
#[inline]
pub fn url(mut self, value: impl Into<String>) -> Self {
self.body.url = Some(value.into());
self
}
}
|
use std::{collections::HashSet, fs::File, io::Seek, str::FromStr, time::Instant};
use bbs::issuer::Issuer;
use bbs_revocation::{RegistryBuilder, RegistryReader};
use clap::{App, Arg};
use rand::{distributions::Uniform, rngs::OsRng, Rng};
fn build_test_registry(
output: &str,
block_size: u16,
index_count: u32,
revoked_perc: f64,
verify: bool,
) {
let (issuer_pk, issuer_sk) = Issuer::new_short_keys(None);
let reg_uri = "urn:my-registry";
let check_count = 10;
let revoked_count = ((index_count as f64) * revoked_perc / 100.0) as u32;
let mut rand_index = OsRng.sample_iter(Uniform::from(0..index_count));
let mut revoked = HashSet::new();
let mut r = 0;
while r < revoked_count {
if revoked.insert(rand_index.next().unwrap()) {
r += 1;
}
}
let mut f = File::create(output).expect("Error creating output file");
let timer = Instant::now();
let registry = RegistryBuilder::new(reg_uri, block_size, index_count, &issuer_pk, &issuer_sk);
let entry_count = registry.write(&mut f, revoked.iter().copied()).unwrap();
f.sync_all().unwrap();
let reg_size = f.stream_position().unwrap();
let dur = timer.elapsed();
drop(f); // close file
println!(
"Wrote registry: {} indices, {} revoked in {:0.2}s",
index_count,
revoked_count,
dur.as_secs_f32()
);
println!(
"Registry size: {:0.1}kb, {} entries",
(reg_size as f64) / 1024.0,
entry_count,
);
if verify {
let mut f = File::open(output).expect("Error opening registry file");
let timer = Instant::now();
let mut reader = RegistryReader::new(&mut f).unwrap();
let count = reader.entry_count_reset().unwrap();
let dur = timer.elapsed();
println!(
"Read {} non-revocation entries in {:0.2}s",
count,
dur.as_secs_f32()
);
// for entry in reader {
// let e = entry.unwrap();
// print!("{}: ", e.level);
// for idx in e.unique_indices() {
// print!("{} ", idx);
// }
// print!("\n");
// }
// return;
if revoked_count < index_count {
for _ in 0..check_count {
let verkey = reader.public_key();
let mut check_idx = OsRng.sample(Uniform::from(0..index_count));
loop {
if !revoked.contains(&check_idx) {
if let Some(cred) = reader.find_credential_reset(check_idx).unwrap() {
let verify = cred
.signature
.verify(&cred.messages()[..], &verkey)
.unwrap();
if verify {
println!(
"Checked: signature verifies for non-revoked index ({})",
check_idx
);
} else {
println!(
"Error: signature verification failed for non-revoked index ({})",
check_idx
);
return;
}
} else {
println!(
"Error: signature not found for non-revoked index ({})",
check_idx
);
return;
}
break;
}
check_idx = (check_idx + 1) % index_count;
}
}
}
if !revoked.is_empty() {
let mut rev_iter = revoked.iter().copied();
for _ in 0..check_count {
if let Some(check_idx) = rev_iter.next() {
if let None = reader.find_credential_reset(check_idx).unwrap() {
println!(
"Checked: signature missing for revoked index ({})",
check_idx
);
} else {
println!("Error: found signature for revoked index ({})", check_idx);
return;
}
}
}
}
// verify every entry:
// for check_idx in 0..index_count {
// let sig = reader.find_credential_reset(check_idx).unwrap();
// if revoked.contains(&check_idx) && sig.is_some() {
// println!("Found invalid signature {}", check_idx);
// return;
// } else if !revoked.contains(&check_idx) && sig.is_none() {
// println!("Missing required signature {}", check_idx);
// return;
// }
// }
}
}
fn main() {
let mut args_def = App::new("Test Registry Generator")
.version("0.1")
.author("Andrew Whitehead <cywolf@gmail.com>")
.about("Generate test registries for benchmarking")
.arg(
Arg::with_name("block-size")
.long("block-size")
.short("b")
.takes_value(true)
.help("Set the registry block size (multiple of 8, up to 64)")
.required(true),
)
.arg(
Arg::with_name("output")
.long("output")
.short("o")
.takes_value(true)
.help("Output filename (default 'test.reg')"),
)
.arg(
Arg::with_name("count")
.long("count")
.short("c")
.takes_value(true)
.required(true)
.help("Set the registry size"),
)
.arg(
Arg::with_name("percent")
.long("percent")
.short("p")
.takes_value(true)
.required(true)
.help("Set the (randomly) revoked percentage of the registry"),
)
.arg(
Arg::with_name("verify")
.long("verify")
.short("v")
.help("Verify the registry"),
);
let args = args_def.clone().get_matches();
let result: Result<(), &str> = (|| {
let output = args.value_of("output").unwrap_or("test.reg");
let block_size = args
.value_of("block-size")
.and_then(|s| u16::from_str(s).ok())
.and_then(|b| {
if b > 0 && b % 8 == 0 && b <= 64 {
Some(b)
} else {
None
}
})
.ok_or_else(|| "Block size must be between 8 and 64, and divisible by 8")?;
let index_count = args
.value_of("count")
.and_then(|s| u32::from_str(s).ok())
.and_then(|c| if c > 0 { Some(c) } else { None })
.ok_or_else(|| "Count must be an integer larger than zero")?;
let revoked_perc = args
.value_of("percent")
.and_then(|s| u32::from_str(s).ok())
.and_then(|p| if p <= 100 { Some(p) } else { None })
.ok_or_else(|| "Revocation percentage must be a positive integer")?;
let verify = args.is_present("verify");
build_test_registry(output, block_size, index_count, revoked_perc as f64, verify);
Ok(())
})();
if let Err(err) = result {
args_def.print_long_help().unwrap();
println!("\n{}", err);
}
}
|
const MAX_LEAF_SIZE: usize = 50;
pub trait Point: Copy + std::fmt::Debug {
type Dtype: PartialOrd + Copy + Into<f64> + std::fmt::Debug;
const NUM_DIMENSIONS: u8;
// Dimension parameter guaranteed to be less than NUM_DIMENSIONS.
fn get_val(&self, dimension: u8) -> Self::Dtype;
// Returns the distance-squared between current point and other
// point.
fn dist2(&self, other: &Self) -> f64;
}
#[derive(Debug)]
enum NodeData<T: Point> {
Internal {
left: usize,
right: usize,
dimension: u8,
median_val: T::Dtype,
},
Leaf {
i_initial: usize,
i_final: usize,
},
}
#[derive(Debug)]
struct Node<T: Point> {
num_points: u32,
parent: Option<usize>,
data: NodeData<T>,
}
pub struct KDTree<T: Point> {
points: Vec<Option<T>>,
nodes: Vec<Node<T>>,
}
#[derive(Clone, Copy)]
struct SearchRes {
dist2: f64,
point_index: usize,
leaf_node_index: usize,
}
#[derive(Clone, Copy, Debug)]
pub struct PerformanceStats {
pub nodes_checked: u32,
pub leaf_nodes_checked: u32,
pub points_checked: u32,
}
impl Default for PerformanceStats {
fn default() -> Self {
PerformanceStats {
nodes_checked: 0,
leaf_nodes_checked: 0,
points_checked: 0,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct KdtreeResult<T: Point> {
pub res: Option<T>,
pub stats: PerformanceStats,
}
impl<T> KDTree<T>
where
T: Point,
{
pub fn new(mut points: Vec<T>) -> Self {
let mut nodes = Vec::new();
Self::generate_nodes(&mut nodes, &mut points, 0, 0, None);
let points = points.iter().map(|p| Some(*p)).collect();
KDTree { points, nodes }
}
pub fn num_points(&self) -> usize {
self.nodes[0].num_points as usize
}
pub fn iter_points(&self) -> impl Iterator<Item = &Option<T>> {
self.points.iter()
}
fn generate_nodes(
nodes: &mut Vec<Node<T>>,
points: &mut [T],
point_index_offset: usize,
dimension: u8,
parent_index: Option<usize>,
) {
// If few enough points, make a leaf node.
if points.len() <= MAX_LEAF_SIZE {
let node = Node {
num_points: points.len() as u32,
parent: parent_index,
data: NodeData::Leaf {
i_initial: point_index_offset,
i_final: point_index_offset + points.len(),
},
};
nodes.push(node);
return;
}
let median_point_index = points.len() / 2;
// Can't use select_nth_unstable_by_key because that requires
// Ord, which f32/f64 don't implement. The .unwrap() could
// panic if passed NaN values.
points.select_nth_unstable_by(median_point_index, |a, b| {
a.get_val(dimension)
.partial_cmp(&b.get_val(dimension))
.unwrap()
});
let median_val = points[median_point_index].get_val(dimension);
let this_node_index = nodes.len();
let node = Node {
parent: parent_index,
num_points: points.len() as u32,
data: NodeData::Internal {
left: this_node_index + 1,
right: 0, // Will be overwritten once known
dimension,
median_val,
},
};
nodes.push(node);
let next_dimension = (dimension + 1) % T::NUM_DIMENSIONS;
// Generate the left subtree
Self::generate_nodes(
nodes,
&mut points[..median_point_index],
point_index_offset,
next_dimension,
Some(this_node_index),
);
// Now, the index of the right subtree is known and can be
// updated.
let right_node_index = nodes.len();
if let NodeData::Internal { right, .. } =
&mut nodes[this_node_index].data
{
*right = right_node_index;
}
// Generate the right subtree
Self::generate_nodes(
nodes,
&mut points[median_point_index..],
point_index_offset + median_point_index,
next_dimension,
Some(this_node_index),
);
}
#[allow(dead_code)]
pub fn get_closest(&self, target: &T, epsilon: f64) -> KdtreeResult<T> {
let mut stats = PerformanceStats::default();
let res = self
.get_closest_node(target, 0, &mut stats, epsilon)
.map(|res| self.points[res.point_index])
.flatten();
KdtreeResult { res, stats }
}
pub fn pop_closest(&mut self, target: &T, epsilon: f64) -> KdtreeResult<T> {
let mut stats = PerformanceStats::default();
let res = self.get_closest_node(target, 0, &mut stats, epsilon);
let res = match res {
None => None,
Some(res) => {
let output = self.points[res.point_index];
self.points[res.point_index] = None;
let mut node_index = Some(res.leaf_node_index);
while node_index != None {
let node = &mut self.nodes[node_index.unwrap()];
node.num_points -= 1;
node_index = node.parent;
}
output
}
};
KdtreeResult { res, stats }
}
fn get_closest_node(
&self,
target: &T,
node_index: usize,
stats: &mut PerformanceStats,
epsilon: f64,
) -> Option<SearchRes> {
let node = &self.nodes[node_index];
if node.num_points == 0 {
return None;
}
stats.nodes_checked += 1;
match &node.data {
NodeData::Leaf { i_initial, i_final } => {
stats.leaf_nodes_checked += 1;
stats.points_checked += node.num_points;
// If it is a leaf node, just check each distance.
let (point_index, dist2) = (*i_initial..*i_final)
.map(|i| (i, self.points[i]))
.filter_map(|(i, opt_p)| {
opt_p.map(|p| (i, p.dist2(target)))
})
.min_by(|(_, a_dist2), (_, b_dist2)| {
a_dist2.partial_cmp(b_dist2).unwrap()
})
.unwrap();
Some(SearchRes {
dist2,
leaf_node_index: node_index,
point_index,
})
}
NodeData::Internal {
left,
right,
dimension,
median_val,
} => {
let diff: f64 =
target.get_val(*dimension).into() - (*median_val).into();
let (search_first, search_second) = if diff < 0.0 {
(left, right)
} else {
(right, left)
};
// If it is an internal node, start by checking the
// half that contains the target point.
let res1 = self.get_closest_node(
target,
*search_first,
stats,
epsilon,
);
if res1
.filter(|r| {
let max_dist2 = (diff * (epsilon + 1.0)).powf(2.0);
r.dist2 < max_dist2
})
.is_some()
{
return res1;
}
let res2 = self.get_closest_node(
target,
*search_second,
stats,
epsilon,
);
[res1, res2]
.iter()
.flatten()
.min_by(|a, b| a.dist2.partial_cmp(&b.dist2).unwrap())
.map(|r| *r)
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[derive(Copy, Clone, Debug, PartialEq)]
struct TestPoint {
x: f32,
y: f32,
}
impl Point for TestPoint {
type Dtype = f32;
const NUM_DIMENSIONS: u8 = 2;
fn get_val(&self, dimension: u8) -> Self::Dtype {
match dimension {
0 => self.x,
1 => self.y,
_ => panic!("Invalid dimension requested"),
}
}
fn dist2(&self, other: &Self) -> f64 {
((self.x - other.x).powf(2.0) + (self.y - other.y).powf(2.0)).into()
}
}
#[test]
fn test_make_kdtree() {
let points = vec![
TestPoint { x: 0.0, y: 0.0 },
TestPoint { x: 0.5, y: -0.5 },
TestPoint { x: 1.0, y: 0.0 },
TestPoint { x: 0.0, y: -1.0 },
];
let tree = KDTree::new(points);
assert_eq!(tree.num_points(), 4);
}
#[test]
fn test_leaf_node() {
let points = (0..25)
.map(|i| TestPoint {
x: (i / 5) as f32,
y: (i % 5) as f32,
})
.collect::<Vec<_>>();
let tree = KDTree::new(points);
assert_eq!(
tree.get_closest(&TestPoint { x: 1.2, y: 1.2 }, 0.0).res,
Some(TestPoint { x: 1.0, y: 1.0 })
);
assert_eq!(
tree.get_closest(&TestPoint { x: 3.8, y: 1.49 }, 0.0).res,
Some(TestPoint { x: 4.0, y: 1.0 })
);
}
#[test]
fn test_multiple_layers() {
let points = (0..10000)
.map(|i| TestPoint {
x: (i / 100) as f32,
y: (i % 100) as f32,
})
.collect::<Vec<_>>();
let tree = KDTree::new(points);
assert!(tree.nodes.len() > 10000 / MAX_LEAF_SIZE);
assert_eq!(
tree.get_closest(&TestPoint { x: 1.2, y: 1.2 }, 0.0).res,
Some(TestPoint { x: 1.0, y: 1.0 })
);
assert_eq!(
tree.get_closest(&TestPoint { x: 3.8, y: 1.49 }, 0.0).res,
Some(TestPoint { x: 4.0, y: 1.0 })
);
}
#[test]
fn test_valid_indices() {
let points = (0..10000)
.map(|i| TestPoint {
x: (i / 100) as f32,
y: (i % 100) as f32,
})
.collect::<Vec<_>>();
let tree = KDTree::new(points);
tree.nodes.iter().for_each(|node| {
if let Some(parent) = node.parent {
assert!(parent < tree.nodes.len());
}
match node.data {
NodeData::Internal { left, right, .. } => {
assert!(left < tree.nodes.len());
assert!(right < tree.nodes.len());
}
NodeData::Leaf { i_initial, i_final } => {
assert!(i_initial < i_final);
assert!(i_initial < tree.points.len());
assert!(i_final <= tree.points.len());
}
}
});
}
#[test]
fn test_pop_results() {
let points = (0..10000)
.map(|i| TestPoint {
x: (i / 100) as f32,
y: (i % 100) as f32,
})
.collect::<Vec<_>>();
let mut tree = KDTree::new(points);
assert!(tree.nodes.len() > 10000 / MAX_LEAF_SIZE);
assert_eq!(
tree.pop_closest(&TestPoint { x: 1.45, y: 1.55 }, 0.0).res,
Some(TestPoint { x: 1.0, y: 2.0 })
);
assert_eq!(
tree.pop_closest(&TestPoint { x: 1.45, y: 1.55 }, 0.0).res,
Some(TestPoint { x: 1.0, y: 1.0 })
);
assert_eq!(
tree.pop_closest(&TestPoint { x: 1.45, y: 1.55 }, 0.0).res,
Some(TestPoint { x: 2.0, y: 2.0 })
);
assert_eq!(
tree.pop_closest(&TestPoint { x: 1.45, y: 1.55 }, 0.0).res,
Some(TestPoint { x: 2.0, y: 1.0 })
);
for _i in 0..9995 {
assert_ne!(
tree.pop_closest(&TestPoint { x: 100.0, y: 100.0 }, 0.0).res,
None
)
}
assert_eq!(
tree.pop_closest(&TestPoint { x: 100.0, y: 100.0 }, 0.0).res,
Some(TestPoint { x: 0.0, y: 0.0 })
);
assert_eq!(
tree.pop_closest(&TestPoint { x: 100.0, y: 100.0 }, 0.0).res,
None
);
}
#[test]
fn test_epsilon() {
// This test relies on too many implementation details, maybe
// should be simplified. Makes a kd tree that deliberately
// has two leaf nodes, then look for a point close to the
// median. With epsilon==0, the exact point is found, but
// with more nodes checked. With epsilon>0, a close point is
// found, but with fewer leaf nodes checked.
let q1_points =
(0..MAX_LEAF_SIZE).map(|_i| TestPoint { x: -1.0, y: -2.0 });
let q3_points =
(0..MAX_LEAF_SIZE).map(|_i| TestPoint { x: 1.0, y: 2.0 });
let points = q1_points.chain(q3_points).collect::<Vec<_>>();
let tree = KDTree::new(points);
let res = tree.get_closest(&TestPoint { x: -0.1, y: 2.0 }, 0.0);
assert_eq!(res.res, Some(TestPoint { x: 1.0, y: 2.0 }));
assert_eq!(res.stats.leaf_nodes_checked, 2);
let res = tree.get_closest(&TestPoint { x: -0.1, y: 2.0 }, 5.0);
assert_eq!(res.res, Some(TestPoint { x: -1.0, y: -2.0 }));
assert_eq!(res.stats.leaf_nodes_checked, 1);
}
}
|
extern crate hyper;
extern crate futures;
use futures::future;
use hyper::{Body, Request, Response, Method, StatusCode, Server};
use hyper::Client;
use hyper::rt::{self, Future};
use hyper::service::service_fn;
static SERVICE_NAME: &str = "echo server";
type BoxFuture = Box<dyn Future<Item=Response<Body>, Error=hyper::Error> + Send>;
fn echo(req: Request<Body>) -> BoxFuture {
let method = req.method();
let path = req.uri().path();
println!("{} received request method: {} on path: {}",SERVICE_NAME, method, path);
let mut response = Response::new(Body::empty());
match(method, path) {
(&Method::GET, "/") => {
*response.body_mut() = Body::from("Try POSTing data to /echo\n");
},
(&Method::POST, "/echo") => {
*response.body_mut() = req.into_body();
},
_ => {
*response.status_mut() = StatusCode::NOT_FOUND;
},
};
Box::new(future::ok(response))
}
fn main() {
rt::run(rt::lazy(||{
let client = Client::new();
let json = r#"{
"ID": "echo 1",
"Name":"echo",
"Tags": ["v1"],
"Address": "127.0.0.1",
"Port": 3000,
"Meta": {
"rust_version": "1.35.0"
}
}"#;
let req = Request::builder()
.method("PUT")
.uri("http://127.0.0.1:8500/v1/agent/service/register")
.body(Body::from(json))
.expect("req builder");
client
.request(req)
.map(|res| {
println!("Registration status: {}", res.status());
}).map_err(|err| {
println!("{}", err);
})
}));
let addr = ([127, 0, 0, 1], 3000).into();
let server = Server::bind(&addr)
.serve(|| service_fn(echo))
.map_err(|e| eprintln!("Server error {}", e));
println!("{} running", SERVICE_NAME);
hyper::rt::run(server);
} |
use rand::prelude::*;
use libra_crypto::{
hash::{CryptoHasher, TestOnlyHasher},
HashValue,
};
use sgtypes::s_value::SValue;
use std::time::{SystemTime, UNIX_EPOCH};
fn get_unix_ts() -> u64 {
let start = SystemTime::now();
let since_the_epoch = start
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
since_the_epoch.as_millis() as u64
}
pub fn generate_random_u128() -> u128 {
let mut rng: StdRng = SeedableRng::seed_from_u64(get_unix_ts());
rng.gen::<u128>()
}
pub struct SValueGenerator {
sender_r: u128,
receiver_r: u128,
}
impl SValueGenerator {
pub fn new(sender_r: u128, receiver_r: u128) -> Self {
Self {
sender_r,
receiver_r,
}
}
pub fn get_r(&self) -> HashValue {
let mut bytes_vec = Vec::new();
bytes_vec.extend_from_slice(&self.sender_r.to_le_bytes());
bytes_vec.extend_from_slice(&self.receiver_r.to_le_bytes());
let mut hasher = TestOnlyHasher::default();
hasher.write(bytes_vec.as_slice());
hasher.finish()
}
pub fn get_s(&self, is_sender: bool) -> SValue {
let mut bytes_vec = Vec::new();
bytes_vec.extend_from_slice(&self.sender_r.to_le_bytes());
bytes_vec.extend_from_slice(&self.receiver_r.to_le_bytes());
let mut result: [u8; 33] = [0; 33];
if !is_sender {
result[0] = 1;
}
result[1..33].copy_from_slice(&bytes_vec);
SValue::new(result)
}
}
|
extern crate "cargo-registry" as cargo_registry;
extern crate civet;
extern crate green;
extern crate rustuv;
extern crate git2;
use std::os;
use std::sync::Arc;
use std::io::{mod, fs, File};
use civet::Server;
fn main() {
let url = env("GIT_REPO_URL");
let checkout = Path::new(env("GIT_REPO_CHECKOUT"));
let repo = match git2::Repository::open(&checkout) {
Ok(r) => r,
Err(..) => {
let _ = fs::rmdir_recursive(&checkout);
fs::mkdir_recursive(&checkout, io::UserDir).unwrap();
let config = git2::Config::open_default().unwrap();
let url = url.as_slice();
cargo_registry::git::with_authentication(url, &config, |f| {
let cb = git2::RemoteCallbacks::new().credentials(f);
git2::build::RepoBuilder::new()
.remote_callbacks(cb)
.clone(url, &checkout)
}).unwrap()
}
};
let mut cfg = repo.config().unwrap();
cfg.set_str("user.name", "bors").unwrap();
cfg.set_str("user.email", "bors@rust-lang.org").unwrap();
let config = cargo_registry::Config {
s3_bucket: env("S3_BUCKET"),
s3_access_key: env("S3_ACCESS_KEY"),
s3_secret_key: env("S3_SECRET_KEY"),
s3_proxy: None,
session_key: env("SESSION_KEY"),
git_repo_checkout: checkout,
gh_client_id: env("GH_CLIENT_ID"),
gh_client_secret: env("GH_CLIENT_SECRET"),
db_url: env("DATABASE_URL"),
env: cargo_registry::Development,
max_upload_size: 2 * 1024 * 1024,
};
let app = cargo_registry::App::new(&config);
if os::getenv("RESET").is_some() {
app.db_setup();
}
let app = cargo_registry::middleware(Arc::new(app));
let heroku = os::getenv("HEROKU").is_some();
let port = if heroku {
8888
} else {
os::getenv("PORT").and_then(|s| from_str(s.as_slice()))
.unwrap_or(8888)
};
let _a = Server::start(civet::Config { port: port, threads: 8 }, app);
println!("listening on port {}", port);
if heroku {
File::create(&Path::new("/tmp/app-initialized")).unwrap();
}
wait_for_sigint();
}
fn env(s: &str) -> String {
match os::getenv(s) {
Some(s) => s,
None => fail!("must have `{}` defined", s),
}
}
// libnative doesn't have signal handling yet
fn wait_for_sigint() {
use green::{SchedPool, PoolConfig, GreenTaskBuilder};
use std::io::signal::{Listener, Interrupt};
use std::task::TaskBuilder;
let mut config = PoolConfig::new();
config.event_loop_factory = rustuv::event_loop;
let mut pool = SchedPool::new(config);
TaskBuilder::new().green(&mut pool).spawn(proc() {
let mut l = Listener::new();
l.register(Interrupt).unwrap();
l.rx.recv();
});
pool.shutdown();
}
|
#[doc = "Register `APB1FZR2` reader"]
pub type R = crate::R<APB1FZR2_SPEC>;
#[doc = "Register `APB1FZR2` writer"]
pub type W = crate::W<APB1FZR2_SPEC>;
#[doc = "Field `DBG_LPTIM2_STOP` reader - DBG_LPTIM2_STOP"]
pub type DBG_LPTIM2_STOP_R = crate::BitReader<DBG_LPTIM2_STOP_A>;
#[doc = "DBG_LPTIM2_STOP\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DBG_LPTIM2_STOP_A {
#[doc = "0: LPTIMx counter clock is fed even if the core is halted"]
Continue = 0,
#[doc = "1: LPTIMx counter clock is stopped when the core is halted"]
Stop = 1,
}
impl From<DBG_LPTIM2_STOP_A> for bool {
#[inline(always)]
fn from(variant: DBG_LPTIM2_STOP_A) -> Self {
variant as u8 != 0
}
}
impl DBG_LPTIM2_STOP_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DBG_LPTIM2_STOP_A {
match self.bits {
false => DBG_LPTIM2_STOP_A::Continue,
true => DBG_LPTIM2_STOP_A::Stop,
}
}
#[doc = "LPTIMx counter clock is fed even if the core is halted"]
#[inline(always)]
pub fn is_continue(&self) -> bool {
*self == DBG_LPTIM2_STOP_A::Continue
}
#[doc = "LPTIMx counter clock is stopped when the core is halted"]
#[inline(always)]
pub fn is_stop(&self) -> bool {
*self == DBG_LPTIM2_STOP_A::Stop
}
}
#[doc = "Field `DBG_LPTIM2_STOP` writer - DBG_LPTIM2_STOP"]
pub type DBG_LPTIM2_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_LPTIM2_STOP_A>;
impl<'a, REG, const O: u8> DBG_LPTIM2_STOP_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "LPTIMx counter clock is fed even if the core is halted"]
#[inline(always)]
pub fn continue_(self) -> &'a mut crate::W<REG> {
self.variant(DBG_LPTIM2_STOP_A::Continue)
}
#[doc = "LPTIMx counter clock is stopped when the core is halted"]
#[inline(always)]
pub fn stop(self) -> &'a mut crate::W<REG> {
self.variant(DBG_LPTIM2_STOP_A::Stop)
}
}
#[doc = "Field `DBG_LPTIM3_STOP` reader - DBG_LPTIM3_STOP"]
pub use DBG_LPTIM2_STOP_R as DBG_LPTIM3_STOP_R;
#[doc = "Field `DBG_LPTIM3_STOP` writer - DBG_LPTIM3_STOP"]
pub use DBG_LPTIM2_STOP_W as DBG_LPTIM3_STOP_W;
impl R {
#[doc = "Bit 5 - DBG_LPTIM2_STOP"]
#[inline(always)]
pub fn dbg_lptim2_stop(&self) -> DBG_LPTIM2_STOP_R {
DBG_LPTIM2_STOP_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - DBG_LPTIM3_STOP"]
#[inline(always)]
pub fn dbg_lptim3_stop(&self) -> DBG_LPTIM3_STOP_R {
DBG_LPTIM3_STOP_R::new(((self.bits >> 6) & 1) != 0)
}
}
impl W {
#[doc = "Bit 5 - DBG_LPTIM2_STOP"]
#[inline(always)]
#[must_use]
pub fn dbg_lptim2_stop(&mut self) -> DBG_LPTIM2_STOP_W<APB1FZR2_SPEC, 5> {
DBG_LPTIM2_STOP_W::new(self)
}
#[doc = "Bit 6 - DBG_LPTIM3_STOP"]
#[inline(always)]
#[must_use]
pub fn dbg_lptim3_stop(&mut self) -> DBG_LPTIM3_STOP_W<APB1FZR2_SPEC, 6> {
DBG_LPTIM3_STOP_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "DBGMCU CPU1 APB1 Peripheral Freeze Register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1fzr2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb1fzr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct APB1FZR2_SPEC;
impl crate::RegisterSpec for APB1FZR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`apb1fzr2::R`](R) reader structure"]
impl crate::Readable for APB1FZR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`apb1fzr2::W`](W) writer structure"]
impl crate::Writable for APB1FZR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets APB1FZR2 to value 0"]
impl crate::Resettable for APB1FZR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use async_trait::async_trait;
use uuid::Uuid;
use common::cache::Cache;
use common::error::Error;
use common::infrastructure::cache::InMemCache;
use common::result::Result;
use crate::domain::content_manager::{ContentManager, ContentManagerId, ContentManagerRepository};
use crate::mocks;
pub struct InMemContentManagerRepository {
cache: InMemCache<ContentManagerId, ContentManager>,
}
impl InMemContentManagerRepository {
pub fn new() -> Self {
InMemContentManagerRepository {
cache: InMemCache::new(),
}
}
pub async fn populated() -> Self {
let repo = Self::new();
repo.save(&mut mocks::content_manager1()).await.unwrap();
repo
}
}
impl Default for InMemContentManagerRepository {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl ContentManagerRepository for InMemContentManagerRepository {
async fn next_id(&self) -> Result<ContentManagerId> {
let id = Uuid::new_v4();
ContentManagerId::new(id.to_string())
}
async fn find_by_id(&self, id: &ContentManagerId) -> Result<ContentManager> {
self.cache
.get(id)
.await
.ok_or(Error::new("content_manager", "not_found"))
}
async fn save(&self, content_manager: &mut ContentManager) -> Result<()> {
self.cache
.set(content_manager.base().id().clone(), content_manager.clone())
.await
}
}
|
use crate::{error, helpers};
use std::path::{Path, PathBuf};
use std::{env, io};
use structopt::StructOpt;
mod gui;
mod tmux;
trait OpenBackend {
fn run(&mut self, path: PathBuf, name: &str, opts: crate::EditorOpts) -> error::Result<()>;
}
#[derive(StructOpt, Debug)]
pub struct OpenOpts {
#[structopt(flatten)]
pub(crate) editor_opts: super::EditorOpts,
/// The name of the playground to open
pub(crate) name: String,
/// Do not pass -w flag when opening GUI editor
#[structopt(long, requires("gui"))]
pub(crate) no_w: bool,
/// Indicates the editor is a gui editor
#[structopt(short, long)]
pub gui: bool,
#[structopt(skip = false)]
pub(crate) skip_check: bool,
}
pub fn open(opts: OpenOpts) -> error::Result<()> {
let mut path = helpers::get_dir();
path.push(&opts.name); // Now represents playground path
if !opts.skip_check && !path.is_dir() {
return Err(error::Error::new(
io::ErrorKind::NotFound,
format!("could not find playground with at {:?}", path),
)
.with_help(
"use `cargo playground ls` to list available playgrounds
or `cargo playground new` to create a new playground",
));
}
if opts.gui {
helpers::print_status("Opening", &opts.name);
gui::Gui::new(opts.no_w).run(path, &opts.name, opts.editor_opts)
} else if env::var_os("TMUX").is_some() {
helpers::print_status("Opening", &opts.name);
tmux::Tmux.run(path, &opts.name, opts.editor_opts)
} else {
Err(error::Error::new(
io::ErrorKind::Other,
"currently only terminals running tmux are supported",
)
.with_help("try using the --gui flag with a GUI editor"))
}
}
fn path_to_str<'a>(path: &'a Path, path_name: &str) -> io::Result<&'a str> {
path.to_str().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"could not convert {} path {:?} to a utf-8 string",
path_name, path
),
)
})
}
|
//! This example demonstrates using the [attribute macro](https://doc.rust-lang.org/reference/procedural-macros.html#attribute-macros)
//! [`display_with`] to seamlessly augment field representations in a [`Table`] display.
//!
//! * [`display_with`] functions act as transformers during [`Table`] instantiation.
//!
//! * Note how [`display_with`] works with [std] and custom functions alike.
//!
//! * [`display_with`] attributes can be constructed in two ways (shown below).
//!
//! * Attribute arguments can be directly overridden with static values, effectively ignoring the
//! augmented fields natural value entirely. Even an entire object can be passed as context with `self`.
use std::borrow::Cow;
use tabled::{Table, Tabled};
#[derive(Tabled)]
#[tabled(rename_all = "camelCase")]
struct Country {
name: &'static str,
capital_city: &'static str,
#[tabled(display_with("display_perimeter", self))]
surface_area_km2: f32,
#[tabled(display_with = "str::to_lowercase")]
national_currency: &'static str,
national_currency_short: &'static str,
}
fn display_perimeter(country: &Country) -> Cow<'_, str> {
if country.surface_area_km2 > 1_000_000.0 {
"Very Big Land".into()
} else {
"Big Land".into()
}
}
impl Country {
fn new(
name: &'static str,
national_currency: &'static str,
national_currency_short: &'static str,
capital_city: &'static str,
surface_area_km2: f32,
) -> Self {
Self {
name,
national_currency,
national_currency_short,
capital_city,
surface_area_km2,
}
}
}
fn main() {
let data = [
Country::new("Afghanistan", "Afghani", "AFN", "Kabul", 652867.0),
Country::new("Angola", "Kwanza", "AOA", "Luanda", 1246700.0),
Country::new("Canada", "Canadian Dollar", "CAD", "Ottawa", 9984670.0),
];
let table = Table::new(data);
println!("{table}");
}
|
use std::collections::HashMap;
use std::io::{self, BufRead};
/// A key input constraint to note is that `numbers` contains a set of natural
/// numbers starting from one. The first value in `numbers` to swap into place
/// is `max`, with each subsequent value being less by one. Using `indices` to
/// access the index of values in `numbers` is roughly constant time. This
/// is more time efficient than repeatedly searching for the index of the next
/// value in `numbers` to swap.
fn permute(swaps: u32, numbers: &mut [u32], max: u32, indices: HashMap<u32, usize>) {
let mut indices = indices.clone();
let mut i : usize = 0;
let mut j_val = max;
let mut swaps = swaps;
while swaps > 0 && i < numbers.len() - 1 {
let j = indices.get(&j_val).cloned().unwrap();
// Swap only if necessary
if j != i {
let i_val = numbers[i];
numbers.swap(i, j);
// Updating the index cache for the number swapped into its final
// position is unnecessary since it should not be accessed again
indices.insert(i_val, j);
swaps -= 1;
}
j_val -= 1;
i += 1;
}
}
fn main() {
let stdin = io::stdin();
// Parse swaps allowed
let mut line = String::new();
stdin.read_line(&mut line).unwrap();
let swaps : u32 = line
.split_whitespace()
.map(|c| c.parse::<_>().unwrap())
.nth(1)
.unwrap();
// Parse permutation
line.clear();
stdin.read_line(&mut line).unwrap();
let mut max = 0;
let mut indices : HashMap<u32, usize> = HashMap::new();
let mut numbers : Vec<u32> = line
.split_whitespace()
.enumerate()
.map(|(i, c)| {
let n = c.parse::<_>().unwrap();
indices.insert(n, i);
if n > max {
max = n;
}
n
})
.collect();
permute(swaps, &mut numbers, max, indices);
// Print permutation in the required format
line = numbers
.iter()
.map(|c| c.to_string())
.collect::<Vec<_>>()
.join(" ");
println!("{}", line);
}
|
extern crate clap;
extern crate log;
extern crate rand;
extern crate serde;
extern crate serde_derive;
extern crate tokio;
pub mod agent;
pub mod conf;
pub mod play;
pub mod playexpert;
pub mod start;
pub mod util;
|
use chrono::{DateTime, Utc};
use serde::Deserialize;
use std::collections::HashMap;
#[derive(Debug, Deserialize)]
pub struct MyConfig {
pub projects: HashMap<String, MyProjectConfig>,
}
#[derive(Debug, Deserialize)]
pub struct MyProjectConfig {
pub gid: String,
pub horizon: DateTime<Utc>,
pub cfd_states: Vec<String>,
pub done_states: Vec<String>,
}
pub fn parse_config(config_str: &str) -> MyConfig {
let config: MyConfig = serde_json::from_str(config_str).expect("Invalid config");
return config;
}
|
fn main() {
let nth_prime = 10_001;
let mut counter = 0;
let mut current = 0;
let mut current_prime = 0;
while counter < nth_prime {
if is_prime(current as f64) {
current_prime = current;
counter += 1;
}
current += 1;
}
println!("{}", current_prime);
}
fn is_prime(x: f64) -> bool {
if x == 0.0 || x == 1.0 {
return false
}
let range = x.powf(0.5);
for i in 2..=range as i32 {
if x % i as f64 == 0.0 {
return false;
}
};
return true;
}
|
use serde::Serialize;
#[derive(Serialize, Debug)]
#[serde(untagged)]
pub enum Response {
Error {
error: String,
},
CheckResponse {
online: bool,
#[serde(skip_serializing_if = "Option::is_none")]
response_time: Option<usize>,
},
}
impl Response {
pub fn error(error: &str) -> Response {
Response::Error {
error: error.to_owned(),
}
}
pub fn check_response(online: bool, response_time: Option<usize>) -> Response {
Response::CheckResponse {
online,
response_time,
}
}
}
|
use crate::prelude::*;
pub mod prelude {
pub use super::{
ShiftLeft
};
}
mod marker {
use crate::prelude::*;
use crate::ExprMarker;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct ShiftLeftMarker;
impl ExprMarker for ShiftLeftMarker {
const EXPR_KIND: ExprKind = ExprKind::ShiftLeft;
}
}
/// Binary shift-left term expression.
///
/// # Note
///
/// Shifting to left means shifting the bits of the term expression from
/// the least significant position to the most significant position.
pub type ShiftLeft = BinTermExpr<marker::ShiftLeftMarker>;
impl From<ShiftLeft> for AnyExpr {
fn from(expr: ShiftLeft) -> AnyExpr {
AnyExpr::ShiftLeft(expr)
}
}
|
//! Tests for MetroRail Client
#[cfg(test)]
use super::*;
#[cfg(test)]
use tokio_test::block_on;
#[test]
fn test_constructor() {
let client = Client::new("9e38c3eab34c4e6c990828002828f5ed");
assert_eq!(client.key, "9e38c3eab34c4e6c990828002828f5ed");
}
#[test]
fn test_lines() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let lines = block_on(async { client.lines().await });
assert_eq!(lines.unwrap().lines.len(), 6);
}
#[test]
fn test_entrances() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let entrances = block_on(async { client.entrances(RadiusAtLatLong::new(1, 1.0, 1.0)).await });
assert_eq!(entrances.unwrap().entrances.len(), 0);
}
#[test]
fn test_stations() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let stations = block_on(async { client.stations_on(Some(Line::Red)).await });
assert_eq!(stations.unwrap().stations.len(), 27);
}
#[test]
fn test_all_stations() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let stations = block_on(async { client.stations_on(None).await });
assert_eq!(stations.unwrap().stations.len(), 95);
}
#[test]
fn test_station() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let station_to_station = block_on(async {
client
.station_to_station(Some(Station::A01), Some(Station::A02))
.await
});
assert_eq!(
station_to_station.unwrap().station_to_station_infos.len(),
1
);
}
#[test]
fn test_station_one_station() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let station_to_station =
block_on(async { client.station_to_station(Some(Station::A01), None).await });
assert_eq!(
station_to_station.unwrap().station_to_station_infos.len(),
93
);
}
#[test]
fn test_station_no_stations() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let station_to_station = block_on(async { client.station_to_station(None, None).await });
assert_eq!(
station_to_station.unwrap().station_to_station_infos.len(),
8922
);
}
#[test]
fn test_positions() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let positions = block_on(async { client.positions().await });
assert!(positions.is_ok());
}
#[test]
fn test_routes() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let routes = block_on(async { client.routes().await });
assert_eq!(routes.unwrap().standard_routes.len(), 14);
}
#[test]
fn test_circuits() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let circuits = block_on(async { client.circuits().await });
assert_eq!(circuits.unwrap().track_circuits.len(), 3486);
}
#[test]
fn test_elevator_and_escalator_incidents() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let incidents = block_on(async {
client
.elevator_and_escalator_incidents_at(Some(Station::A01))
.await
});
assert!(incidents.is_ok());
}
#[test]
fn test_all_elevator_and_escalator_incidents() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let incidents = block_on(async { client.elevator_and_escalator_incidents_at(None).await });
assert!(incidents.is_ok());
}
#[test]
fn test_incident() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let incidents = block_on(async { client.incidents_at(Some(Station::A01)).await });
assert!(incidents.is_ok());
}
#[test]
fn test_all_incidents() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let incidents = block_on(async { client.incidents_at(None).await });
assert!(incidents.is_ok());
}
#[test]
fn test_next_trains() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let next_trains = block_on(async { client.next_trains(Station::A01).await });
assert!(next_trains.is_ok());
}
#[test]
fn test_information() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let station_information = block_on(async { client.station_information(Station::A01).await });
assert_eq!(station_information.unwrap().station, Station::A01);
}
#[test]
fn test_parking_information() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let parking_information = block_on(async { client.parking_information(Station::A01).await });
assert_eq!(parking_information.unwrap().stations_parking.len(), 0);
}
#[test]
fn test_path_to_station() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let path = block_on(async { client.path_from(Station::A01, Station::A02).await });
assert_eq!(path.unwrap().path[1].distance_to_previous_station, 4178);
}
#[test]
fn test_timings() {
let client: Client = "9e38c3eab34c4e6c990828002828f5ed".parse().unwrap();
let timings = block_on(async { client.timings(Station::A01).await });
assert_eq!(timings.unwrap().station_times[0].station, Station::A01);
}
#[test]
fn test_station_name() {
let station = Station::A01;
assert_eq!(station.name(), "Metro Center");
}
#[test]
fn test_station_lines() {
let station = Station::N01;
assert_eq!(station.lines(), &[Line::Silver])
}
|
#[doc = "Records the full path to items"];
export mk_pass;
fn mk_pass() -> pass { run }
type ctxt = {
srv: astsrv::srv,
mutable path: [str]
};
fn run(srv: astsrv::srv, doc: doc::cratedoc) -> doc::cratedoc {
let ctxt = {
srv: srv,
mutable path: []
};
let fold = fold::fold({
fold_mod: fn~(
f: fold::fold<ctxt>,
d: doc::moddoc
) -> doc::moddoc {
fold_mod(f, d)
}
with *fold::default_seq_fold(ctxt)
});
fold.fold_crate(fold, doc)
}
fn fold_mod(fold: fold::fold<ctxt>, doc: doc::moddoc) -> doc::moddoc {
let is_topmod = doc.id == rustc::syntax::ast::crate_node_id;
if !is_topmod { vec::push(fold.ctxt.path, doc.name); }
let doc = fold::default_seq_fold_mod(fold, doc);
if !is_topmod { vec::pop(fold.ctxt.path); }
~{
path: fold.ctxt.path
with *doc
}
}
#[test]
fn should_record_mod_paths() {
let source = "mod a { mod b { mod c { } } mod d { mod e { } } }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = run(srv, doc);
assert doc.topmod.mods[0].mods[0].mods[0].path == ["a", "b"];
assert doc.topmod.mods[0].mods[1].mods[0].path == ["a", "d"];
} |
use std::io;
fn knot_hash(lengths: &Vec<usize>, rounds: usize) -> Vec<u32> {
let mut list: Vec<u32> = (0..256).collect();
let mut pos = 0;
let mut skip_size = 0;
for _i in 0..rounds {
for length in lengths {
for i in 0..(length / 2) {
let start = (pos + i) % list.len();
let end = (pos + length - i - 1) % list.len();
let tmp = list[start];
list[start] = list[end];
list[end] = tmp;
}
pos = (pos + length + skip_size) % list.len();
skip_size += 1;
}
}
list
}
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let input = input.trim();
let lengths: Vec<usize> = input.split(',').map(|val| val.parse().unwrap()).collect();
let list = knot_hash(&lengths, 1);
println!("part 1: {}", list[0] * list[1]);
let mut lengths: Vec<usize> = input.as_bytes().iter().map(|&b| b as usize).collect();
lengths.append(&mut vec![17, 31, 73, 47, 23]);
let list = knot_hash(&lengths, 64);
let dense_hash: Vec<u32> = (0..16)
.map(|n| list.iter().skip(n * 16).take(16).fold(0, |acc, b| acc ^ b))
.collect();
print!("part 2: ");
dense_hash.iter().for_each(|x| print!("{:02x}", x));
println!();
}
|
#[macro_use]
extern crate lazy_static;
extern crate ndarray;
extern crate mvdist_sys;
use mvdist_sys::{mvcrit as sys_mvcrit, mvdist as sys_mvdist};
use ndarray::prelude::*;
use std::sync::Mutex;
#[derive(Clone, Debug, Copy)]
pub enum BoundType {
Unbounded,
Above,
Below,
Both,
}
impl Into<i32> for BoundType {
fn into(self) -> i32 {
match self {
BoundType::Unbounded => -1,
BoundType::Above => 0,
BoundType::Below => 1,
BoundType::Both => 2,
}
}
}
#[derive(Clone, Debug, Copy, PartialEq)]
pub struct MVResult {
pub value: f64,
pub error: f64,
pub nevals: i32,
pub state: MVInform,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum MVInform {
Normal,
PtLimitReached,
}
lazy_static! {
static ref MVDIST_MUTEX: Mutex<()> = Mutex::new(());
}
fn column_ordered(ar: &Array2<f64>) -> Vec<f64> {
ar.t().into_iter().cloned().collect()
}
/// Call the `mvdist` function from `mvdist-sys`. This function is *not* thread-safe. **Do not make
/// calls to it from multiple threads and expect better performance.** A mutex is used to ensure
/// this is the case.
pub fn mvdist(cov: &Array2<f64>,
nu: i32,
lb: &Array1<f64>,
ub: &Array1<f64>,
types: &Vec<BoundType>,
constraints: &Array2<f64>,
delta: &Array1<f64>,
maxpts: i32,
abseps: f64,
releps: f64)
-> Result<MVResult, String> {
let shape = constraints.shape();
let (m, n) = (shape[0] as i32, shape[1] as i32);
let infin = types.iter().map(|&t| t.into()).collect::<Vec<i32>>();
let guard = MVDIST_MUTEX.lock();
let (error, value, nevals, inform) = sys_mvdist(n,
&column_ordered(cov),
nu,
m,
lb.as_slice().unwrap(),
&column_ordered(constraints),
ub.as_slice().unwrap(),
&infin,
delta.as_slice().unwrap(),
maxpts,
abseps,
releps);
// I don't normally like to explicitly drop, but this ensures that the guard doesn't get elided
// (which happens if let _ is used) and that I don't need #[allow(unused_variables)] to prevent
// the warning.
drop(guard);
match inform {
0 => Ok(MVInform::Normal),
1 => Ok(MVInform::PtLimitReached),
2 => Err(format!("Invalid choice of N")),
3 => Err(format!("Covariance matrix not positive semidefinite")),
x => Err(format!("Unknown error code {}", x)),
}
.and_then(|inf| {
Ok(MVResult {
error: error,
value: value,
nevals: nevals,
state: inf,
})
})
}
pub fn mvcrit(cov: &Array2<f64>,
nu: i32,
lb: &Array1<f64>,
ub: &Array1<f64>,
types: &Vec<BoundType>,
constraints: &Array2<f64>,
alpha: f64,
maxpts: i32,
abseps: f64)
-> Result<MVResult, String> {
let shape = constraints.shape();
let (m, n) = (shape[0] as i32, shape[1] as i32);
let infin = types.iter().map(|&t| t.into()).collect::<Vec<i32>>();
let guard = MVDIST_MUTEX.lock();
let (error, value, nevals, inform) = sys_mvcrit(n,
&column_ordered(cov),
nu,
m,
lb.as_slice().unwrap(),
&column_ordered(constraints),
ub.as_slice().unwrap(),
&infin,
alpha,
maxpts,
abseps);
// I don't normally like to explicitly drop, but this ensures that the guard doesn't get elided
// (which happens if let _ is used) and that I don't need #[allow(unused_variables)] to prevent
// the warning.
drop(guard);
match inform {
0 => Ok(MVInform::Normal),
1 => Ok(MVInform::PtLimitReached),
2 => Err(format!("Invalid bounds given.")),
x => Err(format!("Unknown error code {}", x)),
}
.and_then(|inf| {
Ok(MVResult {
error: error,
value: value,
nevals: nevals,
state: inf,
})
})
}
#[cfg(test)]
mod tests {
use super::*;
use ndarray::prelude::*;
#[test]
fn mvdist_works() {
let cov = Array::eye(4);
let con = arr2(&[[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
[1.0, 1.0, 1.0, 1.0]]);
let result = mvdist(&cov,
8,
&Array1::from_vec(vec![0.0; 5]),
&Array1::from_vec(vec![1.0; 5]),
&vec![BoundType::Both; 5],
&con,
&Array1::from_vec(vec![0.0; 5]),
100_000,
1e-5,
0.0)
.unwrap();
println!("{:?}", result);
assert!(result.state == MVInform::Normal);
assert!(result.nevals > 0 && result.nevals < 100_000);
assert!((result.value - 0.001).abs() < 0.0001);
assert!(result.error <= 1e-5);
}
#[test]
fn mvdist_works2() {
let a: Array2<f64> = arr2(&[[90.0, 60.0, 90.0],
[90.0, 90.0, 30.0],
[60.0, 60.0, 60.0],
[60.0, 60.0, 90.0],
[30.0, 30.0, 30.0]]);
let con = arr2(&[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 1.0, 1.0]]);
let centered = &a - &a.mean(Axis(0));
let cov = ¢ered.t().dot(¢ered) * (1.0 / (a.len_of(Axis(0)) as f64 - 1.0));
mvdist(&cov,
4,
&Array::zeros((4,)),
&Array1::from_vec(vec![100.0; 4]),
&vec![BoundType::Both; 4],
&con,
&Array::zeros((4,)),
100_000,
1e-5,
0.0)
.unwrap();
}
}
|
pub struct Player;
pub struct TerrainBlock; |
/*
* Copyright (c) 2020 Adel Prokurov
* All rights reserved.
* 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 super::ast::*;
use super::lexer::*;
use super::msg::*;
use super::reader::Reader;
use super::token::*;
use std::mem;
pub struct Parser<'a> {
lexer: Lexer,
token: Token,
ast: &'a mut Vec<Box<Expr>>,
}
macro_rules! expr {
($e:expr,$pos:expr) => {
Box::new(Expr {
pos: $pos,
expr: $e,
})
};
}
type EResult = Result<Box<Expr>, MsgWithPos>;
impl<'a> Parser<'a> {
pub fn new(reader: Reader, ast: &'a mut Vec<Box<Expr>>) -> Parser<'a> {
Self {
lexer: Lexer::new(reader),
token: Token::new(TokenKind::End, Position::new(1, 1)),
ast,
}
}
fn init(&mut self) -> Result<(), MsgWithPos> {
self.advance_token()?;
Ok(())
}
pub fn parse(&mut self) -> Result<(), MsgWithPos> {
self.init()?;
while !self.token.is_eof() {
self.parse_top_level()?;
}
Ok(())
}
fn expect_token(&mut self, kind: TokenKind) -> Result<Token, MsgWithPos> {
if self.token.kind == kind {
let token = self.advance_token()?;
Ok(token)
} else {
Err(MsgWithPos::new(
self.token.position,
Msg::ExpectedToken(kind.name().into(), self.token.name()),
))
}
}
fn parse_top_level(&mut self) -> Result<(), MsgWithPos> {
let expr = self.parse_expression()?;
self.ast.push(expr);
Ok(())
}
fn parse_function(&mut self) -> EResult {
let pos = self.expect_token(TokenKind::Fun)?.position;
let name = if let TokenKind::Identifier(_) = &self.token.kind {
Some(self.expect_identifier()?)
} else {
None
};
self.expect_token(TokenKind::LParen)?;
/* let params = if self.token.kind == TokenKind::RParen {
vec![]
} else {
let mut tmp = vec![];
while !self.token.is(TokenKind::RParen) {
tmp.push(self.expect_identifier()?);
if !self.token.is(TokenKind::RParen) {
self.expect_token(TokenKind::Comma)?;
}
}
tmp
};
self.expect_token(TokenKind::RParen)?;*/
let params = self.parse_comma_list(TokenKind::RParen, |parser| parser.parse_arg())?;
let block = self.parse_block()?;
Ok(expr!(ExprKind::Function(name, params, block), pos))
}
fn parse_arg(&mut self) -> Result<Arg, MsgWithPos> {
let pos = self.token.position;
let tok = self.token.kind.name();
match self.token.kind {
TokenKind::Var => {
self.advance_token()?;
Ok(Arg::Ident(true, self.expect_identifier()?))
}
TokenKind::Identifier { .. } => Ok(Arg::Ident(false, self.expect_identifier()?)),
TokenKind::LBrace => {
self.expect_token(TokenKind::LBrace)?;
let list: Vec<String> =
self.parse_comma_list(TokenKind::RBrace, |parser| parser.expect_identifier())?;
Ok(Arg::Record(list))
}
TokenKind::LBracket => {
self.expect_token(TokenKind::LBracket)?;
let list: Vec<String> = self
.parse_comma_list(TokenKind::RBracket, |parser| parser.expect_identifier())?;
Ok(Arg::Array(list))
}
_ => Err(MsgWithPos::new(
pos,
Msg::Custom(format!("unexpected token '{}' in argument position.", tok,)),
)),
}
}
fn parse_let(&mut self) -> EResult {
let reassignable = self.token.is(TokenKind::Var);
let pos = self.advance_token()?.position;
let pat = self.parse_pattern()?;
self.expect_token(TokenKind::Eq)?;
let expr = self.parse_expression()?;
Ok(expr!(ExprKind::Let(reassignable, pat, expr), pos))
}
fn parse_return(&mut self) -> EResult {
let pos = self.expect_token(TokenKind::Return)?.position;
let expr = self.parse_expression()?;
Ok(expr!(ExprKind::Return(Some(expr)), pos))
}
fn parse_expression(&mut self) -> EResult {
match self.token.kind {
/*TokenKind::New => {
let pos = self.advance_token()?.position;
let calling = self.parse_expression()?;
Ok(expr!(ExprKind::New(calling), pos))
}*/
TokenKind::Fun => self.parse_function(),
TokenKind::Class => self.parse_class(),
TokenKind::Match => self.parse_match(),
TokenKind::Let | TokenKind::Var => self.parse_let(),
TokenKind::LBrace => self.parse_block(),
TokenKind::If => self.parse_if(),
TokenKind::While => self.parse_while(),
TokenKind::Return => self.parse_return(),
TokenKind::Throw => self.parse_throw(),
TokenKind::Try => self.parse_try(),
_ => self.parse_binary(0),
}
}
fn parse_self(&mut self) -> EResult {
let pos = self.expect_token(TokenKind::This)?.position;
Ok(expr!(ExprKind::This, pos))
}
fn parse_throw(&mut self) -> EResult {
let pos = self.token.position;
self.advance_token()?;
Ok(expr!(ExprKind::Throw(self.parse_expression()?), pos))
}
fn parse_try(&mut self) -> EResult {
let pos = self.token.position;
self.advance_token()?;
let e = self.parse_expression()?;
self.expect_token(TokenKind::Catch)?;
let name = self.expect_identifier()?;
let c = self.parse_expression()?;
return Ok(expr!(ExprKind::Try(e, name, c), pos));
}
fn parse_while(&mut self) -> EResult {
let pos = self.expect_token(TokenKind::While)?.position;
let cond = self.parse_expression()?;
let block = self.parse_block()?;
Ok(expr!(ExprKind::While(cond, block), pos))
}
fn parse_if(&mut self) -> EResult {
let pos = self.expect_token(TokenKind::If)?.position;
let cond = self.parse_expression()?;
let then_block = self.parse_expression()?;
let else_block = if self.token.is(TokenKind::Else) {
self.advance_token()?;
if self.token.is(TokenKind::If) {
let if_block = self.parse_if()?;
let block = expr!(ExprKind::Block(vec![if_block]), if_block.pos);
Some(block)
} else {
Some(self.parse_expression()?)
}
} else {
None
};
Ok(expr!(ExprKind::If(cond, then_block, else_block), pos))
}
fn parse_block(&mut self) -> EResult {
let pos = self.expect_token(TokenKind::LBrace)?.position;
let mut exprs = vec![];
while !self.token.is(TokenKind::RBrace) && !self.token.is_eof() {
let expr = self.parse_expression()?;
exprs.push(expr);
}
self.expect_token(TokenKind::RBrace)?;
Ok(expr!(ExprKind::Block(exprs), pos))
}
fn create_binary(&mut self, tok: Token, left: Box<Expr>, right: Box<Expr>) -> Box<Expr> {
let op = match tok.kind {
TokenKind::Eq => return expr!(ExprKind::Assign(left, right), tok.position),
TokenKind::Or => "||",
TokenKind::And => "&&",
TokenKind::BitOr => "|",
TokenKind::BitAnd => "&",
TokenKind::EqEq => "==",
TokenKind::Ne => "!=",
TokenKind::Lt => "<",
TokenKind::Gt => ">",
TokenKind::Le => "<=",
TokenKind::Ge => ">=",
TokenKind::Caret => "^",
TokenKind::Add => "+",
TokenKind::Sub => "-",
TokenKind::Mul => "*",
TokenKind::Div => "/",
TokenKind::LtLt => "<<",
TokenKind::GtGt => ">>",
TokenKind::Mod => "%",
_ => unimplemented!(),
};
expr!(ExprKind::BinOp(left, op.to_owned(), right), tok.position)
}
fn parse_binary(&mut self, precedence: u32) -> EResult {
let mut left = self.parse_unary()?;
loop {
let right_precedence = match self.token.kind {
TokenKind::Or => 1,
TokenKind::And => 2,
TokenKind::Eq => 3,
TokenKind::EqEq
| TokenKind::Ne
| TokenKind::Lt
| TokenKind::Le
| TokenKind::Gt
| TokenKind::Ge => 4,
TokenKind::BitOr | TokenKind::BitAnd | TokenKind::Caret => 6,
TokenKind::LtLt | TokenKind::GtGt | TokenKind::Add | TokenKind::Sub => 8,
TokenKind::Mul | TokenKind::Div | TokenKind::Mod => 9,
_ => {
return Ok(left);
}
};
if precedence >= right_precedence {
return Ok(left);
}
let tok = self.advance_token()?;
left = {
let right = self.parse_binary(right_precedence)?;
self.create_binary(tok, left, right)
};
}
}
pub fn parse_unary(&mut self) -> EResult {
match self.token.kind {
TokenKind::Add | TokenKind::Sub | TokenKind::Not => {
let tok = self.advance_token()?;
let op = match tok.kind {
TokenKind::Add => String::from("+"),
TokenKind::Sub => String::from("-"),
TokenKind::Not => String::from("!"),
_ => unreachable!(),
};
let expr = self.parse_primary()?;
Ok(expr!(ExprKind::Unop(op, expr), tok.position))
}
_ => self.parse_primary(),
}
}
/*pub fn parse_expression(&mut self) -> EResult {
self.parse_binary(0)
}*/
pub fn parse_primary(&mut self) -> EResult {
let mut left = self.parse_factor()?;
loop {
left = match self.token.kind {
TokenKind::Dot => {
let tok = self.advance_token()?;
let ident = self.expect_identifier()?;
expr!(ExprKind::Access(left, ident), tok.position)
}
TokenKind::LBracket => {
let tok = self.advance_token()?;
let index = self.parse_expression()?;
self.expect_token(TokenKind::RBracket)?;
expr!(ExprKind::ArrayIndex(left, index), tok.position)
}
_ => {
if self.token.is(TokenKind::LParen) {
let expr = left;
self.expect_token(TokenKind::LParen)?;
let args =
self.parse_comma_list(TokenKind::RParen, |p| p.parse_expression())?;
expr!(ExprKind::Call(expr, args), expr.pos)
} else {
return Ok(left);
}
}
}
}
}
fn expect_identifier(&mut self) -> Result<String, MsgWithPos> {
let tok = self.advance_token()?;
if let TokenKind::Identifier(ref value) = tok.kind {
Ok(value.to_owned())
} else {
Err(MsgWithPos::new(
tok.position,
Msg::ExpectedIdentifier(tok.name()),
))
}
}
fn parse_comma_list<F, R>(
&mut self,
stop: TokenKind,
mut parse: F,
) -> Result<Vec<R>, MsgWithPos>
where
F: FnMut(&mut Parser) -> Result<R, MsgWithPos>,
{
let mut data = vec![];
let mut comma = true;
while !self.token.is(stop.clone()) && !self.token.is_eof() {
if !comma {
return Err(MsgWithPos::new(
self.token.position,
Msg::ExpectedToken(TokenKind::Comma.name().into(), self.token.name()),
));
}
let entry = parse(self)?;
data.push(entry);
comma = self.token.is(TokenKind::Comma);
if comma {
self.advance_token()?;
}
}
self.expect_token(stop)?;
Ok(data)
}
fn parse_list<F, R>(&mut self, stop: TokenKind, mut parse: F) -> Result<Vec<R>, MsgWithPos>
where
F: FnMut(&mut Parser) -> Result<R, MsgWithPos>,
{
let mut data = vec![];
while !self.token.is(stop.clone()) && !self.token.is_eof() {
let entry = parse(self)?;
data.push(entry);
}
self.expect_token(stop)?;
Ok(data)
}
fn advance_token(&mut self) -> Result<Token, MsgWithPos> {
let tok = self.lexer.read_token()?;
Ok(mem::replace(&mut self.token, tok))
}
fn parse_lambda(&mut self) -> EResult {
let tok = self.advance_token()?;
let params = if tok.kind == TokenKind::Or {
vec![]
} else {
self.parse_comma_list(TokenKind::BitOr, |f| f.parse_arg())?
};
let block = self.parse_expression()?;
Ok(expr!(ExprKind::Lambda(params, block), tok.position))
}
fn parse_class(&mut self) -> EResult {
let pos = self.expect_token(TokenKind::Class)?.position;
let name = self.expect_identifier()?;
let proto = if self.token.is(TokenKind::LParen) {
self.advance_token()?;
let proto = self.parse_expression()?;
self.expect_token(TokenKind::RParen)?;
Some(proto)
} else {
None
};
self.expect_token(TokenKind::LBrace)?;
let body = self.parse_list(TokenKind::RBrace, |p| {
let pos = p.token.position;
let name = p.token.name().to_owned();
let attr = match p.token.kind {
TokenKind::Fun => p.parse_function()?,
_ => return Err(MsgWithPos::new(pos, Msg::ExpectedClassElement(name))),
};
Ok(attr)
})?;
Ok(Expr {
pos,
expr: ExprKind::Class(name, proto, body),
})
.map(Box::new)
}
fn parse_match(&mut self) -> EResult {
let pos = self.expect_token(TokenKind::Match)?.position;
let e = self.parse_expression()?;
self.expect_token(TokenKind::LBrace)?;
let list = self.parse_comma_list(TokenKind::RBrace, |parser: &mut Parser| {
let pat = parser.parse_pattern()?;
let when_clause = if parser.token.is(TokenKind::When) || parser.token.is(TokenKind::Or)
{
parser.advance_token()?;
Some(parser.parse_expression()?)
} else {
None
};
parser.expect_token(TokenKind::Arrow)?;
let expr = parser.parse_expression()?;
Ok((pat, when_clause, expr))
})?;
Ok(Expr {
expr: ExprKind::Match(e, list),
pos,
})
.map(|x| Box::new(x))
}
fn parse_pattern(&mut self) -> Result<Box<Pattern>, MsgWithPos> {
let pos = self.token.position;
match self.token.kind {
TokenKind::Underscore => {
self.advance_token()?;
Ok(Box::new(Pattern {
pos,
decl: PatternDecl::Pass,
}))
}
TokenKind::LitInt { .. } => self.plit_int(),
TokenKind::LitFloat(_) => self.plit_float(),
TokenKind::String(_) => self.plit_str(),
TokenKind::Identifier(_) => self.pident(),
TokenKind::LBracket => self.parray(),
TokenKind::LBrace => self.precord(),
TokenKind::DotDot => {
let pos = self.advance_token()?.position;
Ok(Pattern {
decl: PatternDecl::Rest,
pos: pos,
})
.map(|x| Box::new(x))
}
_ => unimplemented!(),
}
}
pub fn parse_factor(&mut self) -> EResult {
let expr = match self.token.kind {
TokenKind::Fun => self.parse_function(),
TokenKind::LParen => self.parse_parentheses(),
TokenKind::LitChar(_) => self.lit_char(),
TokenKind::LitInt(_, _, _) => self.lit_int(),
TokenKind::LitFloat(_) => self.lit_float(),
TokenKind::String(_) => self.lit_str(),
TokenKind::Identifier(_) => self.ident(),
TokenKind::This => self.parse_self(),
TokenKind::BitOr | TokenKind::Or => self.parse_lambda(),
TokenKind::True => self.parse_bool_literal(),
TokenKind::False => self.parse_bool_literal(),
TokenKind::Nil => self.parse_null(),
TokenKind::New => {
let pos = self.token.position;
self.advance_token()?;
if self.token.is(TokenKind::LBrace) {
self.expect_token(TokenKind::LBrace)?;
let list = self.parse_comma_list(TokenKind::RBrace, |p| {
let name = p.expect_identifier()?;
let value = if p.token.is(TokenKind::Colon) {
p.advance_token()?;
Some(p.parse_expression()?)
} else {
None
};
Ok((name, value))
});
Ok(expr!(ExprKind::NewObject(list?), pos))
} else {
let call = self.parse_expression()?;
if let ExprKind::Call { .. } = call.expr {
Ok(expr!(ExprKind::New(call), pos))
} else {
Err(MsgWithPos::new(
self.token.position,
Msg::Custom("Function call expected".to_owned()),
))
}
}
}
_ => Err(MsgWithPos::new(
self.token.position,
Msg::ExpectedFactor(self.token.name().clone()),
)),
};
expr
}
fn parse_parentheses(&mut self) -> EResult {
self.advance_token()?;
let expr = self.parse_expression();
self.expect_token(TokenKind::RParen)?;
expr
}
fn parse_null(&mut self) -> EResult {
let tok = self.advance_token()?;
let pos = tok.position;
if let TokenKind::Nil = tok.kind {
Ok(expr!(ExprKind::Nil, pos))
} else {
unreachable!()
}
}
fn parse_bool_literal(&mut self) -> EResult {
let tok = self.advance_token()?;
let value = tok.is(TokenKind::True);
Ok(expr!(ExprKind::ConstBool(value), tok.position))
}
fn lit_int(&mut self) -> EResult {
let tok = self.advance_token()?;
let pos = tok.position;
if let TokenKind::LitInt(i, _, _) = tok.kind {
Ok(expr!(ExprKind::ConstInt(i.parse().unwrap()), pos))
} else {
unreachable!()
}
}
fn lit_char(&mut self) -> EResult {
let tok = self.advance_token()?;
let pos = tok.position;
if let TokenKind::LitChar(c) = tok.kind {
Ok(expr!(ExprKind::ConstChar(c), pos))
} else {
unreachable!()
}
}
fn lit_float(&mut self) -> EResult {
let tok = self.advance_token()?;
let pos = tok.position;
if let TokenKind::LitFloat(c) = tok.kind {
Ok(expr!(ExprKind::ConstFloat(c.parse().unwrap()), pos))
} else {
unreachable!()
}
}
fn lit_str(&mut self) -> EResult {
let tok = self.advance_token()?;
let pos = tok.position;
if let TokenKind::String(s) = tok.kind {
Ok(expr!(ExprKind::ConstStr(s), pos))
} else {
unreachable!()
}
}
fn ident(&mut self) -> EResult {
let pos = self.token.position;
let ident = self.expect_identifier()?;
Ok(expr!(ExprKind::Ident(ident), pos))
}
fn plit_int(&mut self) -> Result<Box<Pattern>, MsgWithPos> {
let tok = self.advance_token()?;
let pos = tok.position;
if let TokenKind::LitInt(i, _, _) = tok.kind {
Ok(Box::new(Pattern {
decl: PatternDecl::ConstInt(i.parse::<i64>().unwrap()),
pos,
}))
} else {
unreachable!()
}
}
fn plit_float(&mut self) -> Result<Box<Pattern>, MsgWithPos> {
let tok = self.advance_token()?;
let pos = tok.position;
if let TokenKind::LitFloat(c) = tok.kind {
Ok(Pattern {
decl: PatternDecl::ConstFloat(c.parse().unwrap()),
pos,
})
.map(|x| Box::new(x))
} else {
unreachable!()
}
}
fn plit_str(&mut self) -> Result<Box<Pattern>, MsgWithPos> {
let tok = self.advance_token()?;
let pos = tok.position;
if let TokenKind::String(s) = tok.kind {
Ok(Pattern {
decl: PatternDecl::ConstStr(s),
pos,
})
.map(|x| Box::new(x))
} else {
unreachable!()
}
}
fn pident(&mut self) -> Result<Box<Pattern>, MsgWithPos> {
let pos = self.token.position;
let ident = self.expect_identifier()?;
Ok(Pattern {
decl: PatternDecl::Ident(ident),
pos: pos,
})
.map(|x| Box::new(x))
}
fn parray(&mut self) -> Result<Box<Pattern>, MsgWithPos> {
let pos = self.token.position;
self.expect_token(TokenKind::LBracket)?;
let list = self.parse_comma_list(TokenKind::RBracket, |parser| parser.parse_pattern())?;
Ok(Pattern {
decl: PatternDecl::Array(list),
pos,
})
.map(|x| Box::new(x))
}
fn precord(&mut self) -> Result<Box<Pattern>, MsgWithPos> {
let pos = self.expect_token(TokenKind::LBrace)?.position;
let record = self.parse_comma_list(TokenKind::RBrace, |parser| {
let name = parser.expect_identifier()?;
let pattern = if parser.token.is(TokenKind::Colon) {
parser.expect_token(TokenKind::Colon)?;
Some(parser.parse_pattern()?)
} else {
None
};
Ok((name, pattern))
})?;
Ok(Pattern {
decl: PatternDecl::Record(record),
pos,
})
.map(|x| Box::new(x))
}
}
|
/// Similar to tag population.
macro_rules! make_styles {
// Create shortcut macros for any style; populate these functions in the submodule.
{ $($st_pascal_case:ident => $st:expr),+ } => {
/// The St enum restricts element-creation to only valid styles.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum St {
$(
$st_pascal_case,
)+
Custom(String)
}
impl St {
pub fn as_str(&self) -> &str {
match self {
$ (
St::$st_pascal_case => $st,
) +
St::Custom(val) => &val
}
}
}
impl From<&str> for St {
fn from(st: &str) -> Self {
match st {
$ (
$st => St::$st_pascal_case,
) +
_ => {
crate::error(&format!("Can't find this style: {}", st));
St::Custom(st.to_owned())
}
}
}
}
impl From<String> for St {
fn from(st: String) -> Self {
match st.as_ref() {
$ (
$st => St::$st_pascal_case,
) +
_ => {
crate::error(&format!("Can't find this style: {}", st));
St::Custom(st)
}
}
}
}
}
}
mod style_names;
pub use style_names::St;
|
#[derive(Debug)]
pub enum Stmt {
Define(String),
Assign(String, Box<Expr>),
ExprStmt(Box<Expr>)
}
#[derive(Debug)]
pub enum Expr {
Number(i64),
Variable(String),
Binary(Op, Box<Expr>, Box<Expr>),
Call(String, Vec<Expr>)
}
#[derive(Debug)]
pub enum Op {
Mul,
Div,
Add,
Sub,
Assign,
}
pub type Program = Vec<Stmt>; |
use crate::command_prelude::*;
use cargo::ops;
use std::path::PathBuf;
pub fn cli() -> App {
subcommand("vendor")
.about("Vendor all dependencies for a project locally")
.arg_quiet()
.arg_manifest_path()
.arg(
Arg::new("path")
.value_parser(clap::value_parser!(PathBuf))
.help("Where to vendor crates (`vendor` by default)"),
)
.arg(flag(
"no-delete",
"Don't delete older crates in the vendor directory",
))
.arg(
Arg::new("tomls")
.short('s')
.long("sync")
.help("Additional `Cargo.toml` to sync and vendor")
.value_name("TOML")
.value_parser(clap::value_parser!(PathBuf))
.action(clap::ArgAction::Append),
)
.arg(flag(
"respect-source-config",
"Respect `[source]` config in `.cargo/config`",
))
.arg(flag(
"versioned-dirs",
"Always include version in subdir name",
))
.arg(flag("no-merge-sources", "Not supported").hide(true))
.arg(flag("relative-path", "Not supported").hide(true))
.arg(flag("only-git-deps", "Not supported").hide(true))
.arg(flag("disallow-duplicates", "Not supported").hide(true))
.after_help("Run `cargo help vendor` for more detailed information.\n")
}
pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
// We're doing the vendoring operation ourselves, so we don't actually want
// to respect any of the `source` configuration in Cargo itself. That's
// intended for other consumers of Cargo, but we want to go straight to the
// source, e.g. crates.io, to fetch crates.
if !args.flag("respect-source-config") {
config.values_mut()?.remove("source");
}
// When we moved `cargo vendor` into Cargo itself we didn't stabilize a few
// flags, so try to provide a helpful error message in that case to ensure
// that users currently using the flag aren't tripped up.
let crates_io_cargo_vendor_flag = if args.flag("no-merge-sources") {
Some("--no-merge-sources")
} else if args.flag("relative-path") {
Some("--relative-path")
} else if args.flag("only-git-deps") {
Some("--only-git-deps")
} else if args.flag("disallow-duplicates") {
Some("--disallow-duplicates")
} else {
None
};
if let Some(flag) = crates_io_cargo_vendor_flag {
return Err(anyhow::format_err!(
"\
the crates.io `cargo vendor` command has now been merged into Cargo itself
and does not support the flag `{}` currently; to continue using the flag you
can execute `cargo-vendor vendor ...`, and if you would like to see this flag
supported in Cargo itself please feel free to file an issue at
https://github.com/rust-lang/cargo/issues/new
",
flag
)
.into());
}
let ws = args.workspace(config)?;
let path = args
.get_one::<PathBuf>("path")
.cloned()
.unwrap_or_else(|| PathBuf::from("vendor"));
ops::vendor(
&ws,
&ops::VendorOptions {
no_delete: args.flag("no-delete"),
destination: &path,
versioned_dirs: args.flag("versioned-dirs"),
extra: args
.get_many::<PathBuf>("tomls")
.unwrap_or_default()
.cloned()
.collect(),
},
)?;
Ok(())
}
|
use std::fmt;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::collections::HashSet;
use rand;
use rand::Rng;
use rustc_serialize::hex::ToHex;
use hash::Sha1;
use response::Peer;
use metainfo::Metainfo;
use tracker::Tracker;
pub type TorrentMap = HashMap<Sha1, Metainfo>;
pub type TrackerMap = HashMap<Sha1, HashSet<Tracker>>;
pub type PeerMap = HashMap<Sha1, HashSet<Peer>>;
#[derive(Debug)]
pub struct Daemon {
peer_id: String,
torrents: TorrentMap,
trackers: TrackerMap,
peers: PeerMap,
}
impl Daemon {
pub fn new() -> Self {
Daemon {
peer_id: generate_peer_id(),
torrents: TorrentMap::new(),
trackers: TrackerMap::new(),
peers: PeerMap::new(),
}
}
pub fn register(&mut self, metainfo: Metainfo) {
let hash: Sha1 = metainfo.info_hash();
let tracker = Tracker::new(&self.peer_id, &metainfo);
self.trackers.entry(hash.clone()).or_insert(HashSet::new());
if let Entry::Occupied(mut trackers) = self.trackers.entry(hash.clone()) {
trackers.get_mut().insert(tracker);
}
self.torrents.insert(hash.clone(), metainfo);
}
pub fn update(&mut self) {
for (hash, metainfo) in &self.torrents {
info!("Daemon::update():\n{}", metainfo);
if let Entry::Occupied(trackers) = self.trackers.entry(hash.clone()) {
for tracker in trackers.get() {
tracker.update_peers(&hash, &mut self.peers);
}
}
}
}
}
impl fmt::Display for Daemon {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for (_, metainfo) in &self.torrents {
writeln!(fmt, "{}", metainfo)?;
}
for (hash, peers) in &self.peers {
for peer in peers {
writeln!(fmt, "SHA1: {} => {}", hash.to_hex(), peer)?;
}
}
write!(fmt, "")
}
}
pub fn generate_peer_id() -> String {
const PEER_ID_PREFIX: &'static str = "-RT0002-";
let mut rng = rand::thread_rng();
let rand_chars: String = rng.gen_ascii_chars()
.take(20 - PEER_ID_PREFIX.len())
.collect();
format!("{}{}", PEER_ID_PREFIX, rand_chars)
}
|
use crate::clients::BufferResponse;
use crate::clients::InputMessage;
use directory_client::presence::Topology;
use futures::channel::{mpsc, oneshot};
use futures::future::FutureExt;
use futures::io::Error;
use futures::SinkExt;
use sphinx::route::{Destination, DestinationAddressBytes};
use std::borrow::Borrow;
use std::convert::TryFrom;
use std::io;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::prelude::*;
const SEND_REQUEST_PREFIX: u8 = 1;
const FETCH_REQUEST_PREFIX: u8 = 2;
const GET_CLIENTS_REQUEST_PREFIX: u8 = 3;
const OWN_DETAILS_REQUEST_PREFIX: u8 = 4;
#[derive(Debug)]
pub enum TCPSocketError {
FailedToStartSocketError,
UnknownSocketError,
IncompleteDataError,
UnknownRequestError,
}
impl From<io::Error> for TCPSocketError {
fn from(err: Error) -> Self {
use TCPSocketError::*;
match err.kind() {
io::ErrorKind::ConnectionRefused => FailedToStartSocketError,
io::ErrorKind::ConnectionReset => FailedToStartSocketError,
io::ErrorKind::ConnectionAborted => FailedToStartSocketError,
io::ErrorKind::NotConnected => FailedToStartSocketError,
io::ErrorKind::AddrInUse => FailedToStartSocketError,
io::ErrorKind::AddrNotAvailable => FailedToStartSocketError,
_ => UnknownSocketError,
}
}
}
enum ClientRequest {
Send {
message: Vec<u8>,
recipient_address: DestinationAddressBytes,
},
Fetch,
GetClients,
OwnDetails,
}
impl TryFrom<&[u8]> for ClientRequest {
type Error = TCPSocketError;
fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
use TCPSocketError::*;
if data.is_empty() {
return Err(IncompleteDataError);
}
match data[0] {
SEND_REQUEST_PREFIX => parse_send_request(data),
FETCH_REQUEST_PREFIX => Ok(ClientRequest::Fetch),
GET_CLIENTS_REQUEST_PREFIX => Ok(ClientRequest::GetClients),
OWN_DETAILS_REQUEST_PREFIX => Ok(ClientRequest::OwnDetails),
_ => Err(UnknownRequestError),
}
}
}
fn parse_send_request(data: &[u8]) -> Result<ClientRequest, TCPSocketError> {
if data.len() < 1 + 32 + 1 {
// make sure it has the prefix, destination and at least single byte of data
return Err(TCPSocketError::IncompleteDataError);
}
let mut recipient_address = [0u8; 32];
recipient_address.copy_from_slice(&data[1..33]);
let message = data[33..].to_vec();
Ok(ClientRequest::Send {
message,
recipient_address,
})
}
impl ClientRequest {
async fn handle_send(
msg: Vec<u8>,
recipient_address: DestinationAddressBytes,
mut input_tx: mpsc::UnboundedSender<InputMessage>,
) -> ServerResponse {
println!(
"send handle. sending to: {:?}, msg: {:?}",
recipient_address, msg
);
let dummy_surb = [0; 16];
let input_msg = InputMessage(Destination::new(recipient_address, dummy_surb), msg);
println!("ALMOST ABOUT TO SOMEDAY SEND {:?}", input_msg);
input_tx.send(input_msg).await.unwrap();
ServerResponse::Send
}
async fn handle_fetch(mut msg_query: mpsc::UnboundedSender<BufferResponse>) -> ServerResponse {
println!("fetch handle");
let (res_tx, res_rx) = oneshot::channel();
if msg_query.send(res_tx).await.is_err() {
return ServerResponse::Error {
message: "Server failed to receive messages".to_string(),
};
}
let messages = res_rx.map(|msg| msg).await;
if messages.is_err() {
return ServerResponse::Error {
message: "Server failed to receive messages".to_string(),
};
}
let messages = messages.unwrap();
println!("fetched {} messages", messages.len());
ServerResponse::Fetch { messages }
}
async fn handle_get_clients(topology: &Topology) -> ServerResponse {
println!("get clients handle");
let clients = topology
.mix_provider_nodes
.iter()
.flat_map(|provider| provider.registered_clients.iter())
.map(|client| base64::decode_config(&client.pub_key, base64::URL_SAFE).unwrap()) // TODO: this can potentially throw an error
.collect();
ServerResponse::GetClients { clients }
}
async fn handle_own_details(self_address_bytes: DestinationAddressBytes) -> ServerResponse {
println!("own details handle");
ServerResponse::OwnDetails {
address: self_address_bytes.to_vec(),
}
}
}
enum ServerResponse {
Send,
Fetch { messages: Vec<Vec<u8>> },
GetClients { clients: Vec<Vec<u8>> },
OwnDetails { address: Vec<u8> },
Error { message: String },
}
impl Into<Vec<u8>> for ServerResponse {
fn into(self) -> Vec<u8> {
match self {
ServerResponse::Send => b"ok".to_vec(),
ServerResponse::Fetch { messages } => encode_fetched_messages(messages),
ServerResponse::GetClients { clients } => encode_list_of_clients(clients),
ServerResponse::OwnDetails { address } => address,
ServerResponse::Error { message } => message.as_bytes().to_vec(),
}
}
}
// num_msgs || len1 || len2 || ... || msg1 || msg2 || ...
fn encode_fetched_messages(messages: Vec<Vec<u8>>) -> Vec<u8> {
// for reciprocal of this look into sfw-provider-requests::responses::PullResponse::from_bytes()
let num_msgs = messages.len() as u16;
let msgs_lens: Vec<u16> = messages.iter().map(|msg| msg.len() as u16).collect();
num_msgs
.to_be_bytes()
.to_vec()
.into_iter()
.chain(
msgs_lens
.into_iter()
.flat_map(|len| len.to_be_bytes().to_vec().into_iter()),
)
.chain(messages.iter().flat_map(|msg| msg.clone().into_iter()))
.collect()
}
fn encode_list_of_clients(clients: Vec<Vec<u8>>) -> Vec<u8> {
println!("clients: {:?}", clients);
// we can just concat all clients since all of them got to be 32 bytes long
// (if not, then we have bigger problem somewhere up the line)
// converts [[1,2,3],[4,5,6],...] into [1,2,3,4,5,6,...]
clients.into_iter().flatten().collect()
}
impl ServerResponse {
fn new_error(message: String) -> ServerResponse {
ServerResponse::Error { message }
}
}
async fn handle_connection(
data: &[u8],
request_handling_data: RequestHandlingData,
) -> Result<ServerResponse, TCPSocketError> {
let request = ClientRequest::try_from(data)?;
let response = match request {
ClientRequest::Send {
message,
recipient_address,
} => {
ClientRequest::handle_send(message, recipient_address, request_handling_data.msg_input)
.await
}
ClientRequest::Fetch => ClientRequest::handle_fetch(request_handling_data.msg_query).await,
ClientRequest::GetClients => {
ClientRequest::handle_get_clients(request_handling_data.topology.borrow()).await
}
ClientRequest::OwnDetails => {
ClientRequest::handle_own_details(request_handling_data.self_address).await
}
};
Ok(response)
}
struct RequestHandlingData {
msg_input: mpsc::UnboundedSender<InputMessage>,
msg_query: mpsc::UnboundedSender<BufferResponse>,
self_address: DestinationAddressBytes,
topology: Arc<Topology>,
}
async fn accept_connection(
mut socket: tokio::net::TcpStream,
msg_input: mpsc::UnboundedSender<InputMessage>,
msg_query: mpsc::UnboundedSender<BufferResponse>,
self_address: DestinationAddressBytes,
topology: Topology,
) {
let address = socket
.peer_addr()
.expect("connected streams should have a peer address");
println!("Peer address: {}", address);
let topology = Arc::new(topology);
let mut buf = [0u8; 2048];
// In a loop, read data from the socket and write the data back.
loop {
// TODO: shutdowns?
let response = match socket.read(&mut buf).await {
// socket closed
Ok(n) if n == 0 => {
println!("Remote connection closed.");
return;
}
Ok(n) => {
let request_handling_data = RequestHandlingData {
topology: topology.clone(),
msg_input: msg_input.clone(),
msg_query: msg_query.clone(),
self_address: self_address.clone(),
};
match handle_connection(&buf[..n], request_handling_data).await {
Ok(res) => res,
Err(e) => ServerResponse::new_error(format!("{:?}", e)),
}
}
Err(e) => {
eprintln!("failed to read from socket; err = {:?}", e);
return;
}
};
let response_vec: Vec<u8> = response.into();
if let Err(e) = socket.write_all(&response_vec).await {
eprintln!("failed to write reply to socket; err = {:?}", e);
return;
}
}
}
pub async fn start_tcpsocket(
address: SocketAddr,
message_tx: mpsc::UnboundedSender<InputMessage>,
received_messages_query_tx: mpsc::UnboundedSender<BufferResponse>,
self_address: DestinationAddressBytes,
topology: Topology,
) -> Result<(), TCPSocketError> {
let mut listener = tokio::net::TcpListener::bind(address).await?;
while let Ok((stream, _)) = listener.accept().await {
// it's fine to be cloning the channel on all new connection, because in principle
// this server should only EVER have a single client connected
tokio::spawn(accept_connection(
stream,
message_tx.clone(),
received_messages_query_tx.clone(),
self_address,
topology.clone(),
));
}
eprintln!("The tcpsocket went kaput...");
Ok(())
}
|
//! Growth rate
/// Pokemon growth rate
#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum GrowthRate {
MediumFast = 0,
Erratic = 1,
Fluctuating = 2,
MediumSlow = 3,
Fast = 4,
Slow = 5,
}
impl GrowthRate {
/// Returns the `C` name of this growth rate
pub fn c_name(&self) -> &'static str {
match self {
GrowthRate::MediumFast => "MEDIUM_FAST",
GrowthRate::Erratic => "ERRATIC",
GrowthRate::Fluctuating => "FLUCTUATING",
GrowthRate::MediumSlow => "MEDIUM_SLOW",
GrowthRate::Fast => "FAST",
GrowthRate::Slow => "SLOW",
}
}
}
|
extern crate actix_web;
extern crate handlebars;
#[macro_use]
extern crate serde_json;
extern crate rand;
extern crate serde;
use actix_web::{http, server, App, HttpRequest, HttpResponse};
use handlebars::Handlebars;
use rand::Rng;
use serde::Serialize;
struct State {
handlebars: Handlebars,
}
fn main() {
let server_result = server::new(|| {
App::with_state(State {
handlebars: init_handlebars(),
}).resource("/", |r| r.f(index))
}).bind("0.0.0.0:8080");
server_result
.map(|ok| ok.run())
.expect("Server could not be started!");
}
/**
* Handle index page.
*/
fn index(_req: HttpRequest<State>) -> HttpResponse {
let names = vec!["User", "Friend", "Visitor"];
let random = rand::thread_rng().gen_range(0, names.len());
respond_with_template(_req, "index", json!({ "name": names[random] }))
}
fn init_handlebars() -> Handlebars {
let mut handlebars = Handlebars::new();
handlebars
.register_template_file("index", "./templates/index.hbs")
.expect("Could not load index template!");
handlebars
}
fn respond_with_template<T>(
request: HttpRequest<State>,
template_name: &'static str,
data: T,
) -> HttpResponse
where
T: Serialize,
{
let body_o = request.state().handlebars.render(&template_name, &data);
match body_o {
Ok(body) => HttpResponse::Ok().content_type("text/html").body(body),
_ => HttpResponse::new(http::StatusCode::INTERNAL_SERVER_ERROR),
}
}
|
use cosmwasm_std::{
to_binary, Api, BankMsg, Coin, CosmosMsg, Env, Extern, HandleResponse, HandleResult, HumanAddr,
InitResponse, InitResult, Querier, QueryResult, StdError, StdResult, Storage, Uint128,
};
use cosmwasm_storage::{ReadonlySingleton, Singleton};
use rand::{RngCore, SeedableRng};
use rand_chacha::ChaChaRng;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
#[derive(Serialize, Deserialize, Clone)]
struct State {
player_1: Option<HumanAddr>,
player_1_secret: u128,
player_2: Option<HumanAddr>,
player_2_secret: u128,
dice_result: u8,
winner: Option<HumanAddr>,
}
impl State {
pub fn save<S: Storage>(&self, storage: &mut S) -> StdResult<()> {
Singleton::new(storage, b"state").save(self)
}
pub fn load<S: Storage>(storage: &S) -> StdResult<State> {
ReadonlySingleton::new(storage, b"state").load()
}
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////// Init ////////////////////////////////
//////////////////////////////////////////////////////////////////////
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct InitMsg {}
pub fn init<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
_env: Env,
_msg: InitMsg,
) -> InitResult {
let state = State {
player_1: None,
player_1_secret: 0,
player_2: None,
player_2_secret: 0,
dice_result: 0,
winner: None,
};
state.save(&mut deps.storage)?;
Ok(InitResponse::default())
}
//////////////////////////////////////////////////////////////////////
/////////////////////////////// Handle ///////////////////////////////
//////////////////////////////////////////////////////////////////////
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum HandleMsg {
Join { secret: u128 },
Leave {},
}
pub fn handle<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
env: Env,
msg: HandleMsg,
) -> HandleResult {
match msg {
HandleMsg::Join { secret } => {
// player 1 joins, sends a secret and deposits 1 SCRT to the contract
// player 1's secret is stored privately
//
// player 2 joins, sends a secret and deposits 1 SCRT to the contract
// player 2's secret is stored privately
//
// once player 2 joins, we can derive a shared secret that no one knows
// then we can roll the dice and choose a winner
// dice roll 1-3: player 1 wins / dice roll 4-6: player 2 wins
//
// the winner then gets 2 SCRT
if env.message.sent_funds.len() != 1
|| env.message.sent_funds[0].amount
!= Uint128(1_000_000 /* 1mn uscrt = 1 SCRT */)
|| env.message.sent_funds[0].denom != String::from("uscrt")
{
return Err(StdError::generic_err(
"Must deposit 1 SCRT to enter the game.",
));
}
let mut state = State::load(&deps.storage)?;
if state.player_1.is_none() {
state.player_1 = Some(env.message.sender);
state.player_1_secret = secret;
state.save(&mut deps.storage)?;
Ok(HandleResponse::default())
} else if state.player_2.is_none() {
state.player_2 = Some(env.message.sender);
state.player_2_secret = secret;
let mut combined_secret: Vec<u8> = state.player_1_secret.to_be_bytes().to_vec();
combined_secret.extend(&state.player_2_secret.to_be_bytes());
let random_seed: [u8; 32] = Sha256::digest(&combined_secret).into();
let mut rng = ChaChaRng::from_seed(random_seed);
state.dice_result = ((rng.next_u32() % 6) + 1) as u8; // a number between 1 and 6
if state.dice_result >= 1 && state.dice_result <= 3 {
state.winner = state.player_1.clone();
} else {
state.winner = state.player_2.clone();
}
state.save(&mut deps.storage)?;
Ok(HandleResponse {
messages: vec![CosmosMsg::Bank(BankMsg::Send {
from_address: env.contract.address,
to_address: state.winner.unwrap(),
amount: vec![Coin::new(2_000_000, "uscrt")], // 1mn uscrt = 1 SCRT
})],
log: vec![],
data: None,
})
} else {
Err(StdError::generic_err("Game is full."))
}
}
HandleMsg::Leave {} => {
// if player 2 isn't in yet, player 1 can leave and get their money back
let mut state = State::load(&deps.storage)?;
if state.player_1.as_ref() != Some(&env.message.sender) {
return Err(StdError::generic_err("You are not a player."));
}
if state.winner.is_some() {
return Err(StdError::generic_err(format!(
"Game is already over. Winner is {}.",
state.winner.unwrap()
)));
}
state.player_1 = None;
state.player_1_secret = 0;
state.save(&mut deps.storage)?;
Ok(HandleResponse {
messages: vec![CosmosMsg::Bank(BankMsg::Send {
from_address: env.contract.address,
to_address: env.message.sender,
amount: vec![Coin::new(1_000_000, "uscrt")], // 1mn uscrt = 1 SCRT
})],
log: vec![],
data: None,
})
}
}
}
///////////////////////////////////////////////////////////////////////
//////////////////////////////// Query ////////////////////////////////
///////////////////////////////////////////////////////////////////////
// These are getters, we only return what's public
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
GetResult {},
}
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
struct Result {
winner: HumanAddr,
dice_roll: u8,
}
pub fn query<S: Storage, A: Api, Q: Querier>(deps: &Extern<S, A, Q>, msg: QueryMsg) -> QueryResult {
match msg {
QueryMsg::GetResult {} => {
let state = State::load(&deps.storage)?;
if state.winner.is_none() {
return Err(StdError::generic_err("Still waiting for players."));
}
return Ok(to_binary(&Result {
winner: state.winner.unwrap(),
dice_roll: state.dice_result,
})?);
}
}
}
|
mod config;
use clap::Parser;
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
#[clap(global = true, long)]
check: bool,
}
fn main() {
let args = Args::parse();
println!("{:?}", args);
}
|
use openssl::{aes::{AesKey, aes_ige}, symm::Mode};
use openssl::rand::rand_bytes;
fn main() {
// plaintext we want to encrypt
let plaintext = "levitathan comes from the depths";
let size = plaintext.len();
// random bytes for key generation
let mut key_buff = [0; 16];
rand_bytes(&mut key_buff).unwrap();
let mut iv = *b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F";
// AES Key from random bytes
let key = AesKey::new_encrypt(&key_buff).unwrap();
// output to store the encryption
let mut output: Vec<u8> = vec![0; size];
aes_ige(plaintext.as_bytes(), &mut output, &key, &mut iv, Mode::Encrypt);
// format to hex and print
let hex_value = format!("{:x?}", output);
println!("{}", hex_value);
// decrypt
let mut decrypted = vec![0; size];
aes_ige(&output, &mut decrypted, &key, &mut iv, Mode::Decrypt);
println!("{:?}", decrypted);
} |
#![feature(test)]
extern crate ruruby;
extern crate test;
use ruruby::test::*;
use ruruby::*;
#[test]
fn bool_lit1() {
let program = "(3==3)==true";
let expected = Value::bool(true);
eval_script(program, expected);
}
#[test]
fn bool_lit2() {
let program = "(3==9)==false";
let expected = Value::bool(true);
eval_script(program, expected);
}
#[test]
fn nil_lit1() {
let program = "nil";
let expected = Value::nil();
eval_script(program, expected);
}
#[test]
fn string_lit1() {
let globals = Globals::new();
let program = r#""open " "windows""#;
let expected = Value::string(&globals, "open windows".to_string());
eval_script(program, expected);
}
#[test]
fn string_lit2() {
let globals = Globals::new();
let program = r#""open "
"windows""#;
let expected = Value::string(&globals, "windows".to_string());
eval_script(program, expected);
}
#[test]
fn interpolated_string_lit1() {
let globals = Globals::new();
let program = r###"
x = 20
f = "fibonacci";
"#{f} #{def fibo(x); if x<2 then x else fibo(x-1)+fibo(x-2); end; end;""} fibo(#{x}) = #{fibo(x)}"
"###;
let expected = Value::string(&globals, "fibonacci fibo(20) = 6765".to_string());
eval_script(program, expected);
}
#[test]
fn float_lit1() {
let program = "
assert(123000000.0, 12.3e7)
assert(0.000031, 3.1e-5)
";
assert_script(program);
}
#[test]
fn array_lit1() {
let program = "
assert([1,2,3], [1,2,3])
";
assert_script(program);
}
#[test]
fn percent_notation() {
let program = r#"
assert(%w(We are the champions), ["We", "are", "the", "champions"])
"#;
assert_script(program);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.